1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
39 using namespace clang;
42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
48 /// A convenience routine for creating a decayed reference to a function.
50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 const Expr *Base, bool HadMultipleCandidates,
52 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
71 S.MarkDeclRefReferenced(DRE, Base);
72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
80 bool AllowObjCWritebackConversion);
82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
87 static OverloadingResult
88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
92 bool AllowObjCConversionOnExplicit);
95 static ImplicitConversionSequence::CompareKind
96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
100 static ImplicitConversionSequence::CompareKind
101 CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
105 static ImplicitConversionSequence::CompareKind
106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
110 /// GetConversionRank - Retrieve the implicit conversion rank
111 /// corresponding to the given implicit conversion kind.
112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
134 ICR_OCL_Scalar_Widening,
135 ICR_Complex_Real_Conversion,
138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
143 ICR_C_Conversion_Extension
145 return Rank[(int)Kind];
148 /// GetImplicitConversionName - Return the name of this kind of
149 /// implicit conversion.
150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155 "Function-to-pointer",
156 "Function pointer conversion",
158 "Integral promotion",
159 "Floating point promotion",
161 "Integral conversion",
162 "Floating conversion",
163 "Complex conversion",
164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
167 "Boolean conversion",
168 "Compatible-types conversion",
169 "Derived-to-base conversion",
172 "Complex-real conversion",
173 "Block Pointer conversion",
174 "Transparent Union Conversion",
175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
177 "C specific type conversion",
178 "Incompatible pointer conversion"
183 /// StandardConversionSequence - Set the standard conversion
184 /// sequence to the identity conversion.
185 void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
189 DeprecatedStringLiteralToCharPtr = false;
190 QualificationIncludesObjCLifetime = false;
191 ReferenceBinding = false;
192 DirectBinding = false;
193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
197 ObjCLifetimeConversionBinding = false;
198 CopyConstructor = nullptr;
201 /// getRank - Retrieve the rank of this standard conversion sequence
202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203 /// implicit conversions.
204 ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
215 /// isPointerConversionToBool - Determines whether this conversion is
216 /// a conversion of a pointer or pointer-to-member to bool. This is
217 /// used as part of the ranking of standard conversion sequences
218 /// (C++ 13.3.3.2p4).
219 bool StandardConversionSequence::isPointerConversionToBool() const {
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
224 if (getToType(1)->isBooleanType() &&
225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
228 getFromType()->isNullPtrType() ||
229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 /// isPointerConversionToVoidPointer - Determines whether this
236 /// conversion is a conversion of a pointer to a void pointer. This is
237 /// used as part of the ranking of standard conversion sequences (C++
240 StandardConversionSequence::
241 isPointerConversionToVoidPointer(ASTContext& Context) const {
242 QualType FromType = getFromType();
243 QualType ToType = getToType(1);
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
253 return ToPtrType->getPointeeType()->isVoidType();
258 /// Skip any implicit casts which could be either part of a narrowing conversion
259 /// or after one in an implicit conversion.
260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
267 case CK_BooleanToSignedIntegral:
268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
282 /// Check if this standard conversion sequence represents a narrowing
283 /// conversion, according to C++11 [dcl.init.list]p7.
285 /// \param Ctx The AST context.
286 /// \param Converted The result of applying this standard conversion sequence.
287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288 /// value of the expression prior to the narrowing conversion.
289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290 /// type of the expression prior to the narrowing conversion.
292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue,
295 QualType &ConstantType) const {
296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
320 // -- from a floating-point type to an integer type, or
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 FloatingIntegralConversion:
328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333 assert(Initializer && "Unknown conversion expression");
335 // If it's value-dependent, we can't tell whether it's narrowing.
336 if (Initializer->isValueDependent())
337 return NK_Dependent_Narrowing;
339 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
345 llvm::APSInt ConvertedValue = IntConstantValue;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
352 ConstantType = Initializer->getType();
353 return NK_Constant_Narrowing;
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
360 return NK_Not_Narrowing;
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
378 assert(ConstantValue.isFloat());
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
389 return NK_Constant_Narrowing;
392 return NK_Variable_Narrowing;
395 return NK_Not_Narrowing;
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
402 case ICK_Integral_Conversion:
403 IntegralConversion: {
404 assert(FromType->isIntegralOrUnscopedEnumerationType());
405 assert(ToType->isIntegralOrUnscopedEnumerationType());
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
411 if (FromWidth > ToWidth ||
412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
444 if (ConvertedValue != InitializerValue)
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
453 return NK_Not_Narrowing;
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
462 /// dump - Print this standard conversion sequence to standard
463 /// error. Useful for debugging overloading issues.
464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
465 raw_ostream &OS = llvm::errs();
466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
468 OS << GetImplicitConversionName(First);
469 PrintedSomething = true;
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
476 OS << GetImplicitConversionName(Second);
478 if (CopyConstructor) {
479 OS << " (by copy constructor)";
480 } else if (DirectBinding) {
481 OS << " (direct reference binding)";
482 } else if (ReferenceBinding) {
483 OS << " (reference binding)";
485 PrintedSomething = true;
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
492 OS << GetImplicitConversionName(Third);
493 PrintedSomething = true;
496 if (!PrintedSomething) {
497 OS << "No conversions required";
501 /// dump - Print this user-defined conversion sequence to standard
502 /// error. Useful for debugging overloading issues.
503 void UserDefinedConversionSequence::dump() const {
504 raw_ostream &OS = llvm::errs();
505 if (Before.First || Before.Second || Before.Third) {
509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
512 OS << "aggregate initialization";
513 if (After.First || After.Second || After.Third) {
519 /// dump - Print this implicit conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void ImplicitConversionSequence::dump() const {
522 raw_ostream &OS = llvm::errs();
523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
525 switch (ConversionKind) {
526 case StandardConversion:
527 OS << "Standard conversion: ";
530 case UserDefinedConversion:
531 OS << "User-defined conversion: ";
534 case EllipsisConversion:
535 OS << "Ellipsis conversion";
537 case AmbiguousConversion:
538 OS << "Ambiguous conversion";
541 OS << "Bad conversion";
548 void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
552 void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
564 // Structure used by DeductionFailureInfo to store
565 // template argument information.
566 struct DFIArguments {
567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
570 // Structure used by DeductionFailureInfo to store
571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
583 /// \brief Convert from Sema's representation of template deduction information
584 /// to the form used in overload-candidate information.
586 clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
589 DeductionFailureInfo Result;
590 Result.Result = static_cast<unsigned>(TDK);
591 Result.HasDiagnostic = false;
593 case Sema::TDK_Invalid:
594 case Sema::TDK_InstantiationDepth:
595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
597 case Sema::TDK_MiscellaneousDeductionFailure:
598 case Sema::TDK_CUDATargetMismatch:
599 Result.Data = nullptr;
602 case Sema::TDK_Incomplete:
603 case Sema::TDK_InvalidExplicitArguments:
604 Result.Data = Info.Param.getOpaqueValue();
607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
628 case Sema::TDK_Inconsistent:
629 case Sema::TDK_Underqualified: {
630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
639 case Sema::TDK_SubstitutionFailure:
640 Result.Data = Info.take();
641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure");
657 void DeductionFailureInfo::Destroy() {
658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
660 case Sema::TDK_Invalid:
661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
665 case Sema::TDK_InvalidExplicitArguments:
666 case Sema::TDK_CUDATargetMismatch:
667 case Sema::TDK_NonDependentConversionFailure:
670 case Sema::TDK_Inconsistent:
671 case Sema::TDK_Underqualified:
672 case Sema::TDK_DeducedMismatch:
673 case Sema::TDK_DeducedMismatchNested:
674 case Sema::TDK_NonDeducedMismatch:
675 // FIXME: Destroy the data?
679 case Sema::TDK_SubstitutionFailure:
680 // FIXME: Destroy the template argument list?
682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
689 case Sema::TDK_MiscellaneousDeductionFailure:
694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
700 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_SubstitutionFailure:
708 case Sema::TDK_DeducedMismatch:
709 case Sema::TDK_DeducedMismatchNested:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_CUDATargetMismatch:
712 case Sema::TDK_NonDependentConversionFailure:
713 return TemplateParameter();
715 case Sema::TDK_Incomplete:
716 case Sema::TDK_InvalidExplicitArguments:
717 return TemplateParameter::getFromOpaqueValue(Data);
719 case Sema::TDK_Inconsistent:
720 case Sema::TDK_Underqualified:
721 return static_cast<DFIParamWithArguments*>(Data)->Param;
724 case Sema::TDK_MiscellaneousDeductionFailure:
728 return TemplateParameter();
731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
743 case Sema::TDK_CUDATargetMismatch:
744 case Sema::TDK_NonDependentConversionFailure:
747 case Sema::TDK_DeducedMismatch:
748 case Sema::TDK_DeducedMismatchNested:
749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
755 case Sema::TDK_MiscellaneousDeductionFailure:
762 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
765 case Sema::TDK_Invalid:
766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
770 case Sema::TDK_InvalidExplicitArguments:
771 case Sema::TDK_SubstitutionFailure:
772 case Sema::TDK_CUDATargetMismatch:
773 case Sema::TDK_NonDependentConversionFailure:
776 case Sema::TDK_Inconsistent:
777 case Sema::TDK_Underqualified:
778 case Sema::TDK_DeducedMismatch:
779 case Sema::TDK_DeducedMismatchNested:
780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
784 case Sema::TDK_MiscellaneousDeductionFailure:
791 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
794 case Sema::TDK_Invalid:
795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
799 case Sema::TDK_InvalidExplicitArguments:
800 case Sema::TDK_SubstitutionFailure:
801 case Sema::TDK_CUDATargetMismatch:
802 case Sema::TDK_NonDependentConversionFailure:
805 case Sema::TDK_Inconsistent:
806 case Sema::TDK_Underqualified:
807 case Sema::TDK_DeducedMismatch:
808 case Sema::TDK_DeducedMismatchNested:
809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
813 case Sema::TDK_MiscellaneousDeductionFailure:
820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
831 void OverloadCandidateSet::destroyCandidates() {
832 for (iterator i = begin(), e = end(); i != e; ++i) {
833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
840 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
850 class UnbridgedCastsSet {
855 SmallVector<Entry, 2> Entries;
858 void save(Sema &S, Expr *&E) {
859 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
860 Entry entry = { &E, E };
861 Entries.push_back(entry);
862 E = S.stripARCUnbridgedCast(E);
866 for (SmallVectorImpl<Entry>::iterator
867 i = Entries.begin(), e = Entries.end(); i != e; ++i)
873 /// checkPlaceholderForOverload - Do any interesting placeholder-like
874 /// preprocessing on the given expression.
876 /// \param unbridgedCasts a collection to which to add unbridged casts;
877 /// without this, they will be immediately diagnosed as errors
879 /// Return true on unrecoverable error.
881 checkPlaceholderForOverload(Sema &S, Expr *&E,
882 UnbridgedCastsSet *unbridgedCasts = nullptr) {
883 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
884 // We can't handle overloaded expressions here because overload
885 // resolution might reasonably tweak them.
886 if (placeholder->getKind() == BuiltinType::Overload) return false;
888 // If the context potentially accepts unbridged ARC casts, strip
889 // the unbridged cast and add it to the collection for later restoration.
890 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
892 unbridgedCasts->save(S, E);
896 // Go ahead and check everything else.
897 ExprResult result = S.CheckPlaceholderExpr(E);
898 if (result.isInvalid())
909 /// checkArgPlaceholdersForOverload - Check a set of call operands for
911 static bool checkArgPlaceholdersForOverload(Sema &S,
913 UnbridgedCastsSet &unbridged) {
914 for (unsigned i = 0, e = Args.size(); i != e; ++i)
915 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
921 /// Determine whether the given New declaration is an overload of the
922 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
923 /// New and Old cannot be overloaded, e.g., if New has the same signature as
924 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
925 /// functions (or function templates) at all. When it does return Ovl_Match or
926 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
927 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
930 /// Example: Given the following input:
932 /// void f(int, float); // #1
933 /// void f(int, int); // #2
934 /// int f(int, int); // #3
936 /// When we process #1, there is no previous declaration of "f", so IsOverload
937 /// will not be used.
939 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
940 /// the parameter types, we see that #1 and #2 are overloaded (since they have
941 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
944 /// When we process #3, Old is an overload set containing #1 and #2. We compare
945 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
946 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
947 /// functions are not part of the signature), IsOverload returns Ovl_Match and
948 /// MatchedDecl will be set to point to the FunctionDecl for #2.
950 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
951 /// by a using declaration. The rules for whether to hide shadow declarations
952 /// ignore some properties which otherwise figure into a function template's
955 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956 NamedDecl *&Match, bool NewIsUsingDecl) {
957 for (LookupResult::iterator I = Old.begin(), E = Old.end();
959 NamedDecl *OldD = *I;
961 bool OldIsUsingDecl = false;
962 if (isa<UsingShadowDecl>(OldD)) {
963 OldIsUsingDecl = true;
965 // We can always introduce two using declarations into the same
966 // context, even if they have identical signatures.
967 if (NewIsUsingDecl) continue;
969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
972 // A using-declaration does not conflict with another declaration
973 // if one of them is hidden.
974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
977 // If either declaration was introduced by a using declaration,
978 // we'll need to use slightly different rules for matching.
979 // Essentially, these rules are the normal rules, except that
980 // function templates hide function templates with different
981 // return types or template parameter lists.
982 bool UseMemberUsingDeclRules =
983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984 !New->getFriendObjectKind();
986 if (FunctionDecl *OldF = OldD->getAsFunction()) {
987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
993 if (!isa<FunctionTemplateDecl>(OldD) &&
994 !shouldLinkPossiblyHiddenDecl(*I, New))
1000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1001 // We can overload with these, which can show up when doing
1002 // redeclaration checks for UsingDecls.
1003 assert(Old.getLookupKind() == LookupUsingDeclName);
1004 } else if (isa<TagDecl>(OldD)) {
1005 // We can always overload with tags by hiding them.
1006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1007 // Optimistically assume that an unresolved using decl will
1008 // overload; if it doesn't, we'll have to diagnose during
1009 // template instantiation.
1011 // Exception: if the scope is dependent and this is not a class
1012 // member, the using declaration can only introduce an enumerator.
1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1015 return Ovl_NonFunction;
1019 // Only function declarations can be overloaded; object and type
1020 // declarations cannot be overloaded.
1022 return Ovl_NonFunction;
1026 return Ovl_Overload;
1029 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1031 // C++ [basic.start.main]p2: This function shall not be overloaded.
1035 // MSVCRT user defined entry points cannot be overloaded.
1036 if (New->isMSVCRTEntryPoint())
1039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1042 // C++ [temp.fct]p2:
1043 // A function template can be overloaded with other function templates
1044 // and with normal (non-template) functions.
1045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1048 // Is the function New an overload of the function Old?
1049 QualType OldQType = Context.getCanonicalType(Old->getType());
1050 QualType NewQType = Context.getCanonicalType(New->getType());
1052 // Compare the signatures (C++ 1.3.10) of the two functions to
1053 // determine whether they are overloads. If we find any mismatch
1054 // in the signature, they are overloads.
1056 // If either of these functions is a K&R-style function (no
1057 // prototype), then we consider them to have matching signatures.
1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1065 // The signature of a function includes the types of its
1066 // parameters (C++ 1.3.10), which includes the presence or absence
1067 // of the ellipsis; see C++ DR 357).
1068 if (OldQType != NewQType &&
1069 (OldType->getNumParams() != NewType->getNumParams() ||
1070 OldType->isVariadic() != NewType->isVariadic() ||
1071 !FunctionParamTypesAreEqual(OldType, NewType)))
1074 // C++ [temp.over.link]p4:
1075 // The signature of a function template consists of its function
1076 // signature, its return type and its template parameter list. The names
1077 // of the template parameters are significant only for establishing the
1078 // relationship between the template parameters and the rest of the
1081 // We check the return type and template parameter lists for function
1082 // templates first; the remaining checks follow.
1084 // However, we don't consider either of these when deciding whether
1085 // a member introduced by a shadow declaration is hidden.
1086 if (!UseMemberUsingDeclRules && NewTemplate &&
1087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088 OldTemplate->getTemplateParameters(),
1089 false, TPL_TemplateMatch) ||
1090 OldType->getReturnType() != NewType->getReturnType()))
1093 // If the function is a class member, its signature includes the
1094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1096 // As part of this, also check whether one of the member functions
1097 // is static, in which case they are not overloads (C++
1098 // 13.1p2). While not part of the definition of the signature,
1099 // this check is important to determine whether these functions
1100 // can be overloaded.
1101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1103 if (OldMethod && NewMethod &&
1104 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1106 if (!UseMemberUsingDeclRules &&
1107 (OldMethod->getRefQualifier() == RQ_None ||
1108 NewMethod->getRefQualifier() == RQ_None)) {
1109 // C++0x [over.load]p2:
1110 // - Member function declarations with the same name and the same
1111 // parameter-type-list as well as member function template
1112 // declarations with the same name, the same parameter-type-list, and
1113 // the same template parameter lists cannot be overloaded if any of
1114 // them, but not all, have a ref-qualifier (8.3.5).
1115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1117 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1122 // We may not have applied the implicit const for a constexpr member
1123 // function yet (because we haven't yet resolved whether this is a static
1124 // or non-static member function). Add it now, on the assumption that this
1125 // is a redeclaration of OldMethod.
1126 unsigned OldQuals = OldMethod->getTypeQualifiers();
1127 unsigned NewQuals = NewMethod->getTypeQualifiers();
1128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1129 !isa<CXXConstructorDecl>(NewMethod))
1130 NewQuals |= Qualifiers::Const;
1132 // We do not allow overloading based off of '__restrict'.
1133 OldQuals &= ~Qualifiers::Restrict;
1134 NewQuals &= ~Qualifiers::Restrict;
1135 if (OldQuals != NewQuals)
1139 // Though pass_object_size is placed on parameters and takes an argument, we
1140 // consider it to be a function-level modifier for the sake of function
1141 // identity. Either the function has one or more parameters with
1142 // pass_object_size or it doesn't.
1143 if (functionHasPassObjectSizeParams(New) !=
1144 functionHasPassObjectSizeParams(Old))
1147 // enable_if attributes are an order-sensitive part of the signature.
1148 for (specific_attr_iterator<EnableIfAttr>
1149 NewI = New->specific_attr_begin<EnableIfAttr>(),
1150 NewE = New->specific_attr_end<EnableIfAttr>(),
1151 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152 OldE = Old->specific_attr_end<EnableIfAttr>();
1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154 if (NewI == NewE || OldI == OldE)
1156 llvm::FoldingSetNodeID NewID, OldID;
1157 NewI->getCond()->Profile(NewID, Context, true);
1158 OldI->getCond()->Profile(OldID, Context, true);
1163 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1164 // Don't allow overloading of destructors. (In theory we could, but it
1165 // would be a giant change to clang.)
1166 if (isa<CXXDestructorDecl>(New))
1169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170 OldTarget = IdentifyCUDATarget(Old);
1171 if (NewTarget == CFT_InvalidTarget)
1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1176 // Allow overloading of functions with same signature and different CUDA
1177 // target attributes.
1178 return NewTarget != OldTarget;
1181 // The signatures match; this is not an overload.
1185 /// \brief Checks availability of the function depending on the current
1186 /// function context. Inside an unavailable function, unavailability is ignored.
1188 /// \returns true if \arg FD is unavailable and current context is inside
1189 /// an available function, false otherwise.
1190 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1191 if (!FD->isUnavailable())
1194 // Walk up the context of the caller.
1195 Decl *C = cast<Decl>(CurContext);
1197 if (C->isUnavailable())
1199 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1203 /// \brief Tries a user-defined conversion from From to ToType.
1205 /// Produces an implicit conversion sequence for when a standard conversion
1206 /// is not an option. See TryImplicitConversion for more information.
1207 static ImplicitConversionSequence
1208 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1211 bool InOverloadResolution,
1213 bool AllowObjCWritebackConversion,
1214 bool AllowObjCConversionOnExplicit) {
1215 ImplicitConversionSequence ICS;
1217 if (SuppressUserConversions) {
1218 // We're not in the case above, so there is no conversion that
1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1224 // Attempt user-defined conversion.
1225 OverloadCandidateSet Conversions(From->getExprLoc(),
1226 OverloadCandidateSet::CSK_Normal);
1227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228 Conversions, AllowExplicit,
1229 AllowObjCConversionOnExplicit)) {
1232 ICS.setUserDefined();
1233 // C++ [over.ics.user]p4:
1234 // A conversion of an expression of class type to the same class
1235 // type is given Exact Match rank, and a conversion of an
1236 // expression of class type to a base class of that type is
1237 // given Conversion rank, in spite of the fact that a copy
1238 // constructor (i.e., a user-defined conversion function) is
1239 // called for those cases.
1240 if (CXXConstructorDecl *Constructor
1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246 if (Constructor->isCopyConstructor() &&
1247 (FromCanon == ToCanon ||
1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1249 // Turn this into a "standard" conversion sequence, so that it
1250 // gets ranked with standard conversion sequences.
1251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(From->getType());
1255 ICS.Standard.setAllToTypes(ToType);
1256 ICS.Standard.CopyConstructor = Constructor;
1257 ICS.Standard.FoundCopyConstructor = Found;
1258 if (ToCanon != FromCanon)
1259 ICS.Standard.Second = ICK_Derived_To_Base;
1266 ICS.Ambiguous.setFromType(From->getType());
1267 ICS.Ambiguous.setToType(ToType);
1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269 Cand != Conversions.end(); ++Cand)
1271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1275 case OR_No_Viable_Function:
1276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1283 /// TryImplicitConversion - Attempt to perform an implicit conversion
1284 /// from the given expression (Expr) to the given type (ToType). This
1285 /// function returns an implicit conversion sequence that can be used
1286 /// to perform the initialization. Given
1288 /// void f(float f);
1289 /// void g(int i) { f(i); }
1291 /// this routine would produce an implicit conversion sequence to
1292 /// describe the initialization of f from i, which will be a standard
1293 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1296 /// Note that this routine only determines how the conversion can be
1297 /// performed; it does not actually perform the conversion. As such,
1298 /// it will not produce any diagnostics if no conversion is available,
1299 /// but will instead return an implicit conversion sequence of kind
1300 /// "BadConversion".
1302 /// If @p SuppressUserConversions, then user-defined conversions are
1304 /// If @p AllowExplicit, then explicit user-defined conversions are
1307 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308 /// writeback conversion, which allows __autoreleasing id* parameters to
1309 /// be initialized with __strong id* or __weak id* arguments.
1310 static ImplicitConversionSequence
1311 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312 bool SuppressUserConversions,
1314 bool InOverloadResolution,
1316 bool AllowObjCWritebackConversion,
1317 bool AllowObjCConversionOnExplicit) {
1318 ImplicitConversionSequence ICS;
1319 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1325 if (!S.getLangOpts().CPlusPlus) {
1326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1330 // C++ [over.ics.user]p4:
1331 // A conversion of an expression of class type to the same class
1332 // type is given Exact Match rank, and a conversion of an
1333 // expression of class type to a base class of that type is
1334 // given Conversion rank, in spite of the fact that a copy/move
1335 // constructor (i.e., a user-defined conversion function) is
1336 // called for those cases.
1337 QualType FromType = From->getType();
1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1339 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1342 ICS.Standard.setAsIdentityConversion();
1343 ICS.Standard.setFromType(FromType);
1344 ICS.Standard.setAllToTypes(ToType);
1346 // We don't actually check at this point whether there is a valid
1347 // copy/move constructor, since overloading just assumes that it
1348 // exists. When we actually perform initialization, we'll find the
1349 // appropriate constructor to copy the returned object, if needed.
1350 ICS.Standard.CopyConstructor = nullptr;
1352 // Determine whether this is considered a derived-to-base conversion.
1353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1354 ICS.Standard.Second = ICK_Derived_To_Base;
1359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360 AllowExplicit, InOverloadResolution, CStyle,
1361 AllowObjCWritebackConversion,
1362 AllowObjCConversionOnExplicit);
1365 ImplicitConversionSequence
1366 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367 bool SuppressUserConversions,
1369 bool InOverloadResolution,
1371 bool AllowObjCWritebackConversion) {
1372 return ::TryImplicitConversion(*this, From, ToType,
1373 SuppressUserConversions, AllowExplicit,
1374 InOverloadResolution, CStyle,
1375 AllowObjCWritebackConversion,
1376 /*AllowObjCConversionOnExplicit=*/false);
1379 /// PerformImplicitConversion - Perform an implicit conversion of the
1380 /// expression From to the type ToType. Returns the
1381 /// converted expression. Flavor is the kind of conversion we're
1382 /// performing, used in the error message. If @p AllowExplicit,
1383 /// explicit user-defined conversions are permitted.
1385 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1386 AssignmentAction Action, bool AllowExplicit) {
1387 ImplicitConversionSequence ICS;
1388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1392 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1393 AssignmentAction Action, bool AllowExplicit,
1394 ImplicitConversionSequence& ICS) {
1395 if (checkPlaceholderForOverload(*this, From))
1398 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399 bool AllowObjCWritebackConversion
1400 = getLangOpts().ObjCAutoRefCount &&
1401 (Action == AA_Passing || Action == AA_Sending);
1402 if (getLangOpts().ObjC1)
1403 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404 ToType, From->getType(), From);
1405 ICS = ::TryImplicitConversion(*this, From, ToType,
1406 /*SuppressUserConversions=*/false,
1408 /*InOverloadResolution=*/false,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
1412 return PerformImplicitConversion(From, ToType, ICS, Action);
1415 /// \brief Determine whether the conversion from FromType to ToType is a valid
1416 /// conversion that strips "noexcept" or "noreturn" off the nested function
1418 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1419 QualType &ResultTy) {
1420 if (Context.hasSameUnqualifiedType(FromType, ToType))
1423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1424 // or F(t noexcept) -> F(t)
1425 // where F adds one of the following at most once:
1427 // - a member pointer
1428 // - a block pointer
1429 // Changes here need matching changes in FindCompositePointerType.
1430 CanQualType CanTo = Context.getCanonicalType(ToType);
1431 CanQualType CanFrom = Context.getCanonicalType(FromType);
1432 Type::TypeClass TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435 if (TyClass == Type::Pointer) {
1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438 } else if (TyClass == Type::BlockPointer) {
1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441 } else if (TyClass == Type::MemberPointer) {
1442 auto ToMPT = CanTo.getAs<MemberPointerType>();
1443 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444 // A function pointer conversion cannot change the class of the function.
1445 if (ToMPT->getClass() != FromMPT->getClass())
1447 CanTo = ToMPT->getPointeeType();
1448 CanFrom = FromMPT->getPointeeType();
1453 TyClass = CanTo->getTypeClass();
1454 if (TyClass != CanFrom->getTypeClass()) return false;
1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1459 const auto *FromFn = cast<FunctionType>(CanFrom);
1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1462 const auto *ToFn = cast<FunctionType>(CanTo);
1463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1465 bool Changed = false;
1467 // Drop 'noreturn' if not present in target type.
1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1473 // Drop 'noexcept' if not present in target type.
1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1475 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477 FromFn = cast<FunctionType>(
1478 Context.getFunctionType(FromFPT->getReturnType(),
1479 FromFPT->getParamTypes(),
1480 FromFPT->getExtProtoInfo().withExceptionSpec(
1481 FunctionProtoType::ExceptionSpecInfo()))
1486 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1487 // only if the ExtParameterInfo lists of the two function prototypes can be
1488 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1489 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1490 bool CanUseToFPT, CanUseFromFPT;
1491 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1492 CanUseFromFPT, NewParamInfos) &&
1493 CanUseToFPT && !CanUseFromFPT) {
1494 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1495 ExtInfo.ExtParameterInfos =
1496 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1497 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1498 FromFPT->getParamTypes(), ExtInfo);
1499 FromFn = QT->getAs<FunctionType>();
1507 assert(QualType(FromFn, 0).isCanonical());
1508 if (QualType(FromFn, 0) != CanTo) return false;
1514 /// \brief Determine whether the conversion from FromType to ToType is a valid
1515 /// vector conversion.
1517 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1519 static bool IsVectorConversion(Sema &S, QualType FromType,
1520 QualType ToType, ImplicitConversionKind &ICK) {
1521 // We need at least one of these types to be a vector type to have a vector
1523 if (!ToType->isVectorType() && !FromType->isVectorType())
1526 // Identical types require no conversions.
1527 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1530 // There are no conversions between extended vector types, only identity.
1531 if (ToType->isExtVectorType()) {
1532 // There are no conversions between extended vector types other than the
1533 // identity conversion.
1534 if (FromType->isExtVectorType())
1537 // Vector splat from any arithmetic type to a vector.
1538 if (FromType->isArithmeticType()) {
1539 ICK = ICK_Vector_Splat;
1544 // We can perform the conversion between vector types in the following cases:
1545 // 1)vector types are equivalent AltiVec and GCC vector types
1546 // 2)lax vector conversions are permitted and the vector types are of the
1548 if (ToType->isVectorType() && FromType->isVectorType()) {
1549 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1550 S.isLaxVectorConversion(FromType, ToType)) {
1551 ICK = ICK_Vector_Conversion;
1559 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1560 bool InOverloadResolution,
1561 StandardConversionSequence &SCS,
1564 /// IsStandardConversion - Determines whether there is a standard
1565 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1566 /// expression From to the type ToType. Standard conversion sequences
1567 /// only consider non-class types; for conversions that involve class
1568 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1569 /// contain the standard conversion sequence required to perform this
1570 /// conversion and this routine will return true. Otherwise, this
1571 /// routine will return false and the value of SCS is unspecified.
1572 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1573 bool InOverloadResolution,
1574 StandardConversionSequence &SCS,
1576 bool AllowObjCWritebackConversion) {
1577 QualType FromType = From->getType();
1579 // Standard conversions (C++ [conv])
1580 SCS.setAsIdentityConversion();
1581 SCS.IncompatibleObjC = false;
1582 SCS.setFromType(FromType);
1583 SCS.CopyConstructor = nullptr;
1585 // There are no standard conversions for class types in C++, so
1586 // abort early. When overloading in C, however, we do permit them.
1587 if (S.getLangOpts().CPlusPlus &&
1588 (FromType->isRecordType() || ToType->isRecordType()))
1591 // The first conversion can be an lvalue-to-rvalue conversion,
1592 // array-to-pointer conversion, or function-to-pointer conversion
1595 if (FromType == S.Context.OverloadTy) {
1596 DeclAccessPair AccessPair;
1597 if (FunctionDecl *Fn
1598 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1600 // We were able to resolve the address of the overloaded function,
1601 // so we can convert to the type of that function.
1602 FromType = Fn->getType();
1603 SCS.setFromType(FromType);
1605 // we can sometimes resolve &foo<int> regardless of ToType, so check
1606 // if the type matches (identity) or we are converting to bool
1607 if (!S.Context.hasSameUnqualifiedType(
1608 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1610 // if the function type matches except for [[noreturn]], it's ok
1611 if (!S.IsFunctionConversion(FromType,
1612 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1613 // otherwise, only a boolean conversion is standard
1614 if (!ToType->isBooleanType())
1618 // Check if the "from" expression is taking the address of an overloaded
1619 // function and recompute the FromType accordingly. Take advantage of the
1620 // fact that non-static member functions *must* have such an address-of
1622 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1623 if (Method && !Method->isStatic()) {
1624 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1625 "Non-unary operator on non-static member address");
1626 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1628 "Non-address-of operator on non-static member address");
1629 const Type *ClassType
1630 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1631 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1632 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1633 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1635 "Non-address-of operator for overloaded function expression");
1636 FromType = S.Context.getPointerType(FromType);
1639 // Check that we've computed the proper type after overload resolution.
1640 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1641 // be calling it from within an NDEBUG block.
1642 assert(S.Context.hasSameType(
1644 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1649 // Lvalue-to-rvalue conversion (C++11 4.1):
1650 // A glvalue (3.10) of a non-function, non-array type T can
1651 // be converted to a prvalue.
1652 bool argIsLValue = From->isGLValue();
1654 !FromType->isFunctionType() && !FromType->isArrayType() &&
1655 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1656 SCS.First = ICK_Lvalue_To_Rvalue;
1659 // ... if the lvalue has atomic type, the value has the non-atomic version
1660 // of the type of the lvalue ...
1661 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1662 FromType = Atomic->getValueType();
1664 // If T is a non-class type, the type of the rvalue is the
1665 // cv-unqualified version of T. Otherwise, the type of the rvalue
1666 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1667 // just strip the qualifiers because they don't matter.
1668 FromType = FromType.getUnqualifiedType();
1669 } else if (FromType->isArrayType()) {
1670 // Array-to-pointer conversion (C++ 4.2)
1671 SCS.First = ICK_Array_To_Pointer;
1673 // An lvalue or rvalue of type "array of N T" or "array of unknown
1674 // bound of T" can be converted to an rvalue of type "pointer to
1676 FromType = S.Context.getArrayDecayedType(FromType);
1678 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1679 // This conversion is deprecated in C++03 (D.4)
1680 SCS.DeprecatedStringLiteralToCharPtr = true;
1682 // For the purpose of ranking in overload resolution
1683 // (13.3.3.1.1), this conversion is considered an
1684 // array-to-pointer conversion followed by a qualification
1685 // conversion (4.4). (C++ 4.2p2)
1686 SCS.Second = ICK_Identity;
1687 SCS.Third = ICK_Qualification;
1688 SCS.QualificationIncludesObjCLifetime = false;
1689 SCS.setAllToTypes(FromType);
1692 } else if (FromType->isFunctionType() && argIsLValue) {
1693 // Function-to-pointer conversion (C++ 4.3).
1694 SCS.First = ICK_Function_To_Pointer;
1696 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1697 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1698 if (!S.checkAddressOfFunctionIsAvailable(FD))
1701 // An lvalue of function type T can be converted to an rvalue of
1702 // type "pointer to T." The result is a pointer to the
1703 // function. (C++ 4.3p1).
1704 FromType = S.Context.getPointerType(FromType);
1706 // We don't require any conversions for the first step.
1707 SCS.First = ICK_Identity;
1709 SCS.setToType(0, FromType);
1711 // The second conversion can be an integral promotion, floating
1712 // point promotion, integral conversion, floating point conversion,
1713 // floating-integral conversion, pointer conversion,
1714 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1715 // For overloading in C, this can also be a "compatible-type"
1717 bool IncompatibleObjC = false;
1718 ImplicitConversionKind SecondICK = ICK_Identity;
1719 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1720 // The unqualified versions of the types are the same: there's no
1721 // conversion to do.
1722 SCS.Second = ICK_Identity;
1723 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1724 // Integral promotion (C++ 4.5).
1725 SCS.Second = ICK_Integral_Promotion;
1726 FromType = ToType.getUnqualifiedType();
1727 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1728 // Floating point promotion (C++ 4.6).
1729 SCS.Second = ICK_Floating_Promotion;
1730 FromType = ToType.getUnqualifiedType();
1731 } else if (S.IsComplexPromotion(FromType, ToType)) {
1732 // Complex promotion (Clang extension)
1733 SCS.Second = ICK_Complex_Promotion;
1734 FromType = ToType.getUnqualifiedType();
1735 } else if (ToType->isBooleanType() &&
1736 (FromType->isArithmeticType() ||
1737 FromType->isAnyPointerType() ||
1738 FromType->isBlockPointerType() ||
1739 FromType->isMemberPointerType() ||
1740 FromType->isNullPtrType())) {
1741 // Boolean conversions (C++ 4.12).
1742 SCS.Second = ICK_Boolean_Conversion;
1743 FromType = S.Context.BoolTy;
1744 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1745 ToType->isIntegralType(S.Context)) {
1746 // Integral conversions (C++ 4.7).
1747 SCS.Second = ICK_Integral_Conversion;
1748 FromType = ToType.getUnqualifiedType();
1749 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1750 // Complex conversions (C99 6.3.1.6)
1751 SCS.Second = ICK_Complex_Conversion;
1752 FromType = ToType.getUnqualifiedType();
1753 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1754 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1755 // Complex-real conversions (C99 6.3.1.7)
1756 SCS.Second = ICK_Complex_Real;
1757 FromType = ToType.getUnqualifiedType();
1758 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1759 // FIXME: disable conversions between long double and __float128 if
1760 // their representation is different until there is back end support
1761 // We of course allow this conversion if long double is really double.
1762 if (&S.Context.getFloatTypeSemantics(FromType) !=
1763 &S.Context.getFloatTypeSemantics(ToType)) {
1764 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1765 ToType == S.Context.LongDoubleTy) ||
1766 (FromType == S.Context.LongDoubleTy &&
1767 ToType == S.Context.Float128Ty));
1768 if (Float128AndLongDouble &&
1769 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1770 &llvm::APFloat::IEEEdouble()))
1773 // Floating point conversions (C++ 4.8).
1774 SCS.Second = ICK_Floating_Conversion;
1775 FromType = ToType.getUnqualifiedType();
1776 } else if ((FromType->isRealFloatingType() &&
1777 ToType->isIntegralType(S.Context)) ||
1778 (FromType->isIntegralOrUnscopedEnumerationType() &&
1779 ToType->isRealFloatingType())) {
1780 // Floating-integral conversions (C++ 4.9).
1781 SCS.Second = ICK_Floating_Integral;
1782 FromType = ToType.getUnqualifiedType();
1783 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1784 SCS.Second = ICK_Block_Pointer_Conversion;
1785 } else if (AllowObjCWritebackConversion &&
1786 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1787 SCS.Second = ICK_Writeback_Conversion;
1788 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1789 FromType, IncompatibleObjC)) {
1790 // Pointer conversions (C++ 4.10).
1791 SCS.Second = ICK_Pointer_Conversion;
1792 SCS.IncompatibleObjC = IncompatibleObjC;
1793 FromType = FromType.getUnqualifiedType();
1794 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1795 InOverloadResolution, FromType)) {
1796 // Pointer to member conversions (4.11).
1797 SCS.Second = ICK_Pointer_Member;
1798 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1799 SCS.Second = SecondICK;
1800 FromType = ToType.getUnqualifiedType();
1801 } else if (!S.getLangOpts().CPlusPlus &&
1802 S.Context.typesAreCompatible(ToType, FromType)) {
1803 // Compatible conversions (Clang extension for C function overloading)
1804 SCS.Second = ICK_Compatible_Conversion;
1805 FromType = ToType.getUnqualifiedType();
1806 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1807 InOverloadResolution,
1809 SCS.Second = ICK_TransparentUnionConversion;
1811 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1813 // tryAtomicConversion has updated the standard conversion sequence
1816 } else if (ToType->isEventT() &&
1817 From->isIntegerConstantExpr(S.getASTContext()) &&
1818 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1819 SCS.Second = ICK_Zero_Event_Conversion;
1821 } else if (ToType->isQueueT() &&
1822 From->isIntegerConstantExpr(S.getASTContext()) &&
1823 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1824 SCS.Second = ICK_Zero_Queue_Conversion;
1827 // No second conversion required.
1828 SCS.Second = ICK_Identity;
1830 SCS.setToType(1, FromType);
1832 // The third conversion can be a function pointer conversion or a
1833 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1834 bool ObjCLifetimeConversion;
1835 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1836 // Function pointer conversions (removing 'noexcept') including removal of
1837 // 'noreturn' (Clang extension).
1838 SCS.Third = ICK_Function_Conversion;
1839 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1840 ObjCLifetimeConversion)) {
1841 SCS.Third = ICK_Qualification;
1842 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1845 // No conversion required
1846 SCS.Third = ICK_Identity;
1849 // C++ [over.best.ics]p6:
1850 // [...] Any difference in top-level cv-qualification is
1851 // subsumed by the initialization itself and does not constitute
1852 // a conversion. [...]
1853 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1854 QualType CanonTo = S.Context.getCanonicalType(ToType);
1855 if (CanonFrom.getLocalUnqualifiedType()
1856 == CanonTo.getLocalUnqualifiedType() &&
1857 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1859 CanonFrom = CanonTo;
1862 SCS.setToType(2, FromType);
1864 if (CanonFrom == CanonTo)
1867 // If we have not converted the argument type to the parameter type,
1868 // this is a bad conversion sequence, unless we're resolving an overload in C.
1869 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1872 ExprResult ER = ExprResult{From};
1873 Sema::AssignConvertType Conv =
1874 S.CheckSingleAssignmentConstraints(ToType, ER,
1876 /*DiagnoseCFAudited=*/false,
1877 /*ConvertRHS=*/false);
1878 ImplicitConversionKind SecondConv;
1880 case Sema::Compatible:
1881 SecondConv = ICK_C_Only_Conversion;
1883 // For our purposes, discarding qualifiers is just as bad as using an
1884 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1885 // qualifiers, as well.
1886 case Sema::CompatiblePointerDiscardsQualifiers:
1887 case Sema::IncompatiblePointer:
1888 case Sema::IncompatiblePointerSign:
1889 SecondConv = ICK_Incompatible_Pointer_Conversion;
1895 // First can only be an lvalue conversion, so we pretend that this was the
1896 // second conversion. First should already be valid from earlier in the
1898 SCS.Second = SecondConv;
1899 SCS.setToType(1, ToType);
1901 // Third is Identity, because Second should rank us worse than any other
1902 // conversion. This could also be ICK_Qualification, but it's simpler to just
1903 // lump everything in with the second conversion, and we don't gain anything
1904 // from making this ICK_Qualification.
1905 SCS.Third = ICK_Identity;
1906 SCS.setToType(2, ToType);
1911 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1913 bool InOverloadResolution,
1914 StandardConversionSequence &SCS,
1917 const RecordType *UT = ToType->getAsUnionType();
1918 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1920 // The field to initialize within the transparent union.
1921 RecordDecl *UD = UT->getDecl();
1922 // It's compatible if the expression matches any of the fields.
1923 for (const auto *it : UD->fields()) {
1924 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1925 CStyle, /*ObjCWritebackConversion=*/false)) {
1926 ToType = it->getType();
1933 /// IsIntegralPromotion - Determines whether the conversion from the
1934 /// expression From (whose potentially-adjusted type is FromType) to
1935 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1936 /// sets PromotedType to the promoted type.
1937 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1938 const BuiltinType *To = ToType->getAs<BuiltinType>();
1939 // All integers are built-in.
1944 // An rvalue of type char, signed char, unsigned char, short int, or
1945 // unsigned short int can be converted to an rvalue of type int if
1946 // int can represent all the values of the source type; otherwise,
1947 // the source rvalue can be converted to an rvalue of type unsigned
1949 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1950 !FromType->isEnumeralType()) {
1951 if (// We can promote any signed, promotable integer type to an int
1952 (FromType->isSignedIntegerType() ||
1953 // We can promote any unsigned integer type whose size is
1954 // less than int to an int.
1955 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1956 return To->getKind() == BuiltinType::Int;
1959 return To->getKind() == BuiltinType::UInt;
1962 // C++11 [conv.prom]p3:
1963 // A prvalue of an unscoped enumeration type whose underlying type is not
1964 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1965 // following types that can represent all the values of the enumeration
1966 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1967 // unsigned int, long int, unsigned long int, long long int, or unsigned
1968 // long long int. If none of the types in that list can represent all the
1969 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1970 // type can be converted to an rvalue a prvalue of the extended integer type
1971 // with lowest integer conversion rank (4.13) greater than the rank of long
1972 // long in which all the values of the enumeration can be represented. If
1973 // there are two such extended types, the signed one is chosen.
1974 // C++11 [conv.prom]p4:
1975 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1976 // can be converted to a prvalue of its underlying type. Moreover, if
1977 // integral promotion can be applied to its underlying type, a prvalue of an
1978 // unscoped enumeration type whose underlying type is fixed can also be
1979 // converted to a prvalue of the promoted underlying type.
1980 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1981 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1982 // provided for a scoped enumeration.
1983 if (FromEnumType->getDecl()->isScoped())
1986 // We can perform an integral promotion to the underlying type of the enum,
1987 // even if that's not the promoted type. Note that the check for promoting
1988 // the underlying type is based on the type alone, and does not consider
1989 // the bitfield-ness of the actual source expression.
1990 if (FromEnumType->getDecl()->isFixed()) {
1991 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1992 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1993 IsIntegralPromotion(nullptr, Underlying, ToType);
1996 // We have already pre-calculated the promotion type, so this is trivial.
1997 if (ToType->isIntegerType() &&
1998 isCompleteType(From->getLocStart(), FromType))
1999 return Context.hasSameUnqualifiedType(
2000 ToType, FromEnumType->getDecl()->getPromotionType());
2003 // C++0x [conv.prom]p2:
2004 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2005 // to an rvalue a prvalue of the first of the following types that can
2006 // represent all the values of its underlying type: int, unsigned int,
2007 // long int, unsigned long int, long long int, or unsigned long long int.
2008 // If none of the types in that list can represent all the values of its
2009 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2010 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2012 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2013 ToType->isIntegerType()) {
2014 // Determine whether the type we're converting from is signed or
2016 bool FromIsSigned = FromType->isSignedIntegerType();
2017 uint64_t FromSize = Context.getTypeSize(FromType);
2019 // The types we'll try to promote to, in the appropriate
2020 // order. Try each of these types.
2021 QualType PromoteTypes[6] = {
2022 Context.IntTy, Context.UnsignedIntTy,
2023 Context.LongTy, Context.UnsignedLongTy ,
2024 Context.LongLongTy, Context.UnsignedLongLongTy
2026 for (int Idx = 0; Idx < 6; ++Idx) {
2027 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2028 if (FromSize < ToSize ||
2029 (FromSize == ToSize &&
2030 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2031 // We found the type that we can promote to. If this is the
2032 // type we wanted, we have a promotion. Otherwise, no
2034 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2039 // An rvalue for an integral bit-field (9.6) can be converted to an
2040 // rvalue of type int if int can represent all the values of the
2041 // bit-field; otherwise, it can be converted to unsigned int if
2042 // unsigned int can represent all the values of the bit-field. If
2043 // the bit-field is larger yet, no integral promotion applies to
2044 // it. If the bit-field has an enumerated type, it is treated as any
2045 // other value of that type for promotion purposes (C++ 4.5p3).
2046 // FIXME: We should delay checking of bit-fields until we actually perform the
2049 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2050 llvm::APSInt BitWidth;
2051 if (FromType->isIntegralType(Context) &&
2052 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2053 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2054 ToSize = Context.getTypeSize(ToType);
2056 // Are we promoting to an int from a bitfield that fits in an int?
2057 if (BitWidth < ToSize ||
2058 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2059 return To->getKind() == BuiltinType::Int;
2062 // Are we promoting to an unsigned int from an unsigned bitfield
2063 // that fits into an unsigned int?
2064 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2065 return To->getKind() == BuiltinType::UInt;
2073 // An rvalue of type bool can be converted to an rvalue of type int,
2074 // with false becoming zero and true becoming one (C++ 4.5p4).
2075 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2082 /// IsFloatingPointPromotion - Determines whether the conversion from
2083 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2084 /// returns true and sets PromotedType to the promoted type.
2085 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2086 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2087 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2088 /// An rvalue of type float can be converted to an rvalue of type
2089 /// double. (C++ 4.6p1).
2090 if (FromBuiltin->getKind() == BuiltinType::Float &&
2091 ToBuiltin->getKind() == BuiltinType::Double)
2095 // When a float is promoted to double or long double, or a
2096 // double is promoted to long double [...].
2097 if (!getLangOpts().CPlusPlus &&
2098 (FromBuiltin->getKind() == BuiltinType::Float ||
2099 FromBuiltin->getKind() == BuiltinType::Double) &&
2100 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2101 ToBuiltin->getKind() == BuiltinType::Float128))
2104 // Half can be promoted to float.
2105 if (!getLangOpts().NativeHalfType &&
2106 FromBuiltin->getKind() == BuiltinType::Half &&
2107 ToBuiltin->getKind() == BuiltinType::Float)
2114 /// \brief Determine if a conversion is a complex promotion.
2116 /// A complex promotion is defined as a complex -> complex conversion
2117 /// where the conversion between the underlying real types is a
2118 /// floating-point or integral promotion.
2119 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2120 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2124 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2128 return IsFloatingPointPromotion(FromComplex->getElementType(),
2129 ToComplex->getElementType()) ||
2130 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2131 ToComplex->getElementType());
2134 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2135 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2136 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2137 /// if non-empty, will be a pointer to ToType that may or may not have
2138 /// the right set of qualifiers on its pointee.
2141 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2142 QualType ToPointee, QualType ToType,
2143 ASTContext &Context,
2144 bool StripObjCLifetime = false) {
2145 assert((FromPtr->getTypeClass() == Type::Pointer ||
2146 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2147 "Invalid similarly-qualified pointer type");
2149 /// Conversions to 'id' subsume cv-qualifier conversions.
2150 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2151 return ToType.getUnqualifiedType();
2153 QualType CanonFromPointee
2154 = Context.getCanonicalType(FromPtr->getPointeeType());
2155 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2156 Qualifiers Quals = CanonFromPointee.getQualifiers();
2158 if (StripObjCLifetime)
2159 Quals.removeObjCLifetime();
2161 // Exact qualifier match -> return the pointer type we're converting to.
2162 if (CanonToPointee.getLocalQualifiers() == Quals) {
2163 // ToType is exactly what we need. Return it.
2164 if (!ToType.isNull())
2165 return ToType.getUnqualifiedType();
2167 // Build a pointer to ToPointee. It has the right qualifiers
2169 if (isa<ObjCObjectPointerType>(ToType))
2170 return Context.getObjCObjectPointerType(ToPointee);
2171 return Context.getPointerType(ToPointee);
2174 // Just build a canonical type that has the right qualifiers.
2175 QualType QualifiedCanonToPointee
2176 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2178 if (isa<ObjCObjectPointerType>(ToType))
2179 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2180 return Context.getPointerType(QualifiedCanonToPointee);
2183 static bool isNullPointerConstantForConversion(Expr *Expr,
2184 bool InOverloadResolution,
2185 ASTContext &Context) {
2186 // Handle value-dependent integral null pointer constants correctly.
2187 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2188 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2189 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2190 return !InOverloadResolution;
2192 return Expr->isNullPointerConstant(Context,
2193 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2194 : Expr::NPC_ValueDependentIsNull);
2197 /// IsPointerConversion - Determines whether the conversion of the
2198 /// expression From, which has the (possibly adjusted) type FromType,
2199 /// can be converted to the type ToType via a pointer conversion (C++
2200 /// 4.10). If so, returns true and places the converted type (that
2201 /// might differ from ToType in its cv-qualifiers at some level) into
2204 /// This routine also supports conversions to and from block pointers
2205 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2206 /// pointers to interfaces. FIXME: Once we've determined the
2207 /// appropriate overloading rules for Objective-C, we may want to
2208 /// split the Objective-C checks into a different routine; however,
2209 /// GCC seems to consider all of these conversions to be pointer
2210 /// conversions, so for now they live here. IncompatibleObjC will be
2211 /// set if the conversion is an allowed Objective-C conversion that
2212 /// should result in a warning.
2213 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2214 bool InOverloadResolution,
2215 QualType& ConvertedType,
2216 bool &IncompatibleObjC) {
2217 IncompatibleObjC = false;
2218 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2222 // Conversion from a null pointer constant to any Objective-C pointer type.
2223 if (ToType->isObjCObjectPointerType() &&
2224 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2225 ConvertedType = ToType;
2229 // Blocks: Block pointers can be converted to void*.
2230 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2231 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2232 ConvertedType = ToType;
2235 // Blocks: A null pointer constant can be converted to a block
2237 if (ToType->isBlockPointerType() &&
2238 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2239 ConvertedType = ToType;
2243 // If the left-hand-side is nullptr_t, the right side can be a null
2244 // pointer constant.
2245 if (ToType->isNullPtrType() &&
2246 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247 ConvertedType = ToType;
2251 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2255 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2256 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2257 ConvertedType = ToType;
2261 // Beyond this point, both types need to be pointers
2262 // , including objective-c pointers.
2263 QualType ToPointeeType = ToTypePtr->getPointeeType();
2264 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2265 !getLangOpts().ObjCAutoRefCount) {
2266 ConvertedType = BuildSimilarlyQualifiedPointerType(
2267 FromType->getAs<ObjCObjectPointerType>(),
2272 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2276 QualType FromPointeeType = FromTypePtr->getPointeeType();
2278 // If the unqualified pointee types are the same, this can't be a
2279 // pointer conversion, so don't do all of the work below.
2280 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2283 // An rvalue of type "pointer to cv T," where T is an object type,
2284 // can be converted to an rvalue of type "pointer to cv void" (C++
2286 if (FromPointeeType->isIncompleteOrObjectType() &&
2287 ToPointeeType->isVoidType()) {
2288 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2291 /*StripObjCLifetime=*/true);
2295 // MSVC allows implicit function to void* type conversion.
2296 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2297 ToPointeeType->isVoidType()) {
2298 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2304 // When we're overloading in C, we allow a special kind of pointer
2305 // conversion for compatible-but-not-identical pointee types.
2306 if (!getLangOpts().CPlusPlus &&
2307 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2308 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2314 // C++ [conv.ptr]p3:
2316 // An rvalue of type "pointer to cv D," where D is a class type,
2317 // can be converted to an rvalue of type "pointer to cv B," where
2318 // B is a base class (clause 10) of D. If B is an inaccessible
2319 // (clause 11) or ambiguous (10.2) base class of D, a program that
2320 // necessitates this conversion is ill-formed. The result of the
2321 // conversion is a pointer to the base class sub-object of the
2322 // derived class object. The null pointer value is converted to
2323 // the null pointer value of the destination type.
2325 // Note that we do not check for ambiguity or inaccessibility
2326 // here. That is handled by CheckPointerConversion.
2327 if (getLangOpts().CPlusPlus &&
2328 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2329 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2330 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2331 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2337 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2338 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2339 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2348 /// \brief Adopt the given qualifiers for the given type.
2349 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2350 Qualifiers TQs = T.getQualifiers();
2352 // Check whether qualifiers already match.
2356 if (Qs.compatiblyIncludes(TQs))
2357 return Context.getQualifiedType(T, Qs);
2359 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2362 /// isObjCPointerConversion - Determines whether this is an
2363 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2364 /// with the same arguments and return values.
2365 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2366 QualType& ConvertedType,
2367 bool &IncompatibleObjC) {
2368 if (!getLangOpts().ObjC1)
2371 // The set of qualifiers on the type we're converting from.
2372 Qualifiers FromQualifiers = FromType.getQualifiers();
2374 // First, we handle all conversions on ObjC object pointer types.
2375 const ObjCObjectPointerType* ToObjCPtr =
2376 ToType->getAs<ObjCObjectPointerType>();
2377 const ObjCObjectPointerType *FromObjCPtr =
2378 FromType->getAs<ObjCObjectPointerType>();
2380 if (ToObjCPtr && FromObjCPtr) {
2381 // If the pointee types are the same (ignoring qualifications),
2382 // then this is not a pointer conversion.
2383 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2384 FromObjCPtr->getPointeeType()))
2387 // Conversion between Objective-C pointers.
2388 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2389 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2390 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2391 if (getLangOpts().CPlusPlus && LHS && RHS &&
2392 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2393 FromObjCPtr->getPointeeType()))
2395 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2396 ToObjCPtr->getPointeeType(),
2398 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2402 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2403 // Okay: this is some kind of implicit downcast of Objective-C
2404 // interfaces, which is permitted. However, we're going to
2405 // complain about it.
2406 IncompatibleObjC = true;
2407 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2408 ToObjCPtr->getPointeeType(),
2410 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2414 // Beyond this point, both types need to be C pointers or block pointers.
2415 QualType ToPointeeType;
2416 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2417 ToPointeeType = ToCPtr->getPointeeType();
2418 else if (const BlockPointerType *ToBlockPtr =
2419 ToType->getAs<BlockPointerType>()) {
2420 // Objective C++: We're able to convert from a pointer to any object
2421 // to a block pointer type.
2422 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2423 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2426 ToPointeeType = ToBlockPtr->getPointeeType();
2428 else if (FromType->getAs<BlockPointerType>() &&
2429 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2430 // Objective C++: We're able to convert from a block pointer type to a
2431 // pointer to any object.
2432 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2438 QualType FromPointeeType;
2439 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2440 FromPointeeType = FromCPtr->getPointeeType();
2441 else if (const BlockPointerType *FromBlockPtr =
2442 FromType->getAs<BlockPointerType>())
2443 FromPointeeType = FromBlockPtr->getPointeeType();
2447 // If we have pointers to pointers, recursively check whether this
2448 // is an Objective-C conversion.
2449 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2450 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2451 IncompatibleObjC)) {
2452 // We always complain about this conversion.
2453 IncompatibleObjC = true;
2454 ConvertedType = Context.getPointerType(ConvertedType);
2455 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2458 // Allow conversion of pointee being objective-c pointer to another one;
2460 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2461 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2462 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2463 IncompatibleObjC)) {
2465 ConvertedType = Context.getPointerType(ConvertedType);
2466 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2470 // If we have pointers to functions or blocks, check whether the only
2471 // differences in the argument and result types are in Objective-C
2472 // pointer conversions. If so, we permit the conversion (but
2473 // complain about it).
2474 const FunctionProtoType *FromFunctionType
2475 = FromPointeeType->getAs<FunctionProtoType>();
2476 const FunctionProtoType *ToFunctionType
2477 = ToPointeeType->getAs<FunctionProtoType>();
2478 if (FromFunctionType && ToFunctionType) {
2479 // If the function types are exactly the same, this isn't an
2480 // Objective-C pointer conversion.
2481 if (Context.getCanonicalType(FromPointeeType)
2482 == Context.getCanonicalType(ToPointeeType))
2485 // Perform the quick checks that will tell us whether these
2486 // function types are obviously different.
2487 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2488 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2489 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2492 bool HasObjCConversion = false;
2493 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2494 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2497 ToFunctionType->getReturnType(),
2498 ConvertedType, IncompatibleObjC)) {
2499 // Okay, we have an Objective-C pointer conversion.
2500 HasObjCConversion = true;
2502 // Function types are too different. Abort.
2506 // Check argument types.
2507 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2508 ArgIdx != NumArgs; ++ArgIdx) {
2509 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2510 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2511 if (Context.getCanonicalType(FromArgType)
2512 == Context.getCanonicalType(ToArgType)) {
2513 // Okay, the types match exactly. Nothing to do.
2514 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2515 ConvertedType, IncompatibleObjC)) {
2516 // Okay, we have an Objective-C pointer conversion.
2517 HasObjCConversion = true;
2519 // Argument types are too different. Abort.
2524 if (HasObjCConversion) {
2525 // We had an Objective-C conversion. Allow this pointer
2526 // conversion, but complain about it.
2527 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2528 IncompatibleObjC = true;
2536 /// \brief Determine whether this is an Objective-C writeback conversion,
2537 /// used for parameter passing when performing automatic reference counting.
2539 /// \param FromType The type we're converting form.
2541 /// \param ToType The type we're converting to.
2543 /// \param ConvertedType The type that will be produced after applying
2544 /// this conversion.
2545 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2546 QualType &ConvertedType) {
2547 if (!getLangOpts().ObjCAutoRefCount ||
2548 Context.hasSameUnqualifiedType(FromType, ToType))
2551 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2553 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2554 ToPointee = ToPointer->getPointeeType();
2558 Qualifiers ToQuals = ToPointee.getQualifiers();
2559 if (!ToPointee->isObjCLifetimeType() ||
2560 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2561 !ToQuals.withoutObjCLifetime().empty())
2564 // Argument must be a pointer to __strong to __weak.
2565 QualType FromPointee;
2566 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2567 FromPointee = FromPointer->getPointeeType();
2571 Qualifiers FromQuals = FromPointee.getQualifiers();
2572 if (!FromPointee->isObjCLifetimeType() ||
2573 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2574 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2577 // Make sure that we have compatible qualifiers.
2578 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2579 if (!ToQuals.compatiblyIncludes(FromQuals))
2582 // Remove qualifiers from the pointee type we're converting from; they
2583 // aren't used in the compatibility check belong, and we'll be adding back
2584 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2585 FromPointee = FromPointee.getUnqualifiedType();
2587 // The unqualified form of the pointee types must be compatible.
2588 ToPointee = ToPointee.getUnqualifiedType();
2589 bool IncompatibleObjC;
2590 if (Context.typesAreCompatible(FromPointee, ToPointee))
2591 FromPointee = ToPointee;
2592 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2596 /// \brief Construct the type we're converting to, which is a pointer to
2597 /// __autoreleasing pointee.
2598 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2599 ConvertedType = Context.getPointerType(FromPointee);
2603 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2604 QualType& ConvertedType) {
2605 QualType ToPointeeType;
2606 if (const BlockPointerType *ToBlockPtr =
2607 ToType->getAs<BlockPointerType>())
2608 ToPointeeType = ToBlockPtr->getPointeeType();
2612 QualType FromPointeeType;
2613 if (const BlockPointerType *FromBlockPtr =
2614 FromType->getAs<BlockPointerType>())
2615 FromPointeeType = FromBlockPtr->getPointeeType();
2618 // We have pointer to blocks, check whether the only
2619 // differences in the argument and result types are in Objective-C
2620 // pointer conversions. If so, we permit the conversion.
2622 const FunctionProtoType *FromFunctionType
2623 = FromPointeeType->getAs<FunctionProtoType>();
2624 const FunctionProtoType *ToFunctionType
2625 = ToPointeeType->getAs<FunctionProtoType>();
2627 if (!FromFunctionType || !ToFunctionType)
2630 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2633 // Perform the quick checks that will tell us whether these
2634 // function types are obviously different.
2635 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2636 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2639 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2640 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2641 if (FromEInfo != ToEInfo)
2644 bool IncompatibleObjC = false;
2645 if (Context.hasSameType(FromFunctionType->getReturnType(),
2646 ToFunctionType->getReturnType())) {
2647 // Okay, the types match exactly. Nothing to do.
2649 QualType RHS = FromFunctionType->getReturnType();
2650 QualType LHS = ToFunctionType->getReturnType();
2651 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2652 !RHS.hasQualifiers() && LHS.hasQualifiers())
2653 LHS = LHS.getUnqualifiedType();
2655 if (Context.hasSameType(RHS,LHS)) {
2657 } else if (isObjCPointerConversion(RHS, LHS,
2658 ConvertedType, IncompatibleObjC)) {
2659 if (IncompatibleObjC)
2661 // Okay, we have an Objective-C pointer conversion.
2667 // Check argument types.
2668 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2669 ArgIdx != NumArgs; ++ArgIdx) {
2670 IncompatibleObjC = false;
2671 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2672 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2673 if (Context.hasSameType(FromArgType, ToArgType)) {
2674 // Okay, the types match exactly. Nothing to do.
2675 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2676 ConvertedType, IncompatibleObjC)) {
2677 if (IncompatibleObjC)
2679 // Okay, we have an Objective-C pointer conversion.
2681 // Argument types are too different. Abort.
2685 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2686 bool CanUseToFPT, CanUseFromFPT;
2687 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2688 CanUseToFPT, CanUseFromFPT,
2692 ConvertedType = ToType;
2700 ft_parameter_mismatch,
2702 ft_qualifer_mismatch,
2706 /// Attempts to get the FunctionProtoType from a Type. Handles
2707 /// MemberFunctionPointers properly.
2708 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2709 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2712 if (auto *MPT = FromType->getAs<MemberPointerType>())
2713 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2718 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2719 /// function types. Catches different number of parameter, mismatch in
2720 /// parameter types, and different return types.
2721 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2722 QualType FromType, QualType ToType) {
2723 // If either type is not valid, include no extra info.
2724 if (FromType.isNull() || ToType.isNull()) {
2725 PDiag << ft_default;
2729 // Get the function type from the pointers.
2730 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2731 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2732 *ToMember = ToType->getAs<MemberPointerType>();
2733 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2734 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2735 << QualType(FromMember->getClass(), 0);
2738 FromType = FromMember->getPointeeType();
2739 ToType = ToMember->getPointeeType();
2742 if (FromType->isPointerType())
2743 FromType = FromType->getPointeeType();
2744 if (ToType->isPointerType())
2745 ToType = ToType->getPointeeType();
2747 // Remove references.
2748 FromType = FromType.getNonReferenceType();
2749 ToType = ToType.getNonReferenceType();
2751 // Don't print extra info for non-specialized template functions.
2752 if (FromType->isInstantiationDependentType() &&
2753 !FromType->getAs<TemplateSpecializationType>()) {
2754 PDiag << ft_default;
2758 // No extra info for same types.
2759 if (Context.hasSameType(FromType, ToType)) {
2760 PDiag << ft_default;
2764 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2765 *ToFunction = tryGetFunctionProtoType(ToType);
2767 // Both types need to be function types.
2768 if (!FromFunction || !ToFunction) {
2769 PDiag << ft_default;
2773 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2774 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2775 << FromFunction->getNumParams();
2779 // Handle different parameter types.
2781 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2782 PDiag << ft_parameter_mismatch << ArgPos + 1
2783 << ToFunction->getParamType(ArgPos)
2784 << FromFunction->getParamType(ArgPos);
2788 // Handle different return type.
2789 if (!Context.hasSameType(FromFunction->getReturnType(),
2790 ToFunction->getReturnType())) {
2791 PDiag << ft_return_type << ToFunction->getReturnType()
2792 << FromFunction->getReturnType();
2796 unsigned FromQuals = FromFunction->getTypeQuals(),
2797 ToQuals = ToFunction->getTypeQuals();
2798 if (FromQuals != ToQuals) {
2799 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2803 // Handle exception specification differences on canonical type (in C++17
2805 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2806 ->isNothrow(Context) !=
2807 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2808 ->isNothrow(Context)) {
2809 PDiag << ft_noexcept;
2813 // Unable to find a difference, so add no extra info.
2814 PDiag << ft_default;
2817 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2818 /// for equality of their argument types. Caller has already checked that
2819 /// they have same number of arguments. If the parameters are different,
2820 /// ArgPos will have the parameter index of the first different parameter.
2821 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2822 const FunctionProtoType *NewType,
2824 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2825 N = NewType->param_type_begin(),
2826 E = OldType->param_type_end();
2827 O && (O != E); ++O, ++N) {
2828 if (!Context.hasSameType(O->getUnqualifiedType(),
2829 N->getUnqualifiedType())) {
2831 *ArgPos = O - OldType->param_type_begin();
2838 /// CheckPointerConversion - Check the pointer conversion from the
2839 /// expression From to the type ToType. This routine checks for
2840 /// ambiguous or inaccessible derived-to-base pointer
2841 /// conversions for which IsPointerConversion has already returned
2842 /// true. It returns true and produces a diagnostic if there was an
2843 /// error, or returns false otherwise.
2844 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2846 CXXCastPath& BasePath,
2847 bool IgnoreBaseAccess,
2849 QualType FromType = From->getType();
2850 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2854 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2855 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2856 Expr::NPCK_ZeroExpression) {
2857 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2858 DiagRuntimeBehavior(From->getExprLoc(), From,
2859 PDiag(diag::warn_impcast_bool_to_null_pointer)
2860 << ToType << From->getSourceRange());
2861 else if (!isUnevaluatedContext())
2862 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2863 << ToType << From->getSourceRange();
2865 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2866 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2867 QualType FromPointeeType = FromPtrType->getPointeeType(),
2868 ToPointeeType = ToPtrType->getPointeeType();
2870 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2871 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2872 // We must have a derived-to-base conversion. Check an
2873 // ambiguous or inaccessible conversion.
2874 unsigned InaccessibleID = 0;
2875 unsigned AmbigiousID = 0;
2877 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2878 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2880 if (CheckDerivedToBaseConversion(
2881 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2882 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2883 &BasePath, IgnoreBaseAccess))
2886 // The conversion was successful.
2887 Kind = CK_DerivedToBase;
2890 if (Diagnose && !IsCStyleOrFunctionalCast &&
2891 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2892 assert(getLangOpts().MSVCCompat &&
2893 "this should only be possible with MSVCCompat!");
2894 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2895 << From->getSourceRange();
2898 } else if (const ObjCObjectPointerType *ToPtrType =
2899 ToType->getAs<ObjCObjectPointerType>()) {
2900 if (const ObjCObjectPointerType *FromPtrType =
2901 FromType->getAs<ObjCObjectPointerType>()) {
2902 // Objective-C++ conversions are always okay.
2903 // FIXME: We should have a different class of conversions for the
2904 // Objective-C++ implicit conversions.
2905 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2907 } else if (FromType->isBlockPointerType()) {
2908 Kind = CK_BlockPointerToObjCPointerCast;
2910 Kind = CK_CPointerToObjCPointerCast;
2912 } else if (ToType->isBlockPointerType()) {
2913 if (!FromType->isBlockPointerType())
2914 Kind = CK_AnyPointerToBlockPointerCast;
2917 // We shouldn't fall into this case unless it's valid for other
2919 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2920 Kind = CK_NullToPointer;
2925 /// IsMemberPointerConversion - Determines whether the conversion of the
2926 /// expression From, which has the (possibly adjusted) type FromType, can be
2927 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2928 /// If so, returns true and places the converted type (that might differ from
2929 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2930 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2932 bool InOverloadResolution,
2933 QualType &ConvertedType) {
2934 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2938 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2939 if (From->isNullPointerConstant(Context,
2940 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2941 : Expr::NPC_ValueDependentIsNull)) {
2942 ConvertedType = ToType;
2946 // Otherwise, both types have to be member pointers.
2947 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2951 // A pointer to member of B can be converted to a pointer to member of D,
2952 // where D is derived from B (C++ 4.11p2).
2953 QualType FromClass(FromTypePtr->getClass(), 0);
2954 QualType ToClass(ToTypePtr->getClass(), 0);
2956 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2957 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2958 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2959 ToClass.getTypePtr());
2966 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2967 /// expression From to the type ToType. This routine checks for ambiguous or
2968 /// virtual or inaccessible base-to-derived member pointer conversions
2969 /// for which IsMemberPointerConversion has already returned true. It returns
2970 /// true and produces a diagnostic if there was an error, or returns false
2972 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2974 CXXCastPath &BasePath,
2975 bool IgnoreBaseAccess) {
2976 QualType FromType = From->getType();
2977 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2979 // This must be a null pointer to member pointer conversion
2980 assert(From->isNullPointerConstant(Context,
2981 Expr::NPC_ValueDependentIsNull) &&
2982 "Expr must be null pointer constant!");
2983 Kind = CK_NullToMemberPointer;
2987 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2988 assert(ToPtrType && "No member pointer cast has a target type "
2989 "that is not a member pointer.");
2991 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2992 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2994 // FIXME: What about dependent types?
2995 assert(FromClass->isRecordType() && "Pointer into non-class.");
2996 assert(ToClass->isRecordType() && "Pointer into non-class.");
2998 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2999 /*DetectVirtual=*/true);
3000 bool DerivationOkay =
3001 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3002 assert(DerivationOkay &&
3003 "Should not have been called if derivation isn't OK.");
3004 (void)DerivationOkay;
3006 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3007 getUnqualifiedType())) {
3008 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3009 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3010 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3014 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3015 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3016 << FromClass << ToClass << QualType(VBase, 0)
3017 << From->getSourceRange();
3021 if (!IgnoreBaseAccess)
3022 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3024 diag::err_downcast_from_inaccessible_base);
3026 // Must be a base to derived member conversion.
3027 BuildBasePathArray(Paths, BasePath);
3028 Kind = CK_BaseToDerivedMemberPointer;
3032 /// Determine whether the lifetime conversion between the two given
3033 /// qualifiers sets is nontrivial.
3034 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3035 Qualifiers ToQuals) {
3036 // Converting anything to const __unsafe_unretained is trivial.
3037 if (ToQuals.hasConst() &&
3038 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3044 /// IsQualificationConversion - Determines whether the conversion from
3045 /// an rvalue of type FromType to ToType is a qualification conversion
3048 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3049 /// when the qualification conversion involves a change in the Objective-C
3050 /// object lifetime.
3052 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3053 bool CStyle, bool &ObjCLifetimeConversion) {
3054 FromType = Context.getCanonicalType(FromType);
3055 ToType = Context.getCanonicalType(ToType);
3056 ObjCLifetimeConversion = false;
3058 // If FromType and ToType are the same type, this is not a
3059 // qualification conversion.
3060 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3064 // A conversion can add cv-qualifiers at levels other than the first
3065 // in multi-level pointers, subject to the following rules: [...]
3066 bool PreviousToQualsIncludeConst = true;
3067 bool UnwrappedAnyPointer = false;
3068 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3069 // Within each iteration of the loop, we check the qualifiers to
3070 // determine if this still looks like a qualification
3071 // conversion. Then, if all is well, we unwrap one more level of
3072 // pointers or pointers-to-members and do it all again
3073 // until there are no more pointers or pointers-to-members left to
3075 UnwrappedAnyPointer = true;
3077 Qualifiers FromQuals = FromType.getQualifiers();
3078 Qualifiers ToQuals = ToType.getQualifiers();
3080 // Ignore __unaligned qualifier if this type is void.
3081 if (ToType.getUnqualifiedType()->isVoidType())
3082 FromQuals.removeUnaligned();
3085 // Check Objective-C lifetime conversions.
3086 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3087 UnwrappedAnyPointer) {
3088 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3089 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3090 ObjCLifetimeConversion = true;
3091 FromQuals.removeObjCLifetime();
3092 ToQuals.removeObjCLifetime();
3094 // Qualification conversions cannot cast between different
3095 // Objective-C lifetime qualifiers.
3100 // Allow addition/removal of GC attributes but not changing GC attributes.
3101 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3102 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3103 FromQuals.removeObjCGCAttr();
3104 ToQuals.removeObjCGCAttr();
3107 // -- for every j > 0, if const is in cv 1,j then const is in cv
3108 // 2,j, and similarly for volatile.
3109 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3112 // -- if the cv 1,j and cv 2,j are different, then const is in
3113 // every cv for 0 < k < j.
3114 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3115 && !PreviousToQualsIncludeConst)
3118 // Keep track of whether all prior cv-qualifiers in the "to" type
3120 PreviousToQualsIncludeConst
3121 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3124 // We are left with FromType and ToType being the pointee types
3125 // after unwrapping the original FromType and ToType the same number
3126 // of types. If we unwrapped any pointers, and if FromType and
3127 // ToType have the same unqualified type (since we checked
3128 // qualifiers above), then this is a qualification conversion.
3129 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3132 /// \brief - Determine whether this is a conversion from a scalar type to an
3135 /// If successful, updates \c SCS's second and third steps in the conversion
3136 /// sequence to finish the conversion.
3137 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3138 bool InOverloadResolution,
3139 StandardConversionSequence &SCS,
3141 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3145 StandardConversionSequence InnerSCS;
3146 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3147 InOverloadResolution, InnerSCS,
3148 CStyle, /*AllowObjCWritebackConversion=*/false))
3151 SCS.Second = InnerSCS.Second;
3152 SCS.setToType(1, InnerSCS.getToType(1));
3153 SCS.Third = InnerSCS.Third;
3154 SCS.QualificationIncludesObjCLifetime
3155 = InnerSCS.QualificationIncludesObjCLifetime;
3156 SCS.setToType(2, InnerSCS.getToType(2));
3160 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3161 CXXConstructorDecl *Constructor,
3163 const FunctionProtoType *CtorType =
3164 Constructor->getType()->getAs<FunctionProtoType>();
3165 if (CtorType->getNumParams() > 0) {
3166 QualType FirstArg = CtorType->getParamType(0);
3167 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3173 static OverloadingResult
3174 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3176 UserDefinedConversionSequence &User,
3177 OverloadCandidateSet &CandidateSet,
3178 bool AllowExplicit) {
3179 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3180 for (auto *D : S.LookupConstructors(To)) {
3181 auto Info = getConstructorInfo(D);
3185 bool Usable = !Info.Constructor->isInvalidDecl() &&
3186 S.isInitListConstructor(Info.Constructor) &&
3187 (AllowExplicit || !Info.Constructor->isExplicit());
3189 // If the first argument is (a reference to) the target type,
3190 // suppress conversions.
3191 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3192 S.Context, Info.Constructor, ToType);
3193 if (Info.ConstructorTmpl)
3194 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3195 /*ExplicitArgs*/ nullptr, From,
3196 CandidateSet, SuppressUserConversions);
3198 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3199 CandidateSet, SuppressUserConversions);
3203 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3205 OverloadCandidateSet::iterator Best;
3206 switch (auto Result =
3207 CandidateSet.BestViableFunction(S, From->getLocStart(),
3211 // Record the standard conversion we used and the conversion function.
3212 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3213 QualType ThisType = Constructor->getThisType(S.Context);
3214 // Initializer lists don't have conversions as such.
3215 User.Before.setAsIdentityConversion();
3216 User.HadMultipleCandidates = HadMultipleCandidates;
3217 User.ConversionFunction = Constructor;
3218 User.FoundConversionFunction = Best->FoundDecl;
3219 User.After.setAsIdentityConversion();
3220 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3221 User.After.setAllToTypes(ToType);
3225 case OR_No_Viable_Function:
3226 return OR_No_Viable_Function;
3228 return OR_Ambiguous;
3231 llvm_unreachable("Invalid OverloadResult!");
3234 /// Determines whether there is a user-defined conversion sequence
3235 /// (C++ [over.ics.user]) that converts expression From to the type
3236 /// ToType. If such a conversion exists, User will contain the
3237 /// user-defined conversion sequence that performs such a conversion
3238 /// and this routine will return true. Otherwise, this routine returns
3239 /// false and User is unspecified.
3241 /// \param AllowExplicit true if the conversion should consider C++0x
3242 /// "explicit" conversion functions as well as non-explicit conversion
3243 /// functions (C++0x [class.conv.fct]p2).
3245 /// \param AllowObjCConversionOnExplicit true if the conversion should
3246 /// allow an extra Objective-C pointer conversion on uses of explicit
3247 /// constructors. Requires \c AllowExplicit to also be set.
3248 static OverloadingResult
3249 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3250 UserDefinedConversionSequence &User,
3251 OverloadCandidateSet &CandidateSet,
3253 bool AllowObjCConversionOnExplicit) {
3254 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3255 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3257 // Whether we will only visit constructors.
3258 bool ConstructorsOnly = false;
3260 // If the type we are conversion to is a class type, enumerate its
3262 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3263 // C++ [over.match.ctor]p1:
3264 // When objects of class type are direct-initialized (8.5), or
3265 // copy-initialized from an expression of the same or a
3266 // derived class type (8.5), overload resolution selects the
3267 // constructor. [...] For copy-initialization, the candidate
3268 // functions are all the converting constructors (12.3.1) of
3269 // that class. The argument list is the expression-list within
3270 // the parentheses of the initializer.
3271 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3272 (From->getType()->getAs<RecordType>() &&
3273 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3274 ConstructorsOnly = true;
3276 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3277 // We're not going to find any constructors.
3278 } else if (CXXRecordDecl *ToRecordDecl
3279 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3281 Expr **Args = &From;
3282 unsigned NumArgs = 1;
3283 bool ListInitializing = false;
3284 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3285 // But first, see if there is an init-list-constructor that will work.
3286 OverloadingResult Result = IsInitializerListConstructorConversion(
3287 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3288 if (Result != OR_No_Viable_Function)
3292 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3294 // If we're list-initializing, we pass the individual elements as
3295 // arguments, not the entire list.
3296 Args = InitList->getInits();
3297 NumArgs = InitList->getNumInits();
3298 ListInitializing = true;
3301 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3302 auto Info = getConstructorInfo(D);
3306 bool Usable = !Info.Constructor->isInvalidDecl();
3307 if (ListInitializing)
3308 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3311 Info.Constructor->isConvertingConstructor(AllowExplicit);
3313 bool SuppressUserConversions = !ConstructorsOnly;
3314 if (SuppressUserConversions && ListInitializing) {
3315 SuppressUserConversions = false;
3317 // If the first argument is (a reference to) the target type,
3318 // suppress conversions.
3319 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3320 S.Context, Info.Constructor, ToType);
3323 if (Info.ConstructorTmpl)
3324 S.AddTemplateOverloadCandidate(
3325 Info.ConstructorTmpl, Info.FoundDecl,
3326 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3327 CandidateSet, SuppressUserConversions);
3329 // Allow one user-defined conversion when user specifies a
3330 // From->ToType conversion via an static cast (c-style, etc).
3331 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3332 llvm::makeArrayRef(Args, NumArgs),
3333 CandidateSet, SuppressUserConversions);
3339 // Enumerate conversion functions, if we're allowed to.
3340 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3341 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3342 // No conversion functions from incomplete types.
3343 } else if (const RecordType *FromRecordType
3344 = From->getType()->getAs<RecordType>()) {
3345 if (CXXRecordDecl *FromRecordDecl
3346 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3347 // Add all of the conversion functions as candidates.
3348 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3349 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3350 DeclAccessPair FoundDecl = I.getPair();
3351 NamedDecl *D = FoundDecl.getDecl();
3352 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3353 if (isa<UsingShadowDecl>(D))
3354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3356 CXXConversionDecl *Conv;
3357 FunctionTemplateDecl *ConvTemplate;
3358 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3359 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3361 Conv = cast<CXXConversionDecl>(D);
3363 if (AllowExplicit || !Conv->isExplicit()) {
3365 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3366 ActingContext, From, ToType,
3368 AllowObjCConversionOnExplicit);
3370 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3371 From, ToType, CandidateSet,
3372 AllowObjCConversionOnExplicit);
3378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3380 OverloadCandidateSet::iterator Best;
3381 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3385 // Record the standard conversion we used and the conversion function.
3386 if (CXXConstructorDecl *Constructor
3387 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3388 // C++ [over.ics.user]p1:
3389 // If the user-defined conversion is specified by a
3390 // constructor (12.3.1), the initial standard conversion
3391 // sequence converts the source type to the type required by
3392 // the argument of the constructor.
3394 QualType ThisType = Constructor->getThisType(S.Context);
3395 if (isa<InitListExpr>(From)) {
3396 // Initializer lists don't have conversions as such.
3397 User.Before.setAsIdentityConversion();
3399 if (Best->Conversions[0].isEllipsis())
3400 User.EllipsisConversion = true;
3402 User.Before = Best->Conversions[0].Standard;
3403 User.EllipsisConversion = false;
3406 User.HadMultipleCandidates = HadMultipleCandidates;
3407 User.ConversionFunction = Constructor;
3408 User.FoundConversionFunction = Best->FoundDecl;
3409 User.After.setAsIdentityConversion();
3410 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3411 User.After.setAllToTypes(ToType);
3414 if (CXXConversionDecl *Conversion
3415 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3416 // C++ [over.ics.user]p1:
3418 // [...] If the user-defined conversion is specified by a
3419 // conversion function (12.3.2), the initial standard
3420 // conversion sequence converts the source type to the
3421 // implicit object parameter of the conversion function.
3422 User.Before = Best->Conversions[0].Standard;
3423 User.HadMultipleCandidates = HadMultipleCandidates;
3424 User.ConversionFunction = Conversion;
3425 User.FoundConversionFunction = Best->FoundDecl;
3426 User.EllipsisConversion = false;
3428 // C++ [over.ics.user]p2:
3429 // The second standard conversion sequence converts the
3430 // result of the user-defined conversion to the target type
3431 // for the sequence. Since an implicit conversion sequence
3432 // is an initialization, the special rules for
3433 // initialization by user-defined conversion apply when
3434 // selecting the best user-defined conversion for a
3435 // user-defined conversion sequence (see 13.3.3 and
3437 User.After = Best->FinalConversion;
3440 llvm_unreachable("Not a constructor or conversion function?");
3442 case OR_No_Viable_Function:
3443 return OR_No_Viable_Function;
3446 return OR_Ambiguous;
3449 llvm_unreachable("Invalid OverloadResult!");
3453 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3454 ImplicitConversionSequence ICS;
3455 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3456 OverloadCandidateSet::CSK_Normal);
3457 OverloadingResult OvResult =
3458 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3459 CandidateSet, false, false);
3460 if (OvResult == OR_Ambiguous)
3461 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3462 << From->getType() << ToType << From->getSourceRange();
3463 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3464 if (!RequireCompleteType(From->getLocStart(), ToType,
3465 diag::err_typecheck_nonviable_condition_incomplete,
3466 From->getType(), From->getSourceRange()))
3467 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3468 << false << From->getType() << From->getSourceRange() << ToType;
3471 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3475 /// \brief Compare the user-defined conversion functions or constructors
3476 /// of two user-defined conversion sequences to determine whether any ordering
3478 static ImplicitConversionSequence::CompareKind
3479 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3480 FunctionDecl *Function2) {
3481 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3482 return ImplicitConversionSequence::Indistinguishable;
3485 // If both conversion functions are implicitly-declared conversions from
3486 // a lambda closure type to a function pointer and a block pointer,
3487 // respectively, always prefer the conversion to a function pointer,
3488 // because the function pointer is more lightweight and is more likely
3489 // to keep code working.
3490 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3492 return ImplicitConversionSequence::Indistinguishable;
3494 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3496 return ImplicitConversionSequence::Indistinguishable;
3498 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3499 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3500 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3501 if (Block1 != Block2)
3502 return Block1 ? ImplicitConversionSequence::Worse
3503 : ImplicitConversionSequence::Better;
3506 return ImplicitConversionSequence::Indistinguishable;
3509 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3510 const ImplicitConversionSequence &ICS) {
3511 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3512 (ICS.isUserDefined() &&
3513 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3516 /// CompareImplicitConversionSequences - Compare two implicit
3517 /// conversion sequences to determine whether one is better than the
3518 /// other or if they are indistinguishable (C++ 13.3.3.2).
3519 static ImplicitConversionSequence::CompareKind
3520 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3521 const ImplicitConversionSequence& ICS1,
3522 const ImplicitConversionSequence& ICS2)
3524 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3525 // conversion sequences (as defined in 13.3.3.1)
3526 // -- a standard conversion sequence (13.3.3.1.1) is a better
3527 // conversion sequence than a user-defined conversion sequence or
3528 // an ellipsis conversion sequence, and
3529 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3530 // conversion sequence than an ellipsis conversion sequence
3533 // C++0x [over.best.ics]p10:
3534 // For the purpose of ranking implicit conversion sequences as
3535 // described in 13.3.3.2, the ambiguous conversion sequence is
3536 // treated as a user-defined sequence that is indistinguishable
3537 // from any other user-defined conversion sequence.
3539 // String literal to 'char *' conversion has been deprecated in C++03. It has
3540 // been removed from C++11. We still accept this conversion, if it happens at
3541 // the best viable function. Otherwise, this conversion is considered worse
3542 // than ellipsis conversion. Consider this as an extension; this is not in the
3543 // standard. For example:
3545 // int &f(...); // #1
3546 // void f(char*); // #2
3547 // void g() { int &r = f("foo"); }
3549 // In C++03, we pick #2 as the best viable function.
3550 // In C++11, we pick #1 as the best viable function, because ellipsis
3551 // conversion is better than string-literal to char* conversion (since there
3552 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3553 // convert arguments, #2 would be the best viable function in C++11.
3554 // If the best viable function has this conversion, a warning will be issued
3555 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3557 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3558 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3559 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3560 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3561 ? ImplicitConversionSequence::Worse
3562 : ImplicitConversionSequence::Better;
3564 if (ICS1.getKindRank() < ICS2.getKindRank())
3565 return ImplicitConversionSequence::Better;
3566 if (ICS2.getKindRank() < ICS1.getKindRank())
3567 return ImplicitConversionSequence::Worse;
3569 // The following checks require both conversion sequences to be of
3571 if (ICS1.getKind() != ICS2.getKind())
3572 return ImplicitConversionSequence::Indistinguishable;
3574 ImplicitConversionSequence::CompareKind Result =
3575 ImplicitConversionSequence::Indistinguishable;
3577 // Two implicit conversion sequences of the same form are
3578 // indistinguishable conversion sequences unless one of the
3579 // following rules apply: (C++ 13.3.3.2p3):
3581 // List-initialization sequence L1 is a better conversion sequence than
3582 // list-initialization sequence L2 if:
3583 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3585 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3586 // and N1 is smaller than N2.,
3587 // even if one of the other rules in this paragraph would otherwise apply.
3588 if (!ICS1.isBad()) {
3589 if (ICS1.isStdInitializerListElement() &&
3590 !ICS2.isStdInitializerListElement())
3591 return ImplicitConversionSequence::Better;
3592 if (!ICS1.isStdInitializerListElement() &&
3593 ICS2.isStdInitializerListElement())
3594 return ImplicitConversionSequence::Worse;
3597 if (ICS1.isStandard())
3598 // Standard conversion sequence S1 is a better conversion sequence than
3599 // standard conversion sequence S2 if [...]
3600 Result = CompareStandardConversionSequences(S, Loc,
3601 ICS1.Standard, ICS2.Standard);
3602 else if (ICS1.isUserDefined()) {
3603 // User-defined conversion sequence U1 is a better conversion
3604 // sequence than another user-defined conversion sequence U2 if
3605 // they contain the same user-defined conversion function or
3606 // constructor and if the second standard conversion sequence of
3607 // U1 is better than the second standard conversion sequence of
3608 // U2 (C++ 13.3.3.2p3).
3609 if (ICS1.UserDefined.ConversionFunction ==
3610 ICS2.UserDefined.ConversionFunction)
3611 Result = CompareStandardConversionSequences(S, Loc,
3612 ICS1.UserDefined.After,
3613 ICS2.UserDefined.After);
3615 Result = compareConversionFunctions(S,
3616 ICS1.UserDefined.ConversionFunction,
3617 ICS2.UserDefined.ConversionFunction);
3623 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3624 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3626 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3627 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3630 return Context.hasSameUnqualifiedType(T1, T2);
3633 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3634 // determine if one is a proper subset of the other.
3635 static ImplicitConversionSequence::CompareKind
3636 compareStandardConversionSubsets(ASTContext &Context,
3637 const StandardConversionSequence& SCS1,
3638 const StandardConversionSequence& SCS2) {
3639 ImplicitConversionSequence::CompareKind Result
3640 = ImplicitConversionSequence::Indistinguishable;
3642 // the identity conversion sequence is considered to be a subsequence of
3643 // any non-identity conversion sequence
3644 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3645 return ImplicitConversionSequence::Better;
3646 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3647 return ImplicitConversionSequence::Worse;
3649 if (SCS1.Second != SCS2.Second) {
3650 if (SCS1.Second == ICK_Identity)
3651 Result = ImplicitConversionSequence::Better;
3652 else if (SCS2.Second == ICK_Identity)
3653 Result = ImplicitConversionSequence::Worse;
3655 return ImplicitConversionSequence::Indistinguishable;
3656 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3657 return ImplicitConversionSequence::Indistinguishable;
3659 if (SCS1.Third == SCS2.Third) {
3660 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3661 : ImplicitConversionSequence::Indistinguishable;
3664 if (SCS1.Third == ICK_Identity)
3665 return Result == ImplicitConversionSequence::Worse
3666 ? ImplicitConversionSequence::Indistinguishable
3667 : ImplicitConversionSequence::Better;
3669 if (SCS2.Third == ICK_Identity)
3670 return Result == ImplicitConversionSequence::Better
3671 ? ImplicitConversionSequence::Indistinguishable
3672 : ImplicitConversionSequence::Worse;
3674 return ImplicitConversionSequence::Indistinguishable;
3677 /// \brief Determine whether one of the given reference bindings is better
3678 /// than the other based on what kind of bindings they are.
3680 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3681 const StandardConversionSequence &SCS2) {
3682 // C++0x [over.ics.rank]p3b4:
3683 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3684 // implicit object parameter of a non-static member function declared
3685 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3686 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3687 // lvalue reference to a function lvalue and S2 binds an rvalue
3690 // FIXME: Rvalue references. We're going rogue with the above edits,
3691 // because the semantics in the current C++0x working paper (N3225 at the
3692 // time of this writing) break the standard definition of std::forward
3693 // and std::reference_wrapper when dealing with references to functions.
3694 // Proposed wording changes submitted to CWG for consideration.
3695 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3696 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3699 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3700 SCS2.IsLvalueReference) ||
3701 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3702 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3705 /// CompareStandardConversionSequences - Compare two standard
3706 /// conversion sequences to determine whether one is better than the
3707 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3708 static ImplicitConversionSequence::CompareKind
3709 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3710 const StandardConversionSequence& SCS1,
3711 const StandardConversionSequence& SCS2)
3713 // Standard conversion sequence S1 is a better conversion sequence
3714 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3716 // -- S1 is a proper subsequence of S2 (comparing the conversion
3717 // sequences in the canonical form defined by 13.3.3.1.1,
3718 // excluding any Lvalue Transformation; the identity conversion
3719 // sequence is considered to be a subsequence of any
3720 // non-identity conversion sequence) or, if not that,
3721 if (ImplicitConversionSequence::CompareKind CK
3722 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3725 // -- the rank of S1 is better than the rank of S2 (by the rules
3726 // defined below), or, if not that,
3727 ImplicitConversionRank Rank1 = SCS1.getRank();
3728 ImplicitConversionRank Rank2 = SCS2.getRank();
3730 return ImplicitConversionSequence::Better;
3731 else if (Rank2 < Rank1)
3732 return ImplicitConversionSequence::Worse;
3734 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3735 // are indistinguishable unless one of the following rules
3738 // A conversion that is not a conversion of a pointer, or
3739 // pointer to member, to bool is better than another conversion
3740 // that is such a conversion.
3741 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3742 return SCS2.isPointerConversionToBool()
3743 ? ImplicitConversionSequence::Better
3744 : ImplicitConversionSequence::Worse;
3746 // C++ [over.ics.rank]p4b2:
3748 // If class B is derived directly or indirectly from class A,
3749 // conversion of B* to A* is better than conversion of B* to
3750 // void*, and conversion of A* to void* is better than conversion
3752 bool SCS1ConvertsToVoid
3753 = SCS1.isPointerConversionToVoidPointer(S.Context);
3754 bool SCS2ConvertsToVoid
3755 = SCS2.isPointerConversionToVoidPointer(S.Context);
3756 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3757 // Exactly one of the conversion sequences is a conversion to
3758 // a void pointer; it's the worse conversion.
3759 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3760 : ImplicitConversionSequence::Worse;
3761 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3762 // Neither conversion sequence converts to a void pointer; compare
3763 // their derived-to-base conversions.
3764 if (ImplicitConversionSequence::CompareKind DerivedCK
3765 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3767 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3768 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3769 // Both conversion sequences are conversions to void
3770 // pointers. Compare the source types to determine if there's an
3771 // inheritance relationship in their sources.
3772 QualType FromType1 = SCS1.getFromType();
3773 QualType FromType2 = SCS2.getFromType();
3775 // Adjust the types we're converting from via the array-to-pointer
3776 // conversion, if we need to.
3777 if (SCS1.First == ICK_Array_To_Pointer)
3778 FromType1 = S.Context.getArrayDecayedType(FromType1);
3779 if (SCS2.First == ICK_Array_To_Pointer)
3780 FromType2 = S.Context.getArrayDecayedType(FromType2);
3782 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3783 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3785 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3786 return ImplicitConversionSequence::Better;
3787 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3788 return ImplicitConversionSequence::Worse;
3790 // Objective-C++: If one interface is more specific than the
3791 // other, it is the better one.
3792 const ObjCObjectPointerType* FromObjCPtr1
3793 = FromType1->getAs<ObjCObjectPointerType>();
3794 const ObjCObjectPointerType* FromObjCPtr2
3795 = FromType2->getAs<ObjCObjectPointerType>();
3796 if (FromObjCPtr1 && FromObjCPtr2) {
3797 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3799 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3801 if (AssignLeft != AssignRight) {
3802 return AssignLeft? ImplicitConversionSequence::Better
3803 : ImplicitConversionSequence::Worse;
3808 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3810 if (ImplicitConversionSequence::CompareKind QualCK
3811 = CompareQualificationConversions(S, SCS1, SCS2))
3814 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3815 // Check for a better reference binding based on the kind of bindings.
3816 if (isBetterReferenceBindingKind(SCS1, SCS2))
3817 return ImplicitConversionSequence::Better;
3818 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3819 return ImplicitConversionSequence::Worse;
3821 // C++ [over.ics.rank]p3b4:
3822 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3823 // which the references refer are the same type except for
3824 // top-level cv-qualifiers, and the type to which the reference
3825 // initialized by S2 refers is more cv-qualified than the type
3826 // to which the reference initialized by S1 refers.
3827 QualType T1 = SCS1.getToType(2);
3828 QualType T2 = SCS2.getToType(2);
3829 T1 = S.Context.getCanonicalType(T1);
3830 T2 = S.Context.getCanonicalType(T2);
3831 Qualifiers T1Quals, T2Quals;
3832 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3833 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3834 if (UnqualT1 == UnqualT2) {
3835 // Objective-C++ ARC: If the references refer to objects with different
3836 // lifetimes, prefer bindings that don't change lifetime.
3837 if (SCS1.ObjCLifetimeConversionBinding !=
3838 SCS2.ObjCLifetimeConversionBinding) {
3839 return SCS1.ObjCLifetimeConversionBinding
3840 ? ImplicitConversionSequence::Worse
3841 : ImplicitConversionSequence::Better;
3844 // If the type is an array type, promote the element qualifiers to the
3845 // type for comparison.
3846 if (isa<ArrayType>(T1) && T1Quals)
3847 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3848 if (isa<ArrayType>(T2) && T2Quals)
3849 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3850 if (T2.isMoreQualifiedThan(T1))
3851 return ImplicitConversionSequence::Better;
3852 else if (T1.isMoreQualifiedThan(T2))
3853 return ImplicitConversionSequence::Worse;
3857 // In Microsoft mode, prefer an integral conversion to a
3858 // floating-to-integral conversion if the integral conversion
3859 // is between types of the same size.
3867 // Here, MSVC will call f(int) instead of generating a compile error
3868 // as clang will do in standard mode.
3869 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3870 SCS2.Second == ICK_Floating_Integral &&
3871 S.Context.getTypeSize(SCS1.getFromType()) ==
3872 S.Context.getTypeSize(SCS1.getToType(2)))
3873 return ImplicitConversionSequence::Better;
3875 return ImplicitConversionSequence::Indistinguishable;
3878 /// CompareQualificationConversions - Compares two standard conversion
3879 /// sequences to determine whether they can be ranked based on their
3880 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3881 static ImplicitConversionSequence::CompareKind
3882 CompareQualificationConversions(Sema &S,
3883 const StandardConversionSequence& SCS1,
3884 const StandardConversionSequence& SCS2) {
3886 // -- S1 and S2 differ only in their qualification conversion and
3887 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3888 // cv-qualification signature of type T1 is a proper subset of
3889 // the cv-qualification signature of type T2, and S1 is not the
3890 // deprecated string literal array-to-pointer conversion (4.2).
3891 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3892 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3893 return ImplicitConversionSequence::Indistinguishable;
3895 // FIXME: the example in the standard doesn't use a qualification
3897 QualType T1 = SCS1.getToType(2);
3898 QualType T2 = SCS2.getToType(2);
3899 T1 = S.Context.getCanonicalType(T1);
3900 T2 = S.Context.getCanonicalType(T2);
3901 Qualifiers T1Quals, T2Quals;
3902 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3903 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3905 // If the types are the same, we won't learn anything by unwrapped
3907 if (UnqualT1 == UnqualT2)
3908 return ImplicitConversionSequence::Indistinguishable;
3910 // If the type is an array type, promote the element qualifiers to the type
3912 if (isa<ArrayType>(T1) && T1Quals)
3913 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3914 if (isa<ArrayType>(T2) && T2Quals)
3915 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3917 ImplicitConversionSequence::CompareKind Result
3918 = ImplicitConversionSequence::Indistinguishable;
3920 // Objective-C++ ARC:
3921 // Prefer qualification conversions not involving a change in lifetime
3922 // to qualification conversions that do not change lifetime.
3923 if (SCS1.QualificationIncludesObjCLifetime !=
3924 SCS2.QualificationIncludesObjCLifetime) {
3925 Result = SCS1.QualificationIncludesObjCLifetime
3926 ? ImplicitConversionSequence::Worse
3927 : ImplicitConversionSequence::Better;
3930 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3931 // Within each iteration of the loop, we check the qualifiers to
3932 // determine if this still looks like a qualification
3933 // conversion. Then, if all is well, we unwrap one more level of
3934 // pointers or pointers-to-members and do it all again
3935 // until there are no more pointers or pointers-to-members left
3936 // to unwrap. This essentially mimics what
3937 // IsQualificationConversion does, but here we're checking for a
3938 // strict subset of qualifiers.
3939 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3940 // The qualifiers are the same, so this doesn't tell us anything
3941 // about how the sequences rank.
3943 else if (T2.isMoreQualifiedThan(T1)) {
3944 // T1 has fewer qualifiers, so it could be the better sequence.
3945 if (Result == ImplicitConversionSequence::Worse)
3946 // Neither has qualifiers that are a subset of the other's
3948 return ImplicitConversionSequence::Indistinguishable;
3950 Result = ImplicitConversionSequence::Better;
3951 } else if (T1.isMoreQualifiedThan(T2)) {
3952 // T2 has fewer qualifiers, so it could be the better sequence.
3953 if (Result == ImplicitConversionSequence::Better)
3954 // Neither has qualifiers that are a subset of the other's
3956 return ImplicitConversionSequence::Indistinguishable;
3958 Result = ImplicitConversionSequence::Worse;
3960 // Qualifiers are disjoint.
3961 return ImplicitConversionSequence::Indistinguishable;
3964 // If the types after this point are equivalent, we're done.
3965 if (S.Context.hasSameUnqualifiedType(T1, T2))
3969 // Check that the winning standard conversion sequence isn't using
3970 // the deprecated string literal array to pointer conversion.
3972 case ImplicitConversionSequence::Better:
3973 if (SCS1.DeprecatedStringLiteralToCharPtr)
3974 Result = ImplicitConversionSequence::Indistinguishable;
3977 case ImplicitConversionSequence::Indistinguishable:
3980 case ImplicitConversionSequence::Worse:
3981 if (SCS2.DeprecatedStringLiteralToCharPtr)
3982 Result = ImplicitConversionSequence::Indistinguishable;
3989 /// CompareDerivedToBaseConversions - Compares two standard conversion
3990 /// sequences to determine whether they can be ranked based on their
3991 /// various kinds of derived-to-base conversions (C++
3992 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3993 /// conversions between Objective-C interface types.
3994 static ImplicitConversionSequence::CompareKind
3995 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3996 const StandardConversionSequence& SCS1,
3997 const StandardConversionSequence& SCS2) {
3998 QualType FromType1 = SCS1.getFromType();
3999 QualType ToType1 = SCS1.getToType(1);
4000 QualType FromType2 = SCS2.getFromType();
4001 QualType ToType2 = SCS2.getToType(1);
4003 // Adjust the types we're converting from via the array-to-pointer
4004 // conversion, if we need to.
4005 if (SCS1.First == ICK_Array_To_Pointer)
4006 FromType1 = S.Context.getArrayDecayedType(FromType1);
4007 if (SCS2.First == ICK_Array_To_Pointer)
4008 FromType2 = S.Context.getArrayDecayedType(FromType2);
4010 // Canonicalize all of the types.
4011 FromType1 = S.Context.getCanonicalType(FromType1);
4012 ToType1 = S.Context.getCanonicalType(ToType1);
4013 FromType2 = S.Context.getCanonicalType(FromType2);
4014 ToType2 = S.Context.getCanonicalType(ToType2);
4016 // C++ [over.ics.rank]p4b3:
4018 // If class B is derived directly or indirectly from class A and
4019 // class C is derived directly or indirectly from B,
4021 // Compare based on pointer conversions.
4022 if (SCS1.Second == ICK_Pointer_Conversion &&
4023 SCS2.Second == ICK_Pointer_Conversion &&
4024 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4025 FromType1->isPointerType() && FromType2->isPointerType() &&
4026 ToType1->isPointerType() && ToType2->isPointerType()) {
4027 QualType FromPointee1
4028 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4030 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4031 QualType FromPointee2
4032 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4034 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4036 // -- conversion of C* to B* is better than conversion of C* to A*,
4037 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4038 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4039 return ImplicitConversionSequence::Better;
4040 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4041 return ImplicitConversionSequence::Worse;
4044 // -- conversion of B* to A* is better than conversion of C* to A*,
4045 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4046 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4047 return ImplicitConversionSequence::Better;
4048 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4049 return ImplicitConversionSequence::Worse;
4051 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4052 SCS2.Second == ICK_Pointer_Conversion) {
4053 const ObjCObjectPointerType *FromPtr1
4054 = FromType1->getAs<ObjCObjectPointerType>();
4055 const ObjCObjectPointerType *FromPtr2
4056 = FromType2->getAs<ObjCObjectPointerType>();
4057 const ObjCObjectPointerType *ToPtr1
4058 = ToType1->getAs<ObjCObjectPointerType>();
4059 const ObjCObjectPointerType *ToPtr2
4060 = ToType2->getAs<ObjCObjectPointerType>();
4062 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4063 // Apply the same conversion ranking rules for Objective-C pointer types
4064 // that we do for C++ pointers to class types. However, we employ the
4065 // Objective-C pseudo-subtyping relationship used for assignment of
4066 // Objective-C pointer types.
4068 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4069 bool FromAssignRight
4070 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4072 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4074 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4076 // A conversion to an a non-id object pointer type or qualified 'id'
4077 // type is better than a conversion to 'id'.
4078 if (ToPtr1->isObjCIdType() &&
4079 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCIdType() &&
4082 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4083 return ImplicitConversionSequence::Better;
4085 // A conversion to a non-id object pointer type is better than a
4086 // conversion to a qualified 'id' type
4087 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4088 return ImplicitConversionSequence::Worse;
4089 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4090 return ImplicitConversionSequence::Better;
4092 // A conversion to an a non-Class object pointer type or qualified 'Class'
4093 // type is better than a conversion to 'Class'.
4094 if (ToPtr1->isObjCClassType() &&
4095 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4096 return ImplicitConversionSequence::Worse;
4097 if (ToPtr2->isObjCClassType() &&
4098 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4099 return ImplicitConversionSequence::Better;
4101 // A conversion to a non-Class object pointer type is better than a
4102 // conversion to a qualified 'Class' type.
4103 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4104 return ImplicitConversionSequence::Worse;
4105 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4106 return ImplicitConversionSequence::Better;
4108 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4109 if (S.Context.hasSameType(FromType1, FromType2) &&
4110 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4111 (ToAssignLeft != ToAssignRight)) {
4112 if (FromPtr1->isSpecialized()) {
4113 // "conversion of B<A> * to B * is better than conversion of B * to
4116 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4118 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4121 return ImplicitConversionSequence::Better;
4122 } else if (IsSecondSame)
4123 return ImplicitConversionSequence::Worse;
4125 return ToAssignLeft? ImplicitConversionSequence::Worse
4126 : ImplicitConversionSequence::Better;
4129 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4130 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4131 (FromAssignLeft != FromAssignRight))
4132 return FromAssignLeft? ImplicitConversionSequence::Better
4133 : ImplicitConversionSequence::Worse;
4137 // Ranking of member-pointer types.
4138 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4139 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4140 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4141 const MemberPointerType * FromMemPointer1 =
4142 FromType1->getAs<MemberPointerType>();
4143 const MemberPointerType * ToMemPointer1 =
4144 ToType1->getAs<MemberPointerType>();
4145 const MemberPointerType * FromMemPointer2 =
4146 FromType2->getAs<MemberPointerType>();
4147 const MemberPointerType * ToMemPointer2 =
4148 ToType2->getAs<MemberPointerType>();
4149 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4150 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4151 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4152 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4153 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4154 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4155 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4156 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4157 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4158 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4159 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4160 return ImplicitConversionSequence::Worse;
4161 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4162 return ImplicitConversionSequence::Better;
4164 // conversion of B::* to C::* is better than conversion of A::* to C::*
4165 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4166 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4167 return ImplicitConversionSequence::Better;
4168 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4169 return ImplicitConversionSequence::Worse;
4173 if (SCS1.Second == ICK_Derived_To_Base) {
4174 // -- conversion of C to B is better than conversion of C to A,
4175 // -- binding of an expression of type C to a reference of type
4176 // B& is better than binding an expression of type C to a
4177 // reference of type A&,
4178 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4179 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4180 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4181 return ImplicitConversionSequence::Better;
4182 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4183 return ImplicitConversionSequence::Worse;
4186 // -- conversion of B to A is better than conversion of C to A.
4187 // -- binding of an expression of type B to a reference of type
4188 // A& is better than binding an expression of type C to a
4189 // reference of type A&,
4190 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4191 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4192 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4193 return ImplicitConversionSequence::Better;
4194 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4195 return ImplicitConversionSequence::Worse;
4199 return ImplicitConversionSequence::Indistinguishable;
4202 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4204 static bool isTypeValid(QualType T) {
4205 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4206 return !Record->isInvalidDecl();
4211 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4212 /// determine whether they are reference-related,
4213 /// reference-compatible, reference-compatible with added
4214 /// qualification, or incompatible, for use in C++ initialization by
4215 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4216 /// type, and the first type (T1) is the pointee type of the reference
4217 /// type being initialized.
4218 Sema::ReferenceCompareResult
4219 Sema::CompareReferenceRelationship(SourceLocation Loc,
4220 QualType OrigT1, QualType OrigT2,
4221 bool &DerivedToBase,
4222 bool &ObjCConversion,
4223 bool &ObjCLifetimeConversion) {
4224 assert(!OrigT1->isReferenceType() &&
4225 "T1 must be the pointee type of the reference type");
4226 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4228 QualType T1 = Context.getCanonicalType(OrigT1);
4229 QualType T2 = Context.getCanonicalType(OrigT2);
4230 Qualifiers T1Quals, T2Quals;
4231 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4232 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4234 // C++ [dcl.init.ref]p4:
4235 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4236 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4237 // T1 is a base class of T2.
4238 DerivedToBase = false;
4239 ObjCConversion = false;
4240 ObjCLifetimeConversion = false;
4241 QualType ConvertedT2;
4242 if (UnqualT1 == UnqualT2) {
4244 } else if (isCompleteType(Loc, OrigT2) &&
4245 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4246 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4247 DerivedToBase = true;
4248 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4249 UnqualT2->isObjCObjectOrInterfaceType() &&
4250 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4251 ObjCConversion = true;
4252 else if (UnqualT2->isFunctionType() &&
4253 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4254 // C++1z [dcl.init.ref]p4:
4255 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4256 // function" and T1 is "function"
4258 // We extend this to also apply to 'noreturn', so allow any function
4259 // conversion between function types.
4260 return Ref_Compatible;
4262 return Ref_Incompatible;
4264 // At this point, we know that T1 and T2 are reference-related (at
4267 // If the type is an array type, promote the element qualifiers to the type
4269 if (isa<ArrayType>(T1) && T1Quals)
4270 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4271 if (isa<ArrayType>(T2) && T2Quals)
4272 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4274 // C++ [dcl.init.ref]p4:
4275 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4276 // reference-related to T2 and cv1 is the same cv-qualification
4277 // as, or greater cv-qualification than, cv2. For purposes of
4278 // overload resolution, cases for which cv1 is greater
4279 // cv-qualification than cv2 are identified as
4280 // reference-compatible with added qualification (see 13.3.3.2).
4282 // Note that we also require equivalence of Objective-C GC and address-space
4283 // qualifiers when performing these computations, so that e.g., an int in
4284 // address space 1 is not reference-compatible with an int in address
4286 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4287 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4288 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4289 ObjCLifetimeConversion = true;
4291 T1Quals.removeObjCLifetime();
4292 T2Quals.removeObjCLifetime();
4295 // MS compiler ignores __unaligned qualifier for references; do the same.
4296 T1Quals.removeUnaligned();
4297 T2Quals.removeUnaligned();
4299 if (T1Quals.compatiblyIncludes(T2Quals))
4300 return Ref_Compatible;
4305 /// \brief Look for a user-defined conversion to a value reference-compatible
4306 /// with DeclType. Return true if something definite is found.
4308 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4309 QualType DeclType, SourceLocation DeclLoc,
4310 Expr *Init, QualType T2, bool AllowRvalues,
4311 bool AllowExplicit) {
4312 assert(T2->isRecordType() && "Can only find conversions of record types.");
4313 CXXRecordDecl *T2RecordDecl
4314 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4316 OverloadCandidateSet CandidateSet(
4317 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4318 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4319 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4321 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4322 if (isa<UsingShadowDecl>(D))
4323 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4325 FunctionTemplateDecl *ConvTemplate
4326 = dyn_cast<FunctionTemplateDecl>(D);
4327 CXXConversionDecl *Conv;
4329 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4331 Conv = cast<CXXConversionDecl>(D);
4333 // If this is an explicit conversion, and we're not allowed to consider
4334 // explicit conversions, skip it.
4335 if (!AllowExplicit && Conv->isExplicit())
4339 bool DerivedToBase = false;
4340 bool ObjCConversion = false;
4341 bool ObjCLifetimeConversion = false;
4343 // If we are initializing an rvalue reference, don't permit conversion
4344 // functions that return lvalues.
4345 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4346 const ReferenceType *RefType
4347 = Conv->getConversionType()->getAs<LValueReferenceType>();
4348 if (RefType && !RefType->getPointeeType()->isFunctionType())
4352 if (!ConvTemplate &&
4353 S.CompareReferenceRelationship(
4355 Conv->getConversionType().getNonReferenceType()
4356 .getUnqualifiedType(),
4357 DeclType.getNonReferenceType().getUnqualifiedType(),
4358 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4359 Sema::Ref_Incompatible)
4362 // If the conversion function doesn't return a reference type,
4363 // it can't be considered for this conversion. An rvalue reference
4364 // is only acceptable if its referencee is a function type.
4366 const ReferenceType *RefType =
4367 Conv->getConversionType()->getAs<ReferenceType>();
4369 (!RefType->isLValueReferenceType() &&
4370 !RefType->getPointeeType()->isFunctionType()))
4375 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4376 Init, DeclType, CandidateSet,
4377 /*AllowObjCConversionOnExplicit=*/false);
4379 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4380 DeclType, CandidateSet,
4381 /*AllowObjCConversionOnExplicit=*/false);
4384 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4386 OverloadCandidateSet::iterator Best;
4387 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4389 // C++ [over.ics.ref]p1:
4391 // [...] If the parameter binds directly to the result of
4392 // applying a conversion function to the argument
4393 // expression, the implicit conversion sequence is a
4394 // user-defined conversion sequence (13.3.3.1.2), with the
4395 // second standard conversion sequence either an identity
4396 // conversion or, if the conversion function returns an
4397 // entity of a type that is a derived class of the parameter
4398 // type, a derived-to-base Conversion.
4399 if (!Best->FinalConversion.DirectBinding)
4402 ICS.setUserDefined();
4403 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4404 ICS.UserDefined.After = Best->FinalConversion;
4405 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4406 ICS.UserDefined.ConversionFunction = Best->Function;
4407 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4408 ICS.UserDefined.EllipsisConversion = false;
4409 assert(ICS.UserDefined.After.ReferenceBinding &&
4410 ICS.UserDefined.After.DirectBinding &&
4411 "Expected a direct reference binding!");
4416 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4417 Cand != CandidateSet.end(); ++Cand)
4419 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4422 case OR_No_Viable_Function:
4424 // There was no suitable conversion, or we found a deleted
4425 // conversion; continue with other checks.
4429 llvm_unreachable("Invalid OverloadResult!");
4432 /// \brief Compute an implicit conversion sequence for reference
4434 static ImplicitConversionSequence
4435 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4436 SourceLocation DeclLoc,
4437 bool SuppressUserConversions,
4438 bool AllowExplicit) {
4439 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4441 // Most paths end in a failed conversion.
4442 ImplicitConversionSequence ICS;
4443 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4445 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4446 QualType T2 = Init->getType();
4448 // If the initializer is the address of an overloaded function, try
4449 // to resolve the overloaded function. If all goes well, T2 is the
4450 // type of the resulting function.
4451 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452 DeclAccessPair Found;
4453 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4458 // Compute some basic properties of the types and the initializer.
4459 bool isRValRef = DeclType->isRValueReferenceType();
4460 bool DerivedToBase = false;
4461 bool ObjCConversion = false;
4462 bool ObjCLifetimeConversion = false;
4463 Expr::Classification InitCategory = Init->Classify(S.Context);
4464 Sema::ReferenceCompareResult RefRelationship
4465 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4466 ObjCConversion, ObjCLifetimeConversion);
4469 // C++0x [dcl.init.ref]p5:
4470 // A reference to type "cv1 T1" is initialized by an expression
4471 // of type "cv2 T2" as follows:
4473 // -- If reference is an lvalue reference and the initializer expression
4475 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4476 // reference-compatible with "cv2 T2," or
4478 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4479 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4480 // C++ [over.ics.ref]p1:
4481 // When a parameter of reference type binds directly (8.5.3)
4482 // to an argument expression, the implicit conversion sequence
4483 // is the identity conversion, unless the argument expression
4484 // has a type that is a derived class of the parameter type,
4485 // in which case the implicit conversion sequence is a
4486 // derived-to-base Conversion (13.3.3.1).
4488 ICS.Standard.First = ICK_Identity;
4489 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4490 : ObjCConversion? ICK_Compatible_Conversion
4492 ICS.Standard.Third = ICK_Identity;
4493 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4494 ICS.Standard.setToType(0, T2);
4495 ICS.Standard.setToType(1, T1);
4496 ICS.Standard.setToType(2, T1);
4497 ICS.Standard.ReferenceBinding = true;
4498 ICS.Standard.DirectBinding = true;
4499 ICS.Standard.IsLvalueReference = !isRValRef;
4500 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4501 ICS.Standard.BindsToRvalue = false;
4502 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4503 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4504 ICS.Standard.CopyConstructor = nullptr;
4505 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4507 // Nothing more to do: the inaccessibility/ambiguity check for
4508 // derived-to-base conversions is suppressed when we're
4509 // computing the implicit conversion sequence (C++
4510 // [over.best.ics]p2).
4514 // -- has a class type (i.e., T2 is a class type), where T1 is
4515 // not reference-related to T2, and can be implicitly
4516 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4517 // is reference-compatible with "cv3 T3" 92) (this
4518 // conversion is selected by enumerating the applicable
4519 // conversion functions (13.3.1.6) and choosing the best
4520 // one through overload resolution (13.3)),
4521 if (!SuppressUserConversions && T2->isRecordType() &&
4522 S.isCompleteType(DeclLoc, T2) &&
4523 RefRelationship == Sema::Ref_Incompatible) {
4524 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4525 Init, T2, /*AllowRvalues=*/false,
4531 // -- Otherwise, the reference shall be an lvalue reference to a
4532 // non-volatile const type (i.e., cv1 shall be const), or the reference
4533 // shall be an rvalue reference.
4534 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4537 // -- If the initializer expression
4539 // -- is an xvalue, class prvalue, array prvalue or function
4540 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4541 if (RefRelationship == Sema::Ref_Compatible &&
4542 (InitCategory.isXValue() ||
4543 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4544 (InitCategory.isLValue() && T2->isFunctionType()))) {
4546 ICS.Standard.First = ICK_Identity;
4547 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4548 : ObjCConversion? ICK_Compatible_Conversion
4550 ICS.Standard.Third = ICK_Identity;
4551 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4552 ICS.Standard.setToType(0, T2);
4553 ICS.Standard.setToType(1, T1);
4554 ICS.Standard.setToType(2, T1);
4555 ICS.Standard.ReferenceBinding = true;
4556 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4557 // binding unless we're binding to a class prvalue.
4558 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4559 // allow the use of rvalue references in C++98/03 for the benefit of
4560 // standard library implementors; therefore, we need the xvalue check here.
4561 ICS.Standard.DirectBinding =
4562 S.getLangOpts().CPlusPlus11 ||
4563 !(InitCategory.isPRValue() || T2->isRecordType());
4564 ICS.Standard.IsLvalueReference = !isRValRef;
4565 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4566 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4567 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4568 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4569 ICS.Standard.CopyConstructor = nullptr;
4570 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4574 // -- has a class type (i.e., T2 is a class type), where T1 is not
4575 // reference-related to T2, and can be implicitly converted to
4576 // an xvalue, class prvalue, or function lvalue of type
4577 // "cv3 T3", where "cv1 T1" is reference-compatible with
4580 // then the reference is bound to the value of the initializer
4581 // expression in the first case and to the result of the conversion
4582 // in the second case (or, in either case, to an appropriate base
4583 // class subobject).
4584 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4585 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4586 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4587 Init, T2, /*AllowRvalues=*/true,
4589 // In the second case, if the reference is an rvalue reference
4590 // and the second standard conversion sequence of the
4591 // user-defined conversion sequence includes an lvalue-to-rvalue
4592 // conversion, the program is ill-formed.
4593 if (ICS.isUserDefined() && isRValRef &&
4594 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4595 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4600 // A temporary of function type cannot be created; don't even try.
4601 if (T1->isFunctionType())
4604 // -- Otherwise, a temporary of type "cv1 T1" is created and
4605 // initialized from the initializer expression using the
4606 // rules for a non-reference copy initialization (8.5). The
4607 // reference is then bound to the temporary. If T1 is
4608 // reference-related to T2, cv1 must be the same
4609 // cv-qualification as, or greater cv-qualification than,
4610 // cv2; otherwise, the program is ill-formed.
4611 if (RefRelationship == Sema::Ref_Related) {
4612 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4613 // we would be reference-compatible or reference-compatible with
4614 // added qualification. But that wasn't the case, so the reference
4615 // initialization fails.
4617 // Note that we only want to check address spaces and cvr-qualifiers here.
4618 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4619 Qualifiers T1Quals = T1.getQualifiers();
4620 Qualifiers T2Quals = T2.getQualifiers();
4621 T1Quals.removeObjCGCAttr();
4622 T1Quals.removeObjCLifetime();
4623 T2Quals.removeObjCGCAttr();
4624 T2Quals.removeObjCLifetime();
4625 // MS compiler ignores __unaligned qualifier for references; do the same.
4626 T1Quals.removeUnaligned();
4627 T2Quals.removeUnaligned();
4628 if (!T1Quals.compatiblyIncludes(T2Quals))
4632 // If at least one of the types is a class type, the types are not
4633 // related, and we aren't allowed any user conversions, the
4634 // reference binding fails. This case is important for breaking
4635 // recursion, since TryImplicitConversion below will attempt to
4636 // create a temporary through the use of a copy constructor.
4637 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4638 (T1->isRecordType() || T2->isRecordType()))
4641 // If T1 is reference-related to T2 and the reference is an rvalue
4642 // reference, the initializer expression shall not be an lvalue.
4643 if (RefRelationship >= Sema::Ref_Related &&
4644 isRValRef && Init->Classify(S.Context).isLValue())
4647 // C++ [over.ics.ref]p2:
4648 // When a parameter of reference type is not bound directly to
4649 // an argument expression, the conversion sequence is the one
4650 // required to convert the argument expression to the
4651 // underlying type of the reference according to
4652 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4653 // to copy-initializing a temporary of the underlying type with
4654 // the argument expression. Any difference in top-level
4655 // cv-qualification is subsumed by the initialization itself
4656 // and does not constitute a conversion.
4657 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4658 /*AllowExplicit=*/false,
4659 /*InOverloadResolution=*/false,
4661 /*AllowObjCWritebackConversion=*/false,
4662 /*AllowObjCConversionOnExplicit=*/false);
4664 // Of course, that's still a reference binding.
4665 if (ICS.isStandard()) {
4666 ICS.Standard.ReferenceBinding = true;
4667 ICS.Standard.IsLvalueReference = !isRValRef;
4668 ICS.Standard.BindsToFunctionLvalue = false;
4669 ICS.Standard.BindsToRvalue = true;
4670 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4671 ICS.Standard.ObjCLifetimeConversionBinding = false;
4672 } else if (ICS.isUserDefined()) {
4673 const ReferenceType *LValRefType =
4674 ICS.UserDefined.ConversionFunction->getReturnType()
4675 ->getAs<LValueReferenceType>();
4677 // C++ [over.ics.ref]p3:
4678 // Except for an implicit object parameter, for which see 13.3.1, a
4679 // standard conversion sequence cannot be formed if it requires [...]
4680 // binding an rvalue reference to an lvalue other than a function
4682 // Note that the function case is not possible here.
4683 if (DeclType->isRValueReferenceType() && LValRefType) {
4684 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4685 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4686 // reference to an rvalue!
4687 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4691 ICS.UserDefined.After.ReferenceBinding = true;
4692 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4693 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4694 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4695 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4696 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4702 static ImplicitConversionSequence
4703 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4704 bool SuppressUserConversions,
4705 bool InOverloadResolution,
4706 bool AllowObjCWritebackConversion,
4707 bool AllowExplicit = false);
4709 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4710 /// initializer list From.
4711 static ImplicitConversionSequence
4712 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4713 bool SuppressUserConversions,
4714 bool InOverloadResolution,
4715 bool AllowObjCWritebackConversion) {
4716 // C++11 [over.ics.list]p1:
4717 // When an argument is an initializer list, it is not an expression and
4718 // special rules apply for converting it to a parameter type.
4720 ImplicitConversionSequence Result;
4721 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4723 // We need a complete type for what follows. Incomplete types can never be
4724 // initialized from init lists.
4725 if (!S.isCompleteType(From->getLocStart(), ToType))
4729 // If the parameter type is a class X and the initializer list has a single
4730 // element of type cv U, where U is X or a class derived from X, the
4731 // implicit conversion sequence is the one required to convert the element
4732 // to the parameter type.
4734 // Otherwise, if the parameter type is a character array [... ]
4735 // and the initializer list has a single element that is an
4736 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4737 // implicit conversion sequence is the identity conversion.
4738 if (From->getNumInits() == 1) {
4739 if (ToType->isRecordType()) {
4740 QualType InitType = From->getInit(0)->getType();
4741 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4742 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4743 return TryCopyInitialization(S, From->getInit(0), ToType,
4744 SuppressUserConversions,
4745 InOverloadResolution,
4746 AllowObjCWritebackConversion);
4748 // FIXME: Check the other conditions here: array of character type,
4749 // initializer is a string literal.
4750 if (ToType->isArrayType()) {
4751 InitializedEntity Entity =
4752 InitializedEntity::InitializeParameter(S.Context, ToType,
4753 /*Consumed=*/false);
4754 if (S.CanPerformCopyInitialization(Entity, From)) {
4755 Result.setStandard();
4756 Result.Standard.setAsIdentityConversion();
4757 Result.Standard.setFromType(ToType);
4758 Result.Standard.setAllToTypes(ToType);
4764 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4765 // C++11 [over.ics.list]p2:
4766 // If the parameter type is std::initializer_list<X> or "array of X" and
4767 // all the elements can be implicitly converted to X, the implicit
4768 // conversion sequence is the worst conversion necessary to convert an
4769 // element of the list to X.
4771 // C++14 [over.ics.list]p3:
4772 // Otherwise, if the parameter type is "array of N X", if the initializer
4773 // list has exactly N elements or if it has fewer than N elements and X is
4774 // default-constructible, and if all the elements of the initializer list
4775 // can be implicitly converted to X, the implicit conversion sequence is
4776 // the worst conversion necessary to convert an element of the list to X.
4778 // FIXME: We're missing a lot of these checks.
4779 bool toStdInitializerList = false;
4781 if (ToType->isArrayType())
4782 X = S.Context.getAsArrayType(ToType)->getElementType();
4784 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4786 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4787 Expr *Init = From->getInit(i);
4788 ImplicitConversionSequence ICS =
4789 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4790 InOverloadResolution,
4791 AllowObjCWritebackConversion);
4792 // If a single element isn't convertible, fail.
4797 // Otherwise, look for the worst conversion.
4798 if (Result.isBad() ||
4799 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4801 ImplicitConversionSequence::Worse)
4805 // For an empty list, we won't have computed any conversion sequence.
4806 // Introduce the identity conversion sequence.
4807 if (From->getNumInits() == 0) {
4808 Result.setStandard();
4809 Result.Standard.setAsIdentityConversion();
4810 Result.Standard.setFromType(ToType);
4811 Result.Standard.setAllToTypes(ToType);
4814 Result.setStdInitializerListElement(toStdInitializerList);
4818 // C++14 [over.ics.list]p4:
4819 // C++11 [over.ics.list]p3:
4820 // Otherwise, if the parameter is a non-aggregate class X and overload
4821 // resolution chooses a single best constructor [...] the implicit
4822 // conversion sequence is a user-defined conversion sequence. If multiple
4823 // constructors are viable but none is better than the others, the
4824 // implicit conversion sequence is a user-defined conversion sequence.
4825 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4826 // This function can deal with initializer lists.
4827 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4828 /*AllowExplicit=*/false,
4829 InOverloadResolution, /*CStyle=*/false,
4830 AllowObjCWritebackConversion,
4831 /*AllowObjCConversionOnExplicit=*/false);
4834 // C++14 [over.ics.list]p5:
4835 // C++11 [over.ics.list]p4:
4836 // Otherwise, if the parameter has an aggregate type which can be
4837 // initialized from the initializer list [...] the implicit conversion
4838 // sequence is a user-defined conversion sequence.
4839 if (ToType->isAggregateType()) {
4840 // Type is an aggregate, argument is an init list. At this point it comes
4841 // down to checking whether the initialization works.
4842 // FIXME: Find out whether this parameter is consumed or not.
4843 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4844 // need to call into the initialization code here; overload resolution
4845 // should not be doing that.
4846 InitializedEntity Entity =
4847 InitializedEntity::InitializeParameter(S.Context, ToType,
4848 /*Consumed=*/false);
4849 if (S.CanPerformCopyInitialization(Entity, From)) {
4850 Result.setUserDefined();
4851 Result.UserDefined.Before.setAsIdentityConversion();
4852 // Initializer lists don't have a type.
4853 Result.UserDefined.Before.setFromType(QualType());
4854 Result.UserDefined.Before.setAllToTypes(QualType());
4856 Result.UserDefined.After.setAsIdentityConversion();
4857 Result.UserDefined.After.setFromType(ToType);
4858 Result.UserDefined.After.setAllToTypes(ToType);
4859 Result.UserDefined.ConversionFunction = nullptr;
4864 // C++14 [over.ics.list]p6:
4865 // C++11 [over.ics.list]p5:
4866 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4867 if (ToType->isReferenceType()) {
4868 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4869 // mention initializer lists in any way. So we go by what list-
4870 // initialization would do and try to extrapolate from that.
4872 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4874 // If the initializer list has a single element that is reference-related
4875 // to the parameter type, we initialize the reference from that.
4876 if (From->getNumInits() == 1) {
4877 Expr *Init = From->getInit(0);
4879 QualType T2 = Init->getType();
4881 // If the initializer is the address of an overloaded function, try
4882 // to resolve the overloaded function. If all goes well, T2 is the
4883 // type of the resulting function.
4884 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4885 DeclAccessPair Found;
4886 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4887 Init, ToType, false, Found))
4891 // Compute some basic properties of the types and the initializer.
4892 bool dummy1 = false;
4893 bool dummy2 = false;
4894 bool dummy3 = false;
4895 Sema::ReferenceCompareResult RefRelationship
4896 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4899 if (RefRelationship >= Sema::Ref_Related) {
4900 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4901 SuppressUserConversions,
4902 /*AllowExplicit=*/false);
4906 // Otherwise, we bind the reference to a temporary created from the
4907 // initializer list.
4908 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4909 InOverloadResolution,
4910 AllowObjCWritebackConversion);
4911 if (Result.isFailure())
4913 assert(!Result.isEllipsis() &&
4914 "Sub-initialization cannot result in ellipsis conversion.");
4916 // Can we even bind to a temporary?
4917 if (ToType->isRValueReferenceType() ||
4918 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4919 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4920 Result.UserDefined.After;
4921 SCS.ReferenceBinding = true;
4922 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4923 SCS.BindsToRvalue = true;
4924 SCS.BindsToFunctionLvalue = false;
4925 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4926 SCS.ObjCLifetimeConversionBinding = false;
4928 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4933 // C++14 [over.ics.list]p7:
4934 // C++11 [over.ics.list]p6:
4935 // Otherwise, if the parameter type is not a class:
4936 if (!ToType->isRecordType()) {
4937 // - if the initializer list has one element that is not itself an
4938 // initializer list, the implicit conversion sequence is the one
4939 // required to convert the element to the parameter type.
4940 unsigned NumInits = From->getNumInits();
4941 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4942 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4943 SuppressUserConversions,
4944 InOverloadResolution,
4945 AllowObjCWritebackConversion);
4946 // - if the initializer list has no elements, the implicit conversion
4947 // sequence is the identity conversion.
4948 else if (NumInits == 0) {
4949 Result.setStandard();
4950 Result.Standard.setAsIdentityConversion();
4951 Result.Standard.setFromType(ToType);
4952 Result.Standard.setAllToTypes(ToType);
4957 // C++14 [over.ics.list]p8:
4958 // C++11 [over.ics.list]p7:
4959 // In all cases other than those enumerated above, no conversion is possible
4963 /// TryCopyInitialization - Try to copy-initialize a value of type
4964 /// ToType from the expression From. Return the implicit conversion
4965 /// sequence required to pass this argument, which may be a bad
4966 /// conversion sequence (meaning that the argument cannot be passed to
4967 /// a parameter of this type). If @p SuppressUserConversions, then we
4968 /// do not permit any user-defined conversion sequences.
4969 static ImplicitConversionSequence
4970 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4971 bool SuppressUserConversions,
4972 bool InOverloadResolution,
4973 bool AllowObjCWritebackConversion,
4974 bool AllowExplicit) {
4975 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4976 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4977 InOverloadResolution,AllowObjCWritebackConversion);
4979 if (ToType->isReferenceType())
4980 return TryReferenceInit(S, From, ToType,
4981 /*FIXME:*/From->getLocStart(),
4982 SuppressUserConversions,
4985 return TryImplicitConversion(S, From, ToType,
4986 SuppressUserConversions,
4987 /*AllowExplicit=*/false,
4988 InOverloadResolution,
4990 AllowObjCWritebackConversion,
4991 /*AllowObjCConversionOnExplicit=*/false);
4994 static bool TryCopyInitialization(const CanQualType FromQTy,
4995 const CanQualType ToQTy,
4998 ExprValueKind FromVK) {
4999 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5000 ImplicitConversionSequence ICS =
5001 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5003 return !ICS.isBad();
5006 /// TryObjectArgumentInitialization - Try to initialize the object
5007 /// parameter of the given member function (@c Method) from the
5008 /// expression @p From.
5009 static ImplicitConversionSequence
5010 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5011 Expr::Classification FromClassification,
5012 CXXMethodDecl *Method,
5013 CXXRecordDecl *ActingContext) {
5014 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5015 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5016 // const volatile object.
5017 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5018 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5019 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
5021 // Set up the conversion sequence as a "bad" conversion, to allow us
5023 ImplicitConversionSequence ICS;
5025 // We need to have an object of class type.
5026 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5027 FromType = PT->getPointeeType();
5029 // When we had a pointer, it's implicitly dereferenced, so we
5030 // better have an lvalue.
5031 assert(FromClassification.isLValue());
5034 assert(FromType->isRecordType());
5036 // C++0x [over.match.funcs]p4:
5037 // For non-static member functions, the type of the implicit object
5040 // - "lvalue reference to cv X" for functions declared without a
5041 // ref-qualifier or with the & ref-qualifier
5042 // - "rvalue reference to cv X" for functions declared with the &&
5045 // where X is the class of which the function is a member and cv is the
5046 // cv-qualification on the member function declaration.
5048 // However, when finding an implicit conversion sequence for the argument, we
5049 // are not allowed to perform user-defined conversions
5050 // (C++ [over.match.funcs]p5). We perform a simplified version of
5051 // reference binding here, that allows class rvalues to bind to
5052 // non-constant references.
5054 // First check the qualifiers.
5055 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5056 if (ImplicitParamType.getCVRQualifiers()
5057 != FromTypeCanon.getLocalCVRQualifiers() &&
5058 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5059 ICS.setBad(BadConversionSequence::bad_qualifiers,
5060 FromType, ImplicitParamType);
5064 // Check that we have either the same type or a derived type. It
5065 // affects the conversion rank.
5066 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5067 ImplicitConversionKind SecondKind;
5068 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5069 SecondKind = ICK_Identity;
5070 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5071 SecondKind = ICK_Derived_To_Base;
5073 ICS.setBad(BadConversionSequence::unrelated_class,
5074 FromType, ImplicitParamType);
5078 // Check the ref-qualifier.
5079 switch (Method->getRefQualifier()) {
5081 // Do nothing; we don't care about lvalueness or rvalueness.
5085 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5086 // non-const lvalue reference cannot bind to an rvalue
5087 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5094 if (!FromClassification.isRValue()) {
5095 // rvalue reference cannot bind to an lvalue
5096 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5103 // Success. Mark this as a reference binding.
5105 ICS.Standard.setAsIdentityConversion();
5106 ICS.Standard.Second = SecondKind;
5107 ICS.Standard.setFromType(FromType);
5108 ICS.Standard.setAllToTypes(ImplicitParamType);
5109 ICS.Standard.ReferenceBinding = true;
5110 ICS.Standard.DirectBinding = true;
5111 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5112 ICS.Standard.BindsToFunctionLvalue = false;
5113 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5114 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5115 = (Method->getRefQualifier() == RQ_None);
5119 /// PerformObjectArgumentInitialization - Perform initialization of
5120 /// the implicit object parameter for the given Method with the given
5123 Sema::PerformObjectArgumentInitialization(Expr *From,
5124 NestedNameSpecifier *Qualifier,
5125 NamedDecl *FoundDecl,
5126 CXXMethodDecl *Method) {
5127 QualType FromRecordType, DestType;
5128 QualType ImplicitParamRecordType =
5129 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5131 Expr::Classification FromClassification;
5132 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5133 FromRecordType = PT->getPointeeType();
5134 DestType = Method->getThisType(Context);
5135 FromClassification = Expr::Classification::makeSimpleLValue();
5137 FromRecordType = From->getType();
5138 DestType = ImplicitParamRecordType;
5139 FromClassification = From->Classify(Context);
5142 // Note that we always use the true parent context when performing
5143 // the actual argument initialization.
5144 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5145 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5146 Method->getParent());
5148 switch (ICS.Bad.Kind) {
5149 case BadConversionSequence::bad_qualifiers: {
5150 Qualifiers FromQs = FromRecordType.getQualifiers();
5151 Qualifiers ToQs = DestType.getQualifiers();
5152 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5154 Diag(From->getLocStart(),
5155 diag::err_member_function_call_bad_cvr)
5156 << Method->getDeclName() << FromRecordType << (CVR - 1)
5157 << From->getSourceRange();
5158 Diag(Method->getLocation(), diag::note_previous_decl)
5159 << Method->getDeclName();
5165 case BadConversionSequence::lvalue_ref_to_rvalue:
5166 case BadConversionSequence::rvalue_ref_to_lvalue: {
5167 bool IsRValueQualified =
5168 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5169 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5170 << Method->getDeclName() << FromClassification.isRValue()
5171 << IsRValueQualified;
5172 Diag(Method->getLocation(), diag::note_previous_decl)
5173 << Method->getDeclName();
5177 case BadConversionSequence::no_conversion:
5178 case BadConversionSequence::unrelated_class:
5182 return Diag(From->getLocStart(),
5183 diag::err_member_function_call_bad_type)
5184 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5187 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5188 ExprResult FromRes =
5189 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5190 if (FromRes.isInvalid())
5192 From = FromRes.get();
5195 if (!Context.hasSameType(From->getType(), DestType))
5196 From = ImpCastExprToType(From, DestType, CK_NoOp,
5197 From->getValueKind()).get();
5201 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5202 /// expression From to bool (C++0x [conv]p3).
5203 static ImplicitConversionSequence
5204 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5205 return TryImplicitConversion(S, From, S.Context.BoolTy,
5206 /*SuppressUserConversions=*/false,
5207 /*AllowExplicit=*/true,
5208 /*InOverloadResolution=*/false,
5210 /*AllowObjCWritebackConversion=*/false,
5211 /*AllowObjCConversionOnExplicit=*/false);
5214 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5215 /// of the expression From to bool (C++0x [conv]p3).
5216 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5217 if (checkPlaceholderForOverload(*this, From))
5220 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5222 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5224 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5225 return Diag(From->getLocStart(),
5226 diag::err_typecheck_bool_condition)
5227 << From->getType() << From->getSourceRange();
5231 /// Check that the specified conversion is permitted in a converted constant
5232 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5234 static bool CheckConvertedConstantConversions(Sema &S,
5235 StandardConversionSequence &SCS) {
5236 // Since we know that the target type is an integral or unscoped enumeration
5237 // type, most conversion kinds are impossible. All possible First and Third
5238 // conversions are fine.
5239 switch (SCS.Second) {
5241 case ICK_Function_Conversion:
5242 case ICK_Integral_Promotion:
5243 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5244 case ICK_Zero_Queue_Conversion:
5247 case ICK_Boolean_Conversion:
5248 // Conversion from an integral or unscoped enumeration type to bool is
5249 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5250 // conversion, so we allow it in a converted constant expression.
5252 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5253 // a lot of popular code. We should at least add a warning for this
5254 // (non-conforming) extension.
5255 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5256 SCS.getToType(2)->isBooleanType();
5258 case ICK_Pointer_Conversion:
5259 case ICK_Pointer_Member:
5260 // C++1z: null pointer conversions and null member pointer conversions are
5261 // only permitted if the source type is std::nullptr_t.
5262 return SCS.getFromType()->isNullPtrType();
5264 case ICK_Floating_Promotion:
5265 case ICK_Complex_Promotion:
5266 case ICK_Floating_Conversion:
5267 case ICK_Complex_Conversion:
5268 case ICK_Floating_Integral:
5269 case ICK_Compatible_Conversion:
5270 case ICK_Derived_To_Base:
5271 case ICK_Vector_Conversion:
5272 case ICK_Vector_Splat:
5273 case ICK_Complex_Real:
5274 case ICK_Block_Pointer_Conversion:
5275 case ICK_TransparentUnionConversion:
5276 case ICK_Writeback_Conversion:
5277 case ICK_Zero_Event_Conversion:
5278 case ICK_C_Only_Conversion:
5279 case ICK_Incompatible_Pointer_Conversion:
5282 case ICK_Lvalue_To_Rvalue:
5283 case ICK_Array_To_Pointer:
5284 case ICK_Function_To_Pointer:
5285 llvm_unreachable("found a first conversion kind in Second");
5287 case ICK_Qualification:
5288 llvm_unreachable("found a third conversion kind in Second");
5290 case ICK_Num_Conversion_Kinds:
5294 llvm_unreachable("unknown conversion kind");
5297 /// CheckConvertedConstantExpression - Check that the expression From is a
5298 /// converted constant expression of type T, perform the conversion and produce
5299 /// the converted expression, per C++11 [expr.const]p3.
5300 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5301 QualType T, APValue &Value,
5304 assert(S.getLangOpts().CPlusPlus11 &&
5305 "converted constant expression outside C++11");
5307 if (checkPlaceholderForOverload(S, From))
5310 // C++1z [expr.const]p3:
5311 // A converted constant expression of type T is an expression,
5312 // implicitly converted to type T, where the converted
5313 // expression is a constant expression and the implicit conversion
5314 // sequence contains only [... list of conversions ...].
5315 // C++1z [stmt.if]p2:
5316 // If the if statement is of the form if constexpr, the value of the
5317 // condition shall be a contextually converted constant expression of type
5319 ImplicitConversionSequence ICS =
5320 CCE == Sema::CCEK_ConstexprIf
5321 ? TryContextuallyConvertToBool(S, From)
5322 : TryCopyInitialization(S, From, T,
5323 /*SuppressUserConversions=*/false,
5324 /*InOverloadResolution=*/false,
5325 /*AllowObjcWritebackConversion=*/false,
5326 /*AllowExplicit=*/false);
5327 StandardConversionSequence *SCS = nullptr;
5328 switch (ICS.getKind()) {
5329 case ImplicitConversionSequence::StandardConversion:
5330 SCS = &ICS.Standard;
5332 case ImplicitConversionSequence::UserDefinedConversion:
5333 // We are converting to a non-class type, so the Before sequence
5335 SCS = &ICS.UserDefined.After;
5337 case ImplicitConversionSequence::AmbiguousConversion:
5338 case ImplicitConversionSequence::BadConversion:
5339 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5340 return S.Diag(From->getLocStart(),
5341 diag::err_typecheck_converted_constant_expression)
5342 << From->getType() << From->getSourceRange() << T;
5345 case ImplicitConversionSequence::EllipsisConversion:
5346 llvm_unreachable("ellipsis conversion in converted constant expression");
5349 // Check that we would only use permitted conversions.
5350 if (!CheckConvertedConstantConversions(S, *SCS)) {
5351 return S.Diag(From->getLocStart(),
5352 diag::err_typecheck_converted_constant_expression_disallowed)
5353 << From->getType() << From->getSourceRange() << T;
5355 // [...] and where the reference binding (if any) binds directly.
5356 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5357 return S.Diag(From->getLocStart(),
5358 diag::err_typecheck_converted_constant_expression_indirect)
5359 << From->getType() << From->getSourceRange() << T;
5363 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5364 if (Result.isInvalid())
5367 // Check for a narrowing implicit conversion.
5368 APValue PreNarrowingValue;
5369 QualType PreNarrowingType;
5370 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5371 PreNarrowingType)) {
5372 case NK_Dependent_Narrowing:
5373 // Implicit conversion to a narrower type, but the expression is
5374 // value-dependent so we can't tell whether it's actually narrowing.
5375 case NK_Variable_Narrowing:
5376 // Implicit conversion to a narrower type, and the value is not a constant
5377 // expression. We'll diagnose this in a moment.
5378 case NK_Not_Narrowing:
5381 case NK_Constant_Narrowing:
5382 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5383 << CCE << /*Constant*/1
5384 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5387 case NK_Type_Narrowing:
5388 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5389 << CCE << /*Constant*/0 << From->getType() << T;
5393 if (Result.get()->isValueDependent()) {
5398 // Check the expression is a constant expression.
5399 SmallVector<PartialDiagnosticAt, 8> Notes;
5400 Expr::EvalResult Eval;
5403 if ((T->isReferenceType()
5404 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5405 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5406 (RequireInt && !Eval.Val.isInt())) {
5407 // The expression can't be folded, so we can't keep it at this position in
5409 Result = ExprError();
5413 if (Notes.empty()) {
5414 // It's a constant expression.
5419 // It's not a constant expression. Produce an appropriate diagnostic.
5420 if (Notes.size() == 1 &&
5421 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5422 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5424 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5425 << CCE << From->getSourceRange();
5426 for (unsigned I = 0; I < Notes.size(); ++I)
5427 S.Diag(Notes[I].first, Notes[I].second);
5432 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5433 APValue &Value, CCEKind CCE) {
5434 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5437 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5438 llvm::APSInt &Value,
5440 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5443 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5444 if (!R.isInvalid() && !R.get()->isValueDependent())
5450 /// dropPointerConversions - If the given standard conversion sequence
5451 /// involves any pointer conversions, remove them. This may change
5452 /// the result type of the conversion sequence.
5453 static void dropPointerConversion(StandardConversionSequence &SCS) {
5454 if (SCS.Second == ICK_Pointer_Conversion) {
5455 SCS.Second = ICK_Identity;
5456 SCS.Third = ICK_Identity;
5457 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5461 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5462 /// convert the expression From to an Objective-C pointer type.
5463 static ImplicitConversionSequence
5464 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5465 // Do an implicit conversion to 'id'.
5466 QualType Ty = S.Context.getObjCIdType();
5467 ImplicitConversionSequence ICS
5468 = TryImplicitConversion(S, From, Ty,
5469 // FIXME: Are these flags correct?
5470 /*SuppressUserConversions=*/false,
5471 /*AllowExplicit=*/true,
5472 /*InOverloadResolution=*/false,
5474 /*AllowObjCWritebackConversion=*/false,
5475 /*AllowObjCConversionOnExplicit=*/true);
5477 // Strip off any final conversions to 'id'.
5478 switch (ICS.getKind()) {
5479 case ImplicitConversionSequence::BadConversion:
5480 case ImplicitConversionSequence::AmbiguousConversion:
5481 case ImplicitConversionSequence::EllipsisConversion:
5484 case ImplicitConversionSequence::UserDefinedConversion:
5485 dropPointerConversion(ICS.UserDefined.After);
5488 case ImplicitConversionSequence::StandardConversion:
5489 dropPointerConversion(ICS.Standard);
5496 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5497 /// conversion of the expression From to an Objective-C pointer type.
5498 /// Returns a valid but null ExprResult if no conversion sequence exists.
5499 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5500 if (checkPlaceholderForOverload(*this, From))
5503 QualType Ty = Context.getObjCIdType();
5504 ImplicitConversionSequence ICS =
5505 TryContextuallyConvertToObjCPointer(*this, From);
5507 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5508 return ExprResult();
5511 /// Determine whether the provided type is an integral type, or an enumeration
5512 /// type of a permitted flavor.
5513 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5514 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5515 : T->isIntegralOrUnscopedEnumerationType();
5519 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5520 Sema::ContextualImplicitConverter &Converter,
5521 QualType T, UnresolvedSetImpl &ViableConversions) {
5523 if (Converter.Suppress)
5526 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5527 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5528 CXXConversionDecl *Conv =
5529 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5530 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5531 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5537 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5538 Sema::ContextualImplicitConverter &Converter,
5539 QualType T, bool HadMultipleCandidates,
5540 UnresolvedSetImpl &ExplicitConversions) {
5541 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5542 DeclAccessPair Found = ExplicitConversions[0];
5543 CXXConversionDecl *Conversion =
5544 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5546 // The user probably meant to invoke the given explicit
5547 // conversion; use it.
5548 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5549 std::string TypeStr;
5550 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5552 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5553 << FixItHint::CreateInsertion(From->getLocStart(),
5554 "static_cast<" + TypeStr + ">(")
5555 << FixItHint::CreateInsertion(
5556 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5557 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5559 // If we aren't in a SFINAE context, build a call to the
5560 // explicit conversion function.
5561 if (SemaRef.isSFINAEContext())
5564 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5565 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5566 HadMultipleCandidates);
5567 if (Result.isInvalid())
5569 // Record usage of conversion in an implicit cast.
5570 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5571 CK_UserDefinedConversion, Result.get(),
5572 nullptr, Result.get()->getValueKind());
5577 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5578 Sema::ContextualImplicitConverter &Converter,
5579 QualType T, bool HadMultipleCandidates,
5580 DeclAccessPair &Found) {
5581 CXXConversionDecl *Conversion =
5582 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5583 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5585 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5586 if (!Converter.SuppressConversion) {
5587 if (SemaRef.isSFINAEContext())
5590 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5591 << From->getSourceRange();
5594 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5595 HadMultipleCandidates);
5596 if (Result.isInvalid())
5598 // Record usage of conversion in an implicit cast.
5599 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5600 CK_UserDefinedConversion, Result.get(),
5601 nullptr, Result.get()->getValueKind());
5605 static ExprResult finishContextualImplicitConversion(
5606 Sema &SemaRef, SourceLocation Loc, Expr *From,
5607 Sema::ContextualImplicitConverter &Converter) {
5608 if (!Converter.match(From->getType()) && !Converter.Suppress)
5609 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5610 << From->getSourceRange();
5612 return SemaRef.DefaultLvalueConversion(From);
5616 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5617 UnresolvedSetImpl &ViableConversions,
5618 OverloadCandidateSet &CandidateSet) {
5619 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5620 DeclAccessPair FoundDecl = ViableConversions[I];
5621 NamedDecl *D = FoundDecl.getDecl();
5622 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5623 if (isa<UsingShadowDecl>(D))
5624 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5626 CXXConversionDecl *Conv;
5627 FunctionTemplateDecl *ConvTemplate;
5628 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5629 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5631 Conv = cast<CXXConversionDecl>(D);
5634 SemaRef.AddTemplateConversionCandidate(
5635 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5636 /*AllowObjCConversionOnExplicit=*/false);
5638 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5639 ToType, CandidateSet,
5640 /*AllowObjCConversionOnExplicit=*/false);
5644 /// \brief Attempt to convert the given expression to a type which is accepted
5645 /// by the given converter.
5647 /// This routine will attempt to convert an expression of class type to a
5648 /// type accepted by the specified converter. In C++11 and before, the class
5649 /// must have a single non-explicit conversion function converting to a matching
5650 /// type. In C++1y, there can be multiple such conversion functions, but only
5651 /// one target type.
5653 /// \param Loc The source location of the construct that requires the
5656 /// \param From The expression we're converting from.
5658 /// \param Converter Used to control and diagnose the conversion process.
5660 /// \returns The expression, converted to an integral or enumeration type if
5662 ExprResult Sema::PerformContextualImplicitConversion(
5663 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5664 // We can't perform any more checking for type-dependent expressions.
5665 if (From->isTypeDependent())
5668 // Process placeholders immediately.
5669 if (From->hasPlaceholderType()) {
5670 ExprResult result = CheckPlaceholderExpr(From);
5671 if (result.isInvalid())
5673 From = result.get();
5676 // If the expression already has a matching type, we're golden.
5677 QualType T = From->getType();
5678 if (Converter.match(T))
5679 return DefaultLvalueConversion(From);
5681 // FIXME: Check for missing '()' if T is a function type?
5683 // We can only perform contextual implicit conversions on objects of class
5685 const RecordType *RecordTy = T->getAs<RecordType>();
5686 if (!RecordTy || !getLangOpts().CPlusPlus) {
5687 if (!Converter.Suppress)
5688 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5692 // We must have a complete class type.
5693 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5694 ContextualImplicitConverter &Converter;
5697 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5698 : Converter(Converter), From(From) {}
5700 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5701 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5703 } IncompleteDiagnoser(Converter, From);
5705 if (Converter.Suppress ? !isCompleteType(Loc, T)
5706 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5709 // Look for a conversion to an integral or enumeration type.
5711 ViableConversions; // These are *potentially* viable in C++1y.
5712 UnresolvedSet<4> ExplicitConversions;
5713 const auto &Conversions =
5714 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5716 bool HadMultipleCandidates =
5717 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5719 // To check that there is only one target type, in C++1y:
5721 bool HasUniqueTargetType = true;
5723 // Collect explicit or viable (potentially in C++1y) conversions.
5724 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5725 NamedDecl *D = (*I)->getUnderlyingDecl();
5726 CXXConversionDecl *Conversion;
5727 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5729 if (getLangOpts().CPlusPlus14)
5730 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5732 continue; // C++11 does not consider conversion operator templates(?).
5734 Conversion = cast<CXXConversionDecl>(D);
5736 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5737 "Conversion operator templates are considered potentially "
5740 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5741 if (Converter.match(CurToType) || ConvTemplate) {
5743 if (Conversion->isExplicit()) {
5744 // FIXME: For C++1y, do we need this restriction?
5745 // cf. diagnoseNoViableConversion()
5747 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5749 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5750 if (ToType.isNull())
5751 ToType = CurToType.getUnqualifiedType();
5752 else if (HasUniqueTargetType &&
5753 (CurToType.getUnqualifiedType() != ToType))
5754 HasUniqueTargetType = false;
5756 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5761 if (getLangOpts().CPlusPlus14) {
5763 // ... An expression e of class type E appearing in such a context
5764 // is said to be contextually implicitly converted to a specified
5765 // type T and is well-formed if and only if e can be implicitly
5766 // converted to a type T that is determined as follows: E is searched
5767 // for conversion functions whose return type is cv T or reference to
5768 // cv T such that T is allowed by the context. There shall be
5769 // exactly one such T.
5771 // If no unique T is found:
5772 if (ToType.isNull()) {
5773 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5774 HadMultipleCandidates,
5775 ExplicitConversions))
5777 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5780 // If more than one unique Ts are found:
5781 if (!HasUniqueTargetType)
5782 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5785 // If one unique T is found:
5786 // First, build a candidate set from the previously recorded
5787 // potentially viable conversions.
5788 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5789 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5792 // Then, perform overload resolution over the candidate set.
5793 OverloadCandidateSet::iterator Best;
5794 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5796 // Apply this conversion.
5797 DeclAccessPair Found =
5798 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5799 if (recordConversion(*this, Loc, From, Converter, T,
5800 HadMultipleCandidates, Found))
5805 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5807 case OR_No_Viable_Function:
5808 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5809 HadMultipleCandidates,
5810 ExplicitConversions))
5814 // We'll complain below about a non-integral condition type.
5818 switch (ViableConversions.size()) {
5820 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5821 HadMultipleCandidates,
5822 ExplicitConversions))
5825 // We'll complain below about a non-integral condition type.
5829 // Apply this conversion.
5830 DeclAccessPair Found = ViableConversions[0];
5831 if (recordConversion(*this, Loc, From, Converter, T,
5832 HadMultipleCandidates, Found))
5837 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5842 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5845 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5846 /// an acceptable non-member overloaded operator for a call whose
5847 /// arguments have types T1 (and, if non-empty, T2). This routine
5848 /// implements the check in C++ [over.match.oper]p3b2 concerning
5849 /// enumeration types.
5850 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5852 ArrayRef<Expr *> Args) {
5853 QualType T1 = Args[0]->getType();
5854 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5856 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5859 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5862 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5863 if (Proto->getNumParams() < 1)
5866 if (T1->isEnumeralType()) {
5867 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5868 if (Context.hasSameUnqualifiedType(T1, ArgType))
5872 if (Proto->getNumParams() < 2)
5875 if (!T2.isNull() && T2->isEnumeralType()) {
5876 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5877 if (Context.hasSameUnqualifiedType(T2, ArgType))
5884 /// AddOverloadCandidate - Adds the given function to the set of
5885 /// candidate functions, using the given function call arguments. If
5886 /// @p SuppressUserConversions, then don't allow user-defined
5887 /// conversions via constructors or conversion operators.
5889 /// \param PartialOverloading true if we are performing "partial" overloading
5890 /// based on an incomplete set of function arguments. This feature is used by
5891 /// code completion.
5893 Sema::AddOverloadCandidate(FunctionDecl *Function,
5894 DeclAccessPair FoundDecl,
5895 ArrayRef<Expr *> Args,
5896 OverloadCandidateSet &CandidateSet,
5897 bool SuppressUserConversions,
5898 bool PartialOverloading,
5900 ConversionSequenceList EarlyConversions) {
5901 const FunctionProtoType *Proto
5902 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5903 assert(Proto && "Functions without a prototype cannot be overloaded");
5904 assert(!Function->getDescribedFunctionTemplate() &&
5905 "Use AddTemplateOverloadCandidate for function templates");
5907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5908 if (!isa<CXXConstructorDecl>(Method)) {
5909 // If we get here, it's because we're calling a member function
5910 // that is named without a member access expression (e.g.,
5911 // "this->f") that was either written explicitly or created
5912 // implicitly. This can happen with a qualified call to a member
5913 // function, e.g., X::f(). We use an empty type for the implied
5914 // object argument (C++ [over.call.func]p3), and the acting context
5916 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5917 Expr::Classification::makeSimpleLValue(), Args,
5918 CandidateSet, SuppressUserConversions,
5919 PartialOverloading, EarlyConversions);
5922 // We treat a constructor like a non-member function, since its object
5923 // argument doesn't participate in overload resolution.
5926 if (!CandidateSet.isNewCandidate(Function))
5929 // C++ [over.match.oper]p3:
5930 // if no operand has a class type, only those non-member functions in the
5931 // lookup set that have a first parameter of type T1 or "reference to
5932 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5933 // is a right operand) a second parameter of type T2 or "reference to
5934 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5935 // candidate functions.
5936 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5937 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5940 // C++11 [class.copy]p11: [DR1402]
5941 // A defaulted move constructor that is defined as deleted is ignored by
5942 // overload resolution.
5943 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5944 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5945 Constructor->isMoveConstructor())
5948 // Overload resolution is always an unevaluated context.
5949 EnterExpressionEvaluationContext Unevaluated(
5950 *this, Sema::ExpressionEvaluationContext::Unevaluated);
5952 // Add this candidate
5953 OverloadCandidate &Candidate =
5954 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5955 Candidate.FoundDecl = FoundDecl;
5956 Candidate.Function = Function;
5957 Candidate.Viable = true;
5958 Candidate.IsSurrogate = false;
5959 Candidate.IgnoreObjectArgument = false;
5960 Candidate.ExplicitCallArguments = Args.size();
5963 // C++ [class.copy]p3:
5964 // A member function template is never instantiated to perform the copy
5965 // of a class object to an object of its class type.
5966 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5967 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5968 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5969 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5971 Candidate.Viable = false;
5972 Candidate.FailureKind = ovl_fail_illegal_constructor;
5976 // C++ [over.match.funcs]p8: (proposed DR resolution)
5977 // A constructor inherited from class type C that has a first parameter
5978 // of type "reference to P" (including such a constructor instantiated
5979 // from a template) is excluded from the set of candidate functions when
5980 // constructing an object of type cv D if the argument list has exactly
5981 // one argument and D is reference-related to P and P is reference-related
5983 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5984 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5985 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5986 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5987 QualType C = Context.getRecordType(Constructor->getParent());
5988 QualType D = Context.getRecordType(Shadow->getParent());
5989 SourceLocation Loc = Args.front()->getExprLoc();
5990 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5991 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5992 Candidate.Viable = false;
5993 Candidate.FailureKind = ovl_fail_inhctor_slice;
5999 unsigned NumParams = Proto->getNumParams();
6001 // (C++ 13.3.2p2): A candidate function having fewer than m
6002 // parameters is viable only if it has an ellipsis in its parameter
6004 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6005 !Proto->isVariadic()) {
6006 Candidate.Viable = false;
6007 Candidate.FailureKind = ovl_fail_too_many_arguments;
6011 // (C++ 13.3.2p2): A candidate function having more than m parameters
6012 // is viable only if the (m+1)st parameter has a default argument
6013 // (8.3.6). For the purposes of overload resolution, the
6014 // parameter list is truncated on the right, so that there are
6015 // exactly m parameters.
6016 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6017 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6018 // Not enough arguments.
6019 Candidate.Viable = false;
6020 Candidate.FailureKind = ovl_fail_too_few_arguments;
6024 // (CUDA B.1): Check for invalid calls between targets.
6025 if (getLangOpts().CUDA)
6026 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6027 // Skip the check for callers that are implicit members, because in this
6028 // case we may not yet know what the member's target is; the target is
6029 // inferred for the member automatically, based on the bases and fields of
6031 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6032 Candidate.Viable = false;
6033 Candidate.FailureKind = ovl_fail_bad_target;
6037 // Determine the implicit conversion sequences for each of the
6039 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6040 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6041 // We already formed a conversion sequence for this parameter during
6042 // template argument deduction.
6043 } else if (ArgIdx < NumParams) {
6044 // (C++ 13.3.2p3): for F to be a viable function, there shall
6045 // exist for each argument an implicit conversion sequence
6046 // (13.3.3.1) that converts that argument to the corresponding
6048 QualType ParamType = Proto->getParamType(ArgIdx);
6049 Candidate.Conversions[ArgIdx]
6050 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6051 SuppressUserConversions,
6052 /*InOverloadResolution=*/true,
6053 /*AllowObjCWritebackConversion=*/
6054 getLangOpts().ObjCAutoRefCount,
6056 if (Candidate.Conversions[ArgIdx].isBad()) {
6057 Candidate.Viable = false;
6058 Candidate.FailureKind = ovl_fail_bad_conversion;
6062 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6063 // argument for which there is no corresponding parameter is
6064 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6065 Candidate.Conversions[ArgIdx].setEllipsis();
6069 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6070 Candidate.Viable = false;
6071 Candidate.FailureKind = ovl_fail_enable_if;
6072 Candidate.DeductionFailure.Data = FailedAttr;
6076 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6077 Candidate.Viable = false;
6078 Candidate.FailureKind = ovl_fail_ext_disabled;
6084 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6085 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6086 if (Methods.size() <= 1)
6089 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6091 ObjCMethodDecl *Method = Methods[b];
6092 unsigned NumNamedArgs = Sel.getNumArgs();
6093 // Method might have more arguments than selector indicates. This is due
6094 // to addition of c-style arguments in method.
6095 if (Method->param_size() > NumNamedArgs)
6096 NumNamedArgs = Method->param_size();
6097 if (Args.size() < NumNamedArgs)
6100 for (unsigned i = 0; i < NumNamedArgs; i++) {
6101 // We can't do any type-checking on a type-dependent argument.
6102 if (Args[i]->isTypeDependent()) {
6107 ParmVarDecl *param = Method->parameters()[i];
6108 Expr *argExpr = Args[i];
6109 assert(argExpr && "SelectBestMethod(): missing expression");
6111 // Strip the unbridged-cast placeholder expression off unless it's
6112 // a consumed argument.
6113 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6114 !param->hasAttr<CFConsumedAttr>())
6115 argExpr = stripARCUnbridgedCast(argExpr);
6117 // If the parameter is __unknown_anytype, move on to the next method.
6118 if (param->getType() == Context.UnknownAnyTy) {
6123 ImplicitConversionSequence ConversionState
6124 = TryCopyInitialization(*this, argExpr, param->getType(),
6125 /*SuppressUserConversions*/false,
6126 /*InOverloadResolution=*/true,
6127 /*AllowObjCWritebackConversion=*/
6128 getLangOpts().ObjCAutoRefCount,
6129 /*AllowExplicit*/false);
6130 // This function looks for a reasonably-exact match, so we consider
6131 // incompatible pointer conversions to be a failure here.
6132 if (ConversionState.isBad() ||
6133 (ConversionState.isStandard() &&
6134 ConversionState.Standard.Second ==
6135 ICK_Incompatible_Pointer_Conversion)) {
6140 // Promote additional arguments to variadic methods.
6141 if (Match && Method->isVariadic()) {
6142 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6143 if (Args[i]->isTypeDependent()) {
6147 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6149 if (Arg.isInvalid()) {
6155 // Check for extra arguments to non-variadic methods.
6156 if (Args.size() != NumNamedArgs)
6158 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6159 // Special case when selectors have no argument. In this case, select
6160 // one with the most general result type of 'id'.
6161 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6162 QualType ReturnT = Methods[b]->getReturnType();
6163 if (ReturnT->isObjCIdType())
6175 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6176 // enable_if is order-sensitive. As a result, we need to reverse things
6177 // sometimes. Size of 4 elements is arbitrary.
6178 static SmallVector<EnableIfAttr *, 4>
6179 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6180 SmallVector<EnableIfAttr *, 4> Result;
6181 if (!Function->hasAttrs())
6184 const auto &FuncAttrs = Function->getAttrs();
6185 for (Attr *Attr : FuncAttrs)
6186 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6187 Result.push_back(EnableIf);
6189 std::reverse(Result.begin(), Result.end());
6194 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6195 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6196 bool MissingImplicitThis, Expr *&ConvertedThis,
6197 SmallVectorImpl<Expr *> &ConvertedArgs) {
6199 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6200 assert(!isa<CXXConstructorDecl>(Method) &&
6201 "Shouldn't have `this` for ctors!");
6202 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6203 ExprResult R = S.PerformObjectArgumentInitialization(
6204 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6207 ConvertedThis = R.get();
6209 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6211 assert((MissingImplicitThis || MD->isStatic() ||
6212 isa<CXXConstructorDecl>(MD)) &&
6213 "Expected `this` for non-ctor instance methods");
6215 ConvertedThis = nullptr;
6218 // Ignore any variadic arguments. Converting them is pointless, since the
6219 // user can't refer to them in the function condition.
6220 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6222 // Convert the arguments.
6223 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6225 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6226 S.Context, Function->getParamDecl(I)),
6227 SourceLocation(), Args[I]);
6232 ConvertedArgs.push_back(R.get());
6235 if (Trap.hasErrorOccurred())
6238 // Push default arguments if needed.
6239 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6240 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6241 ParmVarDecl *P = Function->getParamDecl(i);
6242 ExprResult R = S.PerformCopyInitialization(
6243 InitializedEntity::InitializeParameter(S.Context,
6244 Function->getParamDecl(i)),
6246 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6247 : P->getDefaultArg());
6250 ConvertedArgs.push_back(R.get());
6253 if (Trap.hasErrorOccurred())
6259 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6260 bool MissingImplicitThis) {
6261 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6262 getOrderedEnableIfAttrs(Function);
6263 if (EnableIfAttrs.empty())
6266 SFINAETrap Trap(*this);
6267 SmallVector<Expr *, 16> ConvertedArgs;
6268 // FIXME: We should look into making enable_if late-parsed.
6269 Expr *DiscardedThis;
6270 if (!convertArgsForAvailabilityChecks(
6271 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6272 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6273 return EnableIfAttrs[0];
6275 for (auto *EIA : EnableIfAttrs) {
6277 // FIXME: This doesn't consider value-dependent cases, because doing so is
6278 // very difficult. Ideally, we should handle them more gracefully.
6279 if (!EIA->getCond()->EvaluateWithSubstitution(
6280 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6283 if (!Result.isInt() || !Result.getInt().getBoolValue())
6289 template <typename CheckFn>
6290 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6291 bool ArgDependent, SourceLocation Loc,
6292 CheckFn &&IsSuccessful) {
6293 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6294 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6295 if (ArgDependent == DIA->getArgDependent())
6296 Attrs.push_back(DIA);
6299 // Common case: No diagnose_if attributes, so we can quit early.
6303 auto WarningBegin = std::stable_partition(
6304 Attrs.begin(), Attrs.end(),
6305 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6307 // Note that diagnose_if attributes are late-parsed, so they appear in the
6308 // correct order (unlike enable_if attributes).
6309 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6311 if (ErrAttr != WarningBegin) {
6312 const DiagnoseIfAttr *DIA = *ErrAttr;
6313 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6314 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6315 << DIA->getParent() << DIA->getCond()->getSourceRange();
6319 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6320 if (IsSuccessful(DIA)) {
6321 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6322 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6323 << DIA->getParent() << DIA->getCond()->getSourceRange();
6329 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6330 const Expr *ThisArg,
6331 ArrayRef<const Expr *> Args,
6332 SourceLocation Loc) {
6333 return diagnoseDiagnoseIfAttrsWith(
6334 *this, Function, /*ArgDependent=*/true, Loc,
6335 [&](const DiagnoseIfAttr *DIA) {
6337 // It's sane to use the same Args for any redecl of this function, since
6338 // EvaluateWithSubstitution only cares about the position of each
6339 // argument in the arg list, not the ParmVarDecl* it maps to.
6340 if (!DIA->getCond()->EvaluateWithSubstitution(
6341 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6343 return Result.isInt() && Result.getInt().getBoolValue();
6347 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6348 SourceLocation Loc) {
6349 return diagnoseDiagnoseIfAttrsWith(
6350 *this, ND, /*ArgDependent=*/false, Loc,
6351 [&](const DiagnoseIfAttr *DIA) {
6353 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6358 /// \brief Add all of the function declarations in the given function set to
6359 /// the overload candidate set.
6360 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6361 ArrayRef<Expr *> Args,
6362 OverloadCandidateSet& CandidateSet,
6363 TemplateArgumentListInfo *ExplicitTemplateArgs,
6364 bool SuppressUserConversions,
6365 bool PartialOverloading,
6366 bool FirstArgumentIsBase) {
6367 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6368 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6369 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6370 ArrayRef<Expr *> FunctionArgs = Args;
6371 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6372 QualType ObjectType;
6373 Expr::Classification ObjectClassification;
6374 if (Args.size() > 0) {
6375 if (Expr *E = Args[0]) {
6376 // Use the explit base to restrict the lookup:
6377 ObjectType = E->getType();
6378 ObjectClassification = E->Classify(Context);
6379 } // .. else there is an implit base.
6380 FunctionArgs = Args.slice(1);
6382 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6383 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6384 ObjectClassification, FunctionArgs, CandidateSet,
6385 SuppressUserConversions, PartialOverloading);
6387 // Slice the first argument (which is the base) when we access
6388 // static method as non-static
6389 if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6390 !isa<CXXConstructorDecl>(FD)))) {
6391 assert(cast<CXXMethodDecl>(FD)->isStatic());
6392 FunctionArgs = Args.slice(1);
6394 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6395 SuppressUserConversions, PartialOverloading);
6398 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6399 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6400 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6401 QualType ObjectType;
6402 Expr::Classification ObjectClassification;
6403 if (Expr *E = Args[0]) {
6404 // Use the explit base to restrict the lookup:
6405 ObjectType = E->getType();
6406 ObjectClassification = E->Classify(Context);
6407 } // .. else there is an implit base.
6408 AddMethodTemplateCandidate(
6409 FunTmpl, F.getPair(),
6410 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6411 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6412 Args.slice(1), CandidateSet, SuppressUserConversions,
6413 PartialOverloading);
6415 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6416 ExplicitTemplateArgs, Args,
6417 CandidateSet, SuppressUserConversions,
6418 PartialOverloading);
6424 /// AddMethodCandidate - Adds a named decl (which is some kind of
6425 /// method) as a method candidate to the given overload set.
6426 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6427 QualType ObjectType,
6428 Expr::Classification ObjectClassification,
6429 ArrayRef<Expr *> Args,
6430 OverloadCandidateSet& CandidateSet,
6431 bool SuppressUserConversions) {
6432 NamedDecl *Decl = FoundDecl.getDecl();
6433 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6435 if (isa<UsingShadowDecl>(Decl))
6436 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6438 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6439 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6440 "Expected a member function template");
6441 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6442 /*ExplicitArgs*/ nullptr, ObjectType,
6443 ObjectClassification, Args, CandidateSet,
6444 SuppressUserConversions);
6446 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6447 ObjectType, ObjectClassification, Args, CandidateSet,
6448 SuppressUserConversions);
6452 /// AddMethodCandidate - Adds the given C++ member function to the set
6453 /// of candidate functions, using the given function call arguments
6454 /// and the object argument (@c Object). For example, in a call
6455 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6456 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6457 /// allow user-defined conversions via constructors or conversion
6460 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6461 CXXRecordDecl *ActingContext, QualType ObjectType,
6462 Expr::Classification ObjectClassification,
6463 ArrayRef<Expr *> Args,
6464 OverloadCandidateSet &CandidateSet,
6465 bool SuppressUserConversions,
6466 bool PartialOverloading,
6467 ConversionSequenceList EarlyConversions) {
6468 const FunctionProtoType *Proto
6469 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6470 assert(Proto && "Methods without a prototype cannot be overloaded");
6471 assert(!isa<CXXConstructorDecl>(Method) &&
6472 "Use AddOverloadCandidate for constructors");
6474 if (!CandidateSet.isNewCandidate(Method))
6477 // C++11 [class.copy]p23: [DR1402]
6478 // A defaulted move assignment operator that is defined as deleted is
6479 // ignored by overload resolution.
6480 if (Method->isDefaulted() && Method->isDeleted() &&
6481 Method->isMoveAssignmentOperator())
6484 // Overload resolution is always an unevaluated context.
6485 EnterExpressionEvaluationContext Unevaluated(
6486 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6488 // Add this candidate
6489 OverloadCandidate &Candidate =
6490 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6491 Candidate.FoundDecl = FoundDecl;
6492 Candidate.Function = Method;
6493 Candidate.IsSurrogate = false;
6494 Candidate.IgnoreObjectArgument = false;
6495 Candidate.ExplicitCallArguments = Args.size();
6497 unsigned NumParams = Proto->getNumParams();
6499 // (C++ 13.3.2p2): A candidate function having fewer than m
6500 // parameters is viable only if it has an ellipsis in its parameter
6502 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6503 !Proto->isVariadic()) {
6504 Candidate.Viable = false;
6505 Candidate.FailureKind = ovl_fail_too_many_arguments;
6509 // (C++ 13.3.2p2): A candidate function having more than m parameters
6510 // is viable only if the (m+1)st parameter has a default argument
6511 // (8.3.6). For the purposes of overload resolution, the
6512 // parameter list is truncated on the right, so that there are
6513 // exactly m parameters.
6514 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6515 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6516 // Not enough arguments.
6517 Candidate.Viable = false;
6518 Candidate.FailureKind = ovl_fail_too_few_arguments;
6522 Candidate.Viable = true;
6524 if (Method->isStatic() || ObjectType.isNull())
6525 // The implicit object argument is ignored.
6526 Candidate.IgnoreObjectArgument = true;
6528 // Determine the implicit conversion sequence for the object
6530 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6531 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6532 Method, ActingContext);
6533 if (Candidate.Conversions[0].isBad()) {
6534 Candidate.Viable = false;
6535 Candidate.FailureKind = ovl_fail_bad_conversion;
6540 // (CUDA B.1): Check for invalid calls between targets.
6541 if (getLangOpts().CUDA)
6542 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6543 if (!IsAllowedCUDACall(Caller, Method)) {
6544 Candidate.Viable = false;
6545 Candidate.FailureKind = ovl_fail_bad_target;
6549 // Determine the implicit conversion sequences for each of the
6551 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6552 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6553 // We already formed a conversion sequence for this parameter during
6554 // template argument deduction.
6555 } else if (ArgIdx < NumParams) {
6556 // (C++ 13.3.2p3): for F to be a viable function, there shall
6557 // exist for each argument an implicit conversion sequence
6558 // (13.3.3.1) that converts that argument to the corresponding
6560 QualType ParamType = Proto->getParamType(ArgIdx);
6561 Candidate.Conversions[ArgIdx + 1]
6562 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6563 SuppressUserConversions,
6564 /*InOverloadResolution=*/true,
6565 /*AllowObjCWritebackConversion=*/
6566 getLangOpts().ObjCAutoRefCount);
6567 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6568 Candidate.Viable = false;
6569 Candidate.FailureKind = ovl_fail_bad_conversion;
6573 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6574 // argument for which there is no corresponding parameter is
6575 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6576 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6580 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6581 Candidate.Viable = false;
6582 Candidate.FailureKind = ovl_fail_enable_if;
6583 Candidate.DeductionFailure.Data = FailedAttr;
6588 /// \brief Add a C++ member function template as a candidate to the candidate
6589 /// set, using template argument deduction to produce an appropriate member
6590 /// function template specialization.
6592 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6593 DeclAccessPair FoundDecl,
6594 CXXRecordDecl *ActingContext,
6595 TemplateArgumentListInfo *ExplicitTemplateArgs,
6596 QualType ObjectType,
6597 Expr::Classification ObjectClassification,
6598 ArrayRef<Expr *> Args,
6599 OverloadCandidateSet& CandidateSet,
6600 bool SuppressUserConversions,
6601 bool PartialOverloading) {
6602 if (!CandidateSet.isNewCandidate(MethodTmpl))
6605 // C++ [over.match.funcs]p7:
6606 // In each case where a candidate is a function template, candidate
6607 // function template specializations are generated using template argument
6608 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6609 // candidate functions in the usual way.113) A given name can refer to one
6610 // or more function templates and also to a set of overloaded non-template
6611 // functions. In such a case, the candidate functions generated from each
6612 // function template are combined with the set of non-template candidate
6614 TemplateDeductionInfo Info(CandidateSet.getLocation());
6615 FunctionDecl *Specialization = nullptr;
6616 ConversionSequenceList Conversions;
6617 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6618 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6619 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6620 return CheckNonDependentConversions(
6621 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6622 SuppressUserConversions, ActingContext, ObjectType,
6623 ObjectClassification);
6625 OverloadCandidate &Candidate =
6626 CandidateSet.addCandidate(Conversions.size(), Conversions);
6627 Candidate.FoundDecl = FoundDecl;
6628 Candidate.Function = MethodTmpl->getTemplatedDecl();
6629 Candidate.Viable = false;
6630 Candidate.IsSurrogate = false;
6631 Candidate.IgnoreObjectArgument =
6632 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6633 ObjectType.isNull();
6634 Candidate.ExplicitCallArguments = Args.size();
6635 if (Result == TDK_NonDependentConversionFailure)
6636 Candidate.FailureKind = ovl_fail_bad_conversion;
6638 Candidate.FailureKind = ovl_fail_bad_deduction;
6639 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6645 // Add the function template specialization produced by template argument
6646 // deduction as a candidate.
6647 assert(Specialization && "Missing member function template specialization?");
6648 assert(isa<CXXMethodDecl>(Specialization) &&
6649 "Specialization is not a member function?");
6650 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6651 ActingContext, ObjectType, ObjectClassification, Args,
6652 CandidateSet, SuppressUserConversions, PartialOverloading,
6656 /// \brief Add a C++ function template specialization as a candidate
6657 /// in the candidate set, using template argument deduction to produce
6658 /// an appropriate function template specialization.
6660 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6661 DeclAccessPair FoundDecl,
6662 TemplateArgumentListInfo *ExplicitTemplateArgs,
6663 ArrayRef<Expr *> Args,
6664 OverloadCandidateSet& CandidateSet,
6665 bool SuppressUserConversions,
6666 bool PartialOverloading) {
6667 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6670 // C++ [over.match.funcs]p7:
6671 // In each case where a candidate is a function template, candidate
6672 // function template specializations are generated using template argument
6673 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6674 // candidate functions in the usual way.113) A given name can refer to one
6675 // or more function templates and also to a set of overloaded non-template
6676 // functions. In such a case, the candidate functions generated from each
6677 // function template are combined with the set of non-template candidate
6679 TemplateDeductionInfo Info(CandidateSet.getLocation());
6680 FunctionDecl *Specialization = nullptr;
6681 ConversionSequenceList Conversions;
6682 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6683 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6684 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6685 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6686 Args, CandidateSet, Conversions,
6687 SuppressUserConversions);
6689 OverloadCandidate &Candidate =
6690 CandidateSet.addCandidate(Conversions.size(), Conversions);
6691 Candidate.FoundDecl = FoundDecl;
6692 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6693 Candidate.Viable = false;
6694 Candidate.IsSurrogate = false;
6695 // Ignore the object argument if there is one, since we don't have an object
6697 Candidate.IgnoreObjectArgument =
6698 isa<CXXMethodDecl>(Candidate.Function) &&
6699 !isa<CXXConstructorDecl>(Candidate.Function);
6700 Candidate.ExplicitCallArguments = Args.size();
6701 if (Result == TDK_NonDependentConversionFailure)
6702 Candidate.FailureKind = ovl_fail_bad_conversion;
6704 Candidate.FailureKind = ovl_fail_bad_deduction;
6705 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6711 // Add the function template specialization produced by template argument
6712 // deduction as a candidate.
6713 assert(Specialization && "Missing function template specialization?");
6714 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6715 SuppressUserConversions, PartialOverloading,
6716 /*AllowExplicit*/false, Conversions);
6719 /// Check that implicit conversion sequences can be formed for each argument
6720 /// whose corresponding parameter has a non-dependent type, per DR1391's
6721 /// [temp.deduct.call]p10.
6722 bool Sema::CheckNonDependentConversions(
6723 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6724 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6725 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6726 CXXRecordDecl *ActingContext, QualType ObjectType,
6727 Expr::Classification ObjectClassification) {
6728 // FIXME: The cases in which we allow explicit conversions for constructor
6729 // arguments never consider calling a constructor template. It's not clear
6731 const bool AllowExplicit = false;
6733 auto *FD = FunctionTemplate->getTemplatedDecl();
6734 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6735 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6736 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6739 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6741 // Overload resolution is always an unevaluated context.
6742 EnterExpressionEvaluationContext Unevaluated(
6743 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6745 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6746 // require that, but this check should never result in a hard error, and
6747 // overload resolution is permitted to sidestep instantiations.
6748 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6749 !ObjectType.isNull()) {
6750 Conversions[0] = TryObjectArgumentInitialization(
6751 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6752 Method, ActingContext);
6753 if (Conversions[0].isBad())
6757 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6759 QualType ParamType = ParamTypes[I];
6760 if (!ParamType->isDependentType()) {
6761 Conversions[ThisConversions + I]
6762 = TryCopyInitialization(*this, Args[I], ParamType,
6763 SuppressUserConversions,
6764 /*InOverloadResolution=*/true,
6765 /*AllowObjCWritebackConversion=*/
6766 getLangOpts().ObjCAutoRefCount,
6768 if (Conversions[ThisConversions + I].isBad())
6776 /// Determine whether this is an allowable conversion from the result
6777 /// of an explicit conversion operator to the expected type, per C++
6778 /// [over.match.conv]p1 and [over.match.ref]p1.
6780 /// \param ConvType The return type of the conversion function.
6782 /// \param ToType The type we are converting to.
6784 /// \param AllowObjCPointerConversion Allow a conversion from one
6785 /// Objective-C pointer to another.
6787 /// \returns true if the conversion is allowable, false otherwise.
6788 static bool isAllowableExplicitConversion(Sema &S,
6789 QualType ConvType, QualType ToType,
6790 bool AllowObjCPointerConversion) {
6791 QualType ToNonRefType = ToType.getNonReferenceType();
6793 // Easy case: the types are the same.
6794 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6797 // Allow qualification conversions.
6798 bool ObjCLifetimeConversion;
6799 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6800 ObjCLifetimeConversion))
6803 // If we're not allowed to consider Objective-C pointer conversions,
6805 if (!AllowObjCPointerConversion)
6808 // Is this an Objective-C pointer conversion?
6809 bool IncompatibleObjC = false;
6810 QualType ConvertedType;
6811 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6815 /// AddConversionCandidate - Add a C++ conversion function as a
6816 /// candidate in the candidate set (C++ [over.match.conv],
6817 /// C++ [over.match.copy]). From is the expression we're converting from,
6818 /// and ToType is the type that we're eventually trying to convert to
6819 /// (which may or may not be the same type as the type that the
6820 /// conversion function produces).
6822 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6823 DeclAccessPair FoundDecl,
6824 CXXRecordDecl *ActingContext,
6825 Expr *From, QualType ToType,
6826 OverloadCandidateSet& CandidateSet,
6827 bool AllowObjCConversionOnExplicit,
6828 bool AllowResultConversion) {
6829 assert(!Conversion->getDescribedFunctionTemplate() &&
6830 "Conversion function templates use AddTemplateConversionCandidate");
6831 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6832 if (!CandidateSet.isNewCandidate(Conversion))
6835 // If the conversion function has an undeduced return type, trigger its
6837 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6838 if (DeduceReturnType(Conversion, From->getExprLoc()))
6840 ConvType = Conversion->getConversionType().getNonReferenceType();
6843 // If we don't allow any conversion of the result type, ignore conversion
6844 // functions that don't convert to exactly (possibly cv-qualified) T.
6845 if (!AllowResultConversion &&
6846 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6849 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6850 // operator is only a candidate if its return type is the target type or
6851 // can be converted to the target type with a qualification conversion.
6852 if (Conversion->isExplicit() &&
6853 !isAllowableExplicitConversion(*this, ConvType, ToType,
6854 AllowObjCConversionOnExplicit))
6857 // Overload resolution is always an unevaluated context.
6858 EnterExpressionEvaluationContext Unevaluated(
6859 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6861 // Add this candidate
6862 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6863 Candidate.FoundDecl = FoundDecl;
6864 Candidate.Function = Conversion;
6865 Candidate.IsSurrogate = false;
6866 Candidate.IgnoreObjectArgument = false;
6867 Candidate.FinalConversion.setAsIdentityConversion();
6868 Candidate.FinalConversion.setFromType(ConvType);
6869 Candidate.FinalConversion.setAllToTypes(ToType);
6870 Candidate.Viable = true;
6871 Candidate.ExplicitCallArguments = 1;
6873 // C++ [over.match.funcs]p4:
6874 // For conversion functions, the function is considered to be a member of
6875 // the class of the implicit implied object argument for the purpose of
6876 // defining the type of the implicit object parameter.
6878 // Determine the implicit conversion sequence for the implicit
6879 // object parameter.
6880 QualType ImplicitParamType = From->getType();
6881 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6882 ImplicitParamType = FromPtrType->getPointeeType();
6883 CXXRecordDecl *ConversionContext
6884 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6886 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6887 *this, CandidateSet.getLocation(), From->getType(),
6888 From->Classify(Context), Conversion, ConversionContext);
6890 if (Candidate.Conversions[0].isBad()) {
6891 Candidate.Viable = false;
6892 Candidate.FailureKind = ovl_fail_bad_conversion;
6896 // We won't go through a user-defined type conversion function to convert a
6897 // derived to base as such conversions are given Conversion Rank. They only
6898 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6900 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6901 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6902 if (FromCanon == ToCanon ||
6903 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6904 Candidate.Viable = false;
6905 Candidate.FailureKind = ovl_fail_trivial_conversion;
6909 // To determine what the conversion from the result of calling the
6910 // conversion function to the type we're eventually trying to
6911 // convert to (ToType), we need to synthesize a call to the
6912 // conversion function and attempt copy initialization from it. This
6913 // makes sure that we get the right semantics with respect to
6914 // lvalues/rvalues and the type. Fortunately, we can allocate this
6915 // call on the stack and we don't need its arguments to be
6917 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6918 VK_LValue, From->getLocStart());
6919 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6920 Context.getPointerType(Conversion->getType()),
6921 CK_FunctionToPointerDecay,
6922 &ConversionRef, VK_RValue);
6924 QualType ConversionType = Conversion->getConversionType();
6925 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6926 Candidate.Viable = false;
6927 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6931 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6933 // Note that it is safe to allocate CallExpr on the stack here because
6934 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6936 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6937 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6938 From->getLocStart());
6939 ImplicitConversionSequence ICS =
6940 TryCopyInitialization(*this, &Call, ToType,
6941 /*SuppressUserConversions=*/true,
6942 /*InOverloadResolution=*/false,
6943 /*AllowObjCWritebackConversion=*/false);
6945 switch (ICS.getKind()) {
6946 case ImplicitConversionSequence::StandardConversion:
6947 Candidate.FinalConversion = ICS.Standard;
6949 // C++ [over.ics.user]p3:
6950 // If the user-defined conversion is specified by a specialization of a
6951 // conversion function template, the second standard conversion sequence
6952 // shall have exact match rank.
6953 if (Conversion->getPrimaryTemplate() &&
6954 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6955 Candidate.Viable = false;
6956 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6960 // C++0x [dcl.init.ref]p5:
6961 // In the second case, if the reference is an rvalue reference and
6962 // the second standard conversion sequence of the user-defined
6963 // conversion sequence includes an lvalue-to-rvalue conversion, the
6964 // program is ill-formed.
6965 if (ToType->isRValueReferenceType() &&
6966 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6967 Candidate.Viable = false;
6968 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6973 case ImplicitConversionSequence::BadConversion:
6974 Candidate.Viable = false;
6975 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6980 "Can only end up with a standard conversion sequence or failure");
6983 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6984 Candidate.Viable = false;
6985 Candidate.FailureKind = ovl_fail_enable_if;
6986 Candidate.DeductionFailure.Data = FailedAttr;
6991 /// \brief Adds a conversion function template specialization
6992 /// candidate to the overload set, using template argument deduction
6993 /// to deduce the template arguments of the conversion function
6994 /// template from the type that we are converting to (C++
6995 /// [temp.deduct.conv]).
6997 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6998 DeclAccessPair FoundDecl,
6999 CXXRecordDecl *ActingDC,
7000 Expr *From, QualType ToType,
7001 OverloadCandidateSet &CandidateSet,
7002 bool AllowObjCConversionOnExplicit,
7003 bool AllowResultConversion) {
7004 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7005 "Only conversion function templates permitted here");
7007 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7010 TemplateDeductionInfo Info(CandidateSet.getLocation());
7011 CXXConversionDecl *Specialization = nullptr;
7012 if (TemplateDeductionResult Result
7013 = DeduceTemplateArguments(FunctionTemplate, ToType,
7014 Specialization, Info)) {
7015 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7016 Candidate.FoundDecl = FoundDecl;
7017 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7018 Candidate.Viable = false;
7019 Candidate.FailureKind = ovl_fail_bad_deduction;
7020 Candidate.IsSurrogate = false;
7021 Candidate.IgnoreObjectArgument = false;
7022 Candidate.ExplicitCallArguments = 1;
7023 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7028 // Add the conversion function template specialization produced by
7029 // template argument deduction as a candidate.
7030 assert(Specialization && "Missing function template specialization?");
7031 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7032 CandidateSet, AllowObjCConversionOnExplicit,
7033 AllowResultConversion);
7036 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7037 /// converts the given @c Object to a function pointer via the
7038 /// conversion function @c Conversion, and then attempts to call it
7039 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7040 /// the type of function that we'll eventually be calling.
7041 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7042 DeclAccessPair FoundDecl,
7043 CXXRecordDecl *ActingContext,
7044 const FunctionProtoType *Proto,
7046 ArrayRef<Expr *> Args,
7047 OverloadCandidateSet& CandidateSet) {
7048 if (!CandidateSet.isNewCandidate(Conversion))
7051 // Overload resolution is always an unevaluated context.
7052 EnterExpressionEvaluationContext Unevaluated(
7053 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7055 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7056 Candidate.FoundDecl = FoundDecl;
7057 Candidate.Function = nullptr;
7058 Candidate.Surrogate = Conversion;
7059 Candidate.Viable = true;
7060 Candidate.IsSurrogate = true;
7061 Candidate.IgnoreObjectArgument = false;
7062 Candidate.ExplicitCallArguments = Args.size();
7064 // Determine the implicit conversion sequence for the implicit
7065 // object parameter.
7066 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7067 *this, CandidateSet.getLocation(), Object->getType(),
7068 Object->Classify(Context), Conversion, ActingContext);
7069 if (ObjectInit.isBad()) {
7070 Candidate.Viable = false;
7071 Candidate.FailureKind = ovl_fail_bad_conversion;
7072 Candidate.Conversions[0] = ObjectInit;
7076 // The first conversion is actually a user-defined conversion whose
7077 // first conversion is ObjectInit's standard conversion (which is
7078 // effectively a reference binding). Record it as such.
7079 Candidate.Conversions[0].setUserDefined();
7080 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7081 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7082 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7083 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7084 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7085 Candidate.Conversions[0].UserDefined.After
7086 = Candidate.Conversions[0].UserDefined.Before;
7087 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7090 unsigned NumParams = Proto->getNumParams();
7092 // (C++ 13.3.2p2): A candidate function having fewer than m
7093 // parameters is viable only if it has an ellipsis in its parameter
7095 if (Args.size() > NumParams && !Proto->isVariadic()) {
7096 Candidate.Viable = false;
7097 Candidate.FailureKind = ovl_fail_too_many_arguments;
7101 // Function types don't have any default arguments, so just check if
7102 // we have enough arguments.
7103 if (Args.size() < NumParams) {
7104 // Not enough arguments.
7105 Candidate.Viable = false;
7106 Candidate.FailureKind = ovl_fail_too_few_arguments;
7110 // Determine the implicit conversion sequences for each of the
7112 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7113 if (ArgIdx < NumParams) {
7114 // (C++ 13.3.2p3): for F to be a viable function, there shall
7115 // exist for each argument an implicit conversion sequence
7116 // (13.3.3.1) that converts that argument to the corresponding
7118 QualType ParamType = Proto->getParamType(ArgIdx);
7119 Candidate.Conversions[ArgIdx + 1]
7120 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7121 /*SuppressUserConversions=*/false,
7122 /*InOverloadResolution=*/false,
7123 /*AllowObjCWritebackConversion=*/
7124 getLangOpts().ObjCAutoRefCount);
7125 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7126 Candidate.Viable = false;
7127 Candidate.FailureKind = ovl_fail_bad_conversion;
7131 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7132 // argument for which there is no corresponding parameter is
7133 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7134 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7138 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7139 Candidate.Viable = false;
7140 Candidate.FailureKind = ovl_fail_enable_if;
7141 Candidate.DeductionFailure.Data = FailedAttr;
7146 /// \brief Add overload candidates for overloaded operators that are
7147 /// member functions.
7149 /// Add the overloaded operator candidates that are member functions
7150 /// for the operator Op that was used in an operator expression such
7151 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7152 /// CandidateSet will store the added overload candidates. (C++
7153 /// [over.match.oper]).
7154 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7155 SourceLocation OpLoc,
7156 ArrayRef<Expr *> Args,
7157 OverloadCandidateSet& CandidateSet,
7158 SourceRange OpRange) {
7159 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7161 // C++ [over.match.oper]p3:
7162 // For a unary operator @ with an operand of a type whose
7163 // cv-unqualified version is T1, and for a binary operator @ with
7164 // a left operand of a type whose cv-unqualified version is T1 and
7165 // a right operand of a type whose cv-unqualified version is T2,
7166 // three sets of candidate functions, designated member
7167 // candidates, non-member candidates and built-in candidates, are
7168 // constructed as follows:
7169 QualType T1 = Args[0]->getType();
7171 // -- If T1 is a complete class type or a class currently being
7172 // defined, the set of member candidates is the result of the
7173 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7174 // the set of member candidates is empty.
7175 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7176 // Complete the type if it can be completed.
7177 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7179 // If the type is neither complete nor being defined, bail out now.
7180 if (!T1Rec->getDecl()->getDefinition())
7183 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7184 LookupQualifiedName(Operators, T1Rec->getDecl());
7185 Operators.suppressDiagnostics();
7187 for (LookupResult::iterator Oper = Operators.begin(),
7188 OperEnd = Operators.end();
7191 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7192 Args[0]->Classify(Context), Args.slice(1),
7193 CandidateSet, /*SuppressUserConversions=*/false);
7197 /// AddBuiltinCandidate - Add a candidate for a built-in
7198 /// operator. ResultTy and ParamTys are the result and parameter types
7199 /// of the built-in candidate, respectively. Args and NumArgs are the
7200 /// arguments being passed to the candidate. IsAssignmentOperator
7201 /// should be true when this built-in candidate is an assignment
7202 /// operator. NumContextualBoolArguments is the number of arguments
7203 /// (at the beginning of the argument list) that will be contextually
7204 /// converted to bool.
7205 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7206 OverloadCandidateSet& CandidateSet,
7207 bool IsAssignmentOperator,
7208 unsigned NumContextualBoolArguments) {
7209 // Overload resolution is always an unevaluated context.
7210 EnterExpressionEvaluationContext Unevaluated(
7211 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7213 // Add this candidate
7214 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7215 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7216 Candidate.Function = nullptr;
7217 Candidate.IsSurrogate = false;
7218 Candidate.IgnoreObjectArgument = false;
7219 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7221 // Determine the implicit conversion sequences for each of the
7223 Candidate.Viable = true;
7224 Candidate.ExplicitCallArguments = Args.size();
7225 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7226 // C++ [over.match.oper]p4:
7227 // For the built-in assignment operators, conversions of the
7228 // left operand are restricted as follows:
7229 // -- no temporaries are introduced to hold the left operand, and
7230 // -- no user-defined conversions are applied to the left
7231 // operand to achieve a type match with the left-most
7232 // parameter of a built-in candidate.
7234 // We block these conversions by turning off user-defined
7235 // conversions, since that is the only way that initialization of
7236 // a reference to a non-class type can occur from something that
7237 // is not of the same type.
7238 if (ArgIdx < NumContextualBoolArguments) {
7239 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7240 "Contextual conversion to bool requires bool type");
7241 Candidate.Conversions[ArgIdx]
7242 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7244 Candidate.Conversions[ArgIdx]
7245 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7246 ArgIdx == 0 && IsAssignmentOperator,
7247 /*InOverloadResolution=*/false,
7248 /*AllowObjCWritebackConversion=*/
7249 getLangOpts().ObjCAutoRefCount);
7251 if (Candidate.Conversions[ArgIdx].isBad()) {
7252 Candidate.Viable = false;
7253 Candidate.FailureKind = ovl_fail_bad_conversion;
7261 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7262 /// candidate operator functions for built-in operators (C++
7263 /// [over.built]). The types are separated into pointer types and
7264 /// enumeration types.
7265 class BuiltinCandidateTypeSet {
7266 /// TypeSet - A set of types.
7267 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7268 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7270 /// PointerTypes - The set of pointer types that will be used in the
7271 /// built-in candidates.
7272 TypeSet PointerTypes;
7274 /// MemberPointerTypes - The set of member pointer types that will be
7275 /// used in the built-in candidates.
7276 TypeSet MemberPointerTypes;
7278 /// EnumerationTypes - The set of enumeration types that will be
7279 /// used in the built-in candidates.
7280 TypeSet EnumerationTypes;
7282 /// \brief The set of vector types that will be used in the built-in
7284 TypeSet VectorTypes;
7286 /// \brief A flag indicating non-record types are viable candidates
7287 bool HasNonRecordTypes;
7289 /// \brief A flag indicating whether either arithmetic or enumeration types
7290 /// were present in the candidate set.
7291 bool HasArithmeticOrEnumeralTypes;
7293 /// \brief A flag indicating whether the nullptr type was present in the
7295 bool HasNullPtrType;
7297 /// Sema - The semantic analysis instance where we are building the
7298 /// candidate type set.
7301 /// Context - The AST context in which we will build the type sets.
7302 ASTContext &Context;
7304 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7305 const Qualifiers &VisibleQuals);
7306 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7309 /// iterator - Iterates through the types that are part of the set.
7310 typedef TypeSet::iterator iterator;
7312 BuiltinCandidateTypeSet(Sema &SemaRef)
7313 : HasNonRecordTypes(false),
7314 HasArithmeticOrEnumeralTypes(false),
7315 HasNullPtrType(false),
7317 Context(SemaRef.Context) { }
7319 void AddTypesConvertedFrom(QualType Ty,
7321 bool AllowUserConversions,
7322 bool AllowExplicitConversions,
7323 const Qualifiers &VisibleTypeConversionsQuals);
7325 /// pointer_begin - First pointer type found;
7326 iterator pointer_begin() { return PointerTypes.begin(); }
7328 /// pointer_end - Past the last pointer type found;
7329 iterator pointer_end() { return PointerTypes.end(); }
7331 /// member_pointer_begin - First member pointer type found;
7332 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7334 /// member_pointer_end - Past the last member pointer type found;
7335 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7337 /// enumeration_begin - First enumeration type found;
7338 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7340 /// enumeration_end - Past the last enumeration type found;
7341 iterator enumeration_end() { return EnumerationTypes.end(); }
7343 iterator vector_begin() { return VectorTypes.begin(); }
7344 iterator vector_end() { return VectorTypes.end(); }
7346 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7347 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7348 bool hasNullPtrType() const { return HasNullPtrType; }
7351 } // end anonymous namespace
7353 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7354 /// the set of pointer types along with any more-qualified variants of
7355 /// that type. For example, if @p Ty is "int const *", this routine
7356 /// will add "int const *", "int const volatile *", "int const
7357 /// restrict *", and "int const volatile restrict *" to the set of
7358 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7359 /// false otherwise.
7361 /// FIXME: what to do about extended qualifiers?
7363 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7364 const Qualifiers &VisibleQuals) {
7366 // Insert this type.
7367 if (!PointerTypes.insert(Ty))
7371 const PointerType *PointerTy = Ty->getAs<PointerType>();
7372 bool buildObjCPtr = false;
7374 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7375 PointeeTy = PTy->getPointeeType();
7376 buildObjCPtr = true;
7378 PointeeTy = PointerTy->getPointeeType();
7381 // Don't add qualified variants of arrays. For one, they're not allowed
7382 // (the qualifier would sink to the element type), and for another, the
7383 // only overload situation where it matters is subscript or pointer +- int,
7384 // and those shouldn't have qualifier variants anyway.
7385 if (PointeeTy->isArrayType())
7388 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7389 bool hasVolatile = VisibleQuals.hasVolatile();
7390 bool hasRestrict = VisibleQuals.hasRestrict();
7392 // Iterate through all strict supersets of BaseCVR.
7393 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7394 if ((CVR | BaseCVR) != CVR) continue;
7395 // Skip over volatile if no volatile found anywhere in the types.
7396 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7398 // Skip over restrict if no restrict found anywhere in the types, or if
7399 // the type cannot be restrict-qualified.
7400 if ((CVR & Qualifiers::Restrict) &&
7402 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7405 // Build qualified pointee type.
7406 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7408 // Build qualified pointer type.
7409 QualType QPointerTy;
7411 QPointerTy = Context.getPointerType(QPointeeTy);
7413 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7415 // Insert qualified pointer type.
7416 PointerTypes.insert(QPointerTy);
7422 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7423 /// to the set of pointer types along with any more-qualified variants of
7424 /// that type. For example, if @p Ty is "int const *", this routine
7425 /// will add "int const *", "int const volatile *", "int const
7426 /// restrict *", and "int const volatile restrict *" to the set of
7427 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7428 /// false otherwise.
7430 /// FIXME: what to do about extended qualifiers?
7432 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7434 // Insert this type.
7435 if (!MemberPointerTypes.insert(Ty))
7438 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7439 assert(PointerTy && "type was not a member pointer type!");
7441 QualType PointeeTy = PointerTy->getPointeeType();
7442 // Don't add qualified variants of arrays. For one, they're not allowed
7443 // (the qualifier would sink to the element type), and for another, the
7444 // only overload situation where it matters is subscript or pointer +- int,
7445 // and those shouldn't have qualifier variants anyway.
7446 if (PointeeTy->isArrayType())
7448 const Type *ClassTy = PointerTy->getClass();
7450 // Iterate through all strict supersets of the pointee type's CVR
7452 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7453 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7454 if ((CVR | BaseCVR) != CVR) continue;
7456 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7457 MemberPointerTypes.insert(
7458 Context.getMemberPointerType(QPointeeTy, ClassTy));
7464 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7465 /// Ty can be implicit converted to the given set of @p Types. We're
7466 /// primarily interested in pointer types and enumeration types. We also
7467 /// take member pointer types, for the conditional operator.
7468 /// AllowUserConversions is true if we should look at the conversion
7469 /// functions of a class type, and AllowExplicitConversions if we
7470 /// should also include the explicit conversion functions of a class
7473 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7475 bool AllowUserConversions,
7476 bool AllowExplicitConversions,
7477 const Qualifiers &VisibleQuals) {
7478 // Only deal with canonical types.
7479 Ty = Context.getCanonicalType(Ty);
7481 // Look through reference types; they aren't part of the type of an
7482 // expression for the purposes of conversions.
7483 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7484 Ty = RefTy->getPointeeType();
7486 // If we're dealing with an array type, decay to the pointer.
7487 if (Ty->isArrayType())
7488 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7490 // Otherwise, we don't care about qualifiers on the type.
7491 Ty = Ty.getLocalUnqualifiedType();
7493 // Flag if we ever add a non-record type.
7494 const RecordType *TyRec = Ty->getAs<RecordType>();
7495 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7497 // Flag if we encounter an arithmetic type.
7498 HasArithmeticOrEnumeralTypes =
7499 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7501 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7502 PointerTypes.insert(Ty);
7503 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7504 // Insert our type, and its more-qualified variants, into the set
7506 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7508 } else if (Ty->isMemberPointerType()) {
7509 // Member pointers are far easier, since the pointee can't be converted.
7510 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7512 } else if (Ty->isEnumeralType()) {
7513 HasArithmeticOrEnumeralTypes = true;
7514 EnumerationTypes.insert(Ty);
7515 } else if (Ty->isVectorType()) {
7516 // We treat vector types as arithmetic types in many contexts as an
7518 HasArithmeticOrEnumeralTypes = true;
7519 VectorTypes.insert(Ty);
7520 } else if (Ty->isNullPtrType()) {
7521 HasNullPtrType = true;
7522 } else if (AllowUserConversions && TyRec) {
7523 // No conversion functions in incomplete types.
7524 if (!SemaRef.isCompleteType(Loc, Ty))
7527 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7528 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7529 if (isa<UsingShadowDecl>(D))
7530 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7532 // Skip conversion function templates; they don't tell us anything
7533 // about which builtin types we can convert to.
7534 if (isa<FunctionTemplateDecl>(D))
7537 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7538 if (AllowExplicitConversions || !Conv->isExplicit()) {
7539 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7546 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7547 /// the volatile- and non-volatile-qualified assignment operators for the
7548 /// given type to the candidate set.
7549 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7551 ArrayRef<Expr *> Args,
7552 OverloadCandidateSet &CandidateSet) {
7553 QualType ParamTypes[2];
7555 // T& operator=(T&, T)
7556 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7558 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7559 /*IsAssignmentOperator=*/true);
7561 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7562 // volatile T& operator=(volatile T&, T)
7564 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7566 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7567 /*IsAssignmentOperator=*/true);
7571 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7572 /// if any, found in visible type conversion functions found in ArgExpr's type.
7573 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7575 const RecordType *TyRec;
7576 if (const MemberPointerType *RHSMPType =
7577 ArgExpr->getType()->getAs<MemberPointerType>())
7578 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7580 TyRec = ArgExpr->getType()->getAs<RecordType>();
7582 // Just to be safe, assume the worst case.
7583 VRQuals.addVolatile();
7584 VRQuals.addRestrict();
7588 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7589 if (!ClassDecl->hasDefinition())
7592 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7593 if (isa<UsingShadowDecl>(D))
7594 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7595 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7596 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7597 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7598 CanTy = ResTypeRef->getPointeeType();
7599 // Need to go down the pointer/mempointer chain and add qualifiers
7603 if (CanTy.isRestrictQualified())
7604 VRQuals.addRestrict();
7605 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7606 CanTy = ResTypePtr->getPointeeType();
7607 else if (const MemberPointerType *ResTypeMPtr =
7608 CanTy->getAs<MemberPointerType>())
7609 CanTy = ResTypeMPtr->getPointeeType();
7612 if (CanTy.isVolatileQualified())
7613 VRQuals.addVolatile();
7614 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7624 /// \brief Helper class to manage the addition of builtin operator overload
7625 /// candidates. It provides shared state and utility methods used throughout
7626 /// the process, as well as a helper method to add each group of builtin
7627 /// operator overloads from the standard to a candidate set.
7628 class BuiltinOperatorOverloadBuilder {
7629 // Common instance state available to all overload candidate addition methods.
7631 ArrayRef<Expr *> Args;
7632 Qualifiers VisibleTypeConversionsQuals;
7633 bool HasArithmeticOrEnumeralCandidateType;
7634 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7635 OverloadCandidateSet &CandidateSet;
7637 static constexpr int ArithmeticTypesCap = 24;
7638 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7640 // Define some indices used to iterate over the arithemetic types in
7641 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
7642 // types are that preserved by promotion (C++ [over.built]p2).
7643 unsigned FirstIntegralType,
7645 unsigned FirstPromotedIntegralType,
7646 LastPromotedIntegralType;
7647 unsigned FirstPromotedArithmeticType,
7648 LastPromotedArithmeticType;
7649 unsigned NumArithmeticTypes;
7651 void InitArithmeticTypes() {
7652 // Start of promoted types.
7653 FirstPromotedArithmeticType = 0;
7654 ArithmeticTypes.push_back(S.Context.FloatTy);
7655 ArithmeticTypes.push_back(S.Context.DoubleTy);
7656 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7657 if (S.Context.getTargetInfo().hasFloat128Type())
7658 ArithmeticTypes.push_back(S.Context.Float128Ty);
7660 // Start of integral types.
7661 FirstIntegralType = ArithmeticTypes.size();
7662 FirstPromotedIntegralType = ArithmeticTypes.size();
7663 ArithmeticTypes.push_back(S.Context.IntTy);
7664 ArithmeticTypes.push_back(S.Context.LongTy);
7665 ArithmeticTypes.push_back(S.Context.LongLongTy);
7666 if (S.Context.getTargetInfo().hasInt128Type())
7667 ArithmeticTypes.push_back(S.Context.Int128Ty);
7668 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7669 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7670 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7671 if (S.Context.getTargetInfo().hasInt128Type())
7672 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7673 LastPromotedIntegralType = ArithmeticTypes.size();
7674 LastPromotedArithmeticType = ArithmeticTypes.size();
7675 // End of promoted types.
7677 ArithmeticTypes.push_back(S.Context.BoolTy);
7678 ArithmeticTypes.push_back(S.Context.CharTy);
7679 ArithmeticTypes.push_back(S.Context.WCharTy);
7680 ArithmeticTypes.push_back(S.Context.Char16Ty);
7681 ArithmeticTypes.push_back(S.Context.Char32Ty);
7682 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7683 ArithmeticTypes.push_back(S.Context.ShortTy);
7684 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7685 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7686 LastIntegralType = ArithmeticTypes.size();
7687 NumArithmeticTypes = ArithmeticTypes.size();
7688 // End of integral types.
7689 // FIXME: What about complex? What about half?
7691 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7692 "Enough inline storage for all arithmetic types.");
7695 /// \brief Helper method to factor out the common pattern of adding overloads
7696 /// for '++' and '--' builtin operators.
7697 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7700 QualType ParamTypes[2] = {
7701 S.Context.getLValueReferenceType(CandidateTy),
7705 // Non-volatile version.
7706 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7708 // Use a heuristic to reduce number of builtin candidates in the set:
7709 // add volatile version only if there are conversions to a volatile type.
7712 S.Context.getLValueReferenceType(
7713 S.Context.getVolatileType(CandidateTy));
7714 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7717 // Add restrict version only if there are conversions to a restrict type
7718 // and our candidate type is a non-restrict-qualified pointer.
7719 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7720 !CandidateTy.isRestrictQualified()) {
7722 = S.Context.getLValueReferenceType(
7723 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7724 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7728 = S.Context.getLValueReferenceType(
7729 S.Context.getCVRQualifiedType(CandidateTy,
7730 (Qualifiers::Volatile |
7731 Qualifiers::Restrict)));
7732 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7739 BuiltinOperatorOverloadBuilder(
7740 Sema &S, ArrayRef<Expr *> Args,
7741 Qualifiers VisibleTypeConversionsQuals,
7742 bool HasArithmeticOrEnumeralCandidateType,
7743 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7744 OverloadCandidateSet &CandidateSet)
7746 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7747 HasArithmeticOrEnumeralCandidateType(
7748 HasArithmeticOrEnumeralCandidateType),
7749 CandidateTypes(CandidateTypes),
7750 CandidateSet(CandidateSet) {
7752 InitArithmeticTypes();
7755 // C++ [over.built]p3:
7757 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7758 // is either volatile or empty, there exist candidate operator
7759 // functions of the form
7761 // VQ T& operator++(VQ T&);
7762 // T operator++(VQ T&, int);
7764 // C++ [over.built]p4:
7766 // For every pair (T, VQ), where T is an arithmetic type other
7767 // than bool, and VQ is either volatile or empty, there exist
7768 // candidate operator functions of the form
7770 // VQ T& operator--(VQ T&);
7771 // T operator--(VQ T&, int);
7772 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7773 if (!HasArithmeticOrEnumeralCandidateType)
7776 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7777 Arith < NumArithmeticTypes; ++Arith) {
7778 addPlusPlusMinusMinusStyleOverloads(
7779 ArithmeticTypes[Arith],
7780 VisibleTypeConversionsQuals.hasVolatile(),
7781 VisibleTypeConversionsQuals.hasRestrict());
7785 // C++ [over.built]p5:
7787 // For every pair (T, VQ), where T is a cv-qualified or
7788 // cv-unqualified object type, and VQ is either volatile or
7789 // empty, there exist candidate operator functions of the form
7791 // T*VQ& operator++(T*VQ&);
7792 // T*VQ& operator--(T*VQ&);
7793 // T* operator++(T*VQ&, int);
7794 // T* operator--(T*VQ&, int);
7795 void addPlusPlusMinusMinusPointerOverloads() {
7796 for (BuiltinCandidateTypeSet::iterator
7797 Ptr = CandidateTypes[0].pointer_begin(),
7798 PtrEnd = CandidateTypes[0].pointer_end();
7799 Ptr != PtrEnd; ++Ptr) {
7800 // Skip pointer types that aren't pointers to object types.
7801 if (!(*Ptr)->getPointeeType()->isObjectType())
7804 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7805 (!(*Ptr).isVolatileQualified() &&
7806 VisibleTypeConversionsQuals.hasVolatile()),
7807 (!(*Ptr).isRestrictQualified() &&
7808 VisibleTypeConversionsQuals.hasRestrict()));
7812 // C++ [over.built]p6:
7813 // For every cv-qualified or cv-unqualified object type T, there
7814 // exist candidate operator functions of the form
7816 // T& operator*(T*);
7818 // C++ [over.built]p7:
7819 // For every function type T that does not have cv-qualifiers or a
7820 // ref-qualifier, there exist candidate operator functions of the form
7821 // T& operator*(T*);
7822 void addUnaryStarPointerOverloads() {
7823 for (BuiltinCandidateTypeSet::iterator
7824 Ptr = CandidateTypes[0].pointer_begin(),
7825 PtrEnd = CandidateTypes[0].pointer_end();
7826 Ptr != PtrEnd; ++Ptr) {
7827 QualType ParamTy = *Ptr;
7828 QualType PointeeTy = ParamTy->getPointeeType();
7829 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7832 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7833 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7836 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7840 // C++ [over.built]p9:
7841 // For every promoted arithmetic type T, there exist candidate
7842 // operator functions of the form
7846 void addUnaryPlusOrMinusArithmeticOverloads() {
7847 if (!HasArithmeticOrEnumeralCandidateType)
7850 for (unsigned Arith = FirstPromotedArithmeticType;
7851 Arith < LastPromotedArithmeticType; ++Arith) {
7852 QualType ArithTy = ArithmeticTypes[Arith];
7853 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7856 // Extension: We also add these operators for vector types.
7857 for (BuiltinCandidateTypeSet::iterator
7858 Vec = CandidateTypes[0].vector_begin(),
7859 VecEnd = CandidateTypes[0].vector_end();
7860 Vec != VecEnd; ++Vec) {
7861 QualType VecTy = *Vec;
7862 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7866 // C++ [over.built]p8:
7867 // For every type T, there exist candidate operator functions of
7870 // T* operator+(T*);
7871 void addUnaryPlusPointerOverloads() {
7872 for (BuiltinCandidateTypeSet::iterator
7873 Ptr = CandidateTypes[0].pointer_begin(),
7874 PtrEnd = CandidateTypes[0].pointer_end();
7875 Ptr != PtrEnd; ++Ptr) {
7876 QualType ParamTy = *Ptr;
7877 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7881 // C++ [over.built]p10:
7882 // For every promoted integral type T, there exist candidate
7883 // operator functions of the form
7886 void addUnaryTildePromotedIntegralOverloads() {
7887 if (!HasArithmeticOrEnumeralCandidateType)
7890 for (unsigned Int = FirstPromotedIntegralType;
7891 Int < LastPromotedIntegralType; ++Int) {
7892 QualType IntTy = ArithmeticTypes[Int];
7893 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7896 // Extension: We also add this operator for vector types.
7897 for (BuiltinCandidateTypeSet::iterator
7898 Vec = CandidateTypes[0].vector_begin(),
7899 VecEnd = CandidateTypes[0].vector_end();
7900 Vec != VecEnd; ++Vec) {
7901 QualType VecTy = *Vec;
7902 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7906 // C++ [over.match.oper]p16:
7907 // For every pointer to member type T or type std::nullptr_t, there
7908 // exist candidate operator functions of the form
7910 // bool operator==(T,T);
7911 // bool operator!=(T,T);
7912 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7913 /// Set of (canonical) types that we've already handled.
7914 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7916 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7917 for (BuiltinCandidateTypeSet::iterator
7918 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7919 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7920 MemPtr != MemPtrEnd;
7922 // Don't add the same builtin candidate twice.
7923 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7926 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7927 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7930 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7931 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7932 if (AddedTypes.insert(NullPtrTy).second) {
7933 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7934 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7940 // C++ [over.built]p15:
7942 // For every T, where T is an enumeration type or a pointer type,
7943 // there exist candidate operator functions of the form
7945 // bool operator<(T, T);
7946 // bool operator>(T, T);
7947 // bool operator<=(T, T);
7948 // bool operator>=(T, T);
7949 // bool operator==(T, T);
7950 // bool operator!=(T, T);
7951 void addRelationalPointerOrEnumeralOverloads() {
7952 // C++ [over.match.oper]p3:
7953 // [...]the built-in candidates include all of the candidate operator
7954 // functions defined in 13.6 that, compared to the given operator, [...]
7955 // do not have the same parameter-type-list as any non-template non-member
7958 // Note that in practice, this only affects enumeration types because there
7959 // aren't any built-in candidates of record type, and a user-defined operator
7960 // must have an operand of record or enumeration type. Also, the only other
7961 // overloaded operator with enumeration arguments, operator=,
7962 // cannot be overloaded for enumeration types, so this is the only place
7963 // where we must suppress candidates like this.
7964 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7965 UserDefinedBinaryOperators;
7967 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7968 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7969 CandidateTypes[ArgIdx].enumeration_end()) {
7970 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7971 CEnd = CandidateSet.end();
7973 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7976 if (C->Function->isFunctionTemplateSpecialization())
7979 QualType FirstParamType =
7980 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7981 QualType SecondParamType =
7982 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7984 // Skip if either parameter isn't of enumeral type.
7985 if (!FirstParamType->isEnumeralType() ||
7986 !SecondParamType->isEnumeralType())
7989 // Add this operator to the set of known user-defined operators.
7990 UserDefinedBinaryOperators.insert(
7991 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7992 S.Context.getCanonicalType(SecondParamType)));
7997 /// Set of (canonical) types that we've already handled.
7998 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8000 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8001 for (BuiltinCandidateTypeSet::iterator
8002 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8003 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8004 Ptr != PtrEnd; ++Ptr) {
8005 // Don't add the same builtin candidate twice.
8006 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8009 QualType ParamTypes[2] = { *Ptr, *Ptr };
8010 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8012 for (BuiltinCandidateTypeSet::iterator
8013 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8014 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8015 Enum != EnumEnd; ++Enum) {
8016 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8018 // Don't add the same builtin candidate twice, or if a user defined
8019 // candidate exists.
8020 if (!AddedTypes.insert(CanonType).second ||
8021 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8025 QualType ParamTypes[2] = { *Enum, *Enum };
8026 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8031 // C++ [over.built]p13:
8033 // For every cv-qualified or cv-unqualified object type T
8034 // there exist candidate operator functions of the form
8036 // T* operator+(T*, ptrdiff_t);
8037 // T& operator[](T*, ptrdiff_t); [BELOW]
8038 // T* operator-(T*, ptrdiff_t);
8039 // T* operator+(ptrdiff_t, T*);
8040 // T& operator[](ptrdiff_t, T*); [BELOW]
8042 // C++ [over.built]p14:
8044 // For every T, where T is a pointer to object type, there
8045 // exist candidate operator functions of the form
8047 // ptrdiff_t operator-(T, T);
8048 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8049 /// Set of (canonical) types that we've already handled.
8050 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8052 for (int Arg = 0; Arg < 2; ++Arg) {
8053 QualType AsymmetricParamTypes[2] = {
8054 S.Context.getPointerDiffType(),
8055 S.Context.getPointerDiffType(),
8057 for (BuiltinCandidateTypeSet::iterator
8058 Ptr = CandidateTypes[Arg].pointer_begin(),
8059 PtrEnd = CandidateTypes[Arg].pointer_end();
8060 Ptr != PtrEnd; ++Ptr) {
8061 QualType PointeeTy = (*Ptr)->getPointeeType();
8062 if (!PointeeTy->isObjectType())
8065 AsymmetricParamTypes[Arg] = *Ptr;
8066 if (Arg == 0 || Op == OO_Plus) {
8067 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8068 // T* operator+(ptrdiff_t, T*);
8069 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8071 if (Op == OO_Minus) {
8072 // ptrdiff_t operator-(T, T);
8073 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8076 QualType ParamTypes[2] = { *Ptr, *Ptr };
8077 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8083 // C++ [over.built]p12:
8085 // For every pair of promoted arithmetic types L and R, there
8086 // exist candidate operator functions of the form
8088 // LR operator*(L, R);
8089 // LR operator/(L, R);
8090 // LR operator+(L, R);
8091 // LR operator-(L, R);
8092 // bool operator<(L, R);
8093 // bool operator>(L, R);
8094 // bool operator<=(L, R);
8095 // bool operator>=(L, R);
8096 // bool operator==(L, R);
8097 // bool operator!=(L, R);
8099 // where LR is the result of the usual arithmetic conversions
8100 // between types L and R.
8102 // C++ [over.built]p24:
8104 // For every pair of promoted arithmetic types L and R, there exist
8105 // candidate operator functions of the form
8107 // LR operator?(bool, L, R);
8109 // where LR is the result of the usual arithmetic conversions
8110 // between types L and R.
8111 // Our candidates ignore the first parameter.
8112 void addGenericBinaryArithmeticOverloads() {
8113 if (!HasArithmeticOrEnumeralCandidateType)
8116 for (unsigned Left = FirstPromotedArithmeticType;
8117 Left < LastPromotedArithmeticType; ++Left) {
8118 for (unsigned Right = FirstPromotedArithmeticType;
8119 Right < LastPromotedArithmeticType; ++Right) {
8120 QualType LandR[2] = { ArithmeticTypes[Left],
8121 ArithmeticTypes[Right] };
8122 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8126 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8127 // conditional operator for vector types.
8128 for (BuiltinCandidateTypeSet::iterator
8129 Vec1 = CandidateTypes[0].vector_begin(),
8130 Vec1End = CandidateTypes[0].vector_end();
8131 Vec1 != Vec1End; ++Vec1) {
8132 for (BuiltinCandidateTypeSet::iterator
8133 Vec2 = CandidateTypes[1].vector_begin(),
8134 Vec2End = CandidateTypes[1].vector_end();
8135 Vec2 != Vec2End; ++Vec2) {
8136 QualType LandR[2] = { *Vec1, *Vec2 };
8137 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8142 // C++ [over.built]p17:
8144 // For every pair of promoted integral types L and R, there
8145 // exist candidate operator functions of the form
8147 // LR operator%(L, R);
8148 // LR operator&(L, R);
8149 // LR operator^(L, R);
8150 // LR operator|(L, R);
8151 // L operator<<(L, R);
8152 // L operator>>(L, R);
8154 // where LR is the result of the usual arithmetic conversions
8155 // between types L and R.
8156 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8157 if (!HasArithmeticOrEnumeralCandidateType)
8160 for (unsigned Left = FirstPromotedIntegralType;
8161 Left < LastPromotedIntegralType; ++Left) {
8162 for (unsigned Right = FirstPromotedIntegralType;
8163 Right < LastPromotedIntegralType; ++Right) {
8164 QualType LandR[2] = { ArithmeticTypes[Left],
8165 ArithmeticTypes[Right] };
8166 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8171 // C++ [over.built]p20:
8173 // For every pair (T, VQ), where T is an enumeration or
8174 // pointer to member type and VQ is either volatile or
8175 // empty, there exist candidate operator functions of the form
8177 // VQ T& operator=(VQ T&, T);
8178 void addAssignmentMemberPointerOrEnumeralOverloads() {
8179 /// Set of (canonical) types that we've already handled.
8180 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8182 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8183 for (BuiltinCandidateTypeSet::iterator
8184 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8185 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8186 Enum != EnumEnd; ++Enum) {
8187 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8190 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8193 for (BuiltinCandidateTypeSet::iterator
8194 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8195 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8196 MemPtr != MemPtrEnd; ++MemPtr) {
8197 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8200 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8205 // C++ [over.built]p19:
8207 // For every pair (T, VQ), where T is any type and VQ is either
8208 // volatile or empty, there exist candidate operator functions
8211 // T*VQ& operator=(T*VQ&, T*);
8213 // C++ [over.built]p21:
8215 // For every pair (T, VQ), where T is a cv-qualified or
8216 // cv-unqualified object type and VQ is either volatile or
8217 // empty, there exist candidate operator functions of the form
8219 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8220 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8221 void addAssignmentPointerOverloads(bool isEqualOp) {
8222 /// Set of (canonical) types that we've already handled.
8223 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8225 for (BuiltinCandidateTypeSet::iterator
8226 Ptr = CandidateTypes[0].pointer_begin(),
8227 PtrEnd = CandidateTypes[0].pointer_end();
8228 Ptr != PtrEnd; ++Ptr) {
8229 // If this is operator=, keep track of the builtin candidates we added.
8231 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8232 else if (!(*Ptr)->getPointeeType()->isObjectType())
8235 // non-volatile version
8236 QualType ParamTypes[2] = {
8237 S.Context.getLValueReferenceType(*Ptr),
8238 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8240 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8241 /*IsAssigmentOperator=*/ isEqualOp);
8243 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8244 VisibleTypeConversionsQuals.hasVolatile();
8248 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8249 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8250 /*IsAssigmentOperator=*/isEqualOp);
8253 if (!(*Ptr).isRestrictQualified() &&
8254 VisibleTypeConversionsQuals.hasRestrict()) {
8257 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8258 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8259 /*IsAssigmentOperator=*/isEqualOp);
8262 // volatile restrict version
8264 = S.Context.getLValueReferenceType(
8265 S.Context.getCVRQualifiedType(*Ptr,
8266 (Qualifiers::Volatile |
8267 Qualifiers::Restrict)));
8268 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8269 /*IsAssigmentOperator=*/isEqualOp);
8275 for (BuiltinCandidateTypeSet::iterator
8276 Ptr = CandidateTypes[1].pointer_begin(),
8277 PtrEnd = CandidateTypes[1].pointer_end();
8278 Ptr != PtrEnd; ++Ptr) {
8279 // Make sure we don't add the same candidate twice.
8280 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8283 QualType ParamTypes[2] = {
8284 S.Context.getLValueReferenceType(*Ptr),
8288 // non-volatile version
8289 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8290 /*IsAssigmentOperator=*/true);
8292 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8293 VisibleTypeConversionsQuals.hasVolatile();
8297 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8298 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8299 /*IsAssigmentOperator=*/true);
8302 if (!(*Ptr).isRestrictQualified() &&
8303 VisibleTypeConversionsQuals.hasRestrict()) {
8306 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8307 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8308 /*IsAssigmentOperator=*/true);
8311 // volatile restrict version
8313 = S.Context.getLValueReferenceType(
8314 S.Context.getCVRQualifiedType(*Ptr,
8315 (Qualifiers::Volatile |
8316 Qualifiers::Restrict)));
8317 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8318 /*IsAssigmentOperator=*/true);
8325 // C++ [over.built]p18:
8327 // For every triple (L, VQ, R), where L is an arithmetic type,
8328 // VQ is either volatile or empty, and R is a promoted
8329 // arithmetic type, there exist candidate operator functions of
8332 // VQ L& operator=(VQ L&, R);
8333 // VQ L& operator*=(VQ L&, R);
8334 // VQ L& operator/=(VQ L&, R);
8335 // VQ L& operator+=(VQ L&, R);
8336 // VQ L& operator-=(VQ L&, R);
8337 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8338 if (!HasArithmeticOrEnumeralCandidateType)
8341 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8342 for (unsigned Right = FirstPromotedArithmeticType;
8343 Right < LastPromotedArithmeticType; ++Right) {
8344 QualType ParamTypes[2];
8345 ParamTypes[1] = ArithmeticTypes[Right];
8347 // Add this built-in operator as a candidate (VQ is empty).
8349 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8350 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8351 /*IsAssigmentOperator=*/isEqualOp);
8353 // Add this built-in operator as a candidate (VQ is 'volatile').
8354 if (VisibleTypeConversionsQuals.hasVolatile()) {
8356 S.Context.getVolatileType(ArithmeticTypes[Left]);
8357 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8358 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8359 /*IsAssigmentOperator=*/isEqualOp);
8364 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8365 for (BuiltinCandidateTypeSet::iterator
8366 Vec1 = CandidateTypes[0].vector_begin(),
8367 Vec1End = CandidateTypes[0].vector_end();
8368 Vec1 != Vec1End; ++Vec1) {
8369 for (BuiltinCandidateTypeSet::iterator
8370 Vec2 = CandidateTypes[1].vector_begin(),
8371 Vec2End = CandidateTypes[1].vector_end();
8372 Vec2 != Vec2End; ++Vec2) {
8373 QualType ParamTypes[2];
8374 ParamTypes[1] = *Vec2;
8375 // Add this built-in operator as a candidate (VQ is empty).
8376 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8377 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8378 /*IsAssigmentOperator=*/isEqualOp);
8380 // Add this built-in operator as a candidate (VQ is 'volatile').
8381 if (VisibleTypeConversionsQuals.hasVolatile()) {
8382 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8383 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8384 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8385 /*IsAssigmentOperator=*/isEqualOp);
8391 // C++ [over.built]p22:
8393 // For every triple (L, VQ, R), where L is an integral type, VQ
8394 // is either volatile or empty, and R is a promoted integral
8395 // type, there exist candidate operator functions of the form
8397 // VQ L& operator%=(VQ L&, R);
8398 // VQ L& operator<<=(VQ L&, R);
8399 // VQ L& operator>>=(VQ L&, R);
8400 // VQ L& operator&=(VQ L&, R);
8401 // VQ L& operator^=(VQ L&, R);
8402 // VQ L& operator|=(VQ L&, R);
8403 void addAssignmentIntegralOverloads() {
8404 if (!HasArithmeticOrEnumeralCandidateType)
8407 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8408 for (unsigned Right = FirstPromotedIntegralType;
8409 Right < LastPromotedIntegralType; ++Right) {
8410 QualType ParamTypes[2];
8411 ParamTypes[1] = ArithmeticTypes[Right];
8413 // Add this built-in operator as a candidate (VQ is empty).
8415 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8416 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8417 if (VisibleTypeConversionsQuals.hasVolatile()) {
8418 // Add this built-in operator as a candidate (VQ is 'volatile').
8419 ParamTypes[0] = ArithmeticTypes[Left];
8420 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8421 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8428 // C++ [over.operator]p23:
8430 // There also exist candidate operator functions of the form
8432 // bool operator!(bool);
8433 // bool operator&&(bool, bool);
8434 // bool operator||(bool, bool);
8435 void addExclaimOverload() {
8436 QualType ParamTy = S.Context.BoolTy;
8437 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8438 /*IsAssignmentOperator=*/false,
8439 /*NumContextualBoolArguments=*/1);
8441 void addAmpAmpOrPipePipeOverload() {
8442 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8443 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8444 /*IsAssignmentOperator=*/false,
8445 /*NumContextualBoolArguments=*/2);
8448 // C++ [over.built]p13:
8450 // For every cv-qualified or cv-unqualified object type T there
8451 // exist candidate operator functions of the form
8453 // T* operator+(T*, ptrdiff_t); [ABOVE]
8454 // T& operator[](T*, ptrdiff_t);
8455 // T* operator-(T*, ptrdiff_t); [ABOVE]
8456 // T* operator+(ptrdiff_t, T*); [ABOVE]
8457 // T& operator[](ptrdiff_t, T*);
8458 void addSubscriptOverloads() {
8459 for (BuiltinCandidateTypeSet::iterator
8460 Ptr = CandidateTypes[0].pointer_begin(),
8461 PtrEnd = CandidateTypes[0].pointer_end();
8462 Ptr != PtrEnd; ++Ptr) {
8463 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8464 QualType PointeeType = (*Ptr)->getPointeeType();
8465 if (!PointeeType->isObjectType())
8468 // T& operator[](T*, ptrdiff_t)
8469 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8472 for (BuiltinCandidateTypeSet::iterator
8473 Ptr = CandidateTypes[1].pointer_begin(),
8474 PtrEnd = CandidateTypes[1].pointer_end();
8475 Ptr != PtrEnd; ++Ptr) {
8476 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8477 QualType PointeeType = (*Ptr)->getPointeeType();
8478 if (!PointeeType->isObjectType())
8481 // T& operator[](ptrdiff_t, T*)
8482 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8486 // C++ [over.built]p11:
8487 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8488 // C1 is the same type as C2 or is a derived class of C2, T is an object
8489 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8490 // there exist candidate operator functions of the form
8492 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8494 // where CV12 is the union of CV1 and CV2.
8495 void addArrowStarOverloads() {
8496 for (BuiltinCandidateTypeSet::iterator
8497 Ptr = CandidateTypes[0].pointer_begin(),
8498 PtrEnd = CandidateTypes[0].pointer_end();
8499 Ptr != PtrEnd; ++Ptr) {
8500 QualType C1Ty = (*Ptr);
8502 QualifierCollector Q1;
8503 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8504 if (!isa<RecordType>(C1))
8506 // heuristic to reduce number of builtin candidates in the set.
8507 // Add volatile/restrict version only if there are conversions to a
8508 // volatile/restrict type.
8509 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8511 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8513 for (BuiltinCandidateTypeSet::iterator
8514 MemPtr = CandidateTypes[1].member_pointer_begin(),
8515 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8516 MemPtr != MemPtrEnd; ++MemPtr) {
8517 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8518 QualType C2 = QualType(mptr->getClass(), 0);
8519 C2 = C2.getUnqualifiedType();
8520 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8522 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8524 QualType T = mptr->getPointeeType();
8525 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8526 T.isVolatileQualified())
8528 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8529 T.isRestrictQualified())
8531 T = Q1.apply(S.Context, T);
8532 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8537 // Note that we don't consider the first argument, since it has been
8538 // contextually converted to bool long ago. The candidates below are
8539 // therefore added as binary.
8541 // C++ [over.built]p25:
8542 // For every type T, where T is a pointer, pointer-to-member, or scoped
8543 // enumeration type, there exist candidate operator functions of the form
8545 // T operator?(bool, T, T);
8547 void addConditionalOperatorOverloads() {
8548 /// Set of (canonical) types that we've already handled.
8549 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8551 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8552 for (BuiltinCandidateTypeSet::iterator
8553 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8554 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8555 Ptr != PtrEnd; ++Ptr) {
8556 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8559 QualType ParamTypes[2] = { *Ptr, *Ptr };
8560 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8563 for (BuiltinCandidateTypeSet::iterator
8564 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8565 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8566 MemPtr != MemPtrEnd; ++MemPtr) {
8567 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8570 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8571 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8574 if (S.getLangOpts().CPlusPlus11) {
8575 for (BuiltinCandidateTypeSet::iterator
8576 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8577 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8578 Enum != EnumEnd; ++Enum) {
8579 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8582 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8585 QualType ParamTypes[2] = { *Enum, *Enum };
8586 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8593 } // end anonymous namespace
8595 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8596 /// operator overloads to the candidate set (C++ [over.built]), based
8597 /// on the operator @p Op and the arguments given. For example, if the
8598 /// operator is a binary '+', this routine might add "int
8599 /// operator+(int, int)" to cover integer addition.
8600 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8601 SourceLocation OpLoc,
8602 ArrayRef<Expr *> Args,
8603 OverloadCandidateSet &CandidateSet) {
8604 // Find all of the types that the arguments can convert to, but only
8605 // if the operator we're looking at has built-in operator candidates
8606 // that make use of these types. Also record whether we encounter non-record
8607 // candidate types or either arithmetic or enumeral candidate types.
8608 Qualifiers VisibleTypeConversionsQuals;
8609 VisibleTypeConversionsQuals.addConst();
8610 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8611 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8613 bool HasNonRecordCandidateType = false;
8614 bool HasArithmeticOrEnumeralCandidateType = false;
8615 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8616 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8617 CandidateTypes.emplace_back(*this);
8618 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8621 (Op == OO_Exclaim ||
8624 VisibleTypeConversionsQuals);
8625 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8626 CandidateTypes[ArgIdx].hasNonRecordTypes();
8627 HasArithmeticOrEnumeralCandidateType =
8628 HasArithmeticOrEnumeralCandidateType ||
8629 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8632 // Exit early when no non-record types have been added to the candidate set
8633 // for any of the arguments to the operator.
8635 // We can't exit early for !, ||, or &&, since there we have always have
8636 // 'bool' overloads.
8637 if (!HasNonRecordCandidateType &&
8638 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8641 // Setup an object to manage the common state for building overloads.
8642 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8643 VisibleTypeConversionsQuals,
8644 HasArithmeticOrEnumeralCandidateType,
8645 CandidateTypes, CandidateSet);
8647 // Dispatch over the operation to add in only those overloads which apply.
8650 case NUM_OVERLOADED_OPERATORS:
8651 llvm_unreachable("Expected an overloaded operator");
8656 case OO_Array_Delete:
8659 "Special operators don't use AddBuiltinOperatorCandidates");
8664 // C++ [over.match.oper]p3:
8665 // -- For the operator ',', the unary operator '&', the
8666 // operator '->', or the operator 'co_await', the
8667 // built-in candidates set is empty.
8670 case OO_Plus: // '+' is either unary or binary
8671 if (Args.size() == 1)
8672 OpBuilder.addUnaryPlusPointerOverloads();
8675 case OO_Minus: // '-' is either unary or binary
8676 if (Args.size() == 1) {
8677 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8679 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8680 OpBuilder.addGenericBinaryArithmeticOverloads();
8684 case OO_Star: // '*' is either unary or binary
8685 if (Args.size() == 1)
8686 OpBuilder.addUnaryStarPointerOverloads();
8688 OpBuilder.addGenericBinaryArithmeticOverloads();
8692 OpBuilder.addGenericBinaryArithmeticOverloads();
8697 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8698 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8702 case OO_ExclaimEqual:
8703 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8709 case OO_GreaterEqual:
8710 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8711 OpBuilder.addGenericBinaryArithmeticOverloads();
8715 llvm_unreachable("<=> expressions not supported yet");
8721 case OO_GreaterGreater:
8722 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8725 case OO_Amp: // '&' is either unary or binary
8726 if (Args.size() == 1)
8727 // C++ [over.match.oper]p3:
8728 // -- For the operator ',', the unary operator '&', or the
8729 // operator '->', the built-in candidates set is empty.
8732 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8736 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8740 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8745 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8750 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8753 case OO_PercentEqual:
8754 case OO_LessLessEqual:
8755 case OO_GreaterGreaterEqual:
8759 OpBuilder.addAssignmentIntegralOverloads();
8763 OpBuilder.addExclaimOverload();
8768 OpBuilder.addAmpAmpOrPipePipeOverload();
8772 OpBuilder.addSubscriptOverloads();
8776 OpBuilder.addArrowStarOverloads();
8779 case OO_Conditional:
8780 OpBuilder.addConditionalOperatorOverloads();
8781 OpBuilder.addGenericBinaryArithmeticOverloads();
8786 /// \brief Add function candidates found via argument-dependent lookup
8787 /// to the set of overloading candidates.
8789 /// This routine performs argument-dependent name lookup based on the
8790 /// given function name (which may also be an operator name) and adds
8791 /// all of the overload candidates found by ADL to the overload
8792 /// candidate set (C++ [basic.lookup.argdep]).
8794 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8796 ArrayRef<Expr *> Args,
8797 TemplateArgumentListInfo *ExplicitTemplateArgs,
8798 OverloadCandidateSet& CandidateSet,
8799 bool PartialOverloading) {
8802 // FIXME: This approach for uniquing ADL results (and removing
8803 // redundant candidates from the set) relies on pointer-equality,
8804 // which means we need to key off the canonical decl. However,
8805 // always going back to the canonical decl might not get us the
8806 // right set of default arguments. What default arguments are
8807 // we supposed to consider on ADL candidates, anyway?
8809 // FIXME: Pass in the explicit template arguments?
8810 ArgumentDependentLookup(Name, Loc, Args, Fns);
8812 // Erase all of the candidates we already knew about.
8813 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8814 CandEnd = CandidateSet.end();
8815 Cand != CandEnd; ++Cand)
8816 if (Cand->Function) {
8817 Fns.erase(Cand->Function);
8818 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8822 // For each of the ADL candidates we found, add it to the overload
8824 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8825 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8826 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8827 if (ExplicitTemplateArgs)
8830 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8831 PartialOverloading);
8833 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8834 FoundDecl, ExplicitTemplateArgs,
8835 Args, CandidateSet, PartialOverloading);
8840 enum class Comparison { Equal, Better, Worse };
8843 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8844 /// overload resolution.
8846 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8847 /// Cand1's first N enable_if attributes have precisely the same conditions as
8848 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8849 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8851 /// Note that you can have a pair of candidates such that Cand1's enable_if
8852 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8853 /// worse than Cand1's.
8854 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8855 const FunctionDecl *Cand2) {
8856 // Common case: One (or both) decls don't have enable_if attrs.
8857 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8858 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8859 if (!Cand1Attr || !Cand2Attr) {
8860 if (Cand1Attr == Cand2Attr)
8861 return Comparison::Equal;
8862 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8865 // FIXME: The next several lines are just
8866 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8867 // instead of reverse order which is how they're stored in the AST.
8868 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8869 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8871 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8872 // has fewer enable_if attributes than Cand2.
8873 if (Cand1Attrs.size() < Cand2Attrs.size())
8874 return Comparison::Worse;
8876 auto Cand1I = Cand1Attrs.begin();
8877 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8878 for (auto &Cand2A : Cand2Attrs) {
8882 auto &Cand1A = *Cand1I++;
8883 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8884 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8885 if (Cand1ID != Cand2ID)
8886 return Comparison::Worse;
8889 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8892 /// isBetterOverloadCandidate - Determines whether the first overload
8893 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8894 bool clang::isBetterOverloadCandidate(
8895 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8896 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8897 // Define viable functions to be better candidates than non-viable
8900 return Cand1.Viable;
8901 else if (!Cand1.Viable)
8904 // C++ [over.match.best]p1:
8906 // -- if F is a static member function, ICS1(F) is defined such
8907 // that ICS1(F) is neither better nor worse than ICS1(G) for
8908 // any function G, and, symmetrically, ICS1(G) is neither
8909 // better nor worse than ICS1(F).
8910 unsigned StartArg = 0;
8911 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8914 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8915 // We don't allow incompatible pointer conversions in C++.
8916 if (!S.getLangOpts().CPlusPlus)
8917 return ICS.isStandard() &&
8918 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8920 // The only ill-formed conversion we allow in C++ is the string literal to
8921 // char* conversion, which is only considered ill-formed after C++11.
8922 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8923 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8926 // Define functions that don't require ill-formed conversions for a given
8927 // argument to be better candidates than functions that do.
8928 unsigned NumArgs = Cand1.Conversions.size();
8929 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8930 bool HasBetterConversion = false;
8931 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8932 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8933 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8934 if (Cand1Bad != Cand2Bad) {
8937 HasBetterConversion = true;
8941 if (HasBetterConversion)
8944 // C++ [over.match.best]p1:
8945 // A viable function F1 is defined to be a better function than another
8946 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8947 // conversion sequence than ICSi(F2), and then...
8948 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8949 switch (CompareImplicitConversionSequences(S, Loc,
8950 Cand1.Conversions[ArgIdx],
8951 Cand2.Conversions[ArgIdx])) {
8952 case ImplicitConversionSequence::Better:
8953 // Cand1 has a better conversion sequence.
8954 HasBetterConversion = true;
8957 case ImplicitConversionSequence::Worse:
8958 // Cand1 can't be better than Cand2.
8961 case ImplicitConversionSequence::Indistinguishable:
8967 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8968 // ICSj(F2), or, if not that,
8969 if (HasBetterConversion)
8972 // -- the context is an initialization by user-defined conversion
8973 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8974 // from the return type of F1 to the destination type (i.e.,
8975 // the type of the entity being initialized) is a better
8976 // conversion sequence than the standard conversion sequence
8977 // from the return type of F2 to the destination type.
8978 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
8979 Cand1.Function && Cand2.Function &&
8980 isa<CXXConversionDecl>(Cand1.Function) &&
8981 isa<CXXConversionDecl>(Cand2.Function)) {
8982 // First check whether we prefer one of the conversion functions over the
8983 // other. This only distinguishes the results in non-standard, extension
8984 // cases such as the conversion from a lambda closure type to a function
8985 // pointer or block.
8986 ImplicitConversionSequence::CompareKind Result =
8987 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8988 if (Result == ImplicitConversionSequence::Indistinguishable)
8989 Result = CompareStandardConversionSequences(S, Loc,
8990 Cand1.FinalConversion,
8991 Cand2.FinalConversion);
8993 if (Result != ImplicitConversionSequence::Indistinguishable)
8994 return Result == ImplicitConversionSequence::Better;
8996 // FIXME: Compare kind of reference binding if conversion functions
8997 // convert to a reference type used in direct reference binding, per
8998 // C++14 [over.match.best]p1 section 2 bullet 3.
9001 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9002 // as combined with the resolution to CWG issue 243.
9004 // When the context is initialization by constructor ([over.match.ctor] or
9005 // either phase of [over.match.list]), a constructor is preferred over
9006 // a conversion function.
9007 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9008 Cand1.Function && Cand2.Function &&
9009 isa<CXXConstructorDecl>(Cand1.Function) !=
9010 isa<CXXConstructorDecl>(Cand2.Function))
9011 return isa<CXXConstructorDecl>(Cand1.Function);
9013 // -- F1 is a non-template function and F2 is a function template
9014 // specialization, or, if not that,
9015 bool Cand1IsSpecialization = Cand1.Function &&
9016 Cand1.Function->getPrimaryTemplate();
9017 bool Cand2IsSpecialization = Cand2.Function &&
9018 Cand2.Function->getPrimaryTemplate();
9019 if (Cand1IsSpecialization != Cand2IsSpecialization)
9020 return Cand2IsSpecialization;
9022 // -- F1 and F2 are function template specializations, and the function
9023 // template for F1 is more specialized than the template for F2
9024 // according to the partial ordering rules described in 14.5.5.2, or,
9026 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9027 if (FunctionTemplateDecl *BetterTemplate
9028 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9029 Cand2.Function->getPrimaryTemplate(),
9031 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9033 Cand1.ExplicitCallArguments,
9034 Cand2.ExplicitCallArguments))
9035 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9038 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9039 // A derived-class constructor beats an (inherited) base class constructor.
9040 bool Cand1IsInherited =
9041 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9042 bool Cand2IsInherited =
9043 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9044 if (Cand1IsInherited != Cand2IsInherited)
9045 return Cand2IsInherited;
9046 else if (Cand1IsInherited) {
9047 assert(Cand2IsInherited);
9048 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9049 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9050 if (Cand1Class->isDerivedFrom(Cand2Class))
9052 if (Cand2Class->isDerivedFrom(Cand1Class))
9054 // Inherited from sibling base classes: still ambiguous.
9057 // Check C++17 tie-breakers for deduction guides.
9059 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9060 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9061 if (Guide1 && Guide2) {
9062 // -- F1 is generated from a deduction-guide and F2 is not
9063 if (Guide1->isImplicit() != Guide2->isImplicit())
9064 return Guide2->isImplicit();
9066 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9067 if (Guide1->isCopyDeductionCandidate())
9072 // Check for enable_if value-based overload resolution.
9073 if (Cand1.Function && Cand2.Function) {
9074 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9075 if (Cmp != Comparison::Equal)
9076 return Cmp == Comparison::Better;
9079 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9080 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9081 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9082 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9085 bool HasPS1 = Cand1.Function != nullptr &&
9086 functionHasPassObjectSizeParams(Cand1.Function);
9087 bool HasPS2 = Cand2.Function != nullptr &&
9088 functionHasPassObjectSizeParams(Cand2.Function);
9089 return HasPS1 != HasPS2 && HasPS1;
9092 /// Determine whether two declarations are "equivalent" for the purposes of
9093 /// name lookup and overload resolution. This applies when the same internal/no
9094 /// linkage entity is defined by two modules (probably by textually including
9095 /// the same header). In such a case, we don't consider the declarations to
9096 /// declare the same entity, but we also don't want lookups with both
9097 /// declarations visible to be ambiguous in some cases (this happens when using
9098 /// a modularized libstdc++).
9099 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9100 const NamedDecl *B) {
9101 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9102 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9106 // The declarations must be declaring the same name as an internal linkage
9107 // entity in different modules.
9108 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9109 VB->getDeclContext()->getRedeclContext()) ||
9110 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9111 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9112 VA->isExternallyVisible() || VB->isExternallyVisible())
9115 // Check that the declarations appear to be equivalent.
9117 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9118 // For constants and functions, we should check the initializer or body is
9119 // the same. For non-constant variables, we shouldn't allow it at all.
9120 if (Context.hasSameType(VA->getType(), VB->getType()))
9123 // Enum constants within unnamed enumerations will have different types, but
9124 // may still be similar enough to be interchangeable for our purposes.
9125 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9126 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9127 // Only handle anonymous enums. If the enumerations were named and
9128 // equivalent, they would have been merged to the same type.
9129 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9130 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9131 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9132 !Context.hasSameType(EnumA->getIntegerType(),
9133 EnumB->getIntegerType()))
9135 // Allow this only if the value is the same for both enumerators.
9136 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9140 // Nothing else is sufficiently similar.
9144 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9145 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9146 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9148 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9149 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9150 << !M << (M ? M->getFullModuleName() : "");
9152 for (auto *E : Equiv) {
9153 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9154 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9155 << !M << (M ? M->getFullModuleName() : "");
9159 /// \brief Computes the best viable function (C++ 13.3.3)
9160 /// within an overload candidate set.
9162 /// \param Loc The location of the function name (or operator symbol) for
9163 /// which overload resolution occurs.
9165 /// \param Best If overload resolution was successful or found a deleted
9166 /// function, \p Best points to the candidate function found.
9168 /// \returns The result of overload resolution.
9170 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9172 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9173 std::transform(begin(), end(), std::back_inserter(Candidates),
9174 [](OverloadCandidate &Cand) { return &Cand; });
9176 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9177 // are accepted by both clang and NVCC. However, during a particular
9178 // compilation mode only one call variant is viable. We need to
9179 // exclude non-viable overload candidates from consideration based
9180 // only on their host/device attributes. Specifically, if one
9181 // candidate call is WrongSide and the other is SameSide, we ignore
9182 // the WrongSide candidate.
9183 if (S.getLangOpts().CUDA) {
9184 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9185 bool ContainsSameSideCandidate =
9186 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9187 return Cand->Function &&
9188 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9191 if (ContainsSameSideCandidate) {
9192 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9193 return Cand->Function &&
9194 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9195 Sema::CFP_WrongSide;
9197 llvm::erase_if(Candidates, IsWrongSideCandidate);
9201 // Find the best viable function.
9203 for (auto *Cand : Candidates)
9205 if (Best == end() ||
9206 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9209 // If we didn't find any viable functions, abort.
9211 return OR_No_Viable_Function;
9213 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9215 // Make sure that this function is better than every other viable
9216 // function. If not, we have an ambiguity.
9217 for (auto *Cand : Candidates) {
9218 if (Cand->Viable && Cand != Best &&
9219 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9220 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9222 EquivalentCands.push_back(Cand->Function);
9227 return OR_Ambiguous;
9231 // Best is the best viable function.
9232 if (Best->Function &&
9233 (Best->Function->isDeleted() ||
9234 S.isFunctionConsideredUnavailable(Best->Function)))
9237 if (!EquivalentCands.empty())
9238 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9246 enum OverloadCandidateKind {
9250 oc_function_template,
9252 oc_constructor_template,
9253 oc_implicit_default_constructor,
9254 oc_implicit_copy_constructor,
9255 oc_implicit_move_constructor,
9256 oc_implicit_copy_assignment,
9257 oc_implicit_move_assignment,
9258 oc_inherited_constructor,
9259 oc_inherited_constructor_template
9262 static OverloadCandidateKind
9263 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9264 std::string &Description) {
9265 bool isTemplate = false;
9267 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9269 Description = S.getTemplateArgumentBindingsText(
9270 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9273 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9274 if (!Ctor->isImplicit()) {
9275 if (isa<ConstructorUsingShadowDecl>(Found))
9276 return isTemplate ? oc_inherited_constructor_template
9277 : oc_inherited_constructor;
9279 return isTemplate ? oc_constructor_template : oc_constructor;
9282 if (Ctor->isDefaultConstructor())
9283 return oc_implicit_default_constructor;
9285 if (Ctor->isMoveConstructor())
9286 return oc_implicit_move_constructor;
9288 assert(Ctor->isCopyConstructor() &&
9289 "unexpected sort of implicit constructor");
9290 return oc_implicit_copy_constructor;
9293 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9294 // This actually gets spelled 'candidate function' for now, but
9295 // it doesn't hurt to split it out.
9296 if (!Meth->isImplicit())
9297 return isTemplate ? oc_method_template : oc_method;
9299 if (Meth->isMoveAssignmentOperator())
9300 return oc_implicit_move_assignment;
9302 if (Meth->isCopyAssignmentOperator())
9303 return oc_implicit_copy_assignment;
9305 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9309 return isTemplate ? oc_function_template : oc_function;
9312 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9313 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9315 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9316 S.Diag(FoundDecl->getLocation(),
9317 diag::note_ovl_candidate_inherited_constructor)
9318 << Shadow->getNominatedBaseClass();
9321 } // end anonymous namespace
9323 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9324 const FunctionDecl *FD) {
9325 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9327 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9335 /// \brief Returns true if we can take the address of the function.
9337 /// \param Complain - If true, we'll emit a diagnostic
9338 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9339 /// we in overload resolution?
9340 /// \param Loc - The location of the statement we're complaining about. Ignored
9341 /// if we're not complaining, or if we're in overload resolution.
9342 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9344 bool InOverloadResolution,
9345 SourceLocation Loc) {
9346 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9348 if (InOverloadResolution)
9349 S.Diag(FD->getLocStart(),
9350 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9352 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9357 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9358 return P->hasAttr<PassObjectSizeAttr>();
9360 if (I == FD->param_end())
9364 // Add one to ParamNo because it's user-facing
9365 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9366 if (InOverloadResolution)
9367 S.Diag(FD->getLocation(),
9368 diag::note_ovl_candidate_has_pass_object_size_params)
9371 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9377 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9378 const FunctionDecl *FD) {
9379 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9380 /*InOverloadResolution=*/true,
9381 /*Loc=*/SourceLocation());
9384 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9386 SourceLocation Loc) {
9387 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9388 /*InOverloadResolution=*/false,
9392 // Notes the location of an overload candidate.
9393 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9394 QualType DestType, bool TakingAddress) {
9395 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9399 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9400 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9401 << (unsigned) K << Fn << FnDesc;
9403 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9404 Diag(Fn->getLocation(), PD);
9405 MaybeEmitInheritedConstructorNote(*this, Found);
9408 // Notes the location of all overload candidates designated through
9410 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9411 bool TakingAddress) {
9412 assert(OverloadedExpr->getType() == Context.OverloadTy);
9414 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9415 OverloadExpr *OvlExpr = Ovl.Expression;
9417 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9418 IEnd = OvlExpr->decls_end();
9420 if (FunctionTemplateDecl *FunTmpl =
9421 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9422 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9424 } else if (FunctionDecl *Fun
9425 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9426 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9431 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
9432 /// "lead" diagnostic; it will be given two arguments, the source and
9433 /// target types of the conversion.
9434 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9436 SourceLocation CaretLoc,
9437 const PartialDiagnostic &PDiag) const {
9438 S.Diag(CaretLoc, PDiag)
9439 << Ambiguous.getFromType() << Ambiguous.getToType();
9440 // FIXME: The note limiting machinery is borrowed from
9441 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9442 // refactoring here.
9443 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9444 unsigned CandsShown = 0;
9445 AmbiguousConversionSequence::const_iterator I, E;
9446 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9447 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9450 S.NoteOverloadCandidate(I->first, I->second);
9453 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9456 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9457 unsigned I, bool TakingCandidateAddress) {
9458 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9459 assert(Conv.isBad());
9460 assert(Cand->Function && "for now, candidate must be a function");
9461 FunctionDecl *Fn = Cand->Function;
9463 // There's a conversion slot for the object argument if this is a
9464 // non-constructor method. Note that 'I' corresponds the
9465 // conversion-slot index.
9466 bool isObjectArgument = false;
9467 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9469 isObjectArgument = true;
9475 OverloadCandidateKind FnKind =
9476 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9478 Expr *FromExpr = Conv.Bad.FromExpr;
9479 QualType FromTy = Conv.Bad.getFromType();
9480 QualType ToTy = Conv.Bad.getToType();
9482 if (FromTy == S.Context.OverloadTy) {
9483 assert(FromExpr && "overload set argument came from implicit argument?");
9484 Expr *E = FromExpr->IgnoreParens();
9485 if (isa<UnaryOperator>(E))
9486 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9487 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9489 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9490 << (unsigned) FnKind << FnDesc
9491 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9492 << ToTy << Name << I+1;
9493 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9497 // Do some hand-waving analysis to see if the non-viability is due
9498 // to a qualifier mismatch.
9499 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9500 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9501 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9502 CToTy = RT->getPointeeType();
9504 // TODO: detect and diagnose the full richness of const mismatches.
9505 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9506 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9507 CFromTy = FromPT->getPointeeType();
9508 CToTy = ToPT->getPointeeType();
9512 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9513 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9514 Qualifiers FromQs = CFromTy.getQualifiers();
9515 Qualifiers ToQs = CToTy.getQualifiers();
9517 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9519 << (unsigned) FnKind << FnDesc
9520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9522 << FromQs.getAddressSpaceAttributePrintValue()
9523 << ToQs.getAddressSpaceAttributePrintValue()
9524 << (unsigned) isObjectArgument << I+1;
9525 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9529 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9530 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9531 << (unsigned) FnKind << FnDesc
9532 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9534 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9535 << (unsigned) isObjectArgument << I+1;
9536 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9540 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9541 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9542 << (unsigned) FnKind << FnDesc
9543 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9545 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9546 << (unsigned) isObjectArgument << I+1;
9547 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9551 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9552 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9553 << (unsigned) FnKind << FnDesc
9554 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9555 << FromTy << FromQs.hasUnaligned() << I+1;
9556 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9560 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9561 assert(CVR && "unexpected qualifiers mismatch");
9563 if (isObjectArgument) {
9564 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9565 << (unsigned) FnKind << FnDesc
9566 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9567 << FromTy << (CVR - 1);
9569 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9570 << (unsigned) FnKind << FnDesc
9571 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9572 << FromTy << (CVR - 1) << I+1;
9574 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9578 // Special diagnostic for failure to convert an initializer list, since
9579 // telling the user that it has type void is not useful.
9580 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9582 << (unsigned) FnKind << FnDesc
9583 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9584 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9585 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9589 // Diagnose references or pointers to incomplete types differently,
9590 // since it's far from impossible that the incompleteness triggered
9592 QualType TempFromTy = FromTy.getNonReferenceType();
9593 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9594 TempFromTy = PTy->getPointeeType();
9595 if (TempFromTy->isIncompleteType()) {
9596 // Emit the generic diagnostic and, optionally, add the hints to it.
9597 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9598 << (unsigned) FnKind << FnDesc
9599 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9600 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9601 << (unsigned) (Cand->Fix.Kind);
9603 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9607 // Diagnose base -> derived pointer conversions.
9608 unsigned BaseToDerivedConversion = 0;
9609 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9610 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9611 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9612 FromPtrTy->getPointeeType()) &&
9613 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9614 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9615 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9616 FromPtrTy->getPointeeType()))
9617 BaseToDerivedConversion = 1;
9619 } else if (const ObjCObjectPointerType *FromPtrTy
9620 = FromTy->getAs<ObjCObjectPointerType>()) {
9621 if (const ObjCObjectPointerType *ToPtrTy
9622 = ToTy->getAs<ObjCObjectPointerType>())
9623 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9624 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9625 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9626 FromPtrTy->getPointeeType()) &&
9627 FromIface->isSuperClassOf(ToIface))
9628 BaseToDerivedConversion = 2;
9629 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9630 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9631 !FromTy->isIncompleteType() &&
9632 !ToRefTy->getPointeeType()->isIncompleteType() &&
9633 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9634 BaseToDerivedConversion = 3;
9635 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9636 ToTy.getNonReferenceType().getCanonicalType() ==
9637 FromTy.getNonReferenceType().getCanonicalType()) {
9638 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9639 << (unsigned) FnKind << FnDesc
9640 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9641 << (unsigned) isObjectArgument << I + 1;
9642 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9647 if (BaseToDerivedConversion) {
9648 S.Diag(Fn->getLocation(),
9649 diag::note_ovl_candidate_bad_base_to_derived_conv)
9650 << (unsigned) FnKind << FnDesc
9651 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9652 << (BaseToDerivedConversion - 1)
9653 << FromTy << ToTy << I+1;
9654 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9658 if (isa<ObjCObjectPointerType>(CFromTy) &&
9659 isa<PointerType>(CToTy)) {
9660 Qualifiers FromQs = CFromTy.getQualifiers();
9661 Qualifiers ToQs = CToTy.getQualifiers();
9662 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9664 << (unsigned) FnKind << FnDesc
9665 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9666 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9667 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9672 if (TakingCandidateAddress &&
9673 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9676 // Emit the generic diagnostic and, optionally, add the hints to it.
9677 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9678 FDiag << (unsigned) FnKind << FnDesc
9679 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9680 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9681 << (unsigned) (Cand->Fix.Kind);
9683 // If we can fix the conversion, suggest the FixIts.
9684 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9685 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9687 S.Diag(Fn->getLocation(), FDiag);
9689 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9692 /// Additional arity mismatch diagnosis specific to a function overload
9693 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9694 /// over a candidate in any candidate set.
9695 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9697 FunctionDecl *Fn = Cand->Function;
9698 unsigned MinParams = Fn->getMinRequiredArguments();
9700 // With invalid overloaded operators, it's possible that we think we
9701 // have an arity mismatch when in fact it looks like we have the
9702 // right number of arguments, because only overloaded operators have
9703 // the weird behavior of overloading member and non-member functions.
9704 // Just don't report anything.
9705 if (Fn->isInvalidDecl() &&
9706 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9709 if (NumArgs < MinParams) {
9710 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9711 (Cand->FailureKind == ovl_fail_bad_deduction &&
9712 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9714 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9715 (Cand->FailureKind == ovl_fail_bad_deduction &&
9716 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9722 /// General arity mismatch diagnosis over a candidate in a candidate set.
9723 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9724 unsigned NumFormalArgs) {
9725 assert(isa<FunctionDecl>(D) &&
9726 "The templated declaration should at least be a function"
9727 " when diagnosing bad template argument deduction due to too many"
9728 " or too few arguments");
9730 FunctionDecl *Fn = cast<FunctionDecl>(D);
9732 // TODO: treat calls to a missing default constructor as a special case
9733 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9734 unsigned MinParams = Fn->getMinRequiredArguments();
9736 // at least / at most / exactly
9737 unsigned mode, modeCount;
9738 if (NumFormalArgs < MinParams) {
9739 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9740 FnTy->isTemplateVariadic())
9741 mode = 0; // "at least"
9743 mode = 2; // "exactly"
9744 modeCount = MinParams;
9746 if (MinParams != FnTy->getNumParams())
9747 mode = 1; // "at most"
9749 mode = 2; // "exactly"
9750 modeCount = FnTy->getNumParams();
9753 std::string Description;
9754 OverloadCandidateKind FnKind =
9755 ClassifyOverloadCandidate(S, Found, Fn, Description);
9757 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9759 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9760 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9763 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9764 << mode << modeCount << NumFormalArgs;
9765 MaybeEmitInheritedConstructorNote(S, Found);
9768 /// Arity mismatch diagnosis specific to a function overload candidate.
9769 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9770 unsigned NumFormalArgs) {
9771 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9772 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9775 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9776 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9778 llvm_unreachable("Unsupported: Getting the described template declaration"
9779 " for bad deduction diagnosis");
9782 /// Diagnose a failed template-argument deduction.
9783 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9784 DeductionFailureInfo &DeductionFailure,
9786 bool TakingCandidateAddress) {
9787 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9789 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9790 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9791 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9792 switch (DeductionFailure.Result) {
9793 case Sema::TDK_Success:
9794 llvm_unreachable("TDK_success while diagnosing bad deduction");
9796 case Sema::TDK_Incomplete: {
9797 assert(ParamD && "no parameter found for incomplete deduction result");
9798 S.Diag(Templated->getLocation(),
9799 diag::note_ovl_candidate_incomplete_deduction)
9800 << ParamD->getDeclName();
9801 MaybeEmitInheritedConstructorNote(S, Found);
9805 case Sema::TDK_Underqualified: {
9806 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9807 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9809 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9811 // Param will have been canonicalized, but it should just be a
9812 // qualified version of ParamD, so move the qualifiers to that.
9813 QualifierCollector Qs;
9815 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9816 assert(S.Context.hasSameType(Param, NonCanonParam));
9818 // Arg has also been canonicalized, but there's nothing we can do
9819 // about that. It also doesn't matter as much, because it won't
9820 // have any template parameters in it (because deduction isn't
9821 // done on dependent types).
9822 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9824 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9825 << ParamD->getDeclName() << Arg << NonCanonParam;
9826 MaybeEmitInheritedConstructorNote(S, Found);
9830 case Sema::TDK_Inconsistent: {
9831 assert(ParamD && "no parameter found for inconsistent deduction result");
9833 if (isa<TemplateTypeParmDecl>(ParamD))
9835 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9836 // Deduction might have failed because we deduced arguments of two
9837 // different types for a non-type template parameter.
9838 // FIXME: Use a different TDK value for this.
9840 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9842 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9843 if (!S.Context.hasSameType(T1, T2)) {
9844 S.Diag(Templated->getLocation(),
9845 diag::note_ovl_candidate_inconsistent_deduction_types)
9846 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9847 << *DeductionFailure.getSecondArg() << T2;
9848 MaybeEmitInheritedConstructorNote(S, Found);
9857 S.Diag(Templated->getLocation(),
9858 diag::note_ovl_candidate_inconsistent_deduction)
9859 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9860 << *DeductionFailure.getSecondArg();
9861 MaybeEmitInheritedConstructorNote(S, Found);
9865 case Sema::TDK_InvalidExplicitArguments:
9866 assert(ParamD && "no parameter found for invalid explicit arguments");
9867 if (ParamD->getDeclName())
9868 S.Diag(Templated->getLocation(),
9869 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9870 << ParamD->getDeclName();
9873 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9874 index = TTP->getIndex();
9875 else if (NonTypeTemplateParmDecl *NTTP
9876 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9877 index = NTTP->getIndex();
9879 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9880 S.Diag(Templated->getLocation(),
9881 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9884 MaybeEmitInheritedConstructorNote(S, Found);
9887 case Sema::TDK_TooManyArguments:
9888 case Sema::TDK_TooFewArguments:
9889 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9892 case Sema::TDK_InstantiationDepth:
9893 S.Diag(Templated->getLocation(),
9894 diag::note_ovl_candidate_instantiation_depth);
9895 MaybeEmitInheritedConstructorNote(S, Found);
9898 case Sema::TDK_SubstitutionFailure: {
9899 // Format the template argument list into the argument string.
9900 SmallString<128> TemplateArgString;
9901 if (TemplateArgumentList *Args =
9902 DeductionFailure.getTemplateArgumentList()) {
9903 TemplateArgString = " ";
9904 TemplateArgString += S.getTemplateArgumentBindingsText(
9905 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9908 // If this candidate was disabled by enable_if, say so.
9909 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9910 if (PDiag && PDiag->second.getDiagID() ==
9911 diag::err_typename_nested_not_found_enable_if) {
9912 // FIXME: Use the source range of the condition, and the fully-qualified
9913 // name of the enable_if template. These are both present in PDiag.
9914 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9915 << "'enable_if'" << TemplateArgString;
9919 // We found a specific requirement that disabled the enable_if.
9920 if (PDiag && PDiag->second.getDiagID() ==
9921 diag::err_typename_nested_not_found_requirement) {
9922 S.Diag(Templated->getLocation(),
9923 diag::note_ovl_candidate_disabled_by_requirement)
9924 << PDiag->second.getStringArg(0) << TemplateArgString;
9928 // Format the SFINAE diagnostic into the argument string.
9929 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9930 // formatted message in another diagnostic.
9931 SmallString<128> SFINAEArgString;
9934 SFINAEArgString = ": ";
9935 R = SourceRange(PDiag->first, PDiag->first);
9936 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9939 S.Diag(Templated->getLocation(),
9940 diag::note_ovl_candidate_substitution_failure)
9941 << TemplateArgString << SFINAEArgString << R;
9942 MaybeEmitInheritedConstructorNote(S, Found);
9946 case Sema::TDK_DeducedMismatch:
9947 case Sema::TDK_DeducedMismatchNested: {
9948 // Format the template argument list into the argument string.
9949 SmallString<128> TemplateArgString;
9950 if (TemplateArgumentList *Args =
9951 DeductionFailure.getTemplateArgumentList()) {
9952 TemplateArgString = " ";
9953 TemplateArgString += S.getTemplateArgumentBindingsText(
9954 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9957 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9958 << (*DeductionFailure.getCallArgIndex() + 1)
9959 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9960 << TemplateArgString
9961 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9965 case Sema::TDK_NonDeducedMismatch: {
9966 // FIXME: Provide a source location to indicate what we couldn't match.
9967 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9968 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9969 if (FirstTA.getKind() == TemplateArgument::Template &&
9970 SecondTA.getKind() == TemplateArgument::Template) {
9971 TemplateName FirstTN = FirstTA.getAsTemplate();
9972 TemplateName SecondTN = SecondTA.getAsTemplate();
9973 if (FirstTN.getKind() == TemplateName::Template &&
9974 SecondTN.getKind() == TemplateName::Template) {
9975 if (FirstTN.getAsTemplateDecl()->getName() ==
9976 SecondTN.getAsTemplateDecl()->getName()) {
9977 // FIXME: This fixes a bad diagnostic where both templates are named
9978 // the same. This particular case is a bit difficult since:
9979 // 1) It is passed as a string to the diagnostic printer.
9980 // 2) The diagnostic printer only attempts to find a better
9981 // name for types, not decls.
9982 // Ideally, this should folded into the diagnostic printer.
9983 S.Diag(Templated->getLocation(),
9984 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9985 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9991 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9992 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9995 // FIXME: For generic lambda parameters, check if the function is a lambda
9996 // call operator, and if so, emit a prettier and more informative
9997 // diagnostic that mentions 'auto' and lambda in addition to
9998 // (or instead of?) the canonical template type parameters.
9999 S.Diag(Templated->getLocation(),
10000 diag::note_ovl_candidate_non_deduced_mismatch)
10001 << FirstTA << SecondTA;
10004 // TODO: diagnose these individually, then kill off
10005 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10006 case Sema::TDK_MiscellaneousDeductionFailure:
10007 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10008 MaybeEmitInheritedConstructorNote(S, Found);
10010 case Sema::TDK_CUDATargetMismatch:
10011 S.Diag(Templated->getLocation(),
10012 diag::note_cuda_ovl_candidate_target_mismatch);
10017 /// Diagnose a failed template-argument deduction, for function calls.
10018 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10020 bool TakingCandidateAddress) {
10021 unsigned TDK = Cand->DeductionFailure.Result;
10022 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10023 if (CheckArityMismatch(S, Cand, NumArgs))
10026 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10027 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10030 /// CUDA: diagnose an invalid call across targets.
10031 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10032 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10033 FunctionDecl *Callee = Cand->Function;
10035 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10036 CalleeTarget = S.IdentifyCUDATarget(Callee);
10038 std::string FnDesc;
10039 OverloadCandidateKind FnKind =
10040 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10042 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10043 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10045 // This could be an implicit constructor for which we could not infer the
10046 // target due to a collsion. Diagnose that case.
10047 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10048 if (Meth != nullptr && Meth->isImplicit()) {
10049 CXXRecordDecl *ParentClass = Meth->getParent();
10050 Sema::CXXSpecialMember CSM;
10055 case oc_implicit_default_constructor:
10056 CSM = Sema::CXXDefaultConstructor;
10058 case oc_implicit_copy_constructor:
10059 CSM = Sema::CXXCopyConstructor;
10061 case oc_implicit_move_constructor:
10062 CSM = Sema::CXXMoveConstructor;
10064 case oc_implicit_copy_assignment:
10065 CSM = Sema::CXXCopyAssignment;
10067 case oc_implicit_move_assignment:
10068 CSM = Sema::CXXMoveAssignment;
10072 bool ConstRHS = false;
10073 if (Meth->getNumParams()) {
10074 if (const ReferenceType *RT =
10075 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10076 ConstRHS = RT->getPointeeType().isConstQualified();
10080 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10081 /* ConstRHS */ ConstRHS,
10082 /* Diagnose */ true);
10086 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10087 FunctionDecl *Callee = Cand->Function;
10088 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10090 S.Diag(Callee->getLocation(),
10091 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10092 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10095 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10096 FunctionDecl *Callee = Cand->Function;
10098 S.Diag(Callee->getLocation(),
10099 diag::note_ovl_candidate_disabled_by_extension);
10102 /// Generates a 'note' diagnostic for an overload candidate. We've
10103 /// already generated a primary error at the call site.
10105 /// It really does need to be a single diagnostic with its caret
10106 /// pointed at the candidate declaration. Yes, this creates some
10107 /// major challenges of technical writing. Yes, this makes pointing
10108 /// out problems with specific arguments quite awkward. It's still
10109 /// better than generating twenty screens of text for every failed
10112 /// It would be great to be able to express per-candidate problems
10113 /// more richly for those diagnostic clients that cared, but we'd
10114 /// still have to be just as careful with the default diagnostics.
10115 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10117 bool TakingCandidateAddress) {
10118 FunctionDecl *Fn = Cand->Function;
10120 // Note deleted candidates, but only if they're viable.
10121 if (Cand->Viable) {
10122 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10123 std::string FnDesc;
10124 OverloadCandidateKind FnKind =
10125 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10128 << FnKind << FnDesc
10129 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10130 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10134 // We don't really have anything else to say about viable candidates.
10135 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10139 switch (Cand->FailureKind) {
10140 case ovl_fail_too_many_arguments:
10141 case ovl_fail_too_few_arguments:
10142 return DiagnoseArityMismatch(S, Cand, NumArgs);
10144 case ovl_fail_bad_deduction:
10145 return DiagnoseBadDeduction(S, Cand, NumArgs,
10146 TakingCandidateAddress);
10148 case ovl_fail_illegal_constructor: {
10149 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10150 << (Fn->getPrimaryTemplate() ? 1 : 0);
10151 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10155 case ovl_fail_trivial_conversion:
10156 case ovl_fail_bad_final_conversion:
10157 case ovl_fail_final_conversion_not_exact:
10158 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10160 case ovl_fail_bad_conversion: {
10161 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10162 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10163 if (Cand->Conversions[I].isBad())
10164 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10166 // FIXME: this currently happens when we're called from SemaInit
10167 // when user-conversion overload fails. Figure out how to handle
10168 // those conditions and diagnose them well.
10169 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10172 case ovl_fail_bad_target:
10173 return DiagnoseBadTarget(S, Cand);
10175 case ovl_fail_enable_if:
10176 return DiagnoseFailedEnableIfAttr(S, Cand);
10178 case ovl_fail_ext_disabled:
10179 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10181 case ovl_fail_inhctor_slice:
10182 // It's generally not interesting to note copy/move constructors here.
10183 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10185 S.Diag(Fn->getLocation(),
10186 diag::note_ovl_candidate_inherited_constructor_slice)
10187 << (Fn->getPrimaryTemplate() ? 1 : 0)
10188 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10189 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10192 case ovl_fail_addr_not_available: {
10193 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10195 assert(!Available);
10201 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10202 // Desugar the type of the surrogate down to a function type,
10203 // retaining as many typedefs as possible while still showing
10204 // the function type (and, therefore, its parameter types).
10205 QualType FnType = Cand->Surrogate->getConversionType();
10206 bool isLValueReference = false;
10207 bool isRValueReference = false;
10208 bool isPointer = false;
10209 if (const LValueReferenceType *FnTypeRef =
10210 FnType->getAs<LValueReferenceType>()) {
10211 FnType = FnTypeRef->getPointeeType();
10212 isLValueReference = true;
10213 } else if (const RValueReferenceType *FnTypeRef =
10214 FnType->getAs<RValueReferenceType>()) {
10215 FnType = FnTypeRef->getPointeeType();
10216 isRValueReference = true;
10218 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10219 FnType = FnTypePtr->getPointeeType();
10222 // Desugar down to a function type.
10223 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10224 // Reconstruct the pointer/reference as appropriate.
10225 if (isPointer) FnType = S.Context.getPointerType(FnType);
10226 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10227 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10229 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10233 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10234 SourceLocation OpLoc,
10235 OverloadCandidate *Cand) {
10236 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10237 std::string TypeStr("operator");
10240 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10241 if (Cand->Conversions.size() == 1) {
10243 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10246 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10248 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10252 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10253 OverloadCandidate *Cand) {
10254 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10255 if (ICS.isBad()) break; // all meaningless after first invalid
10256 if (!ICS.isAmbiguous()) continue;
10258 ICS.DiagnoseAmbiguousConversion(
10259 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10263 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10264 if (Cand->Function)
10265 return Cand->Function->getLocation();
10266 if (Cand->IsSurrogate)
10267 return Cand->Surrogate->getLocation();
10268 return SourceLocation();
10271 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10272 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10273 case Sema::TDK_Success:
10274 case Sema::TDK_NonDependentConversionFailure:
10275 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10277 case Sema::TDK_Invalid:
10278 case Sema::TDK_Incomplete:
10281 case Sema::TDK_Underqualified:
10282 case Sema::TDK_Inconsistent:
10285 case Sema::TDK_SubstitutionFailure:
10286 case Sema::TDK_DeducedMismatch:
10287 case Sema::TDK_DeducedMismatchNested:
10288 case Sema::TDK_NonDeducedMismatch:
10289 case Sema::TDK_MiscellaneousDeductionFailure:
10290 case Sema::TDK_CUDATargetMismatch:
10293 case Sema::TDK_InstantiationDepth:
10296 case Sema::TDK_InvalidExplicitArguments:
10299 case Sema::TDK_TooManyArguments:
10300 case Sema::TDK_TooFewArguments:
10303 llvm_unreachable("Unhandled deduction result");
10307 struct CompareOverloadCandidatesForDisplay {
10309 SourceLocation Loc;
10311 OverloadCandidateSet::CandidateSetKind CSK;
10313 CompareOverloadCandidatesForDisplay(
10314 Sema &S, SourceLocation Loc, size_t NArgs,
10315 OverloadCandidateSet::CandidateSetKind CSK)
10316 : S(S), NumArgs(NArgs), CSK(CSK) {}
10318 bool operator()(const OverloadCandidate *L,
10319 const OverloadCandidate *R) {
10320 // Fast-path this check.
10321 if (L == R) return false;
10323 // Order first by viability.
10325 if (!R->Viable) return true;
10327 // TODO: introduce a tri-valued comparison for overload
10328 // candidates. Would be more worthwhile if we had a sort
10329 // that could exploit it.
10330 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10332 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10334 } else if (R->Viable)
10337 assert(L->Viable == R->Viable);
10339 // Criteria by which we can sort non-viable candidates:
10341 // 1. Arity mismatches come after other candidates.
10342 if (L->FailureKind == ovl_fail_too_many_arguments ||
10343 L->FailureKind == ovl_fail_too_few_arguments) {
10344 if (R->FailureKind == ovl_fail_too_many_arguments ||
10345 R->FailureKind == ovl_fail_too_few_arguments) {
10346 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10347 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10348 if (LDist == RDist) {
10349 if (L->FailureKind == R->FailureKind)
10350 // Sort non-surrogates before surrogates.
10351 return !L->IsSurrogate && R->IsSurrogate;
10352 // Sort candidates requiring fewer parameters than there were
10353 // arguments given after candidates requiring more parameters
10354 // than there were arguments given.
10355 return L->FailureKind == ovl_fail_too_many_arguments;
10357 return LDist < RDist;
10361 if (R->FailureKind == ovl_fail_too_many_arguments ||
10362 R->FailureKind == ovl_fail_too_few_arguments)
10365 // 2. Bad conversions come first and are ordered by the number
10366 // of bad conversions and quality of good conversions.
10367 if (L->FailureKind == ovl_fail_bad_conversion) {
10368 if (R->FailureKind != ovl_fail_bad_conversion)
10371 // The conversion that can be fixed with a smaller number of changes,
10373 unsigned numLFixes = L->Fix.NumConversionsFixed;
10374 unsigned numRFixes = R->Fix.NumConversionsFixed;
10375 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10376 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10377 if (numLFixes != numRFixes) {
10378 return numLFixes < numRFixes;
10381 // If there's any ordering between the defined conversions...
10382 // FIXME: this might not be transitive.
10383 assert(L->Conversions.size() == R->Conversions.size());
10385 int leftBetter = 0;
10386 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10387 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10388 switch (CompareImplicitConversionSequences(S, Loc,
10390 R->Conversions[I])) {
10391 case ImplicitConversionSequence::Better:
10395 case ImplicitConversionSequence::Worse:
10399 case ImplicitConversionSequence::Indistinguishable:
10403 if (leftBetter > 0) return true;
10404 if (leftBetter < 0) return false;
10406 } else if (R->FailureKind == ovl_fail_bad_conversion)
10409 if (L->FailureKind == ovl_fail_bad_deduction) {
10410 if (R->FailureKind != ovl_fail_bad_deduction)
10413 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10414 return RankDeductionFailure(L->DeductionFailure)
10415 < RankDeductionFailure(R->DeductionFailure);
10416 } else if (R->FailureKind == ovl_fail_bad_deduction)
10422 // Sort everything else by location.
10423 SourceLocation LLoc = GetLocationForCandidate(L);
10424 SourceLocation RLoc = GetLocationForCandidate(R);
10426 // Put candidates without locations (e.g. builtins) at the end.
10427 if (LLoc.isInvalid()) return false;
10428 if (RLoc.isInvalid()) return true;
10430 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10435 /// CompleteNonViableCandidate - Normally, overload resolution only
10436 /// computes up to the first bad conversion. Produces the FixIt set if
10438 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10439 ArrayRef<Expr *> Args) {
10440 assert(!Cand->Viable);
10442 // Don't do anything on failures other than bad conversion.
10443 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10445 // We only want the FixIts if all the arguments can be corrected.
10446 bool Unfixable = false;
10447 // Use a implicit copy initialization to check conversion fixes.
10448 Cand->Fix.setConversionChecker(TryCopyInitialization);
10450 // Attempt to fix the bad conversion.
10451 unsigned ConvCount = Cand->Conversions.size();
10452 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10454 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10455 if (Cand->Conversions[ConvIdx].isInitialized() &&
10456 Cand->Conversions[ConvIdx].isBad()) {
10457 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10462 // FIXME: this should probably be preserved from the overload
10463 // operation somehow.
10464 bool SuppressUserConversions = false;
10466 unsigned ConvIdx = 0;
10467 ArrayRef<QualType> ParamTypes;
10469 if (Cand->IsSurrogate) {
10471 = Cand->Surrogate->getConversionType().getNonReferenceType();
10472 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10473 ConvType = ConvPtrType->getPointeeType();
10474 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10475 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10477 } else if (Cand->Function) {
10479 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10480 if (isa<CXXMethodDecl>(Cand->Function) &&
10481 !isa<CXXConstructorDecl>(Cand->Function)) {
10482 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10486 // Builtin operator.
10487 assert(ConvCount <= 3);
10488 ParamTypes = Cand->BuiltinParamTypes;
10491 // Fill in the rest of the conversions.
10492 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10493 if (Cand->Conversions[ConvIdx].isInitialized()) {
10494 // We've already checked this conversion.
10495 } else if (ArgIdx < ParamTypes.size()) {
10496 if (ParamTypes[ArgIdx]->isDependentType())
10497 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10498 Args[ArgIdx]->getType());
10500 Cand->Conversions[ConvIdx] =
10501 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10502 SuppressUserConversions,
10503 /*InOverloadResolution=*/true,
10504 /*AllowObjCWritebackConversion=*/
10505 S.getLangOpts().ObjCAutoRefCount);
10506 // Store the FixIt in the candidate if it exists.
10507 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10508 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10511 Cand->Conversions[ConvIdx].setEllipsis();
10515 /// PrintOverloadCandidates - When overload resolution fails, prints
10516 /// diagnostic messages containing the candidates in the candidate
10518 void OverloadCandidateSet::NoteCandidates(
10519 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10520 StringRef Opc, SourceLocation OpLoc,
10521 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10522 // Sort the candidates by viability and position. Sorting directly would
10523 // be prohibitive, so we make a set of pointers and sort those.
10524 SmallVector<OverloadCandidate*, 32> Cands;
10525 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10526 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10527 if (!Filter(*Cand))
10530 Cands.push_back(Cand);
10531 else if (OCD == OCD_AllCandidates) {
10532 CompleteNonViableCandidate(S, Cand, Args);
10533 if (Cand->Function || Cand->IsSurrogate)
10534 Cands.push_back(Cand);
10535 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10536 // want to list every possible builtin candidate.
10540 std::stable_sort(Cands.begin(), Cands.end(),
10541 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10543 bool ReportedAmbiguousConversions = false;
10545 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10546 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10547 unsigned CandsShown = 0;
10548 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10549 OverloadCandidate *Cand = *I;
10551 // Set an arbitrary limit on the number of candidate functions we'll spam
10552 // the user with. FIXME: This limit should depend on details of the
10554 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10559 if (Cand->Function)
10560 NoteFunctionCandidate(S, Cand, Args.size(),
10561 /*TakingCandidateAddress=*/false);
10562 else if (Cand->IsSurrogate)
10563 NoteSurrogateCandidate(S, Cand);
10565 assert(Cand->Viable &&
10566 "Non-viable built-in candidates are not added to Cands.");
10567 // Generally we only see ambiguities including viable builtin
10568 // operators if overload resolution got screwed up by an
10569 // ambiguous user-defined conversion.
10571 // FIXME: It's quite possible for different conversions to see
10572 // different ambiguities, though.
10573 if (!ReportedAmbiguousConversions) {
10574 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10575 ReportedAmbiguousConversions = true;
10578 // If this is a viable builtin, print it.
10579 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10584 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10587 static SourceLocation
10588 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10589 return Cand->Specialization ? Cand->Specialization->getLocation()
10590 : SourceLocation();
10594 struct CompareTemplateSpecCandidatesForDisplay {
10596 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10598 bool operator()(const TemplateSpecCandidate *L,
10599 const TemplateSpecCandidate *R) {
10600 // Fast-path this check.
10604 // Assuming that both candidates are not matches...
10606 // Sort by the ranking of deduction failures.
10607 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10608 return RankDeductionFailure(L->DeductionFailure) <
10609 RankDeductionFailure(R->DeductionFailure);
10611 // Sort everything else by location.
10612 SourceLocation LLoc = GetLocationForCandidate(L);
10613 SourceLocation RLoc = GetLocationForCandidate(R);
10615 // Put candidates without locations (e.g. builtins) at the end.
10616 if (LLoc.isInvalid())
10618 if (RLoc.isInvalid())
10621 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10626 /// Diagnose a template argument deduction failure.
10627 /// We are treating these failures as overload failures due to bad
10629 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10630 bool ForTakingAddress) {
10631 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10632 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10635 void TemplateSpecCandidateSet::destroyCandidates() {
10636 for (iterator i = begin(), e = end(); i != e; ++i) {
10637 i->DeductionFailure.Destroy();
10641 void TemplateSpecCandidateSet::clear() {
10642 destroyCandidates();
10643 Candidates.clear();
10646 /// NoteCandidates - When no template specialization match is found, prints
10647 /// diagnostic messages containing the non-matching specializations that form
10648 /// the candidate set.
10649 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10650 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10651 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10652 // Sort the candidates by position (assuming no candidate is a match).
10653 // Sorting directly would be prohibitive, so we make a set of pointers
10655 SmallVector<TemplateSpecCandidate *, 32> Cands;
10656 Cands.reserve(size());
10657 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10658 if (Cand->Specialization)
10659 Cands.push_back(Cand);
10660 // Otherwise, this is a non-matching builtin candidate. We do not,
10661 // in general, want to list every possible builtin candidate.
10664 std::sort(Cands.begin(), Cands.end(),
10665 CompareTemplateSpecCandidatesForDisplay(S));
10667 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10668 // for generalization purposes (?).
10669 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10671 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10672 unsigned CandsShown = 0;
10673 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10674 TemplateSpecCandidate *Cand = *I;
10676 // Set an arbitrary limit on the number of candidates we'll spam
10677 // the user with. FIXME: This limit should depend on details of the
10679 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10683 assert(Cand->Specialization &&
10684 "Non-matching built-in candidates are not added to Cands.");
10685 Cand->NoteDeductionFailure(S, ForTakingAddress);
10689 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10692 // [PossiblyAFunctionType] --> [Return]
10693 // NonFunctionType --> NonFunctionType
10695 // R (*)(A) --> R (A)
10696 // R (&)(A) --> R (A)
10697 // R (S::*)(A) --> R (A)
10698 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10699 QualType Ret = PossiblyAFunctionType;
10700 if (const PointerType *ToTypePtr =
10701 PossiblyAFunctionType->getAs<PointerType>())
10702 Ret = ToTypePtr->getPointeeType();
10703 else if (const ReferenceType *ToTypeRef =
10704 PossiblyAFunctionType->getAs<ReferenceType>())
10705 Ret = ToTypeRef->getPointeeType();
10706 else if (const MemberPointerType *MemTypePtr =
10707 PossiblyAFunctionType->getAs<MemberPointerType>())
10708 Ret = MemTypePtr->getPointeeType();
10710 Context.getCanonicalType(Ret).getUnqualifiedType();
10714 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10715 bool Complain = true) {
10716 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10717 S.DeduceReturnType(FD, Loc, Complain))
10720 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10721 if (S.getLangOpts().CPlusPlus17 &&
10722 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10723 !S.ResolveExceptionSpec(Loc, FPT))
10730 // A helper class to help with address of function resolution
10731 // - allows us to avoid passing around all those ugly parameters
10732 class AddressOfFunctionResolver {
10735 const QualType& TargetType;
10736 QualType TargetFunctionType; // Extracted function type from target type
10739 //DeclAccessPair& ResultFunctionAccessPair;
10740 ASTContext& Context;
10742 bool TargetTypeIsNonStaticMemberFunction;
10743 bool FoundNonTemplateFunction;
10744 bool StaticMemberFunctionFromBoundPointer;
10745 bool HasComplained;
10747 OverloadExpr::FindResult OvlExprInfo;
10748 OverloadExpr *OvlExpr;
10749 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10750 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10751 TemplateSpecCandidateSet FailedCandidates;
10754 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10755 const QualType &TargetType, bool Complain)
10756 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10757 Complain(Complain), Context(S.getASTContext()),
10758 TargetTypeIsNonStaticMemberFunction(
10759 !!TargetType->getAs<MemberPointerType>()),
10760 FoundNonTemplateFunction(false),
10761 StaticMemberFunctionFromBoundPointer(false),
10762 HasComplained(false),
10763 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10764 OvlExpr(OvlExprInfo.Expression),
10765 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10766 ExtractUnqualifiedFunctionTypeFromTargetType();
10768 if (TargetFunctionType->isFunctionType()) {
10769 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10770 if (!UME->isImplicitAccess() &&
10771 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10772 StaticMemberFunctionFromBoundPointer = true;
10773 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10774 DeclAccessPair dap;
10775 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10776 OvlExpr, false, &dap)) {
10777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10778 if (!Method->isStatic()) {
10779 // If the target type is a non-function type and the function found
10780 // is a non-static member function, pretend as if that was the
10781 // target, it's the only possible type to end up with.
10782 TargetTypeIsNonStaticMemberFunction = true;
10784 // And skip adding the function if its not in the proper form.
10785 // We'll diagnose this due to an empty set of functions.
10786 if (!OvlExprInfo.HasFormOfMemberPointer)
10790 Matches.push_back(std::make_pair(dap, Fn));
10795 if (OvlExpr->hasExplicitTemplateArgs())
10796 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10798 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10799 // C++ [over.over]p4:
10800 // If more than one function is selected, [...]
10801 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10802 if (FoundNonTemplateFunction)
10803 EliminateAllTemplateMatches();
10805 EliminateAllExceptMostSpecializedTemplate();
10809 if (S.getLangOpts().CUDA && Matches.size() > 1)
10810 EliminateSuboptimalCudaMatches();
10813 bool hasComplained() const { return HasComplained; }
10816 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10818 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10819 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10822 /// \return true if A is considered a better overload candidate for the
10823 /// desired type than B.
10824 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10825 // If A doesn't have exactly the correct type, we don't want to classify it
10826 // as "better" than anything else. This way, the user is required to
10827 // disambiguate for us if there are multiple candidates and no exact match.
10828 return candidateHasExactlyCorrectType(A) &&
10829 (!candidateHasExactlyCorrectType(B) ||
10830 compareEnableIfAttrs(S, A, B) == Comparison::Better);
10833 /// \return true if we were able to eliminate all but one overload candidate,
10834 /// false otherwise.
10835 bool eliminiateSuboptimalOverloadCandidates() {
10836 // Same algorithm as overload resolution -- one pass to pick the "best",
10837 // another pass to be sure that nothing is better than the best.
10838 auto Best = Matches.begin();
10839 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10840 if (isBetterCandidate(I->second, Best->second))
10843 const FunctionDecl *BestFn = Best->second;
10844 auto IsBestOrInferiorToBest = [this, BestFn](
10845 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10846 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10849 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10850 // option, so we can potentially give the user a better error
10851 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10853 Matches[0] = *Best;
10858 bool isTargetTypeAFunction() const {
10859 return TargetFunctionType->isFunctionType();
10862 // [ToType] [Return]
10864 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10865 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10866 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10867 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10868 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10871 // return true if any matching specializations were found
10872 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10873 const DeclAccessPair& CurAccessFunPair) {
10874 if (CXXMethodDecl *Method
10875 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10876 // Skip non-static function templates when converting to pointer, and
10877 // static when converting to member pointer.
10878 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10881 else if (TargetTypeIsNonStaticMemberFunction)
10884 // C++ [over.over]p2:
10885 // If the name is a function template, template argument deduction is
10886 // done (14.8.2.2), and if the argument deduction succeeds, the
10887 // resulting template argument list is used to generate a single
10888 // function template specialization, which is added to the set of
10889 // overloaded functions considered.
10890 FunctionDecl *Specialization = nullptr;
10891 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10892 if (Sema::TemplateDeductionResult Result
10893 = S.DeduceTemplateArguments(FunctionTemplate,
10894 &OvlExplicitTemplateArgs,
10895 TargetFunctionType, Specialization,
10896 Info, /*IsAddressOfFunction*/true)) {
10897 // Make a note of the failed deduction for diagnostics.
10898 FailedCandidates.addCandidate()
10899 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10900 MakeDeductionFailureInfo(Context, Result, Info));
10904 // Template argument deduction ensures that we have an exact match or
10905 // compatible pointer-to-function arguments that would be adjusted by ICS.
10906 // This function template specicalization works.
10907 assert(S.isSameOrCompatibleFunctionType(
10908 Context.getCanonicalType(Specialization->getType()),
10909 Context.getCanonicalType(TargetFunctionType)));
10911 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10914 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10918 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10919 const DeclAccessPair& CurAccessFunPair) {
10920 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10921 // Skip non-static functions when converting to pointer, and static
10922 // when converting to member pointer.
10923 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10926 else if (TargetTypeIsNonStaticMemberFunction)
10929 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10930 if (S.getLangOpts().CUDA)
10931 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10932 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10935 // If any candidate has a placeholder return type, trigger its deduction
10937 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10939 HasComplained |= Complain;
10943 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10946 // If we're in C, we need to support types that aren't exactly identical.
10947 if (!S.getLangOpts().CPlusPlus ||
10948 candidateHasExactlyCorrectType(FunDecl)) {
10949 Matches.push_back(std::make_pair(
10950 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10951 FoundNonTemplateFunction = true;
10959 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10962 // If the overload expression doesn't have the form of a pointer to
10963 // member, don't try to convert it to a pointer-to-member type.
10964 if (IsInvalidFormOfPointerToMemberFunction())
10967 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10968 E = OvlExpr->decls_end();
10970 // Look through any using declarations to find the underlying function.
10971 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10973 // C++ [over.over]p3:
10974 // Non-member functions and static member functions match
10975 // targets of type "pointer-to-function" or "reference-to-function."
10976 // Nonstatic member functions match targets of
10977 // type "pointer-to-member-function."
10978 // Note that according to DR 247, the containing class does not matter.
10979 if (FunctionTemplateDecl *FunctionTemplate
10980 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10981 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10984 // If we have explicit template arguments supplied, skip non-templates.
10985 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10986 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10989 assert(Ret || Matches.empty());
10993 void EliminateAllExceptMostSpecializedTemplate() {
10994 // [...] and any given function template specialization F1 is
10995 // eliminated if the set contains a second function template
10996 // specialization whose function template is more specialized
10997 // than the function template of F1 according to the partial
10998 // ordering rules of 14.5.5.2.
11000 // The algorithm specified above is quadratic. We instead use a
11001 // two-pass algorithm (similar to the one used to identify the
11002 // best viable function in an overload set) that identifies the
11003 // best function template (if it exists).
11005 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11006 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11007 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11009 // TODO: It looks like FailedCandidates does not serve much purpose
11010 // here, since the no_viable diagnostic has index 0.
11011 UnresolvedSetIterator Result = S.getMostSpecialized(
11012 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11013 SourceExpr->getLocStart(), S.PDiag(),
11014 S.PDiag(diag::err_addr_ovl_ambiguous)
11015 << Matches[0].second->getDeclName(),
11016 S.PDiag(diag::note_ovl_candidate)
11017 << (unsigned)oc_function_template,
11018 Complain, TargetFunctionType);
11020 if (Result != MatchesCopy.end()) {
11021 // Make it the first and only element
11022 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11023 Matches[0].second = cast<FunctionDecl>(*Result);
11026 HasComplained |= Complain;
11029 void EliminateAllTemplateMatches() {
11030 // [...] any function template specializations in the set are
11031 // eliminated if the set also contains a non-template function, [...]
11032 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11033 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11036 Matches[I] = Matches[--N];
11042 void EliminateSuboptimalCudaMatches() {
11043 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11047 void ComplainNoMatchesFound() const {
11048 assert(Matches.empty());
11049 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11050 << OvlExpr->getName() << TargetFunctionType
11051 << OvlExpr->getSourceRange();
11052 if (FailedCandidates.empty())
11053 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11054 /*TakingAddress=*/true);
11056 // We have some deduction failure messages. Use them to diagnose
11057 // the function templates, and diagnose the non-template candidates
11059 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11060 IEnd = OvlExpr->decls_end();
11062 if (FunctionDecl *Fun =
11063 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11064 if (!functionHasPassObjectSizeParams(Fun))
11065 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11066 /*TakingAddress=*/true);
11067 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11071 bool IsInvalidFormOfPointerToMemberFunction() const {
11072 return TargetTypeIsNonStaticMemberFunction &&
11073 !OvlExprInfo.HasFormOfMemberPointer;
11076 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11077 // TODO: Should we condition this on whether any functions might
11078 // have matched, or is it more appropriate to do that in callers?
11079 // TODO: a fixit wouldn't hurt.
11080 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11081 << TargetType << OvlExpr->getSourceRange();
11084 bool IsStaticMemberFunctionFromBoundPointer() const {
11085 return StaticMemberFunctionFromBoundPointer;
11088 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11089 S.Diag(OvlExpr->getLocStart(),
11090 diag::err_invalid_form_pointer_member_function)
11091 << OvlExpr->getSourceRange();
11094 void ComplainOfInvalidConversion() const {
11095 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11096 << OvlExpr->getName() << TargetType;
11099 void ComplainMultipleMatchesFound() const {
11100 assert(Matches.size() > 1);
11101 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11102 << OvlExpr->getName()
11103 << OvlExpr->getSourceRange();
11104 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11105 /*TakingAddress=*/true);
11108 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11110 int getNumMatches() const { return Matches.size(); }
11112 FunctionDecl* getMatchingFunctionDecl() const {
11113 if (Matches.size() != 1) return nullptr;
11114 return Matches[0].second;
11117 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11118 if (Matches.size() != 1) return nullptr;
11119 return &Matches[0].first;
11124 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11125 /// an overloaded function (C++ [over.over]), where @p From is an
11126 /// expression with overloaded function type and @p ToType is the type
11127 /// we're trying to resolve to. For example:
11133 /// int (*pfd)(double) = f; // selects f(double)
11136 /// This routine returns the resulting FunctionDecl if it could be
11137 /// resolved, and NULL otherwise. When @p Complain is true, this
11138 /// routine will emit diagnostics if there is an error.
11140 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11141 QualType TargetType,
11143 DeclAccessPair &FoundResult,
11144 bool *pHadMultipleCandidates) {
11145 assert(AddressOfExpr->getType() == Context.OverloadTy);
11147 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11149 int NumMatches = Resolver.getNumMatches();
11150 FunctionDecl *Fn = nullptr;
11151 bool ShouldComplain = Complain && !Resolver.hasComplained();
11152 if (NumMatches == 0 && ShouldComplain) {
11153 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11154 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11156 Resolver.ComplainNoMatchesFound();
11158 else if (NumMatches > 1 && ShouldComplain)
11159 Resolver.ComplainMultipleMatchesFound();
11160 else if (NumMatches == 1) {
11161 Fn = Resolver.getMatchingFunctionDecl();
11163 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11164 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11165 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11167 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11168 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11170 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11174 if (pHadMultipleCandidates)
11175 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11179 /// \brief Given an expression that refers to an overloaded function, try to
11180 /// resolve that function to a single function that can have its address taken.
11181 /// This will modify `Pair` iff it returns non-null.
11183 /// This routine can only realistically succeed if all but one candidates in the
11184 /// overload set for SrcExpr cannot have their addresses taken.
11186 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11187 DeclAccessPair &Pair) {
11188 OverloadExpr::FindResult R = OverloadExpr::find(E);
11189 OverloadExpr *Ovl = R.Expression;
11190 FunctionDecl *Result = nullptr;
11191 DeclAccessPair DAP;
11192 // Don't use the AddressOfResolver because we're specifically looking for
11193 // cases where we have one overload candidate that lacks
11194 // enable_if/pass_object_size/...
11195 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11196 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11200 if (!checkAddressOfFunctionIsAvailable(FD))
11203 // We have more than one result; quit.
11215 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11216 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11217 /// will perform access checks, diagnose the use of the resultant decl, and, if
11218 /// requested, potentially perform a function-to-pointer decay.
11220 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11221 /// Otherwise, returns true. This may emit diagnostics and return true.
11222 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11223 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11224 Expr *E = SrcExpr.get();
11225 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11227 DeclAccessPair DAP;
11228 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11232 // Emitting multiple diagnostics for a function that is both inaccessible and
11233 // unavailable is consistent with our behavior elsewhere. So, always check
11235 DiagnoseUseOfDecl(Found, E->getExprLoc());
11236 CheckAddressOfMemberAccess(E, DAP);
11237 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11238 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11239 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11245 /// \brief Given an expression that refers to an overloaded function, try to
11246 /// resolve that overloaded function expression down to a single function.
11248 /// This routine can only resolve template-ids that refer to a single function
11249 /// template, where that template-id refers to a single template whose template
11250 /// arguments are either provided by the template-id or have defaults,
11251 /// as described in C++0x [temp.arg.explicit]p3.
11253 /// If no template-ids are found, no diagnostics are emitted and NULL is
11256 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11258 DeclAccessPair *FoundResult) {
11259 // C++ [over.over]p1:
11260 // [...] [Note: any redundant set of parentheses surrounding the
11261 // overloaded function name is ignored (5.1). ]
11262 // C++ [over.over]p1:
11263 // [...] The overloaded function name can be preceded by the &
11266 // If we didn't actually find any template-ids, we're done.
11267 if (!ovl->hasExplicitTemplateArgs())
11270 TemplateArgumentListInfo ExplicitTemplateArgs;
11271 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11272 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11274 // Look through all of the overloaded functions, searching for one
11275 // whose type matches exactly.
11276 FunctionDecl *Matched = nullptr;
11277 for (UnresolvedSetIterator I = ovl->decls_begin(),
11278 E = ovl->decls_end(); I != E; ++I) {
11279 // C++0x [temp.arg.explicit]p3:
11280 // [...] In contexts where deduction is done and fails, or in contexts
11281 // where deduction is not done, if a template argument list is
11282 // specified and it, along with any default template arguments,
11283 // identifies a single function template specialization, then the
11284 // template-id is an lvalue for the function template specialization.
11285 FunctionTemplateDecl *FunctionTemplate
11286 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11288 // C++ [over.over]p2:
11289 // If the name is a function template, template argument deduction is
11290 // done (14.8.2.2), and if the argument deduction succeeds, the
11291 // resulting template argument list is used to generate a single
11292 // function template specialization, which is added to the set of
11293 // overloaded functions considered.
11294 FunctionDecl *Specialization = nullptr;
11295 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11296 if (TemplateDeductionResult Result
11297 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11298 Specialization, Info,
11299 /*IsAddressOfFunction*/true)) {
11300 // Make a note of the failed deduction for diagnostics.
11301 // TODO: Actually use the failed-deduction info?
11302 FailedCandidates.addCandidate()
11303 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11304 MakeDeductionFailureInfo(Context, Result, Info));
11308 assert(Specialization && "no specialization and no error?");
11310 // Multiple matches; we can't resolve to a single declaration.
11313 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11315 NoteAllOverloadCandidates(ovl);
11320 Matched = Specialization;
11321 if (FoundResult) *FoundResult = I.getPair();
11325 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11331 // Resolve and fix an overloaded expression that can be resolved
11332 // because it identifies a single function template specialization.
11334 // Last three arguments should only be supplied if Complain = true
11336 // Return true if it was logically possible to so resolve the
11337 // expression, regardless of whether or not it succeeded. Always
11338 // returns true if 'complain' is set.
11339 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11340 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11341 bool complain, SourceRange OpRangeForComplaining,
11342 QualType DestTypeForComplaining,
11343 unsigned DiagIDForComplaining) {
11344 assert(SrcExpr.get()->getType() == Context.OverloadTy);
11346 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11348 DeclAccessPair found;
11349 ExprResult SingleFunctionExpression;
11350 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11351 ovl.Expression, /*complain*/ false, &found)) {
11352 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11353 SrcExpr = ExprError();
11357 // It is only correct to resolve to an instance method if we're
11358 // resolving a form that's permitted to be a pointer to member.
11359 // Otherwise we'll end up making a bound member expression, which
11360 // is illegal in all the contexts we resolve like this.
11361 if (!ovl.HasFormOfMemberPointer &&
11362 isa<CXXMethodDecl>(fn) &&
11363 cast<CXXMethodDecl>(fn)->isInstance()) {
11364 if (!complain) return false;
11366 Diag(ovl.Expression->getExprLoc(),
11367 diag::err_bound_member_function)
11368 << 0 << ovl.Expression->getSourceRange();
11370 // TODO: I believe we only end up here if there's a mix of
11371 // static and non-static candidates (otherwise the expression
11372 // would have 'bound member' type, not 'overload' type).
11373 // Ideally we would note which candidate was chosen and why
11374 // the static candidates were rejected.
11375 SrcExpr = ExprError();
11379 // Fix the expression to refer to 'fn'.
11380 SingleFunctionExpression =
11381 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11383 // If desired, do function-to-pointer decay.
11384 if (doFunctionPointerConverion) {
11385 SingleFunctionExpression =
11386 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11387 if (SingleFunctionExpression.isInvalid()) {
11388 SrcExpr = ExprError();
11394 if (!SingleFunctionExpression.isUsable()) {
11396 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11397 << ovl.Expression->getName()
11398 << DestTypeForComplaining
11399 << OpRangeForComplaining
11400 << ovl.Expression->getQualifierLoc().getSourceRange();
11401 NoteAllOverloadCandidates(SrcExpr.get());
11403 SrcExpr = ExprError();
11410 SrcExpr = SingleFunctionExpression;
11414 /// \brief Add a single candidate to the overload set.
11415 static void AddOverloadedCallCandidate(Sema &S,
11416 DeclAccessPair FoundDecl,
11417 TemplateArgumentListInfo *ExplicitTemplateArgs,
11418 ArrayRef<Expr *> Args,
11419 OverloadCandidateSet &CandidateSet,
11420 bool PartialOverloading,
11422 NamedDecl *Callee = FoundDecl.getDecl();
11423 if (isa<UsingShadowDecl>(Callee))
11424 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11426 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11427 if (ExplicitTemplateArgs) {
11428 assert(!KnownValid && "Explicit template arguments?");
11431 // Prevent ill-formed function decls to be added as overload candidates.
11432 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11435 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11436 /*SuppressUsedConversions=*/false,
11437 PartialOverloading);
11441 if (FunctionTemplateDecl *FuncTemplate
11442 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11443 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11444 ExplicitTemplateArgs, Args, CandidateSet,
11445 /*SuppressUsedConversions=*/false,
11446 PartialOverloading);
11450 assert(!KnownValid && "unhandled case in overloaded call candidate");
11453 /// \brief Add the overload candidates named by callee and/or found by argument
11454 /// dependent lookup to the given overload set.
11455 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11456 ArrayRef<Expr *> Args,
11457 OverloadCandidateSet &CandidateSet,
11458 bool PartialOverloading) {
11461 // Verify that ArgumentDependentLookup is consistent with the rules
11462 // in C++0x [basic.lookup.argdep]p3:
11464 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11465 // and let Y be the lookup set produced by argument dependent
11466 // lookup (defined as follows). If X contains
11468 // -- a declaration of a class member, or
11470 // -- a block-scope function declaration that is not a
11471 // using-declaration, or
11473 // -- a declaration that is neither a function or a function
11476 // then Y is empty.
11478 if (ULE->requiresADL()) {
11479 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11480 E = ULE->decls_end(); I != E; ++I) {
11481 assert(!(*I)->getDeclContext()->isRecord());
11482 assert(isa<UsingShadowDecl>(*I) ||
11483 !(*I)->getDeclContext()->isFunctionOrMethod());
11484 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11489 // It would be nice to avoid this copy.
11490 TemplateArgumentListInfo TABuffer;
11491 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11492 if (ULE->hasExplicitTemplateArgs()) {
11493 ULE->copyTemplateArgumentsInto(TABuffer);
11494 ExplicitTemplateArgs = &TABuffer;
11497 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11498 E = ULE->decls_end(); I != E; ++I)
11499 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11500 CandidateSet, PartialOverloading,
11501 /*KnownValid*/ true);
11503 if (ULE->requiresADL())
11504 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11505 Args, ExplicitTemplateArgs,
11506 CandidateSet, PartialOverloading);
11509 /// Determine whether a declaration with the specified name could be moved into
11510 /// a different namespace.
11511 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11512 switch (Name.getCXXOverloadedOperator()) {
11513 case OO_New: case OO_Array_New:
11514 case OO_Delete: case OO_Array_Delete:
11522 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11523 /// template, where the non-dependent name was declared after the template
11524 /// was defined. This is common in code written for a compilers which do not
11525 /// correctly implement two-stage name lookup.
11527 /// Returns true if a viable candidate was found and a diagnostic was issued.
11529 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11530 const CXXScopeSpec &SS, LookupResult &R,
11531 OverloadCandidateSet::CandidateSetKind CSK,
11532 TemplateArgumentListInfo *ExplicitTemplateArgs,
11533 ArrayRef<Expr *> Args,
11534 bool *DoDiagnoseEmptyLookup = nullptr) {
11535 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11538 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11539 if (DC->isTransparentContext())
11542 SemaRef.LookupQualifiedName(R, DC);
11545 R.suppressDiagnostics();
11547 if (isa<CXXRecordDecl>(DC)) {
11548 // Don't diagnose names we find in classes; we get much better
11549 // diagnostics for these from DiagnoseEmptyLookup.
11551 if (DoDiagnoseEmptyLookup)
11552 *DoDiagnoseEmptyLookup = true;
11556 OverloadCandidateSet Candidates(FnLoc, CSK);
11557 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11558 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11559 ExplicitTemplateArgs, Args,
11560 Candidates, false, /*KnownValid*/ false);
11562 OverloadCandidateSet::iterator Best;
11563 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11564 // No viable functions. Don't bother the user with notes for functions
11565 // which don't work and shouldn't be found anyway.
11570 // Find the namespaces where ADL would have looked, and suggest
11571 // declaring the function there instead.
11572 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11573 Sema::AssociatedClassSet AssociatedClasses;
11574 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11575 AssociatedNamespaces,
11576 AssociatedClasses);
11577 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11578 if (canBeDeclaredInNamespace(R.getLookupName())) {
11579 DeclContext *Std = SemaRef.getStdNamespace();
11580 for (Sema::AssociatedNamespaceSet::iterator
11581 it = AssociatedNamespaces.begin(),
11582 end = AssociatedNamespaces.end(); it != end; ++it) {
11583 // Never suggest declaring a function within namespace 'std'.
11584 if (Std && Std->Encloses(*it))
11587 // Never suggest declaring a function within a namespace with a
11588 // reserved name, like __gnu_cxx.
11589 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11591 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11594 SuggestedNamespaces.insert(*it);
11598 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11599 << R.getLookupName();
11600 if (SuggestedNamespaces.empty()) {
11601 SemaRef.Diag(Best->Function->getLocation(),
11602 diag::note_not_found_by_two_phase_lookup)
11603 << R.getLookupName() << 0;
11604 } else if (SuggestedNamespaces.size() == 1) {
11605 SemaRef.Diag(Best->Function->getLocation(),
11606 diag::note_not_found_by_two_phase_lookup)
11607 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11609 // FIXME: It would be useful to list the associated namespaces here,
11610 // but the diagnostics infrastructure doesn't provide a way to produce
11611 // a localized representation of a list of items.
11612 SemaRef.Diag(Best->Function->getLocation(),
11613 diag::note_not_found_by_two_phase_lookup)
11614 << R.getLookupName() << 2;
11617 // Try to recover by calling this function.
11627 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11628 /// template, where the non-dependent operator was declared after the template
11631 /// Returns true if a viable candidate was found and a diagnostic was issued.
11633 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11634 SourceLocation OpLoc,
11635 ArrayRef<Expr *> Args) {
11636 DeclarationName OpName =
11637 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11638 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11639 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11640 OverloadCandidateSet::CSK_Operator,
11641 /*ExplicitTemplateArgs=*/nullptr, Args);
11645 class BuildRecoveryCallExprRAII {
11648 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11649 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11650 SemaRef.IsBuildingRecoveryCallExpr = true;
11653 ~BuildRecoveryCallExprRAII() {
11654 SemaRef.IsBuildingRecoveryCallExpr = false;
11660 static std::unique_ptr<CorrectionCandidateCallback>
11661 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11662 bool HasTemplateArgs, bool AllowTypoCorrection) {
11663 if (!AllowTypoCorrection)
11664 return llvm::make_unique<NoTypoCorrectionCCC>();
11665 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11666 HasTemplateArgs, ME);
11669 /// Attempts to recover from a call where no functions were found.
11671 /// Returns true if new candidates were found.
11673 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11674 UnresolvedLookupExpr *ULE,
11675 SourceLocation LParenLoc,
11676 MutableArrayRef<Expr *> Args,
11677 SourceLocation RParenLoc,
11678 bool EmptyLookup, bool AllowTypoCorrection) {
11679 // Do not try to recover if it is already building a recovery call.
11680 // This stops infinite loops for template instantiations like
11682 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11683 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11685 if (SemaRef.IsBuildingRecoveryCallExpr)
11686 return ExprError();
11687 BuildRecoveryCallExprRAII RCE(SemaRef);
11690 SS.Adopt(ULE->getQualifierLoc());
11691 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11693 TemplateArgumentListInfo TABuffer;
11694 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11695 if (ULE->hasExplicitTemplateArgs()) {
11696 ULE->copyTemplateArgumentsInto(TABuffer);
11697 ExplicitTemplateArgs = &TABuffer;
11700 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11701 Sema::LookupOrdinaryName);
11702 bool DoDiagnoseEmptyLookup = EmptyLookup;
11703 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11704 OverloadCandidateSet::CSK_Normal,
11705 ExplicitTemplateArgs, Args,
11706 &DoDiagnoseEmptyLookup) &&
11707 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11709 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11710 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11711 ExplicitTemplateArgs, Args)))
11712 return ExprError();
11714 assert(!R.empty() && "lookup results empty despite recovery");
11716 // If recovery created an ambiguity, just bail out.
11717 if (R.isAmbiguous()) {
11718 R.suppressDiagnostics();
11719 return ExprError();
11722 // Build an implicit member call if appropriate. Just drop the
11723 // casts and such from the call, we don't really care.
11724 ExprResult NewFn = ExprError();
11725 if ((*R.begin())->isCXXClassMember())
11726 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11727 ExplicitTemplateArgs, S);
11728 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11729 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11730 ExplicitTemplateArgs);
11732 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11734 if (NewFn.isInvalid())
11735 return ExprError();
11737 // This shouldn't cause an infinite loop because we're giving it
11738 // an expression with viable lookup results, which should never
11740 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11741 MultiExprArg(Args.data(), Args.size()),
11745 /// \brief Constructs and populates an OverloadedCandidateSet from
11746 /// the given function.
11747 /// \returns true when an the ExprResult output parameter has been set.
11748 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11749 UnresolvedLookupExpr *ULE,
11751 SourceLocation RParenLoc,
11752 OverloadCandidateSet *CandidateSet,
11753 ExprResult *Result) {
11755 if (ULE->requiresADL()) {
11756 // To do ADL, we must have found an unqualified name.
11757 assert(!ULE->getQualifier() && "qualified name with ADL");
11759 // We don't perform ADL for implicit declarations of builtins.
11760 // Verify that this was correctly set up.
11762 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11763 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11764 F->getBuiltinID() && F->isImplicit())
11765 llvm_unreachable("performing ADL for builtin");
11767 // We don't perform ADL in C.
11768 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11772 UnbridgedCastsSet UnbridgedCasts;
11773 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11774 *Result = ExprError();
11778 // Add the functions denoted by the callee to the set of candidate
11779 // functions, including those from argument-dependent lookup.
11780 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11782 if (getLangOpts().MSVCCompat &&
11783 CurContext->isDependentContext() && !isSFINAEContext() &&
11784 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11786 OverloadCandidateSet::iterator Best;
11787 if (CandidateSet->empty() ||
11788 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11789 OR_No_Viable_Function) {
11790 // In Microsoft mode, if we are inside a template class member function then
11791 // create a type dependent CallExpr. The goal is to postpone name lookup
11792 // to instantiation time to be able to search into type dependent base
11794 CallExpr *CE = new (Context) CallExpr(
11795 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11796 CE->setTypeDependent(true);
11797 CE->setValueDependent(true);
11798 CE->setInstantiationDependent(true);
11804 if (CandidateSet->empty())
11807 UnbridgedCasts.restore();
11811 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11812 /// the completed call expression. If overload resolution fails, emits
11813 /// diagnostics and returns ExprError()
11814 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11815 UnresolvedLookupExpr *ULE,
11816 SourceLocation LParenLoc,
11818 SourceLocation RParenLoc,
11820 OverloadCandidateSet *CandidateSet,
11821 OverloadCandidateSet::iterator *Best,
11822 OverloadingResult OverloadResult,
11823 bool AllowTypoCorrection) {
11824 if (CandidateSet->empty())
11825 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11826 RParenLoc, /*EmptyLookup=*/true,
11827 AllowTypoCorrection);
11829 switch (OverloadResult) {
11831 FunctionDecl *FDecl = (*Best)->Function;
11832 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11833 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11834 return ExprError();
11835 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11836 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11840 case OR_No_Viable_Function: {
11841 // Try to recover by looking for viable functions which the user might
11842 // have meant to call.
11843 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11845 /*EmptyLookup=*/false,
11846 AllowTypoCorrection);
11847 if (!Recovery.isInvalid())
11850 // If the user passes in a function that we can't take the address of, we
11851 // generally end up emitting really bad error messages. Here, we attempt to
11852 // emit better ones.
11853 for (const Expr *Arg : Args) {
11854 if (!Arg->getType()->isFunctionType())
11856 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11857 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11859 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11860 Arg->getExprLoc()))
11861 return ExprError();
11865 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11866 << ULE->getName() << Fn->getSourceRange();
11867 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11872 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11873 << ULE->getName() << Fn->getSourceRange();
11874 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11878 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11879 << (*Best)->Function->isDeleted()
11881 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11882 << Fn->getSourceRange();
11883 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11885 // We emitted an error for the unvailable/deleted function call but keep
11886 // the call in the AST.
11887 FunctionDecl *FDecl = (*Best)->Function;
11888 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11889 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11894 // Overload resolution failed.
11895 return ExprError();
11898 static void markUnaddressableCandidatesUnviable(Sema &S,
11899 OverloadCandidateSet &CS) {
11900 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11902 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11904 I->FailureKind = ovl_fail_addr_not_available;
11909 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11910 /// (which eventually refers to the declaration Func) and the call
11911 /// arguments Args/NumArgs, attempt to resolve the function call down
11912 /// to a specific function. If overload resolution succeeds, returns
11913 /// the call expression produced by overload resolution.
11914 /// Otherwise, emits diagnostics and returns ExprError.
11915 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11916 UnresolvedLookupExpr *ULE,
11917 SourceLocation LParenLoc,
11919 SourceLocation RParenLoc,
11921 bool AllowTypoCorrection,
11922 bool CalleesAddressIsTaken) {
11923 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11924 OverloadCandidateSet::CSK_Normal);
11927 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11931 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11932 // functions that aren't addressible are considered unviable.
11933 if (CalleesAddressIsTaken)
11934 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11936 OverloadCandidateSet::iterator Best;
11937 OverloadingResult OverloadResult =
11938 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11940 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11941 RParenLoc, ExecConfig, &CandidateSet,
11942 &Best, OverloadResult,
11943 AllowTypoCorrection);
11946 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11947 return Functions.size() > 1 ||
11948 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11951 /// \brief Create a unary operation that may resolve to an overloaded
11954 /// \param OpLoc The location of the operator itself (e.g., '*').
11956 /// \param Opc The UnaryOperatorKind that describes this operator.
11958 /// \param Fns The set of non-member functions that will be
11959 /// considered by overload resolution. The caller needs to build this
11960 /// set based on the context using, e.g.,
11961 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11962 /// set should not contain any member functions; those will be added
11963 /// by CreateOverloadedUnaryOp().
11965 /// \param Input The input argument.
11967 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11968 const UnresolvedSetImpl &Fns,
11969 Expr *Input, bool PerformADL) {
11970 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11971 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11972 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11973 // TODO: provide better source location info.
11974 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11976 if (checkPlaceholderForOverload(*this, Input))
11977 return ExprError();
11979 Expr *Args[2] = { Input, nullptr };
11980 unsigned NumArgs = 1;
11982 // For post-increment and post-decrement, add the implicit '0' as
11983 // the second argument, so that we know this is a post-increment or
11985 if (Opc == UO_PostInc || Opc == UO_PostDec) {
11986 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11987 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11992 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11994 if (Input->isTypeDependent()) {
11996 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11997 VK_RValue, OK_Ordinary, OpLoc);
11999 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12000 UnresolvedLookupExpr *Fn
12001 = UnresolvedLookupExpr::Create(Context, NamingClass,
12002 NestedNameSpecifierLoc(), OpNameInfo,
12003 /*ADL*/ true, IsOverloaded(Fns),
12004 Fns.begin(), Fns.end());
12005 return new (Context)
12006 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12007 VK_RValue, OpLoc, FPOptions());
12010 // Build an empty overload set.
12011 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12013 // Add the candidates from the given function set.
12014 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12016 // Add operator candidates that are member functions.
12017 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12019 // Add candidates from ADL.
12021 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12022 /*ExplicitTemplateArgs*/nullptr,
12026 // Add builtin operator candidates.
12027 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12029 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12031 // Perform overload resolution.
12032 OverloadCandidateSet::iterator Best;
12033 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12035 // We found a built-in operator or an overloaded operator.
12036 FunctionDecl *FnDecl = Best->Function;
12039 Expr *Base = nullptr;
12040 // We matched an overloaded operator. Build a call to that
12043 // Convert the arguments.
12044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12045 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12047 ExprResult InputRes =
12048 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12049 Best->FoundDecl, Method);
12050 if (InputRes.isInvalid())
12051 return ExprError();
12052 Base = Input = InputRes.get();
12054 // Convert the arguments.
12055 ExprResult InputInit
12056 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12058 FnDecl->getParamDecl(0)),
12061 if (InputInit.isInvalid())
12062 return ExprError();
12063 Input = InputInit.get();
12066 // Build the actual expression node.
12067 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12068 Base, HadMultipleCandidates,
12070 if (FnExpr.isInvalid())
12071 return ExprError();
12073 // Determine the result type.
12074 QualType ResultTy = FnDecl->getReturnType();
12075 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12076 ResultTy = ResultTy.getNonLValueExprType(Context);
12079 CallExpr *TheCall =
12080 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12081 ResultTy, VK, OpLoc, FPOptions());
12083 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12084 return ExprError();
12086 if (CheckFunctionCall(FnDecl, TheCall,
12087 FnDecl->getType()->castAs<FunctionProtoType>()))
12088 return ExprError();
12090 return MaybeBindToTemporary(TheCall);
12092 // We matched a built-in operator. Convert the arguments, then
12093 // break out so that we will build the appropriate built-in
12095 ExprResult InputRes = PerformImplicitConversion(
12096 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing);
12097 if (InputRes.isInvalid())
12098 return ExprError();
12099 Input = InputRes.get();
12104 case OR_No_Viable_Function:
12105 // This is an erroneous use of an operator which can be overloaded by
12106 // a non-member function. Check for non-member operators which were
12107 // defined too late to be candidates.
12108 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12109 // FIXME: Recover by calling the found function.
12110 return ExprError();
12112 // No viable function; fall through to handling this as a
12113 // built-in operator, which will produce an error message for us.
12117 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12118 << UnaryOperator::getOpcodeStr(Opc)
12119 << Input->getType()
12120 << Input->getSourceRange();
12121 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12122 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12123 return ExprError();
12126 Diag(OpLoc, diag::err_ovl_deleted_oper)
12127 << Best->Function->isDeleted()
12128 << UnaryOperator::getOpcodeStr(Opc)
12129 << getDeletedOrUnavailableSuffix(Best->Function)
12130 << Input->getSourceRange();
12131 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12132 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12133 return ExprError();
12136 // Either we found no viable overloaded operator or we matched a
12137 // built-in operator. In either case, fall through to trying to
12138 // build a built-in operation.
12139 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12142 /// \brief Create a binary operation that may resolve to an overloaded
12145 /// \param OpLoc The location of the operator itself (e.g., '+').
12147 /// \param Opc The BinaryOperatorKind that describes this operator.
12149 /// \param Fns The set of non-member functions that will be
12150 /// considered by overload resolution. The caller needs to build this
12151 /// set based on the context using, e.g.,
12152 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12153 /// set should not contain any member functions; those will be added
12154 /// by CreateOverloadedBinOp().
12156 /// \param LHS Left-hand argument.
12157 /// \param RHS Right-hand argument.
12159 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12160 BinaryOperatorKind Opc,
12161 const UnresolvedSetImpl &Fns,
12162 Expr *LHS, Expr *RHS, bool PerformADL) {
12163 Expr *Args[2] = { LHS, RHS };
12164 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12166 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12167 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12169 // If either side is type-dependent, create an appropriate dependent
12171 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12173 // If there are no functions to store, just build a dependent
12174 // BinaryOperator or CompoundAssignment.
12175 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12176 return new (Context) BinaryOperator(
12177 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12178 OpLoc, FPFeatures);
12180 return new (Context) CompoundAssignOperator(
12181 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12182 Context.DependentTy, Context.DependentTy, OpLoc,
12186 // FIXME: save results of ADL from here?
12187 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12188 // TODO: provide better source location info in DNLoc component.
12189 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12190 UnresolvedLookupExpr *Fn
12191 = UnresolvedLookupExpr::Create(Context, NamingClass,
12192 NestedNameSpecifierLoc(), OpNameInfo,
12193 /*ADL*/PerformADL, IsOverloaded(Fns),
12194 Fns.begin(), Fns.end());
12195 return new (Context)
12196 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12197 VK_RValue, OpLoc, FPFeatures);
12200 // Always do placeholder-like conversions on the RHS.
12201 if (checkPlaceholderForOverload(*this, Args[1]))
12202 return ExprError();
12204 // Do placeholder-like conversion on the LHS; note that we should
12205 // not get here with a PseudoObject LHS.
12206 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12207 if (checkPlaceholderForOverload(*this, Args[0]))
12208 return ExprError();
12210 // If this is the assignment operator, we only perform overload resolution
12211 // if the left-hand side is a class or enumeration type. This is actually
12212 // a hack. The standard requires that we do overload resolution between the
12213 // various built-in candidates, but as DR507 points out, this can lead to
12214 // problems. So we do it this way, which pretty much follows what GCC does.
12215 // Note that we go the traditional code path for compound assignment forms.
12216 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12217 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12219 // If this is the .* operator, which is not overloadable, just
12220 // create a built-in binary operator.
12221 if (Opc == BO_PtrMemD)
12222 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12224 // Build an empty overload set.
12225 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12227 // Add the candidates from the given function set.
12228 AddFunctionCandidates(Fns, Args, CandidateSet);
12230 // Add operator candidates that are member functions.
12231 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12233 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12234 // performed for an assignment operator (nor for operator[] nor operator->,
12235 // which don't get here).
12236 if (Opc != BO_Assign && PerformADL)
12237 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12238 /*ExplicitTemplateArgs*/ nullptr,
12241 // Add builtin operator candidates.
12242 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12244 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12246 // Perform overload resolution.
12247 OverloadCandidateSet::iterator Best;
12248 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12250 // We found a built-in operator or an overloaded operator.
12251 FunctionDecl *FnDecl = Best->Function;
12254 Expr *Base = nullptr;
12255 // We matched an overloaded operator. Build a call to that
12258 // Convert the arguments.
12259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12260 // Best->Access is only meaningful for class members.
12261 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12264 PerformCopyInitialization(
12265 InitializedEntity::InitializeParameter(Context,
12266 FnDecl->getParamDecl(0)),
12267 SourceLocation(), Args[1]);
12268 if (Arg1.isInvalid())
12269 return ExprError();
12272 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12273 Best->FoundDecl, Method);
12274 if (Arg0.isInvalid())
12275 return ExprError();
12276 Base = Args[0] = Arg0.getAs<Expr>();
12277 Args[1] = RHS = Arg1.getAs<Expr>();
12279 // Convert the arguments.
12280 ExprResult Arg0 = PerformCopyInitialization(
12281 InitializedEntity::InitializeParameter(Context,
12282 FnDecl->getParamDecl(0)),
12283 SourceLocation(), Args[0]);
12284 if (Arg0.isInvalid())
12285 return ExprError();
12288 PerformCopyInitialization(
12289 InitializedEntity::InitializeParameter(Context,
12290 FnDecl->getParamDecl(1)),
12291 SourceLocation(), Args[1]);
12292 if (Arg1.isInvalid())
12293 return ExprError();
12294 Args[0] = LHS = Arg0.getAs<Expr>();
12295 Args[1] = RHS = Arg1.getAs<Expr>();
12298 // Build the actual expression node.
12299 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12300 Best->FoundDecl, Base,
12301 HadMultipleCandidates, OpLoc);
12302 if (FnExpr.isInvalid())
12303 return ExprError();
12305 // Determine the result type.
12306 QualType ResultTy = FnDecl->getReturnType();
12307 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12308 ResultTy = ResultTy.getNonLValueExprType(Context);
12310 CXXOperatorCallExpr *TheCall =
12311 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12312 Args, ResultTy, VK, OpLoc,
12315 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12317 return ExprError();
12319 ArrayRef<const Expr *> ArgsArray(Args, 2);
12320 const Expr *ImplicitThis = nullptr;
12321 // Cut off the implicit 'this'.
12322 if (isa<CXXMethodDecl>(FnDecl)) {
12323 ImplicitThis = ArgsArray[0];
12324 ArgsArray = ArgsArray.slice(1);
12327 // Check for a self move.
12328 if (Op == OO_Equal)
12329 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12331 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12332 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12333 VariadicDoesNotApply);
12335 return MaybeBindToTemporary(TheCall);
12337 // We matched a built-in operator. Convert the arguments, then
12338 // break out so that we will build the appropriate built-in
12340 ExprResult ArgsRes0 =
12341 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12342 Best->Conversions[0], AA_Passing);
12343 if (ArgsRes0.isInvalid())
12344 return ExprError();
12345 Args[0] = ArgsRes0.get();
12347 ExprResult ArgsRes1 =
12348 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12349 Best->Conversions[1], AA_Passing);
12350 if (ArgsRes1.isInvalid())
12351 return ExprError();
12352 Args[1] = ArgsRes1.get();
12357 case OR_No_Viable_Function: {
12358 // C++ [over.match.oper]p9:
12359 // If the operator is the operator , [...] and there are no
12360 // viable functions, then the operator is assumed to be the
12361 // built-in operator and interpreted according to clause 5.
12362 if (Opc == BO_Comma)
12365 // For class as left operand for assignment or compound assigment
12366 // operator do not fall through to handling in built-in, but report that
12367 // no overloaded assignment operator found
12368 ExprResult Result = ExprError();
12369 if (Args[0]->getType()->isRecordType() &&
12370 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12371 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12372 << BinaryOperator::getOpcodeStr(Opc)
12373 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12374 if (Args[0]->getType()->isIncompleteType()) {
12375 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12376 << Args[0]->getType()
12377 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12380 // This is an erroneous use of an operator which can be overloaded by
12381 // a non-member function. Check for non-member operators which were
12382 // defined too late to be candidates.
12383 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12384 // FIXME: Recover by calling the found function.
12385 return ExprError();
12387 // No viable function; try to create a built-in operation, which will
12388 // produce an error. Then, show the non-viable candidates.
12389 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12391 assert(Result.isInvalid() &&
12392 "C++ binary operator overloading is missing candidates!");
12393 if (Result.isInvalid())
12394 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12395 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12400 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12401 << BinaryOperator::getOpcodeStr(Opc)
12402 << Args[0]->getType() << Args[1]->getType()
12403 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12404 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12405 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12406 return ExprError();
12409 if (isImplicitlyDeleted(Best->Function)) {
12410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12411 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12412 << Context.getRecordType(Method->getParent())
12413 << getSpecialMember(Method);
12415 // The user probably meant to call this special member. Just
12416 // explain why it's deleted.
12417 NoteDeletedFunction(Method);
12418 return ExprError();
12420 Diag(OpLoc, diag::err_ovl_deleted_oper)
12421 << Best->Function->isDeleted()
12422 << BinaryOperator::getOpcodeStr(Opc)
12423 << getDeletedOrUnavailableSuffix(Best->Function)
12424 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12426 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12427 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12428 return ExprError();
12431 // We matched a built-in operator; build it.
12432 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12436 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12437 SourceLocation RLoc,
12438 Expr *Base, Expr *Idx) {
12439 Expr *Args[2] = { Base, Idx };
12440 DeclarationName OpName =
12441 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12443 // If either side is type-dependent, create an appropriate dependent
12445 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12447 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12448 // CHECKME: no 'operator' keyword?
12449 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12450 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12451 UnresolvedLookupExpr *Fn
12452 = UnresolvedLookupExpr::Create(Context, NamingClass,
12453 NestedNameSpecifierLoc(), OpNameInfo,
12454 /*ADL*/ true, /*Overloaded*/ false,
12455 UnresolvedSetIterator(),
12456 UnresolvedSetIterator());
12457 // Can't add any actual overloads yet
12459 return new (Context)
12460 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12461 Context.DependentTy, VK_RValue, RLoc, FPOptions());
12464 // Handle placeholders on both operands.
12465 if (checkPlaceholderForOverload(*this, Args[0]))
12466 return ExprError();
12467 if (checkPlaceholderForOverload(*this, Args[1]))
12468 return ExprError();
12470 // Build an empty overload set.
12471 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12473 // Subscript can only be overloaded as a member function.
12475 // Add operator candidates that are member functions.
12476 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12478 // Add builtin operator candidates.
12479 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12481 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12483 // Perform overload resolution.
12484 OverloadCandidateSet::iterator Best;
12485 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12487 // We found a built-in operator or an overloaded operator.
12488 FunctionDecl *FnDecl = Best->Function;
12491 // We matched an overloaded operator. Build a call to that
12494 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12496 // Convert the arguments.
12497 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12499 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12500 Best->FoundDecl, Method);
12501 if (Arg0.isInvalid())
12502 return ExprError();
12503 Args[0] = Arg0.get();
12505 // Convert the arguments.
12506 ExprResult InputInit
12507 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12509 FnDecl->getParamDecl(0)),
12512 if (InputInit.isInvalid())
12513 return ExprError();
12515 Args[1] = InputInit.getAs<Expr>();
12517 // Build the actual expression node.
12518 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12519 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12520 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12523 HadMultipleCandidates,
12524 OpLocInfo.getLoc(),
12525 OpLocInfo.getInfo());
12526 if (FnExpr.isInvalid())
12527 return ExprError();
12529 // Determine the result type
12530 QualType ResultTy = FnDecl->getReturnType();
12531 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12532 ResultTy = ResultTy.getNonLValueExprType(Context);
12534 CXXOperatorCallExpr *TheCall =
12535 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12536 FnExpr.get(), Args,
12537 ResultTy, VK, RLoc,
12540 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12541 return ExprError();
12543 if (CheckFunctionCall(Method, TheCall,
12544 Method->getType()->castAs<FunctionProtoType>()))
12545 return ExprError();
12547 return MaybeBindToTemporary(TheCall);
12549 // We matched a built-in operator. Convert the arguments, then
12550 // break out so that we will build the appropriate built-in
12552 ExprResult ArgsRes0 =
12553 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0],
12554 Best->Conversions[0], AA_Passing);
12555 if (ArgsRes0.isInvalid())
12556 return ExprError();
12557 Args[0] = ArgsRes0.get();
12559 ExprResult ArgsRes1 =
12560 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1],
12561 Best->Conversions[1], AA_Passing);
12562 if (ArgsRes1.isInvalid())
12563 return ExprError();
12564 Args[1] = ArgsRes1.get();
12570 case OR_No_Viable_Function: {
12571 if (CandidateSet.empty())
12572 Diag(LLoc, diag::err_ovl_no_oper)
12573 << Args[0]->getType() << /*subscript*/ 0
12574 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12576 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12577 << Args[0]->getType()
12578 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12579 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12581 return ExprError();
12585 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12587 << Args[0]->getType() << Args[1]->getType()
12588 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12589 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12591 return ExprError();
12594 Diag(LLoc, diag::err_ovl_deleted_oper)
12595 << Best->Function->isDeleted() << "[]"
12596 << getDeletedOrUnavailableSuffix(Best->Function)
12597 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12598 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12600 return ExprError();
12603 // We matched a built-in operator; build it.
12604 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12607 /// BuildCallToMemberFunction - Build a call to a member
12608 /// function. MemExpr is the expression that refers to the member
12609 /// function (and includes the object parameter), Args/NumArgs are the
12610 /// arguments to the function call (not including the object
12611 /// parameter). The caller needs to validate that the member
12612 /// expression refers to a non-static member function or an overloaded
12613 /// member function.
12615 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12616 SourceLocation LParenLoc,
12618 SourceLocation RParenLoc) {
12619 assert(MemExprE->getType() == Context.BoundMemberTy ||
12620 MemExprE->getType() == Context.OverloadTy);
12622 // Dig out the member expression. This holds both the object
12623 // argument and the member function we're referring to.
12624 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12626 // Determine whether this is a call to a pointer-to-member function.
12627 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12628 assert(op->getType() == Context.BoundMemberTy);
12629 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12632 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12634 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12635 QualType resultType = proto->getCallResultType(Context);
12636 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12638 // Check that the object type isn't more qualified than the
12639 // member function we're calling.
12640 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12642 QualType objectType = op->getLHS()->getType();
12643 if (op->getOpcode() == BO_PtrMemI)
12644 objectType = objectType->castAs<PointerType>()->getPointeeType();
12645 Qualifiers objectQuals = objectType.getQualifiers();
12647 Qualifiers difference = objectQuals - funcQuals;
12648 difference.removeObjCGCAttr();
12649 difference.removeAddressSpace();
12651 std::string qualsString = difference.getAsString();
12652 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12653 << fnType.getUnqualifiedType()
12655 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12658 CXXMemberCallExpr *call
12659 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12660 resultType, valueKind, RParenLoc);
12662 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12664 return ExprError();
12666 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12667 return ExprError();
12669 if (CheckOtherCall(call, proto))
12670 return ExprError();
12672 return MaybeBindToTemporary(call);
12675 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12676 return new (Context)
12677 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12679 UnbridgedCastsSet UnbridgedCasts;
12680 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12681 return ExprError();
12683 MemberExpr *MemExpr;
12684 CXXMethodDecl *Method = nullptr;
12685 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12686 NestedNameSpecifier *Qualifier = nullptr;
12687 if (isa<MemberExpr>(NakedMemExpr)) {
12688 MemExpr = cast<MemberExpr>(NakedMemExpr);
12689 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12690 FoundDecl = MemExpr->getFoundDecl();
12691 Qualifier = MemExpr->getQualifier();
12692 UnbridgedCasts.restore();
12694 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12695 Qualifier = UnresExpr->getQualifier();
12697 QualType ObjectType = UnresExpr->getBaseType();
12698 Expr::Classification ObjectClassification
12699 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12700 : UnresExpr->getBase()->Classify(Context);
12702 // Add overload candidates
12703 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12704 OverloadCandidateSet::CSK_Normal);
12706 // FIXME: avoid copy.
12707 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12708 if (UnresExpr->hasExplicitTemplateArgs()) {
12709 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12710 TemplateArgs = &TemplateArgsBuffer;
12713 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12714 E = UnresExpr->decls_end(); I != E; ++I) {
12716 NamedDecl *Func = *I;
12717 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12718 if (isa<UsingShadowDecl>(Func))
12719 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12722 // Microsoft supports direct constructor calls.
12723 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12724 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12725 Args, CandidateSet);
12726 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12727 // If explicit template arguments were provided, we can't call a
12728 // non-template member function.
12732 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12733 ObjectClassification, Args, CandidateSet,
12734 /*SuppressUserConversions=*/false);
12736 AddMethodTemplateCandidate(
12737 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12738 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12739 /*SuppressUsedConversions=*/false);
12743 DeclarationName DeclName = UnresExpr->getMemberName();
12745 UnbridgedCasts.restore();
12747 OverloadCandidateSet::iterator Best;
12748 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12751 Method = cast<CXXMethodDecl>(Best->Function);
12752 FoundDecl = Best->FoundDecl;
12753 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12754 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12755 return ExprError();
12756 // If FoundDecl is different from Method (such as if one is a template
12757 // and the other a specialization), make sure DiagnoseUseOfDecl is
12759 // FIXME: This would be more comprehensively addressed by modifying
12760 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12762 if (Method != FoundDecl.getDecl() &&
12763 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12764 return ExprError();
12767 case OR_No_Viable_Function:
12768 Diag(UnresExpr->getMemberLoc(),
12769 diag::err_ovl_no_viable_member_function_in_call)
12770 << DeclName << MemExprE->getSourceRange();
12771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12772 // FIXME: Leaking incoming expressions!
12773 return ExprError();
12776 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12777 << DeclName << MemExprE->getSourceRange();
12778 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12779 // FIXME: Leaking incoming expressions!
12780 return ExprError();
12783 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12784 << Best->Function->isDeleted()
12786 << getDeletedOrUnavailableSuffix(Best->Function)
12787 << MemExprE->getSourceRange();
12788 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12789 // FIXME: Leaking incoming expressions!
12790 return ExprError();
12793 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12795 // If overload resolution picked a static member, build a
12796 // non-member call based on that function.
12797 if (Method->isStatic()) {
12798 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12802 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12805 QualType ResultType = Method->getReturnType();
12806 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12807 ResultType = ResultType.getNonLValueExprType(Context);
12809 assert(Method && "Member call to something that isn't a method?");
12810 CXXMemberCallExpr *TheCall =
12811 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12812 ResultType, VK, RParenLoc);
12814 // Check for a valid return type.
12815 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12817 return ExprError();
12819 // Convert the object argument (for a non-static member function call).
12820 // We only need to do this if there was actually an overload; otherwise
12821 // it was done at lookup.
12822 if (!Method->isStatic()) {
12823 ExprResult ObjectArg =
12824 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12825 FoundDecl, Method);
12826 if (ObjectArg.isInvalid())
12827 return ExprError();
12828 MemExpr->setBase(ObjectArg.get());
12831 // Convert the rest of the arguments
12832 const FunctionProtoType *Proto =
12833 Method->getType()->getAs<FunctionProtoType>();
12834 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12836 return ExprError();
12838 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12840 if (CheckFunctionCall(Method, TheCall, Proto))
12841 return ExprError();
12843 // In the case the method to call was not selected by the overloading
12844 // resolution process, we still need to handle the enable_if attribute. Do
12845 // that here, so it will not hide previous -- and more relevant -- errors.
12846 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12847 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12848 Diag(MemE->getMemberLoc(),
12849 diag::err_ovl_no_viable_member_function_in_call)
12850 << Method << Method->getSourceRange();
12851 Diag(Method->getLocation(),
12852 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12853 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12854 return ExprError();
12858 if ((isa<CXXConstructorDecl>(CurContext) ||
12859 isa<CXXDestructorDecl>(CurContext)) &&
12860 TheCall->getMethodDecl()->isPure()) {
12861 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12863 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12864 MemExpr->performsVirtualDispatch(getLangOpts())) {
12865 Diag(MemExpr->getLocStart(),
12866 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12867 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12868 << MD->getParent()->getDeclName();
12870 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12871 if (getLangOpts().AppleKext)
12872 Diag(MemExpr->getLocStart(),
12873 diag::note_pure_qualified_call_kext)
12874 << MD->getParent()->getDeclName()
12875 << MD->getDeclName();
12879 if (CXXDestructorDecl *DD =
12880 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12881 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12882 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12883 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12884 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12885 MemExpr->getMemberLoc());
12888 return MaybeBindToTemporary(TheCall);
12891 /// BuildCallToObjectOfClassType - Build a call to an object of class
12892 /// type (C++ [over.call.object]), which can end up invoking an
12893 /// overloaded function call operator (@c operator()) or performing a
12894 /// user-defined conversion on the object argument.
12896 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12897 SourceLocation LParenLoc,
12899 SourceLocation RParenLoc) {
12900 if (checkPlaceholderForOverload(*this, Obj))
12901 return ExprError();
12902 ExprResult Object = Obj;
12904 UnbridgedCastsSet UnbridgedCasts;
12905 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12906 return ExprError();
12908 assert(Object.get()->getType()->isRecordType() &&
12909 "Requires object type argument");
12910 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12912 // C++ [over.call.object]p1:
12913 // If the primary-expression E in the function call syntax
12914 // evaluates to a class object of type "cv T", then the set of
12915 // candidate functions includes at least the function call
12916 // operators of T. The function call operators of T are obtained by
12917 // ordinary lookup of the name operator() in the context of
12919 OverloadCandidateSet CandidateSet(LParenLoc,
12920 OverloadCandidateSet::CSK_Operator);
12921 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12923 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12924 diag::err_incomplete_object_call, Object.get()))
12927 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12928 LookupQualifiedName(R, Record->getDecl());
12929 R.suppressDiagnostics();
12931 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12932 Oper != OperEnd; ++Oper) {
12933 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12934 Object.get()->Classify(Context), Args, CandidateSet,
12935 /*SuppressUserConversions=*/false);
12938 // C++ [over.call.object]p2:
12939 // In addition, for each (non-explicit in C++0x) conversion function
12940 // declared in T of the form
12942 // operator conversion-type-id () cv-qualifier;
12944 // where cv-qualifier is the same cv-qualification as, or a
12945 // greater cv-qualification than, cv, and where conversion-type-id
12946 // denotes the type "pointer to function of (P1,...,Pn) returning
12947 // R", or the type "reference to pointer to function of
12948 // (P1,...,Pn) returning R", or the type "reference to function
12949 // of (P1,...,Pn) returning R", a surrogate call function [...]
12950 // is also considered as a candidate function. Similarly,
12951 // surrogate call functions are added to the set of candidate
12952 // functions for each conversion function declared in an
12953 // accessible base class provided the function is not hidden
12954 // within T by another intervening declaration.
12955 const auto &Conversions =
12956 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12957 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12959 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12960 if (isa<UsingShadowDecl>(D))
12961 D = cast<UsingShadowDecl>(D)->getTargetDecl();
12963 // Skip over templated conversion functions; they aren't
12965 if (isa<FunctionTemplateDecl>(D))
12968 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12969 if (!Conv->isExplicit()) {
12970 // Strip the reference type (if any) and then the pointer type (if
12971 // any) to get down to what might be a function type.
12972 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12973 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12974 ConvType = ConvPtrType->getPointeeType();
12976 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12978 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12979 Object.get(), Args, CandidateSet);
12984 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12986 // Perform overload resolution.
12987 OverloadCandidateSet::iterator Best;
12988 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12991 // Overload resolution succeeded; we'll build the appropriate call
12995 case OR_No_Viable_Function:
12996 if (CandidateSet.empty())
12997 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12998 << Object.get()->getType() << /*call*/ 1
12999 << Object.get()->getSourceRange();
13001 Diag(Object.get()->getLocStart(),
13002 diag::err_ovl_no_viable_object_call)
13003 << Object.get()->getType() << Object.get()->getSourceRange();
13004 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13008 Diag(Object.get()->getLocStart(),
13009 diag::err_ovl_ambiguous_object_call)
13010 << Object.get()->getType() << Object.get()->getSourceRange();
13011 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13015 Diag(Object.get()->getLocStart(),
13016 diag::err_ovl_deleted_object_call)
13017 << Best->Function->isDeleted()
13018 << Object.get()->getType()
13019 << getDeletedOrUnavailableSuffix(Best->Function)
13020 << Object.get()->getSourceRange();
13021 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13025 if (Best == CandidateSet.end())
13028 UnbridgedCasts.restore();
13030 if (Best->Function == nullptr) {
13031 // Since there is no function declaration, this is one of the
13032 // surrogate candidates. Dig out the conversion function.
13033 CXXConversionDecl *Conv
13034 = cast<CXXConversionDecl>(
13035 Best->Conversions[0].UserDefined.ConversionFunction);
13037 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13039 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13040 return ExprError();
13041 assert(Conv == Best->FoundDecl.getDecl() &&
13042 "Found Decl & conversion-to-functionptr should be same, right?!");
13043 // We selected one of the surrogate functions that converts the
13044 // object parameter to a function pointer. Perform the conversion
13045 // on the object argument, then let ActOnCallExpr finish the job.
13047 // Create an implicit member expr to refer to the conversion operator.
13048 // and then call it.
13049 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13050 Conv, HadMultipleCandidates);
13051 if (Call.isInvalid())
13052 return ExprError();
13053 // Record usage of conversion in an implicit cast.
13054 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13055 CK_UserDefinedConversion, Call.get(),
13056 nullptr, VK_RValue);
13058 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13061 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13063 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13064 // that calls this method, using Object for the implicit object
13065 // parameter and passing along the remaining arguments.
13066 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13068 // An error diagnostic has already been printed when parsing the declaration.
13069 if (Method->isInvalidDecl())
13070 return ExprError();
13072 const FunctionProtoType *Proto =
13073 Method->getType()->getAs<FunctionProtoType>();
13075 unsigned NumParams = Proto->getNumParams();
13077 DeclarationNameInfo OpLocInfo(
13078 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13079 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13080 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13081 Obj, HadMultipleCandidates,
13082 OpLocInfo.getLoc(),
13083 OpLocInfo.getInfo());
13084 if (NewFn.isInvalid())
13087 // Build the full argument list for the method call (the implicit object
13088 // parameter is placed at the beginning of the list).
13089 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13090 MethodArgs[0] = Object.get();
13091 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13093 // Once we've built TheCall, all of the expressions are properly
13095 QualType ResultTy = Method->getReturnType();
13096 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13097 ResultTy = ResultTy.getNonLValueExprType(Context);
13099 CXXOperatorCallExpr *TheCall = new (Context)
13100 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13101 VK, RParenLoc, FPOptions());
13103 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13106 // We may have default arguments. If so, we need to allocate more
13107 // slots in the call for them.
13108 if (Args.size() < NumParams)
13109 TheCall->setNumArgs(Context, NumParams + 1);
13111 bool IsError = false;
13113 // Initialize the implicit object parameter.
13114 ExprResult ObjRes =
13115 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13116 Best->FoundDecl, Method);
13117 if (ObjRes.isInvalid())
13121 TheCall->setArg(0, Object.get());
13123 // Check the argument types.
13124 for (unsigned i = 0; i != NumParams; i++) {
13126 if (i < Args.size()) {
13129 // Pass the argument.
13131 ExprResult InputInit
13132 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13134 Method->getParamDecl(i)),
13135 SourceLocation(), Arg);
13137 IsError |= InputInit.isInvalid();
13138 Arg = InputInit.getAs<Expr>();
13141 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13142 if (DefArg.isInvalid()) {
13147 Arg = DefArg.getAs<Expr>();
13150 TheCall->setArg(i + 1, Arg);
13153 // If this is a variadic call, handle args passed through "...".
13154 if (Proto->isVariadic()) {
13155 // Promote the arguments (C99 6.5.2.2p7).
13156 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13157 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13159 IsError |= Arg.isInvalid();
13160 TheCall->setArg(i + 1, Arg.get());
13164 if (IsError) return true;
13166 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13168 if (CheckFunctionCall(Method, TheCall, Proto))
13171 return MaybeBindToTemporary(TheCall);
13174 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13175 /// (if one exists), where @c Base is an expression of class type and
13176 /// @c Member is the name of the member we're trying to find.
13178 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13179 bool *NoArrowOperatorFound) {
13180 assert(Base->getType()->isRecordType() &&
13181 "left-hand side must have class type");
13183 if (checkPlaceholderForOverload(*this, Base))
13184 return ExprError();
13186 SourceLocation Loc = Base->getExprLoc();
13188 // C++ [over.ref]p1:
13190 // [...] An expression x->m is interpreted as (x.operator->())->m
13191 // for a class object x of type T if T::operator->() exists and if
13192 // the operator is selected as the best match function by the
13193 // overload resolution mechanism (13.3).
13194 DeclarationName OpName =
13195 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13196 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13197 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13199 if (RequireCompleteType(Loc, Base->getType(),
13200 diag::err_typecheck_incomplete_tag, Base))
13201 return ExprError();
13203 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13204 LookupQualifiedName(R, BaseRecord->getDecl());
13205 R.suppressDiagnostics();
13207 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13208 Oper != OperEnd; ++Oper) {
13209 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13210 None, CandidateSet, /*SuppressUserConversions=*/false);
13213 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13215 // Perform overload resolution.
13216 OverloadCandidateSet::iterator Best;
13217 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13219 // Overload resolution succeeded; we'll build the call below.
13222 case OR_No_Viable_Function:
13223 if (CandidateSet.empty()) {
13224 QualType BaseType = Base->getType();
13225 if (NoArrowOperatorFound) {
13226 // Report this specific error to the caller instead of emitting a
13227 // diagnostic, as requested.
13228 *NoArrowOperatorFound = true;
13229 return ExprError();
13231 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13232 << BaseType << Base->getSourceRange();
13233 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13234 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13235 << FixItHint::CreateReplacement(OpLoc, ".");
13238 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13239 << "operator->" << Base->getSourceRange();
13240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13241 return ExprError();
13244 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13245 << "->" << Base->getType() << Base->getSourceRange();
13246 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13247 return ExprError();
13250 Diag(OpLoc, diag::err_ovl_deleted_oper)
13251 << Best->Function->isDeleted()
13253 << getDeletedOrUnavailableSuffix(Best->Function)
13254 << Base->getSourceRange();
13255 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13256 return ExprError();
13259 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13261 // Convert the object parameter.
13262 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13263 ExprResult BaseResult =
13264 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13265 Best->FoundDecl, Method);
13266 if (BaseResult.isInvalid())
13267 return ExprError();
13268 Base = BaseResult.get();
13270 // Build the operator call.
13271 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13272 Base, HadMultipleCandidates, OpLoc);
13273 if (FnExpr.isInvalid())
13274 return ExprError();
13276 QualType ResultTy = Method->getReturnType();
13277 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13278 ResultTy = ResultTy.getNonLValueExprType(Context);
13279 CXXOperatorCallExpr *TheCall =
13280 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13281 Base, ResultTy, VK, OpLoc, FPOptions());
13283 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13284 return ExprError();
13286 if (CheckFunctionCall(Method, TheCall,
13287 Method->getType()->castAs<FunctionProtoType>()))
13288 return ExprError();
13290 return MaybeBindToTemporary(TheCall);
13293 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13294 /// a literal operator described by the provided lookup results.
13295 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13296 DeclarationNameInfo &SuffixInfo,
13297 ArrayRef<Expr*> Args,
13298 SourceLocation LitEndLoc,
13299 TemplateArgumentListInfo *TemplateArgs) {
13300 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13302 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13303 OverloadCandidateSet::CSK_Normal);
13304 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13305 /*SuppressUserConversions=*/true);
13307 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13309 // Perform overload resolution. This will usually be trivial, but might need
13310 // to perform substitutions for a literal operator template.
13311 OverloadCandidateSet::iterator Best;
13312 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13317 case OR_No_Viable_Function:
13318 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13319 << R.getLookupName();
13320 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13321 return ExprError();
13324 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13325 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13326 return ExprError();
13329 FunctionDecl *FD = Best->Function;
13330 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13331 nullptr, HadMultipleCandidates,
13332 SuffixInfo.getLoc(),
13333 SuffixInfo.getInfo());
13334 if (Fn.isInvalid())
13337 // Check the argument types. This should almost always be a no-op, except
13338 // that array-to-pointer decay is applied to string literals.
13340 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13341 ExprResult InputInit = PerformCopyInitialization(
13342 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13343 SourceLocation(), Args[ArgIdx]);
13344 if (InputInit.isInvalid())
13346 ConvArgs[ArgIdx] = InputInit.get();
13349 QualType ResultTy = FD->getReturnType();
13350 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13351 ResultTy = ResultTy.getNonLValueExprType(Context);
13353 UserDefinedLiteral *UDL =
13354 new (Context) UserDefinedLiteral(Context, Fn.get(),
13355 llvm::makeArrayRef(ConvArgs, Args.size()),
13356 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13358 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13359 return ExprError();
13361 if (CheckFunctionCall(FD, UDL, nullptr))
13362 return ExprError();
13364 return MaybeBindToTemporary(UDL);
13367 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13368 /// given LookupResult is non-empty, it is assumed to describe a member which
13369 /// will be invoked. Otherwise, the function will be found via argument
13370 /// dependent lookup.
13371 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13372 /// otherwise CallExpr is set to ExprError() and some non-success value
13374 Sema::ForRangeStatus
13375 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13376 SourceLocation RangeLoc,
13377 const DeclarationNameInfo &NameInfo,
13378 LookupResult &MemberLookup,
13379 OverloadCandidateSet *CandidateSet,
13380 Expr *Range, ExprResult *CallExpr) {
13381 Scope *S = nullptr;
13383 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13384 if (!MemberLookup.empty()) {
13385 ExprResult MemberRef =
13386 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13387 /*IsPtr=*/false, CXXScopeSpec(),
13388 /*TemplateKWLoc=*/SourceLocation(),
13389 /*FirstQualifierInScope=*/nullptr,
13391 /*TemplateArgs=*/nullptr, S);
13392 if (MemberRef.isInvalid()) {
13393 *CallExpr = ExprError();
13394 return FRS_DiagnosticIssued;
13396 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13397 if (CallExpr->isInvalid()) {
13398 *CallExpr = ExprError();
13399 return FRS_DiagnosticIssued;
13402 UnresolvedSet<0> FoundNames;
13403 UnresolvedLookupExpr *Fn =
13404 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13405 NestedNameSpecifierLoc(), NameInfo,
13406 /*NeedsADL=*/true, /*Overloaded=*/false,
13407 FoundNames.begin(), FoundNames.end());
13409 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13410 CandidateSet, CallExpr);
13411 if (CandidateSet->empty() || CandidateSetError) {
13412 *CallExpr = ExprError();
13413 return FRS_NoViableFunction;
13415 OverloadCandidateSet::iterator Best;
13416 OverloadingResult OverloadResult =
13417 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13419 if (OverloadResult == OR_No_Viable_Function) {
13420 *CallExpr = ExprError();
13421 return FRS_NoViableFunction;
13423 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13424 Loc, nullptr, CandidateSet, &Best,
13426 /*AllowTypoCorrection=*/false);
13427 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13428 *CallExpr = ExprError();
13429 return FRS_DiagnosticIssued;
13432 return FRS_Success;
13436 /// FixOverloadedFunctionReference - E is an expression that refers to
13437 /// a C++ overloaded function (possibly with some parentheses and
13438 /// perhaps a '&' around it). We have resolved the overloaded function
13439 /// to the function declaration Fn, so patch up the expression E to
13440 /// refer (possibly indirectly) to Fn. Returns the new expr.
13441 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13442 FunctionDecl *Fn) {
13443 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13444 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13446 if (SubExpr == PE->getSubExpr())
13449 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13453 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13455 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13456 SubExpr->getType()) &&
13457 "Implicit cast type cannot be determined from overload");
13458 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13459 if (SubExpr == ICE->getSubExpr())
13462 return ImplicitCastExpr::Create(Context, ICE->getType(),
13463 ICE->getCastKind(),
13465 ICE->getValueKind());
13468 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13469 if (!GSE->isResultDependent()) {
13471 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13472 if (SubExpr == GSE->getResultExpr())
13475 // Replace the resulting type information before rebuilding the generic
13476 // selection expression.
13477 ArrayRef<Expr *> A = GSE->getAssocExprs();
13478 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13479 unsigned ResultIdx = GSE->getResultIndex();
13480 AssocExprs[ResultIdx] = SubExpr;
13482 return new (Context) GenericSelectionExpr(
13483 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13484 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13485 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13488 // Rather than fall through to the unreachable, return the original generic
13489 // selection expression.
13493 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13494 assert(UnOp->getOpcode() == UO_AddrOf &&
13495 "Can only take the address of an overloaded function");
13496 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13497 if (Method->isStatic()) {
13498 // Do nothing: static member functions aren't any different
13499 // from non-member functions.
13501 // Fix the subexpression, which really has to be an
13502 // UnresolvedLookupExpr holding an overloaded member function
13504 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13506 if (SubExpr == UnOp->getSubExpr())
13509 assert(isa<DeclRefExpr>(SubExpr)
13510 && "fixed to something other than a decl ref");
13511 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13512 && "fixed to a member ref with no nested name qualifier");
13514 // We have taken the address of a pointer to member
13515 // function. Perform the computation here so that we get the
13516 // appropriate pointer to member type.
13518 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13519 QualType MemPtrType
13520 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13521 // Under the MS ABI, lock down the inheritance model now.
13522 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13523 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13525 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13526 VK_RValue, OK_Ordinary,
13527 UnOp->getOperatorLoc());
13530 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13532 if (SubExpr == UnOp->getSubExpr())
13535 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13536 Context.getPointerType(SubExpr->getType()),
13537 VK_RValue, OK_Ordinary,
13538 UnOp->getOperatorLoc());
13541 // C++ [except.spec]p17:
13542 // An exception-specification is considered to be needed when:
13543 // - in an expression the function is the unique lookup result or the
13544 // selected member of a set of overloaded functions
13545 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13546 ResolveExceptionSpec(E->getExprLoc(), FPT);
13548 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13549 // FIXME: avoid copy.
13550 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13551 if (ULE->hasExplicitTemplateArgs()) {
13552 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13553 TemplateArgs = &TemplateArgsBuffer;
13556 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13557 ULE->getQualifierLoc(),
13558 ULE->getTemplateKeywordLoc(),
13560 /*enclosing*/ false, // FIXME?
13566 MarkDeclRefReferenced(DRE);
13567 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13571 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13572 // FIXME: avoid copy.
13573 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13574 if (MemExpr->hasExplicitTemplateArgs()) {
13575 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13576 TemplateArgs = &TemplateArgsBuffer;
13581 // If we're filling in a static method where we used to have an
13582 // implicit member access, rewrite to a simple decl ref.
13583 if (MemExpr->isImplicitAccess()) {
13584 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13585 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13586 MemExpr->getQualifierLoc(),
13587 MemExpr->getTemplateKeywordLoc(),
13589 /*enclosing*/ false,
13590 MemExpr->getMemberLoc(),
13595 MarkDeclRefReferenced(DRE);
13596 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13599 SourceLocation Loc = MemExpr->getMemberLoc();
13600 if (MemExpr->getQualifier())
13601 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13602 CheckCXXThisCapture(Loc);
13603 Base = new (Context) CXXThisExpr(Loc,
13604 MemExpr->getBaseType(),
13605 /*isImplicit=*/true);
13608 Base = MemExpr->getBase();
13610 ExprValueKind valueKind;
13612 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13613 valueKind = VK_LValue;
13614 type = Fn->getType();
13616 valueKind = VK_RValue;
13617 type = Context.BoundMemberTy;
13620 MemberExpr *ME = MemberExpr::Create(
13621 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13622 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13623 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13625 ME->setHadMultipleCandidates(true);
13626 MarkMemberReferenced(ME);
13630 llvm_unreachable("Invalid reference to overloaded function");
13633 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13634 DeclAccessPair Found,
13635 FunctionDecl *Fn) {
13636 return FixOverloadedFunctionReference(E.get(), Found, Fn);