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 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);
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] = {
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);
334 // If it's value-dependent, we can't tell whether it's narrowing.
335 if (Initializer->isValueDependent())
336 return NK_Dependent_Narrowing;
339 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() {
842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
849 class UnbridgedCastsSet {
854 SmallVector<Entry, 2> Entries;
857 void save(Sema &S, Expr *&E) {
858 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
859 Entry entry = { &E, E };
860 Entries.push_back(entry);
861 E = S.stripARCUnbridgedCast(E);
865 for (SmallVectorImpl<Entry>::iterator
866 i = Entries.begin(), e = Entries.end(); i != e; ++i)
872 /// checkPlaceholderForOverload - Do any interesting placeholder-like
873 /// preprocessing on the given expression.
875 /// \param unbridgedCasts a collection to which to add unbridged casts;
876 /// without this, they will be immediately diagnosed as errors
878 /// Return true on unrecoverable error.
880 checkPlaceholderForOverload(Sema &S, Expr *&E,
881 UnbridgedCastsSet *unbridgedCasts = nullptr) {
882 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
883 // We can't handle overloaded expressions here because overload
884 // resolution might reasonably tweak them.
885 if (placeholder->getKind() == BuiltinType::Overload) return false;
887 // If the context potentially accepts unbridged ARC casts, strip
888 // the unbridged cast and add it to the collection for later restoration.
889 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
891 unbridgedCasts->save(S, E);
895 // Go ahead and check everything else.
896 ExprResult result = S.CheckPlaceholderExpr(E);
897 if (result.isInvalid())
908 /// checkArgPlaceholdersForOverload - Check a set of call operands for
910 static bool checkArgPlaceholdersForOverload(Sema &S,
912 UnbridgedCastsSet &unbridged) {
913 for (unsigned i = 0, e = Args.size(); i != e; ++i)
914 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
920 // IsOverload - Determine whether the given New declaration is an
921 // overload of the declarations in Old. This routine returns false if
922 // New and Old cannot be overloaded, e.g., if New has the same
923 // signature as some function in Old (C++ 1.3.10) or if the Old
924 // declarations aren't functions (or function templates) at all. When
925 // it does return false, MatchedDecl will point to the decl that New
926 // cannot be overloaded with. This decl may be a UsingShadowDecl on
927 // top of the underlying declaration.
929 // Example: Given the following input:
931 // void f(int, float); // #1
932 // void f(int, int); // #2
933 // int f(int, int); // #3
935 // When we process #1, there is no previous declaration of "f",
936 // so IsOverload will not be used.
938 // When we process #2, Old contains only the FunctionDecl for #1. By
939 // comparing the parameter types, we see that #1 and #2 are overloaded
940 // (since they have different signatures), so this routine returns
941 // false; MatchedDecl is unchanged.
943 // When we process #3, Old is an overload set containing #1 and #2. We
944 // compare the signatures of #3 to #1 (they're overloaded, so we do
945 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
946 // identical (return types of functions are not part of the
947 // signature), IsOverload returns false and MatchedDecl will be set to
948 // point to the FunctionDecl for #2.
950 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
951 // into a class by a using declaration. The rules for whether to hide
952 // shadow declarations ignore some properties which otherwise figure
953 // into a function template's signature.
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()))
1490 assert(QualType(FromFn, 0).isCanonical());
1491 if (QualType(FromFn, 0) != CanTo) return false;
1497 /// \brief Determine whether the conversion from FromType to ToType is a valid
1498 /// vector conversion.
1500 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1502 static bool IsVectorConversion(Sema &S, QualType FromType,
1503 QualType ToType, ImplicitConversionKind &ICK) {
1504 // We need at least one of these types to be a vector type to have a vector
1506 if (!ToType->isVectorType() && !FromType->isVectorType())
1509 // Identical types require no conversions.
1510 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1513 // There are no conversions between extended vector types, only identity.
1514 if (ToType->isExtVectorType()) {
1515 // There are no conversions between extended vector types other than the
1516 // identity conversion.
1517 if (FromType->isExtVectorType())
1520 // Vector splat from any arithmetic type to a vector.
1521 if (FromType->isArithmeticType()) {
1522 ICK = ICK_Vector_Splat;
1527 // We can perform the conversion between vector types in the following cases:
1528 // 1)vector types are equivalent AltiVec and GCC vector types
1529 // 2)lax vector conversions are permitted and the vector types are of the
1531 if (ToType->isVectorType() && FromType->isVectorType()) {
1532 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1533 S.isLaxVectorConversion(FromType, ToType)) {
1534 ICK = ICK_Vector_Conversion;
1542 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1543 bool InOverloadResolution,
1544 StandardConversionSequence &SCS,
1547 /// IsStandardConversion - Determines whether there is a standard
1548 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1549 /// expression From to the type ToType. Standard conversion sequences
1550 /// only consider non-class types; for conversions that involve class
1551 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1552 /// contain the standard conversion sequence required to perform this
1553 /// conversion and this routine will return true. Otherwise, this
1554 /// routine will return false and the value of SCS is unspecified.
1555 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1556 bool InOverloadResolution,
1557 StandardConversionSequence &SCS,
1559 bool AllowObjCWritebackConversion) {
1560 QualType FromType = From->getType();
1562 // Standard conversions (C++ [conv])
1563 SCS.setAsIdentityConversion();
1564 SCS.IncompatibleObjC = false;
1565 SCS.setFromType(FromType);
1566 SCS.CopyConstructor = nullptr;
1568 // There are no standard conversions for class types in C++, so
1569 // abort early. When overloading in C, however, we do permit them.
1570 if (S.getLangOpts().CPlusPlus &&
1571 (FromType->isRecordType() || ToType->isRecordType()))
1574 // The first conversion can be an lvalue-to-rvalue conversion,
1575 // array-to-pointer conversion, or function-to-pointer conversion
1578 if (FromType == S.Context.OverloadTy) {
1579 DeclAccessPair AccessPair;
1580 if (FunctionDecl *Fn
1581 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1583 // We were able to resolve the address of the overloaded function,
1584 // so we can convert to the type of that function.
1585 FromType = Fn->getType();
1586 SCS.setFromType(FromType);
1588 // we can sometimes resolve &foo<int> regardless of ToType, so check
1589 // if the type matches (identity) or we are converting to bool
1590 if (!S.Context.hasSameUnqualifiedType(
1591 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1593 // if the function type matches except for [[noreturn]], it's ok
1594 if (!S.IsFunctionConversion(FromType,
1595 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1596 // otherwise, only a boolean conversion is standard
1597 if (!ToType->isBooleanType())
1601 // Check if the "from" expression is taking the address of an overloaded
1602 // function and recompute the FromType accordingly. Take advantage of the
1603 // fact that non-static member functions *must* have such an address-of
1605 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1606 if (Method && !Method->isStatic()) {
1607 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1608 "Non-unary operator on non-static member address");
1609 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1611 "Non-address-of operator on non-static member address");
1612 const Type *ClassType
1613 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1614 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1615 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1616 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1618 "Non-address-of operator for overloaded function expression");
1619 FromType = S.Context.getPointerType(FromType);
1622 // Check that we've computed the proper type after overload resolution.
1623 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1624 // be calling it from within an NDEBUG block.
1625 assert(S.Context.hasSameType(
1627 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1632 // Lvalue-to-rvalue conversion (C++11 4.1):
1633 // A glvalue (3.10) of a non-function, non-array type T can
1634 // be converted to a prvalue.
1635 bool argIsLValue = From->isGLValue();
1637 !FromType->isFunctionType() && !FromType->isArrayType() &&
1638 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1639 SCS.First = ICK_Lvalue_To_Rvalue;
1642 // ... if the lvalue has atomic type, the value has the non-atomic version
1643 // of the type of the lvalue ...
1644 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1645 FromType = Atomic->getValueType();
1647 // If T is a non-class type, the type of the rvalue is the
1648 // cv-unqualified version of T. Otherwise, the type of the rvalue
1649 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1650 // just strip the qualifiers because they don't matter.
1651 FromType = FromType.getUnqualifiedType();
1652 } else if (FromType->isArrayType()) {
1653 // Array-to-pointer conversion (C++ 4.2)
1654 SCS.First = ICK_Array_To_Pointer;
1656 // An lvalue or rvalue of type "array of N T" or "array of unknown
1657 // bound of T" can be converted to an rvalue of type "pointer to
1659 FromType = S.Context.getArrayDecayedType(FromType);
1661 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1662 // This conversion is deprecated in C++03 (D.4)
1663 SCS.DeprecatedStringLiteralToCharPtr = true;
1665 // For the purpose of ranking in overload resolution
1666 // (13.3.3.1.1), this conversion is considered an
1667 // array-to-pointer conversion followed by a qualification
1668 // conversion (4.4). (C++ 4.2p2)
1669 SCS.Second = ICK_Identity;
1670 SCS.Third = ICK_Qualification;
1671 SCS.QualificationIncludesObjCLifetime = false;
1672 SCS.setAllToTypes(FromType);
1675 } else if (FromType->isFunctionType() && argIsLValue) {
1676 // Function-to-pointer conversion (C++ 4.3).
1677 SCS.First = ICK_Function_To_Pointer;
1679 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1680 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1681 if (!S.checkAddressOfFunctionIsAvailable(FD))
1684 // An lvalue of function type T can be converted to an rvalue of
1685 // type "pointer to T." The result is a pointer to the
1686 // function. (C++ 4.3p1).
1687 FromType = S.Context.getPointerType(FromType);
1689 // We don't require any conversions for the first step.
1690 SCS.First = ICK_Identity;
1692 SCS.setToType(0, FromType);
1694 // The second conversion can be an integral promotion, floating
1695 // point promotion, integral conversion, floating point conversion,
1696 // floating-integral conversion, pointer conversion,
1697 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1698 // For overloading in C, this can also be a "compatible-type"
1700 bool IncompatibleObjC = false;
1701 ImplicitConversionKind SecondICK = ICK_Identity;
1702 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1703 // The unqualified versions of the types are the same: there's no
1704 // conversion to do.
1705 SCS.Second = ICK_Identity;
1706 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1707 // Integral promotion (C++ 4.5).
1708 SCS.Second = ICK_Integral_Promotion;
1709 FromType = ToType.getUnqualifiedType();
1710 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1711 // Floating point promotion (C++ 4.6).
1712 SCS.Second = ICK_Floating_Promotion;
1713 FromType = ToType.getUnqualifiedType();
1714 } else if (S.IsComplexPromotion(FromType, ToType)) {
1715 // Complex promotion (Clang extension)
1716 SCS.Second = ICK_Complex_Promotion;
1717 FromType = ToType.getUnqualifiedType();
1718 } else if (ToType->isBooleanType() &&
1719 (FromType->isArithmeticType() ||
1720 FromType->isAnyPointerType() ||
1721 FromType->isBlockPointerType() ||
1722 FromType->isMemberPointerType() ||
1723 FromType->isNullPtrType())) {
1724 // Boolean conversions (C++ 4.12).
1725 SCS.Second = ICK_Boolean_Conversion;
1726 FromType = S.Context.BoolTy;
1727 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1728 ToType->isIntegralType(S.Context)) {
1729 // Integral conversions (C++ 4.7).
1730 SCS.Second = ICK_Integral_Conversion;
1731 FromType = ToType.getUnqualifiedType();
1732 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1733 // Complex conversions (C99 6.3.1.6)
1734 SCS.Second = ICK_Complex_Conversion;
1735 FromType = ToType.getUnqualifiedType();
1736 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1737 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1738 // Complex-real conversions (C99 6.3.1.7)
1739 SCS.Second = ICK_Complex_Real;
1740 FromType = ToType.getUnqualifiedType();
1741 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1742 // FIXME: disable conversions between long double and __float128 if
1743 // their representation is different until there is back end support
1744 // We of course allow this conversion if long double is really double.
1745 if (&S.Context.getFloatTypeSemantics(FromType) !=
1746 &S.Context.getFloatTypeSemantics(ToType)) {
1747 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1748 ToType == S.Context.LongDoubleTy) ||
1749 (FromType == S.Context.LongDoubleTy &&
1750 ToType == S.Context.Float128Ty));
1751 if (Float128AndLongDouble &&
1752 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1753 &llvm::APFloat::IEEEdouble()))
1756 // Floating point conversions (C++ 4.8).
1757 SCS.Second = ICK_Floating_Conversion;
1758 FromType = ToType.getUnqualifiedType();
1759 } else if ((FromType->isRealFloatingType() &&
1760 ToType->isIntegralType(S.Context)) ||
1761 (FromType->isIntegralOrUnscopedEnumerationType() &&
1762 ToType->isRealFloatingType())) {
1763 // Floating-integral conversions (C++ 4.9).
1764 SCS.Second = ICK_Floating_Integral;
1765 FromType = ToType.getUnqualifiedType();
1766 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1767 SCS.Second = ICK_Block_Pointer_Conversion;
1768 } else if (AllowObjCWritebackConversion &&
1769 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1770 SCS.Second = ICK_Writeback_Conversion;
1771 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1772 FromType, IncompatibleObjC)) {
1773 // Pointer conversions (C++ 4.10).
1774 SCS.Second = ICK_Pointer_Conversion;
1775 SCS.IncompatibleObjC = IncompatibleObjC;
1776 FromType = FromType.getUnqualifiedType();
1777 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1778 InOverloadResolution, FromType)) {
1779 // Pointer to member conversions (4.11).
1780 SCS.Second = ICK_Pointer_Member;
1781 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1782 SCS.Second = SecondICK;
1783 FromType = ToType.getUnqualifiedType();
1784 } else if (!S.getLangOpts().CPlusPlus &&
1785 S.Context.typesAreCompatible(ToType, FromType)) {
1786 // Compatible conversions (Clang extension for C function overloading)
1787 SCS.Second = ICK_Compatible_Conversion;
1788 FromType = ToType.getUnqualifiedType();
1789 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1790 InOverloadResolution,
1792 SCS.Second = ICK_TransparentUnionConversion;
1794 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1796 // tryAtomicConversion has updated the standard conversion sequence
1799 } else if (ToType->isEventT() &&
1800 From->isIntegerConstantExpr(S.getASTContext()) &&
1801 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1802 SCS.Second = ICK_Zero_Event_Conversion;
1804 } else if (ToType->isQueueT() &&
1805 From->isIntegerConstantExpr(S.getASTContext()) &&
1806 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1807 SCS.Second = ICK_Zero_Queue_Conversion;
1810 // No second conversion required.
1811 SCS.Second = ICK_Identity;
1813 SCS.setToType(1, FromType);
1815 // The third conversion can be a function pointer conversion or a
1816 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1817 bool ObjCLifetimeConversion;
1818 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1819 // Function pointer conversions (removing 'noexcept') including removal of
1820 // 'noreturn' (Clang extension).
1821 SCS.Third = ICK_Function_Conversion;
1822 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1823 ObjCLifetimeConversion)) {
1824 SCS.Third = ICK_Qualification;
1825 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1828 // No conversion required
1829 SCS.Third = ICK_Identity;
1832 // C++ [over.best.ics]p6:
1833 // [...] Any difference in top-level cv-qualification is
1834 // subsumed by the initialization itself and does not constitute
1835 // a conversion. [...]
1836 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1837 QualType CanonTo = S.Context.getCanonicalType(ToType);
1838 if (CanonFrom.getLocalUnqualifiedType()
1839 == CanonTo.getLocalUnqualifiedType() &&
1840 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1842 CanonFrom = CanonTo;
1845 SCS.setToType(2, FromType);
1847 if (CanonFrom == CanonTo)
1850 // If we have not converted the argument type to the parameter type,
1851 // this is a bad conversion sequence, unless we're resolving an overload in C.
1852 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1855 ExprResult ER = ExprResult{From};
1856 Sema::AssignConvertType Conv =
1857 S.CheckSingleAssignmentConstraints(ToType, ER,
1859 /*DiagnoseCFAudited=*/false,
1860 /*ConvertRHS=*/false);
1861 ImplicitConversionKind SecondConv;
1863 case Sema::Compatible:
1864 SecondConv = ICK_C_Only_Conversion;
1866 // For our purposes, discarding qualifiers is just as bad as using an
1867 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1868 // qualifiers, as well.
1869 case Sema::CompatiblePointerDiscardsQualifiers:
1870 case Sema::IncompatiblePointer:
1871 case Sema::IncompatiblePointerSign:
1872 SecondConv = ICK_Incompatible_Pointer_Conversion;
1878 // First can only be an lvalue conversion, so we pretend that this was the
1879 // second conversion. First should already be valid from earlier in the
1881 SCS.Second = SecondConv;
1882 SCS.setToType(1, ToType);
1884 // Third is Identity, because Second should rank us worse than any other
1885 // conversion. This could also be ICK_Qualification, but it's simpler to just
1886 // lump everything in with the second conversion, and we don't gain anything
1887 // from making this ICK_Qualification.
1888 SCS.Third = ICK_Identity;
1889 SCS.setToType(2, ToType);
1894 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1896 bool InOverloadResolution,
1897 StandardConversionSequence &SCS,
1900 const RecordType *UT = ToType->getAsUnionType();
1901 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1903 // The field to initialize within the transparent union.
1904 RecordDecl *UD = UT->getDecl();
1905 // It's compatible if the expression matches any of the fields.
1906 for (const auto *it : UD->fields()) {
1907 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1908 CStyle, /*ObjCWritebackConversion=*/false)) {
1909 ToType = it->getType();
1916 /// IsIntegralPromotion - Determines whether the conversion from the
1917 /// expression From (whose potentially-adjusted type is FromType) to
1918 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1919 /// sets PromotedType to the promoted type.
1920 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1921 const BuiltinType *To = ToType->getAs<BuiltinType>();
1922 // All integers are built-in.
1927 // An rvalue of type char, signed char, unsigned char, short int, or
1928 // unsigned short int can be converted to an rvalue of type int if
1929 // int can represent all the values of the source type; otherwise,
1930 // the source rvalue can be converted to an rvalue of type unsigned
1932 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1933 !FromType->isEnumeralType()) {
1934 if (// We can promote any signed, promotable integer type to an int
1935 (FromType->isSignedIntegerType() ||
1936 // We can promote any unsigned integer type whose size is
1937 // less than int to an int.
1938 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1939 return To->getKind() == BuiltinType::Int;
1942 return To->getKind() == BuiltinType::UInt;
1945 // C++11 [conv.prom]p3:
1946 // A prvalue of an unscoped enumeration type whose underlying type is not
1947 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1948 // following types that can represent all the values of the enumeration
1949 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1950 // unsigned int, long int, unsigned long int, long long int, or unsigned
1951 // long long int. If none of the types in that list can represent all the
1952 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1953 // type can be converted to an rvalue a prvalue of the extended integer type
1954 // with lowest integer conversion rank (4.13) greater than the rank of long
1955 // long in which all the values of the enumeration can be represented. If
1956 // there are two such extended types, the signed one is chosen.
1957 // C++11 [conv.prom]p4:
1958 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1959 // can be converted to a prvalue of its underlying type. Moreover, if
1960 // integral promotion can be applied to its underlying type, a prvalue of an
1961 // unscoped enumeration type whose underlying type is fixed can also be
1962 // converted to a prvalue of the promoted underlying type.
1963 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1964 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1965 // provided for a scoped enumeration.
1966 if (FromEnumType->getDecl()->isScoped())
1969 // We can perform an integral promotion to the underlying type of the enum,
1970 // even if that's not the promoted type. Note that the check for promoting
1971 // the underlying type is based on the type alone, and does not consider
1972 // the bitfield-ness of the actual source expression.
1973 if (FromEnumType->getDecl()->isFixed()) {
1974 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1975 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1976 IsIntegralPromotion(nullptr, Underlying, ToType);
1979 // We have already pre-calculated the promotion type, so this is trivial.
1980 if (ToType->isIntegerType() &&
1981 isCompleteType(From->getLocStart(), FromType))
1982 return Context.hasSameUnqualifiedType(
1983 ToType, FromEnumType->getDecl()->getPromotionType());
1986 // C++0x [conv.prom]p2:
1987 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1988 // to an rvalue a prvalue of the first of the following types that can
1989 // represent all the values of its underlying type: int, unsigned int,
1990 // long int, unsigned long int, long long int, or unsigned long long int.
1991 // If none of the types in that list can represent all the values of its
1992 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1993 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1995 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1996 ToType->isIntegerType()) {
1997 // Determine whether the type we're converting from is signed or
1999 bool FromIsSigned = FromType->isSignedIntegerType();
2000 uint64_t FromSize = Context.getTypeSize(FromType);
2002 // The types we'll try to promote to, in the appropriate
2003 // order. Try each of these types.
2004 QualType PromoteTypes[6] = {
2005 Context.IntTy, Context.UnsignedIntTy,
2006 Context.LongTy, Context.UnsignedLongTy ,
2007 Context.LongLongTy, Context.UnsignedLongLongTy
2009 for (int Idx = 0; Idx < 6; ++Idx) {
2010 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2011 if (FromSize < ToSize ||
2012 (FromSize == ToSize &&
2013 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2014 // We found the type that we can promote to. If this is the
2015 // type we wanted, we have a promotion. Otherwise, no
2017 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2022 // An rvalue for an integral bit-field (9.6) can be converted to an
2023 // rvalue of type int if int can represent all the values of the
2024 // bit-field; otherwise, it can be converted to unsigned int if
2025 // unsigned int can represent all the values of the bit-field. If
2026 // the bit-field is larger yet, no integral promotion applies to
2027 // it. If the bit-field has an enumerated type, it is treated as any
2028 // other value of that type for promotion purposes (C++ 4.5p3).
2029 // FIXME: We should delay checking of bit-fields until we actually perform the
2032 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2033 llvm::APSInt BitWidth;
2034 if (FromType->isIntegralType(Context) &&
2035 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2036 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2037 ToSize = Context.getTypeSize(ToType);
2039 // Are we promoting to an int from a bitfield that fits in an int?
2040 if (BitWidth < ToSize ||
2041 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2042 return To->getKind() == BuiltinType::Int;
2045 // Are we promoting to an unsigned int from an unsigned bitfield
2046 // that fits into an unsigned int?
2047 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2048 return To->getKind() == BuiltinType::UInt;
2056 // An rvalue of type bool can be converted to an rvalue of type int,
2057 // with false becoming zero and true becoming one (C++ 4.5p4).
2058 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2065 /// IsFloatingPointPromotion - Determines whether the conversion from
2066 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2067 /// returns true and sets PromotedType to the promoted type.
2068 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2069 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2070 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2071 /// An rvalue of type float can be converted to an rvalue of type
2072 /// double. (C++ 4.6p1).
2073 if (FromBuiltin->getKind() == BuiltinType::Float &&
2074 ToBuiltin->getKind() == BuiltinType::Double)
2078 // When a float is promoted to double or long double, or a
2079 // double is promoted to long double [...].
2080 if (!getLangOpts().CPlusPlus &&
2081 (FromBuiltin->getKind() == BuiltinType::Float ||
2082 FromBuiltin->getKind() == BuiltinType::Double) &&
2083 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2084 ToBuiltin->getKind() == BuiltinType::Float128))
2087 // Half can be promoted to float.
2088 if (!getLangOpts().NativeHalfType &&
2089 FromBuiltin->getKind() == BuiltinType::Half &&
2090 ToBuiltin->getKind() == BuiltinType::Float)
2097 /// \brief Determine if a conversion is a complex promotion.
2099 /// A complex promotion is defined as a complex -> complex conversion
2100 /// where the conversion between the underlying real types is a
2101 /// floating-point or integral promotion.
2102 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2103 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2107 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2111 return IsFloatingPointPromotion(FromComplex->getElementType(),
2112 ToComplex->getElementType()) ||
2113 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2114 ToComplex->getElementType());
2117 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2118 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2119 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2120 /// if non-empty, will be a pointer to ToType that may or may not have
2121 /// the right set of qualifiers on its pointee.
2124 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2125 QualType ToPointee, QualType ToType,
2126 ASTContext &Context,
2127 bool StripObjCLifetime = false) {
2128 assert((FromPtr->getTypeClass() == Type::Pointer ||
2129 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2130 "Invalid similarly-qualified pointer type");
2132 /// Conversions to 'id' subsume cv-qualifier conversions.
2133 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2134 return ToType.getUnqualifiedType();
2136 QualType CanonFromPointee
2137 = Context.getCanonicalType(FromPtr->getPointeeType());
2138 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2139 Qualifiers Quals = CanonFromPointee.getQualifiers();
2141 if (StripObjCLifetime)
2142 Quals.removeObjCLifetime();
2144 // Exact qualifier match -> return the pointer type we're converting to.
2145 if (CanonToPointee.getLocalQualifiers() == Quals) {
2146 // ToType is exactly what we need. Return it.
2147 if (!ToType.isNull())
2148 return ToType.getUnqualifiedType();
2150 // Build a pointer to ToPointee. It has the right qualifiers
2152 if (isa<ObjCObjectPointerType>(ToType))
2153 return Context.getObjCObjectPointerType(ToPointee);
2154 return Context.getPointerType(ToPointee);
2157 // Just build a canonical type that has the right qualifiers.
2158 QualType QualifiedCanonToPointee
2159 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2161 if (isa<ObjCObjectPointerType>(ToType))
2162 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2163 return Context.getPointerType(QualifiedCanonToPointee);
2166 static bool isNullPointerConstantForConversion(Expr *Expr,
2167 bool InOverloadResolution,
2168 ASTContext &Context) {
2169 // Handle value-dependent integral null pointer constants correctly.
2170 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2171 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2172 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2173 return !InOverloadResolution;
2175 return Expr->isNullPointerConstant(Context,
2176 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2177 : Expr::NPC_ValueDependentIsNull);
2180 /// IsPointerConversion - Determines whether the conversion of the
2181 /// expression From, which has the (possibly adjusted) type FromType,
2182 /// can be converted to the type ToType via a pointer conversion (C++
2183 /// 4.10). If so, returns true and places the converted type (that
2184 /// might differ from ToType in its cv-qualifiers at some level) into
2187 /// This routine also supports conversions to and from block pointers
2188 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2189 /// pointers to interfaces. FIXME: Once we've determined the
2190 /// appropriate overloading rules for Objective-C, we may want to
2191 /// split the Objective-C checks into a different routine; however,
2192 /// GCC seems to consider all of these conversions to be pointer
2193 /// conversions, so for now they live here. IncompatibleObjC will be
2194 /// set if the conversion is an allowed Objective-C conversion that
2195 /// should result in a warning.
2196 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2197 bool InOverloadResolution,
2198 QualType& ConvertedType,
2199 bool &IncompatibleObjC) {
2200 IncompatibleObjC = false;
2201 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2205 // Conversion from a null pointer constant to any Objective-C pointer type.
2206 if (ToType->isObjCObjectPointerType() &&
2207 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2208 ConvertedType = ToType;
2212 // Blocks: Block pointers can be converted to void*.
2213 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2214 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2215 ConvertedType = ToType;
2218 // Blocks: A null pointer constant can be converted to a block
2220 if (ToType->isBlockPointerType() &&
2221 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2222 ConvertedType = ToType;
2226 // If the left-hand-side is nullptr_t, the right side can be a null
2227 // pointer constant.
2228 if (ToType->isNullPtrType() &&
2229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2230 ConvertedType = ToType;
2234 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2238 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2239 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2240 ConvertedType = ToType;
2244 // Beyond this point, both types need to be pointers
2245 // , including objective-c pointers.
2246 QualType ToPointeeType = ToTypePtr->getPointeeType();
2247 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2248 !getLangOpts().ObjCAutoRefCount) {
2249 ConvertedType = BuildSimilarlyQualifiedPointerType(
2250 FromType->getAs<ObjCObjectPointerType>(),
2255 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2259 QualType FromPointeeType = FromTypePtr->getPointeeType();
2261 // If the unqualified pointee types are the same, this can't be a
2262 // pointer conversion, so don't do all of the work below.
2263 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2266 // An rvalue of type "pointer to cv T," where T is an object type,
2267 // can be converted to an rvalue of type "pointer to cv void" (C++
2269 if (FromPointeeType->isIncompleteOrObjectType() &&
2270 ToPointeeType->isVoidType()) {
2271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2274 /*StripObjCLifetime=*/true);
2278 // MSVC allows implicit function to void* type conversion.
2279 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2280 ToPointeeType->isVoidType()) {
2281 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2287 // When we're overloading in C, we allow a special kind of pointer
2288 // conversion for compatible-but-not-identical pointee types.
2289 if (!getLangOpts().CPlusPlus &&
2290 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2291 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2297 // C++ [conv.ptr]p3:
2299 // An rvalue of type "pointer to cv D," where D is a class type,
2300 // can be converted to an rvalue of type "pointer to cv B," where
2301 // B is a base class (clause 10) of D. If B is an inaccessible
2302 // (clause 11) or ambiguous (10.2) base class of D, a program that
2303 // necessitates this conversion is ill-formed. The result of the
2304 // conversion is a pointer to the base class sub-object of the
2305 // derived class object. The null pointer value is converted to
2306 // the null pointer value of the destination type.
2308 // Note that we do not check for ambiguity or inaccessibility
2309 // here. That is handled by CheckPointerConversion.
2310 if (getLangOpts().CPlusPlus &&
2311 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2312 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2313 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2320 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2321 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331 /// \brief Adopt the given qualifiers for the given type.
2332 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2333 Qualifiers TQs = T.getQualifiers();
2335 // Check whether qualifiers already match.
2339 if (Qs.compatiblyIncludes(TQs))
2340 return Context.getQualifiedType(T, Qs);
2342 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2345 /// isObjCPointerConversion - Determines whether this is an
2346 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2347 /// with the same arguments and return values.
2348 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2349 QualType& ConvertedType,
2350 bool &IncompatibleObjC) {
2351 if (!getLangOpts().ObjC1)
2354 // The set of qualifiers on the type we're converting from.
2355 Qualifiers FromQualifiers = FromType.getQualifiers();
2357 // First, we handle all conversions on ObjC object pointer types.
2358 const ObjCObjectPointerType* ToObjCPtr =
2359 ToType->getAs<ObjCObjectPointerType>();
2360 const ObjCObjectPointerType *FromObjCPtr =
2361 FromType->getAs<ObjCObjectPointerType>();
2363 if (ToObjCPtr && FromObjCPtr) {
2364 // If the pointee types are the same (ignoring qualifications),
2365 // then this is not a pointer conversion.
2366 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2367 FromObjCPtr->getPointeeType()))
2370 // Conversion between Objective-C pointers.
2371 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2372 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2373 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2374 if (getLangOpts().CPlusPlus && LHS && RHS &&
2375 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2376 FromObjCPtr->getPointeeType()))
2378 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2379 ToObjCPtr->getPointeeType(),
2381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2385 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2386 // Okay: this is some kind of implicit downcast of Objective-C
2387 // interfaces, which is permitted. However, we're going to
2388 // complain about it.
2389 IncompatibleObjC = true;
2390 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2391 ToObjCPtr->getPointeeType(),
2393 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2397 // Beyond this point, both types need to be C pointers or block pointers.
2398 QualType ToPointeeType;
2399 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2400 ToPointeeType = ToCPtr->getPointeeType();
2401 else if (const BlockPointerType *ToBlockPtr =
2402 ToType->getAs<BlockPointerType>()) {
2403 // Objective C++: We're able to convert from a pointer to any object
2404 // to a block pointer type.
2405 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2409 ToPointeeType = ToBlockPtr->getPointeeType();
2411 else if (FromType->getAs<BlockPointerType>() &&
2412 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2413 // Objective C++: We're able to convert from a block pointer type to a
2414 // pointer to any object.
2415 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2421 QualType FromPointeeType;
2422 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2423 FromPointeeType = FromCPtr->getPointeeType();
2424 else if (const BlockPointerType *FromBlockPtr =
2425 FromType->getAs<BlockPointerType>())
2426 FromPointeeType = FromBlockPtr->getPointeeType();
2430 // If we have pointers to pointers, recursively check whether this
2431 // is an Objective-C conversion.
2432 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2433 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2434 IncompatibleObjC)) {
2435 // We always complain about this conversion.
2436 IncompatibleObjC = true;
2437 ConvertedType = Context.getPointerType(ConvertedType);
2438 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2441 // Allow conversion of pointee being objective-c pointer to another one;
2443 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2444 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2445 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2446 IncompatibleObjC)) {
2448 ConvertedType = Context.getPointerType(ConvertedType);
2449 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2453 // If we have pointers to functions or blocks, check whether the only
2454 // differences in the argument and result types are in Objective-C
2455 // pointer conversions. If so, we permit the conversion (but
2456 // complain about it).
2457 const FunctionProtoType *FromFunctionType
2458 = FromPointeeType->getAs<FunctionProtoType>();
2459 const FunctionProtoType *ToFunctionType
2460 = ToPointeeType->getAs<FunctionProtoType>();
2461 if (FromFunctionType && ToFunctionType) {
2462 // If the function types are exactly the same, this isn't an
2463 // Objective-C pointer conversion.
2464 if (Context.getCanonicalType(FromPointeeType)
2465 == Context.getCanonicalType(ToPointeeType))
2468 // Perform the quick checks that will tell us whether these
2469 // function types are obviously different.
2470 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2471 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2472 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2475 bool HasObjCConversion = false;
2476 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2477 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2478 // Okay, the types match exactly. Nothing to do.
2479 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2480 ToFunctionType->getReturnType(),
2481 ConvertedType, IncompatibleObjC)) {
2482 // Okay, we have an Objective-C pointer conversion.
2483 HasObjCConversion = true;
2485 // Function types are too different. Abort.
2489 // Check argument types.
2490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2491 ArgIdx != NumArgs; ++ArgIdx) {
2492 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2493 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2494 if (Context.getCanonicalType(FromArgType)
2495 == Context.getCanonicalType(ToArgType)) {
2496 // Okay, the types match exactly. Nothing to do.
2497 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2498 ConvertedType, IncompatibleObjC)) {
2499 // Okay, we have an Objective-C pointer conversion.
2500 HasObjCConversion = true;
2502 // Argument types are too different. Abort.
2507 if (HasObjCConversion) {
2508 // We had an Objective-C conversion. Allow this pointer
2509 // conversion, but complain about it.
2510 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2511 IncompatibleObjC = true;
2519 /// \brief Determine whether this is an Objective-C writeback conversion,
2520 /// used for parameter passing when performing automatic reference counting.
2522 /// \param FromType The type we're converting form.
2524 /// \param ToType The type we're converting to.
2526 /// \param ConvertedType The type that will be produced after applying
2527 /// this conversion.
2528 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2529 QualType &ConvertedType) {
2530 if (!getLangOpts().ObjCAutoRefCount ||
2531 Context.hasSameUnqualifiedType(FromType, ToType))
2534 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2536 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2537 ToPointee = ToPointer->getPointeeType();
2541 Qualifiers ToQuals = ToPointee.getQualifiers();
2542 if (!ToPointee->isObjCLifetimeType() ||
2543 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2544 !ToQuals.withoutObjCLifetime().empty())
2547 // Argument must be a pointer to __strong to __weak.
2548 QualType FromPointee;
2549 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2550 FromPointee = FromPointer->getPointeeType();
2554 Qualifiers FromQuals = FromPointee.getQualifiers();
2555 if (!FromPointee->isObjCLifetimeType() ||
2556 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2557 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2560 // Make sure that we have compatible qualifiers.
2561 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2562 if (!ToQuals.compatiblyIncludes(FromQuals))
2565 // Remove qualifiers from the pointee type we're converting from; they
2566 // aren't used in the compatibility check belong, and we'll be adding back
2567 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2568 FromPointee = FromPointee.getUnqualifiedType();
2570 // The unqualified form of the pointee types must be compatible.
2571 ToPointee = ToPointee.getUnqualifiedType();
2572 bool IncompatibleObjC;
2573 if (Context.typesAreCompatible(FromPointee, ToPointee))
2574 FromPointee = ToPointee;
2575 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2579 /// \brief Construct the type we're converting to, which is a pointer to
2580 /// __autoreleasing pointee.
2581 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2582 ConvertedType = Context.getPointerType(FromPointee);
2586 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2587 QualType& ConvertedType) {
2588 QualType ToPointeeType;
2589 if (const BlockPointerType *ToBlockPtr =
2590 ToType->getAs<BlockPointerType>())
2591 ToPointeeType = ToBlockPtr->getPointeeType();
2595 QualType FromPointeeType;
2596 if (const BlockPointerType *FromBlockPtr =
2597 FromType->getAs<BlockPointerType>())
2598 FromPointeeType = FromBlockPtr->getPointeeType();
2601 // We have pointer to blocks, check whether the only
2602 // differences in the argument and result types are in Objective-C
2603 // pointer conversions. If so, we permit the conversion.
2605 const FunctionProtoType *FromFunctionType
2606 = FromPointeeType->getAs<FunctionProtoType>();
2607 const FunctionProtoType *ToFunctionType
2608 = ToPointeeType->getAs<FunctionProtoType>();
2610 if (!FromFunctionType || !ToFunctionType)
2613 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2616 // Perform the quick checks that will tell us whether these
2617 // function types are obviously different.
2618 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2619 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2622 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2623 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2624 if (FromEInfo != ToEInfo)
2627 bool IncompatibleObjC = false;
2628 if (Context.hasSameType(FromFunctionType->getReturnType(),
2629 ToFunctionType->getReturnType())) {
2630 // Okay, the types match exactly. Nothing to do.
2632 QualType RHS = FromFunctionType->getReturnType();
2633 QualType LHS = ToFunctionType->getReturnType();
2634 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2635 !RHS.hasQualifiers() && LHS.hasQualifiers())
2636 LHS = LHS.getUnqualifiedType();
2638 if (Context.hasSameType(RHS,LHS)) {
2640 } else if (isObjCPointerConversion(RHS, LHS,
2641 ConvertedType, IncompatibleObjC)) {
2642 if (IncompatibleObjC)
2644 // Okay, we have an Objective-C pointer conversion.
2650 // Check argument types.
2651 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2652 ArgIdx != NumArgs; ++ArgIdx) {
2653 IncompatibleObjC = false;
2654 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2655 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2656 if (Context.hasSameType(FromArgType, ToArgType)) {
2657 // Okay, the types match exactly. Nothing to do.
2658 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2659 ConvertedType, IncompatibleObjC)) {
2660 if (IncompatibleObjC)
2662 // Okay, we have an Objective-C pointer conversion.
2664 // Argument types are too different. Abort.
2667 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2671 ConvertedType = ToType;
2679 ft_parameter_mismatch,
2681 ft_qualifer_mismatch,
2685 /// Attempts to get the FunctionProtoType from a Type. Handles
2686 /// MemberFunctionPointers properly.
2687 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2688 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2691 if (auto *MPT = FromType->getAs<MemberPointerType>())
2692 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2697 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2698 /// function types. Catches different number of parameter, mismatch in
2699 /// parameter types, and different return types.
2700 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2701 QualType FromType, QualType ToType) {
2702 // If either type is not valid, include no extra info.
2703 if (FromType.isNull() || ToType.isNull()) {
2704 PDiag << ft_default;
2708 // Get the function type from the pointers.
2709 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2710 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2711 *ToMember = ToType->getAs<MemberPointerType>();
2712 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2713 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2714 << QualType(FromMember->getClass(), 0);
2717 FromType = FromMember->getPointeeType();
2718 ToType = ToMember->getPointeeType();
2721 if (FromType->isPointerType())
2722 FromType = FromType->getPointeeType();
2723 if (ToType->isPointerType())
2724 ToType = ToType->getPointeeType();
2726 // Remove references.
2727 FromType = FromType.getNonReferenceType();
2728 ToType = ToType.getNonReferenceType();
2730 // Don't print extra info for non-specialized template functions.
2731 if (FromType->isInstantiationDependentType() &&
2732 !FromType->getAs<TemplateSpecializationType>()) {
2733 PDiag << ft_default;
2737 // No extra info for same types.
2738 if (Context.hasSameType(FromType, ToType)) {
2739 PDiag << ft_default;
2743 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2744 *ToFunction = tryGetFunctionProtoType(ToType);
2746 // Both types need to be function types.
2747 if (!FromFunction || !ToFunction) {
2748 PDiag << ft_default;
2752 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2753 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2754 << FromFunction->getNumParams();
2758 // Handle different parameter types.
2760 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2761 PDiag << ft_parameter_mismatch << ArgPos + 1
2762 << ToFunction->getParamType(ArgPos)
2763 << FromFunction->getParamType(ArgPos);
2767 // Handle different return type.
2768 if (!Context.hasSameType(FromFunction->getReturnType(),
2769 ToFunction->getReturnType())) {
2770 PDiag << ft_return_type << ToFunction->getReturnType()
2771 << FromFunction->getReturnType();
2775 unsigned FromQuals = FromFunction->getTypeQuals(),
2776 ToQuals = ToFunction->getTypeQuals();
2777 if (FromQuals != ToQuals) {
2778 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2782 // Handle exception specification differences on canonical type (in C++17
2784 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2785 ->isNothrow(Context) !=
2786 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2787 ->isNothrow(Context)) {
2788 PDiag << ft_noexcept;
2792 // Unable to find a difference, so add no extra info.
2793 PDiag << ft_default;
2796 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2797 /// for equality of their argument types. Caller has already checked that
2798 /// they have same number of arguments. If the parameters are different,
2799 /// ArgPos will have the parameter index of the first different parameter.
2800 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2801 const FunctionProtoType *NewType,
2803 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2804 N = NewType->param_type_begin(),
2805 E = OldType->param_type_end();
2806 O && (O != E); ++O, ++N) {
2807 if (!Context.hasSameType(O->getUnqualifiedType(),
2808 N->getUnqualifiedType())) {
2810 *ArgPos = O - OldType->param_type_begin();
2817 /// CheckPointerConversion - Check the pointer conversion from the
2818 /// expression From to the type ToType. This routine checks for
2819 /// ambiguous or inaccessible derived-to-base pointer
2820 /// conversions for which IsPointerConversion has already returned
2821 /// true. It returns true and produces a diagnostic if there was an
2822 /// error, or returns false otherwise.
2823 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2825 CXXCastPath& BasePath,
2826 bool IgnoreBaseAccess,
2828 QualType FromType = From->getType();
2829 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2833 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2834 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2835 Expr::NPCK_ZeroExpression) {
2836 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2837 DiagRuntimeBehavior(From->getExprLoc(), From,
2838 PDiag(diag::warn_impcast_bool_to_null_pointer)
2839 << ToType << From->getSourceRange());
2840 else if (!isUnevaluatedContext())
2841 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2842 << ToType << From->getSourceRange();
2844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2845 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2846 QualType FromPointeeType = FromPtrType->getPointeeType(),
2847 ToPointeeType = ToPtrType->getPointeeType();
2849 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2850 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2851 // We must have a derived-to-base conversion. Check an
2852 // ambiguous or inaccessible conversion.
2853 unsigned InaccessibleID = 0;
2854 unsigned AmbigiousID = 0;
2856 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2857 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2859 if (CheckDerivedToBaseConversion(
2860 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2861 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2862 &BasePath, IgnoreBaseAccess))
2865 // The conversion was successful.
2866 Kind = CK_DerivedToBase;
2869 if (Diagnose && !IsCStyleOrFunctionalCast &&
2870 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2871 assert(getLangOpts().MSVCCompat &&
2872 "this should only be possible with MSVCCompat!");
2873 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2874 << From->getSourceRange();
2877 } else if (const ObjCObjectPointerType *ToPtrType =
2878 ToType->getAs<ObjCObjectPointerType>()) {
2879 if (const ObjCObjectPointerType *FromPtrType =
2880 FromType->getAs<ObjCObjectPointerType>()) {
2881 // Objective-C++ conversions are always okay.
2882 // FIXME: We should have a different class of conversions for the
2883 // Objective-C++ implicit conversions.
2884 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2886 } else if (FromType->isBlockPointerType()) {
2887 Kind = CK_BlockPointerToObjCPointerCast;
2889 Kind = CK_CPointerToObjCPointerCast;
2891 } else if (ToType->isBlockPointerType()) {
2892 if (!FromType->isBlockPointerType())
2893 Kind = CK_AnyPointerToBlockPointerCast;
2896 // We shouldn't fall into this case unless it's valid for other
2898 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2899 Kind = CK_NullToPointer;
2904 /// IsMemberPointerConversion - Determines whether the conversion of the
2905 /// expression From, which has the (possibly adjusted) type FromType, can be
2906 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2907 /// If so, returns true and places the converted type (that might differ from
2908 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2909 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2911 bool InOverloadResolution,
2912 QualType &ConvertedType) {
2913 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2917 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2918 if (From->isNullPointerConstant(Context,
2919 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2920 : Expr::NPC_ValueDependentIsNull)) {
2921 ConvertedType = ToType;
2925 // Otherwise, both types have to be member pointers.
2926 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2930 // A pointer to member of B can be converted to a pointer to member of D,
2931 // where D is derived from B (C++ 4.11p2).
2932 QualType FromClass(FromTypePtr->getClass(), 0);
2933 QualType ToClass(ToTypePtr->getClass(), 0);
2935 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2936 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2937 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2938 ToClass.getTypePtr());
2945 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2946 /// expression From to the type ToType. This routine checks for ambiguous or
2947 /// virtual or inaccessible base-to-derived member pointer conversions
2948 /// for which IsMemberPointerConversion has already returned true. It returns
2949 /// true and produces a diagnostic if there was an error, or returns false
2951 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2953 CXXCastPath &BasePath,
2954 bool IgnoreBaseAccess) {
2955 QualType FromType = From->getType();
2956 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2958 // This must be a null pointer to member pointer conversion
2959 assert(From->isNullPointerConstant(Context,
2960 Expr::NPC_ValueDependentIsNull) &&
2961 "Expr must be null pointer constant!");
2962 Kind = CK_NullToMemberPointer;
2966 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2967 assert(ToPtrType && "No member pointer cast has a target type "
2968 "that is not a member pointer.");
2970 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2971 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2973 // FIXME: What about dependent types?
2974 assert(FromClass->isRecordType() && "Pointer into non-class.");
2975 assert(ToClass->isRecordType() && "Pointer into non-class.");
2977 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2978 /*DetectVirtual=*/true);
2979 bool DerivationOkay =
2980 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2981 assert(DerivationOkay &&
2982 "Should not have been called if derivation isn't OK.");
2983 (void)DerivationOkay;
2985 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2986 getUnqualifiedType())) {
2987 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2988 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2989 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2993 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2994 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2995 << FromClass << ToClass << QualType(VBase, 0)
2996 << From->getSourceRange();
3000 if (!IgnoreBaseAccess)
3001 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3003 diag::err_downcast_from_inaccessible_base);
3005 // Must be a base to derived member conversion.
3006 BuildBasePathArray(Paths, BasePath);
3007 Kind = CK_BaseToDerivedMemberPointer;
3011 /// Determine whether the lifetime conversion between the two given
3012 /// qualifiers sets is nontrivial.
3013 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3014 Qualifiers ToQuals) {
3015 // Converting anything to const __unsafe_unretained is trivial.
3016 if (ToQuals.hasConst() &&
3017 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3023 /// IsQualificationConversion - Determines whether the conversion from
3024 /// an rvalue of type FromType to ToType is a qualification conversion
3027 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3028 /// when the qualification conversion involves a change in the Objective-C
3029 /// object lifetime.
3031 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3032 bool CStyle, bool &ObjCLifetimeConversion) {
3033 FromType = Context.getCanonicalType(FromType);
3034 ToType = Context.getCanonicalType(ToType);
3035 ObjCLifetimeConversion = false;
3037 // If FromType and ToType are the same type, this is not a
3038 // qualification conversion.
3039 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3043 // A conversion can add cv-qualifiers at levels other than the first
3044 // in multi-level pointers, subject to the following rules: [...]
3045 bool PreviousToQualsIncludeConst = true;
3046 bool UnwrappedAnyPointer = false;
3047 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3048 // Within each iteration of the loop, we check the qualifiers to
3049 // determine if this still looks like a qualification
3050 // conversion. Then, if all is well, we unwrap one more level of
3051 // pointers or pointers-to-members and do it all again
3052 // until there are no more pointers or pointers-to-members left to
3054 UnwrappedAnyPointer = true;
3056 Qualifiers FromQuals = FromType.getQualifiers();
3057 Qualifiers ToQuals = ToType.getQualifiers();
3059 // Ignore __unaligned qualifier if this type is void.
3060 if (ToType.getUnqualifiedType()->isVoidType())
3061 FromQuals.removeUnaligned();
3064 // Check Objective-C lifetime conversions.
3065 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3066 UnwrappedAnyPointer) {
3067 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3068 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3069 ObjCLifetimeConversion = true;
3070 FromQuals.removeObjCLifetime();
3071 ToQuals.removeObjCLifetime();
3073 // Qualification conversions cannot cast between different
3074 // Objective-C lifetime qualifiers.
3079 // Allow addition/removal of GC attributes but not changing GC attributes.
3080 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3081 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3082 FromQuals.removeObjCGCAttr();
3083 ToQuals.removeObjCGCAttr();
3086 // -- for every j > 0, if const is in cv 1,j then const is in cv
3087 // 2,j, and similarly for volatile.
3088 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3091 // -- if the cv 1,j and cv 2,j are different, then const is in
3092 // every cv for 0 < k < j.
3093 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3094 && !PreviousToQualsIncludeConst)
3097 // Keep track of whether all prior cv-qualifiers in the "to" type
3099 PreviousToQualsIncludeConst
3100 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3103 // We are left with FromType and ToType being the pointee types
3104 // after unwrapping the original FromType and ToType the same number
3105 // of types. If we unwrapped any pointers, and if FromType and
3106 // ToType have the same unqualified type (since we checked
3107 // qualifiers above), then this is a qualification conversion.
3108 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3111 /// \brief - Determine whether this is a conversion from a scalar type to an
3114 /// If successful, updates \c SCS's second and third steps in the conversion
3115 /// sequence to finish the conversion.
3116 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3117 bool InOverloadResolution,
3118 StandardConversionSequence &SCS,
3120 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3124 StandardConversionSequence InnerSCS;
3125 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3126 InOverloadResolution, InnerSCS,
3127 CStyle, /*AllowObjCWritebackConversion=*/false))
3130 SCS.Second = InnerSCS.Second;
3131 SCS.setToType(1, InnerSCS.getToType(1));
3132 SCS.Third = InnerSCS.Third;
3133 SCS.QualificationIncludesObjCLifetime
3134 = InnerSCS.QualificationIncludesObjCLifetime;
3135 SCS.setToType(2, InnerSCS.getToType(2));
3139 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3140 CXXConstructorDecl *Constructor,
3142 const FunctionProtoType *CtorType =
3143 Constructor->getType()->getAs<FunctionProtoType>();
3144 if (CtorType->getNumParams() > 0) {
3145 QualType FirstArg = CtorType->getParamType(0);
3146 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3152 static OverloadingResult
3153 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3155 UserDefinedConversionSequence &User,
3156 OverloadCandidateSet &CandidateSet,
3157 bool AllowExplicit) {
3158 for (auto *D : S.LookupConstructors(To)) {
3159 auto Info = getConstructorInfo(D);
3163 bool Usable = !Info.Constructor->isInvalidDecl() &&
3164 S.isInitListConstructor(Info.Constructor) &&
3165 (AllowExplicit || !Info.Constructor->isExplicit());
3167 // If the first argument is (a reference to) the target type,
3168 // suppress conversions.
3169 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3170 S.Context, Info.Constructor, ToType);
3171 if (Info.ConstructorTmpl)
3172 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3173 /*ExplicitArgs*/ nullptr, From,
3174 CandidateSet, SuppressUserConversions);
3176 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3177 CandidateSet, SuppressUserConversions);
3181 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3183 OverloadCandidateSet::iterator Best;
3184 switch (auto Result =
3185 CandidateSet.BestViableFunction(S, From->getLocStart(),
3189 // Record the standard conversion we used and the conversion function.
3190 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3191 QualType ThisType = Constructor->getThisType(S.Context);
3192 // Initializer lists don't have conversions as such.
3193 User.Before.setAsIdentityConversion();
3194 User.HadMultipleCandidates = HadMultipleCandidates;
3195 User.ConversionFunction = Constructor;
3196 User.FoundConversionFunction = Best->FoundDecl;
3197 User.After.setAsIdentityConversion();
3198 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3199 User.After.setAllToTypes(ToType);
3203 case OR_No_Viable_Function:
3204 return OR_No_Viable_Function;
3206 return OR_Ambiguous;
3209 llvm_unreachable("Invalid OverloadResult!");
3212 /// Determines whether there is a user-defined conversion sequence
3213 /// (C++ [over.ics.user]) that converts expression From to the type
3214 /// ToType. If such a conversion exists, User will contain the
3215 /// user-defined conversion sequence that performs such a conversion
3216 /// and this routine will return true. Otherwise, this routine returns
3217 /// false and User is unspecified.
3219 /// \param AllowExplicit true if the conversion should consider C++0x
3220 /// "explicit" conversion functions as well as non-explicit conversion
3221 /// functions (C++0x [class.conv.fct]p2).
3223 /// \param AllowObjCConversionOnExplicit true if the conversion should
3224 /// allow an extra Objective-C pointer conversion on uses of explicit
3225 /// constructors. Requires \c AllowExplicit to also be set.
3226 static OverloadingResult
3227 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3228 UserDefinedConversionSequence &User,
3229 OverloadCandidateSet &CandidateSet,
3231 bool AllowObjCConversionOnExplicit) {
3232 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3234 // Whether we will only visit constructors.
3235 bool ConstructorsOnly = false;
3237 // If the type we are conversion to is a class type, enumerate its
3239 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3240 // C++ [over.match.ctor]p1:
3241 // When objects of class type are direct-initialized (8.5), or
3242 // copy-initialized from an expression of the same or a
3243 // derived class type (8.5), overload resolution selects the
3244 // constructor. [...] For copy-initialization, the candidate
3245 // functions are all the converting constructors (12.3.1) of
3246 // that class. The argument list is the expression-list within
3247 // the parentheses of the initializer.
3248 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3249 (From->getType()->getAs<RecordType>() &&
3250 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3251 ConstructorsOnly = true;
3253 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3254 // We're not going to find any constructors.
3255 } else if (CXXRecordDecl *ToRecordDecl
3256 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3258 Expr **Args = &From;
3259 unsigned NumArgs = 1;
3260 bool ListInitializing = false;
3261 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3262 // But first, see if there is an init-list-constructor that will work.
3263 OverloadingResult Result = IsInitializerListConstructorConversion(
3264 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3265 if (Result != OR_No_Viable_Function)
3268 CandidateSet.clear();
3270 // If we're list-initializing, we pass the individual elements as
3271 // arguments, not the entire list.
3272 Args = InitList->getInits();
3273 NumArgs = InitList->getNumInits();
3274 ListInitializing = true;
3277 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3278 auto Info = getConstructorInfo(D);
3282 bool Usable = !Info.Constructor->isInvalidDecl();
3283 if (ListInitializing)
3284 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3287 Info.Constructor->isConvertingConstructor(AllowExplicit);
3289 bool SuppressUserConversions = !ConstructorsOnly;
3290 if (SuppressUserConversions && ListInitializing) {
3291 SuppressUserConversions = false;
3293 // If the first argument is (a reference to) the target type,
3294 // suppress conversions.
3295 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3296 S.Context, Info.Constructor, ToType);
3299 if (Info.ConstructorTmpl)
3300 S.AddTemplateOverloadCandidate(
3301 Info.ConstructorTmpl, Info.FoundDecl,
3302 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3303 CandidateSet, SuppressUserConversions);
3305 // Allow one user-defined conversion when user specifies a
3306 // From->ToType conversion via an static cast (c-style, etc).
3307 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3308 llvm::makeArrayRef(Args, NumArgs),
3309 CandidateSet, SuppressUserConversions);
3315 // Enumerate conversion functions, if we're allowed to.
3316 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3317 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3318 // No conversion functions from incomplete types.
3319 } else if (const RecordType *FromRecordType
3320 = From->getType()->getAs<RecordType>()) {
3321 if (CXXRecordDecl *FromRecordDecl
3322 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3323 // Add all of the conversion functions as candidates.
3324 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3325 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3326 DeclAccessPair FoundDecl = I.getPair();
3327 NamedDecl *D = FoundDecl.getDecl();
3328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3329 if (isa<UsingShadowDecl>(D))
3330 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3332 CXXConversionDecl *Conv;
3333 FunctionTemplateDecl *ConvTemplate;
3334 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3335 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3337 Conv = cast<CXXConversionDecl>(D);
3339 if (AllowExplicit || !Conv->isExplicit()) {
3341 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3342 ActingContext, From, ToType,
3344 AllowObjCConversionOnExplicit);
3346 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3347 From, ToType, CandidateSet,
3348 AllowObjCConversionOnExplicit);
3354 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3356 OverloadCandidateSet::iterator Best;
3357 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3361 // Record the standard conversion we used and the conversion function.
3362 if (CXXConstructorDecl *Constructor
3363 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3364 // C++ [over.ics.user]p1:
3365 // If the user-defined conversion is specified by a
3366 // constructor (12.3.1), the initial standard conversion
3367 // sequence converts the source type to the type required by
3368 // the argument of the constructor.
3370 QualType ThisType = Constructor->getThisType(S.Context);
3371 if (isa<InitListExpr>(From)) {
3372 // Initializer lists don't have conversions as such.
3373 User.Before.setAsIdentityConversion();
3375 if (Best->Conversions[0].isEllipsis())
3376 User.EllipsisConversion = true;
3378 User.Before = Best->Conversions[0].Standard;
3379 User.EllipsisConversion = false;
3382 User.HadMultipleCandidates = HadMultipleCandidates;
3383 User.ConversionFunction = Constructor;
3384 User.FoundConversionFunction = Best->FoundDecl;
3385 User.After.setAsIdentityConversion();
3386 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3387 User.After.setAllToTypes(ToType);
3390 if (CXXConversionDecl *Conversion
3391 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3392 // C++ [over.ics.user]p1:
3394 // [...] If the user-defined conversion is specified by a
3395 // conversion function (12.3.2), the initial standard
3396 // conversion sequence converts the source type to the
3397 // implicit object parameter of the conversion function.
3398 User.Before = Best->Conversions[0].Standard;
3399 User.HadMultipleCandidates = HadMultipleCandidates;
3400 User.ConversionFunction = Conversion;
3401 User.FoundConversionFunction = Best->FoundDecl;
3402 User.EllipsisConversion = false;
3404 // C++ [over.ics.user]p2:
3405 // The second standard conversion sequence converts the
3406 // result of the user-defined conversion to the target type
3407 // for the sequence. Since an implicit conversion sequence
3408 // is an initialization, the special rules for
3409 // initialization by user-defined conversion apply when
3410 // selecting the best user-defined conversion for a
3411 // user-defined conversion sequence (see 13.3.3 and
3413 User.After = Best->FinalConversion;
3416 llvm_unreachable("Not a constructor or conversion function?");
3418 case OR_No_Viable_Function:
3419 return OR_No_Viable_Function;
3422 return OR_Ambiguous;
3425 llvm_unreachable("Invalid OverloadResult!");
3429 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3430 ImplicitConversionSequence ICS;
3431 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3432 OverloadCandidateSet::CSK_Normal);
3433 OverloadingResult OvResult =
3434 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3435 CandidateSet, false, false);
3436 if (OvResult == OR_Ambiguous)
3437 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3438 << From->getType() << ToType << From->getSourceRange();
3439 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3440 if (!RequireCompleteType(From->getLocStart(), ToType,
3441 diag::err_typecheck_nonviable_condition_incomplete,
3442 From->getType(), From->getSourceRange()))
3443 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3444 << false << From->getType() << From->getSourceRange() << ToType;
3447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3451 /// \brief Compare the user-defined conversion functions or constructors
3452 /// of two user-defined conversion sequences to determine whether any ordering
3454 static ImplicitConversionSequence::CompareKind
3455 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3456 FunctionDecl *Function2) {
3457 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3458 return ImplicitConversionSequence::Indistinguishable;
3461 // If both conversion functions are implicitly-declared conversions from
3462 // a lambda closure type to a function pointer and a block pointer,
3463 // respectively, always prefer the conversion to a function pointer,
3464 // because the function pointer is more lightweight and is more likely
3465 // to keep code working.
3466 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3468 return ImplicitConversionSequence::Indistinguishable;
3470 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3472 return ImplicitConversionSequence::Indistinguishable;
3474 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3475 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3476 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3477 if (Block1 != Block2)
3478 return Block1 ? ImplicitConversionSequence::Worse
3479 : ImplicitConversionSequence::Better;
3482 return ImplicitConversionSequence::Indistinguishable;
3485 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3486 const ImplicitConversionSequence &ICS) {
3487 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3488 (ICS.isUserDefined() &&
3489 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3492 /// CompareImplicitConversionSequences - Compare two implicit
3493 /// conversion sequences to determine whether one is better than the
3494 /// other or if they are indistinguishable (C++ 13.3.3.2).
3495 static ImplicitConversionSequence::CompareKind
3496 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3497 const ImplicitConversionSequence& ICS1,
3498 const ImplicitConversionSequence& ICS2)
3500 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3501 // conversion sequences (as defined in 13.3.3.1)
3502 // -- a standard conversion sequence (13.3.3.1.1) is a better
3503 // conversion sequence than a user-defined conversion sequence or
3504 // an ellipsis conversion sequence, and
3505 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3506 // conversion sequence than an ellipsis conversion sequence
3509 // C++0x [over.best.ics]p10:
3510 // For the purpose of ranking implicit conversion sequences as
3511 // described in 13.3.3.2, the ambiguous conversion sequence is
3512 // treated as a user-defined sequence that is indistinguishable
3513 // from any other user-defined conversion sequence.
3515 // String literal to 'char *' conversion has been deprecated in C++03. It has
3516 // been removed from C++11. We still accept this conversion, if it happens at
3517 // the best viable function. Otherwise, this conversion is considered worse
3518 // than ellipsis conversion. Consider this as an extension; this is not in the
3519 // standard. For example:
3521 // int &f(...); // #1
3522 // void f(char*); // #2
3523 // void g() { int &r = f("foo"); }
3525 // In C++03, we pick #2 as the best viable function.
3526 // In C++11, we pick #1 as the best viable function, because ellipsis
3527 // conversion is better than string-literal to char* conversion (since there
3528 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3529 // convert arguments, #2 would be the best viable function in C++11.
3530 // If the best viable function has this conversion, a warning will be issued
3531 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3533 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3535 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3536 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3537 ? ImplicitConversionSequence::Worse
3538 : ImplicitConversionSequence::Better;
3540 if (ICS1.getKindRank() < ICS2.getKindRank())
3541 return ImplicitConversionSequence::Better;
3542 if (ICS2.getKindRank() < ICS1.getKindRank())
3543 return ImplicitConversionSequence::Worse;
3545 // The following checks require both conversion sequences to be of
3547 if (ICS1.getKind() != ICS2.getKind())
3548 return ImplicitConversionSequence::Indistinguishable;
3550 ImplicitConversionSequence::CompareKind Result =
3551 ImplicitConversionSequence::Indistinguishable;
3553 // Two implicit conversion sequences of the same form are
3554 // indistinguishable conversion sequences unless one of the
3555 // following rules apply: (C++ 13.3.3.2p3):
3557 // List-initialization sequence L1 is a better conversion sequence than
3558 // list-initialization sequence L2 if:
3559 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3561 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3562 // and N1 is smaller than N2.,
3563 // even if one of the other rules in this paragraph would otherwise apply.
3564 if (!ICS1.isBad()) {
3565 if (ICS1.isStdInitializerListElement() &&
3566 !ICS2.isStdInitializerListElement())
3567 return ImplicitConversionSequence::Better;
3568 if (!ICS1.isStdInitializerListElement() &&
3569 ICS2.isStdInitializerListElement())
3570 return ImplicitConversionSequence::Worse;
3573 if (ICS1.isStandard())
3574 // Standard conversion sequence S1 is a better conversion sequence than
3575 // standard conversion sequence S2 if [...]
3576 Result = CompareStandardConversionSequences(S, Loc,
3577 ICS1.Standard, ICS2.Standard);
3578 else if (ICS1.isUserDefined()) {
3579 // User-defined conversion sequence U1 is a better conversion
3580 // sequence than another user-defined conversion sequence U2 if
3581 // they contain the same user-defined conversion function or
3582 // constructor and if the second standard conversion sequence of
3583 // U1 is better than the second standard conversion sequence of
3584 // U2 (C++ 13.3.3.2p3).
3585 if (ICS1.UserDefined.ConversionFunction ==
3586 ICS2.UserDefined.ConversionFunction)
3587 Result = CompareStandardConversionSequences(S, Loc,
3588 ICS1.UserDefined.After,
3589 ICS2.UserDefined.After);
3591 Result = compareConversionFunctions(S,
3592 ICS1.UserDefined.ConversionFunction,
3593 ICS2.UserDefined.ConversionFunction);
3599 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3600 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3602 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3603 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3606 return Context.hasSameUnqualifiedType(T1, T2);
3609 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3610 // determine if one is a proper subset of the other.
3611 static ImplicitConversionSequence::CompareKind
3612 compareStandardConversionSubsets(ASTContext &Context,
3613 const StandardConversionSequence& SCS1,
3614 const StandardConversionSequence& SCS2) {
3615 ImplicitConversionSequence::CompareKind Result
3616 = ImplicitConversionSequence::Indistinguishable;
3618 // the identity conversion sequence is considered to be a subsequence of
3619 // any non-identity conversion sequence
3620 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3621 return ImplicitConversionSequence::Better;
3622 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3623 return ImplicitConversionSequence::Worse;
3625 if (SCS1.Second != SCS2.Second) {
3626 if (SCS1.Second == ICK_Identity)
3627 Result = ImplicitConversionSequence::Better;
3628 else if (SCS2.Second == ICK_Identity)
3629 Result = ImplicitConversionSequence::Worse;
3631 return ImplicitConversionSequence::Indistinguishable;
3632 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3633 return ImplicitConversionSequence::Indistinguishable;
3635 if (SCS1.Third == SCS2.Third) {
3636 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3637 : ImplicitConversionSequence::Indistinguishable;
3640 if (SCS1.Third == ICK_Identity)
3641 return Result == ImplicitConversionSequence::Worse
3642 ? ImplicitConversionSequence::Indistinguishable
3643 : ImplicitConversionSequence::Better;
3645 if (SCS2.Third == ICK_Identity)
3646 return Result == ImplicitConversionSequence::Better
3647 ? ImplicitConversionSequence::Indistinguishable
3648 : ImplicitConversionSequence::Worse;
3650 return ImplicitConversionSequence::Indistinguishable;
3653 /// \brief Determine whether one of the given reference bindings is better
3654 /// than the other based on what kind of bindings they are.
3656 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3657 const StandardConversionSequence &SCS2) {
3658 // C++0x [over.ics.rank]p3b4:
3659 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3660 // implicit object parameter of a non-static member function declared
3661 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3662 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3663 // lvalue reference to a function lvalue and S2 binds an rvalue
3666 // FIXME: Rvalue references. We're going rogue with the above edits,
3667 // because the semantics in the current C++0x working paper (N3225 at the
3668 // time of this writing) break the standard definition of std::forward
3669 // and std::reference_wrapper when dealing with references to functions.
3670 // Proposed wording changes submitted to CWG for consideration.
3671 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3672 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3675 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3676 SCS2.IsLvalueReference) ||
3677 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3678 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3681 /// CompareStandardConversionSequences - Compare two standard
3682 /// conversion sequences to determine whether one is better than the
3683 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3684 static ImplicitConversionSequence::CompareKind
3685 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3686 const StandardConversionSequence& SCS1,
3687 const StandardConversionSequence& SCS2)
3689 // Standard conversion sequence S1 is a better conversion sequence
3690 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3692 // -- S1 is a proper subsequence of S2 (comparing the conversion
3693 // sequences in the canonical form defined by 13.3.3.1.1,
3694 // excluding any Lvalue Transformation; the identity conversion
3695 // sequence is considered to be a subsequence of any
3696 // non-identity conversion sequence) or, if not that,
3697 if (ImplicitConversionSequence::CompareKind CK
3698 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3701 // -- the rank of S1 is better than the rank of S2 (by the rules
3702 // defined below), or, if not that,
3703 ImplicitConversionRank Rank1 = SCS1.getRank();
3704 ImplicitConversionRank Rank2 = SCS2.getRank();
3706 return ImplicitConversionSequence::Better;
3707 else if (Rank2 < Rank1)
3708 return ImplicitConversionSequence::Worse;
3710 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3711 // are indistinguishable unless one of the following rules
3714 // A conversion that is not a conversion of a pointer, or
3715 // pointer to member, to bool is better than another conversion
3716 // that is such a conversion.
3717 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3718 return SCS2.isPointerConversionToBool()
3719 ? ImplicitConversionSequence::Better
3720 : ImplicitConversionSequence::Worse;
3722 // C++ [over.ics.rank]p4b2:
3724 // If class B is derived directly or indirectly from class A,
3725 // conversion of B* to A* is better than conversion of B* to
3726 // void*, and conversion of A* to void* is better than conversion
3728 bool SCS1ConvertsToVoid
3729 = SCS1.isPointerConversionToVoidPointer(S.Context);
3730 bool SCS2ConvertsToVoid
3731 = SCS2.isPointerConversionToVoidPointer(S.Context);
3732 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3733 // Exactly one of the conversion sequences is a conversion to
3734 // a void pointer; it's the worse conversion.
3735 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3736 : ImplicitConversionSequence::Worse;
3737 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3738 // Neither conversion sequence converts to a void pointer; compare
3739 // their derived-to-base conversions.
3740 if (ImplicitConversionSequence::CompareKind DerivedCK
3741 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3743 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3744 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3745 // Both conversion sequences are conversions to void
3746 // pointers. Compare the source types to determine if there's an
3747 // inheritance relationship in their sources.
3748 QualType FromType1 = SCS1.getFromType();
3749 QualType FromType2 = SCS2.getFromType();
3751 // Adjust the types we're converting from via the array-to-pointer
3752 // conversion, if we need to.
3753 if (SCS1.First == ICK_Array_To_Pointer)
3754 FromType1 = S.Context.getArrayDecayedType(FromType1);
3755 if (SCS2.First == ICK_Array_To_Pointer)
3756 FromType2 = S.Context.getArrayDecayedType(FromType2);
3758 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3759 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3762 return ImplicitConversionSequence::Better;
3763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3764 return ImplicitConversionSequence::Worse;
3766 // Objective-C++: If one interface is more specific than the
3767 // other, it is the better one.
3768 const ObjCObjectPointerType* FromObjCPtr1
3769 = FromType1->getAs<ObjCObjectPointerType>();
3770 const ObjCObjectPointerType* FromObjCPtr2
3771 = FromType2->getAs<ObjCObjectPointerType>();
3772 if (FromObjCPtr1 && FromObjCPtr2) {
3773 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3775 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3777 if (AssignLeft != AssignRight) {
3778 return AssignLeft? ImplicitConversionSequence::Better
3779 : ImplicitConversionSequence::Worse;
3784 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3786 if (ImplicitConversionSequence::CompareKind QualCK
3787 = CompareQualificationConversions(S, SCS1, SCS2))
3790 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3791 // Check for a better reference binding based on the kind of bindings.
3792 if (isBetterReferenceBindingKind(SCS1, SCS2))
3793 return ImplicitConversionSequence::Better;
3794 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3795 return ImplicitConversionSequence::Worse;
3797 // C++ [over.ics.rank]p3b4:
3798 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3799 // which the references refer are the same type except for
3800 // top-level cv-qualifiers, and the type to which the reference
3801 // initialized by S2 refers is more cv-qualified than the type
3802 // to which the reference initialized by S1 refers.
3803 QualType T1 = SCS1.getToType(2);
3804 QualType T2 = SCS2.getToType(2);
3805 T1 = S.Context.getCanonicalType(T1);
3806 T2 = S.Context.getCanonicalType(T2);
3807 Qualifiers T1Quals, T2Quals;
3808 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3809 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3810 if (UnqualT1 == UnqualT2) {
3811 // Objective-C++ ARC: If the references refer to objects with different
3812 // lifetimes, prefer bindings that don't change lifetime.
3813 if (SCS1.ObjCLifetimeConversionBinding !=
3814 SCS2.ObjCLifetimeConversionBinding) {
3815 return SCS1.ObjCLifetimeConversionBinding
3816 ? ImplicitConversionSequence::Worse
3817 : ImplicitConversionSequence::Better;
3820 // If the type is an array type, promote the element qualifiers to the
3821 // type for comparison.
3822 if (isa<ArrayType>(T1) && T1Quals)
3823 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3824 if (isa<ArrayType>(T2) && T2Quals)
3825 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3826 if (T2.isMoreQualifiedThan(T1))
3827 return ImplicitConversionSequence::Better;
3828 else if (T1.isMoreQualifiedThan(T2))
3829 return ImplicitConversionSequence::Worse;
3833 // In Microsoft mode, prefer an integral conversion to a
3834 // floating-to-integral conversion if the integral conversion
3835 // is between types of the same size.
3843 // Here, MSVC will call f(int) instead of generating a compile error
3844 // as clang will do in standard mode.
3845 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3846 SCS2.Second == ICK_Floating_Integral &&
3847 S.Context.getTypeSize(SCS1.getFromType()) ==
3848 S.Context.getTypeSize(SCS1.getToType(2)))
3849 return ImplicitConversionSequence::Better;
3851 return ImplicitConversionSequence::Indistinguishable;
3854 /// CompareQualificationConversions - Compares two standard conversion
3855 /// sequences to determine whether they can be ranked based on their
3856 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3857 static ImplicitConversionSequence::CompareKind
3858 CompareQualificationConversions(Sema &S,
3859 const StandardConversionSequence& SCS1,
3860 const StandardConversionSequence& SCS2) {
3862 // -- S1 and S2 differ only in their qualification conversion and
3863 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3864 // cv-qualification signature of type T1 is a proper subset of
3865 // the cv-qualification signature of type T2, and S1 is not the
3866 // deprecated string literal array-to-pointer conversion (4.2).
3867 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3868 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3869 return ImplicitConversionSequence::Indistinguishable;
3871 // FIXME: the example in the standard doesn't use a qualification
3873 QualType T1 = SCS1.getToType(2);
3874 QualType T2 = SCS2.getToType(2);
3875 T1 = S.Context.getCanonicalType(T1);
3876 T2 = S.Context.getCanonicalType(T2);
3877 Qualifiers T1Quals, T2Quals;
3878 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3879 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3881 // If the types are the same, we won't learn anything by unwrapped
3883 if (UnqualT1 == UnqualT2)
3884 return ImplicitConversionSequence::Indistinguishable;
3886 // If the type is an array type, promote the element qualifiers to the type
3888 if (isa<ArrayType>(T1) && T1Quals)
3889 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3890 if (isa<ArrayType>(T2) && T2Quals)
3891 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3893 ImplicitConversionSequence::CompareKind Result
3894 = ImplicitConversionSequence::Indistinguishable;
3896 // Objective-C++ ARC:
3897 // Prefer qualification conversions not involving a change in lifetime
3898 // to qualification conversions that do not change lifetime.
3899 if (SCS1.QualificationIncludesObjCLifetime !=
3900 SCS2.QualificationIncludesObjCLifetime) {
3901 Result = SCS1.QualificationIncludesObjCLifetime
3902 ? ImplicitConversionSequence::Worse
3903 : ImplicitConversionSequence::Better;
3906 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3907 // Within each iteration of the loop, we check the qualifiers to
3908 // determine if this still looks like a qualification
3909 // conversion. Then, if all is well, we unwrap one more level of
3910 // pointers or pointers-to-members and do it all again
3911 // until there are no more pointers or pointers-to-members left
3912 // to unwrap. This essentially mimics what
3913 // IsQualificationConversion does, but here we're checking for a
3914 // strict subset of qualifiers.
3915 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3916 // The qualifiers are the same, so this doesn't tell us anything
3917 // about how the sequences rank.
3919 else if (T2.isMoreQualifiedThan(T1)) {
3920 // T1 has fewer qualifiers, so it could be the better sequence.
3921 if (Result == ImplicitConversionSequence::Worse)
3922 // Neither has qualifiers that are a subset of the other's
3924 return ImplicitConversionSequence::Indistinguishable;
3926 Result = ImplicitConversionSequence::Better;
3927 } else if (T1.isMoreQualifiedThan(T2)) {
3928 // T2 has fewer qualifiers, so it could be the better sequence.
3929 if (Result == ImplicitConversionSequence::Better)
3930 // Neither has qualifiers that are a subset of the other's
3932 return ImplicitConversionSequence::Indistinguishable;
3934 Result = ImplicitConversionSequence::Worse;
3936 // Qualifiers are disjoint.
3937 return ImplicitConversionSequence::Indistinguishable;
3940 // If the types after this point are equivalent, we're done.
3941 if (S.Context.hasSameUnqualifiedType(T1, T2))
3945 // Check that the winning standard conversion sequence isn't using
3946 // the deprecated string literal array to pointer conversion.
3948 case ImplicitConversionSequence::Better:
3949 if (SCS1.DeprecatedStringLiteralToCharPtr)
3950 Result = ImplicitConversionSequence::Indistinguishable;
3953 case ImplicitConversionSequence::Indistinguishable:
3956 case ImplicitConversionSequence::Worse:
3957 if (SCS2.DeprecatedStringLiteralToCharPtr)
3958 Result = ImplicitConversionSequence::Indistinguishable;
3965 /// CompareDerivedToBaseConversions - Compares two standard conversion
3966 /// sequences to determine whether they can be ranked based on their
3967 /// various kinds of derived-to-base conversions (C++
3968 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3969 /// conversions between Objective-C interface types.
3970 static ImplicitConversionSequence::CompareKind
3971 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3972 const StandardConversionSequence& SCS1,
3973 const StandardConversionSequence& SCS2) {
3974 QualType FromType1 = SCS1.getFromType();
3975 QualType ToType1 = SCS1.getToType(1);
3976 QualType FromType2 = SCS2.getFromType();
3977 QualType ToType2 = SCS2.getToType(1);
3979 // Adjust the types we're converting from via the array-to-pointer
3980 // conversion, if we need to.
3981 if (SCS1.First == ICK_Array_To_Pointer)
3982 FromType1 = S.Context.getArrayDecayedType(FromType1);
3983 if (SCS2.First == ICK_Array_To_Pointer)
3984 FromType2 = S.Context.getArrayDecayedType(FromType2);
3986 // Canonicalize all of the types.
3987 FromType1 = S.Context.getCanonicalType(FromType1);
3988 ToType1 = S.Context.getCanonicalType(ToType1);
3989 FromType2 = S.Context.getCanonicalType(FromType2);
3990 ToType2 = S.Context.getCanonicalType(ToType2);
3992 // C++ [over.ics.rank]p4b3:
3994 // If class B is derived directly or indirectly from class A and
3995 // class C is derived directly or indirectly from B,
3997 // Compare based on pointer conversions.
3998 if (SCS1.Second == ICK_Pointer_Conversion &&
3999 SCS2.Second == ICK_Pointer_Conversion &&
4000 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4001 FromType1->isPointerType() && FromType2->isPointerType() &&
4002 ToType1->isPointerType() && ToType2->isPointerType()) {
4003 QualType FromPointee1
4004 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4006 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4007 QualType FromPointee2
4008 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4010 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4012 // -- conversion of C* to B* is better than conversion of C* to A*,
4013 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4014 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4015 return ImplicitConversionSequence::Better;
4016 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4017 return ImplicitConversionSequence::Worse;
4020 // -- conversion of B* to A* is better than conversion of C* to A*,
4021 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4022 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4023 return ImplicitConversionSequence::Better;
4024 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4025 return ImplicitConversionSequence::Worse;
4027 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4028 SCS2.Second == ICK_Pointer_Conversion) {
4029 const ObjCObjectPointerType *FromPtr1
4030 = FromType1->getAs<ObjCObjectPointerType>();
4031 const ObjCObjectPointerType *FromPtr2
4032 = FromType2->getAs<ObjCObjectPointerType>();
4033 const ObjCObjectPointerType *ToPtr1
4034 = ToType1->getAs<ObjCObjectPointerType>();
4035 const ObjCObjectPointerType *ToPtr2
4036 = ToType2->getAs<ObjCObjectPointerType>();
4038 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4039 // Apply the same conversion ranking rules for Objective-C pointer types
4040 // that we do for C++ pointers to class types. However, we employ the
4041 // Objective-C pseudo-subtyping relationship used for assignment of
4042 // Objective-C pointer types.
4044 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4045 bool FromAssignRight
4046 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4048 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4050 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4052 // A conversion to an a non-id object pointer type or qualified 'id'
4053 // type is better than a conversion to 'id'.
4054 if (ToPtr1->isObjCIdType() &&
4055 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4056 return ImplicitConversionSequence::Worse;
4057 if (ToPtr2->isObjCIdType() &&
4058 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4059 return ImplicitConversionSequence::Better;
4061 // A conversion to a non-id object pointer type is better than a
4062 // conversion to a qualified 'id' type
4063 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4064 return ImplicitConversionSequence::Worse;
4065 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4066 return ImplicitConversionSequence::Better;
4068 // A conversion to an a non-Class object pointer type or qualified 'Class'
4069 // type is better than a conversion to 'Class'.
4070 if (ToPtr1->isObjCClassType() &&
4071 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4072 return ImplicitConversionSequence::Worse;
4073 if (ToPtr2->isObjCClassType() &&
4074 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4075 return ImplicitConversionSequence::Better;
4077 // A conversion to a non-Class object pointer type is better than a
4078 // conversion to a qualified 'Class' type.
4079 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4082 return ImplicitConversionSequence::Better;
4084 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4085 if (S.Context.hasSameType(FromType1, FromType2) &&
4086 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4087 (ToAssignLeft != ToAssignRight))
4088 return ToAssignLeft? ImplicitConversionSequence::Worse
4089 : ImplicitConversionSequence::Better;
4091 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4092 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4093 (FromAssignLeft != FromAssignRight))
4094 return FromAssignLeft? ImplicitConversionSequence::Better
4095 : ImplicitConversionSequence::Worse;
4099 // Ranking of member-pointer types.
4100 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4101 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4102 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4103 const MemberPointerType * FromMemPointer1 =
4104 FromType1->getAs<MemberPointerType>();
4105 const MemberPointerType * ToMemPointer1 =
4106 ToType1->getAs<MemberPointerType>();
4107 const MemberPointerType * FromMemPointer2 =
4108 FromType2->getAs<MemberPointerType>();
4109 const MemberPointerType * ToMemPointer2 =
4110 ToType2->getAs<MemberPointerType>();
4111 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4112 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4113 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4114 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4115 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4116 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4117 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4118 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4119 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4122 return ImplicitConversionSequence::Worse;
4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4124 return ImplicitConversionSequence::Better;
4126 // conversion of B::* to C::* is better than conversion of A::* to C::*
4127 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4128 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4129 return ImplicitConversionSequence::Better;
4130 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4131 return ImplicitConversionSequence::Worse;
4135 if (SCS1.Second == ICK_Derived_To_Base) {
4136 // -- conversion of C to B is better than conversion of C to A,
4137 // -- binding of an expression of type C to a reference of type
4138 // B& is better than binding an expression of type C to a
4139 // reference of type A&,
4140 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4141 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4142 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4143 return ImplicitConversionSequence::Better;
4144 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4145 return ImplicitConversionSequence::Worse;
4148 // -- conversion of B to A is better than conversion of C to A.
4149 // -- binding of an expression of type B to a reference of type
4150 // A& is better than binding an expression of type C to a
4151 // reference of type A&,
4152 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4153 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4154 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4155 return ImplicitConversionSequence::Better;
4156 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4157 return ImplicitConversionSequence::Worse;
4161 return ImplicitConversionSequence::Indistinguishable;
4164 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4166 static bool isTypeValid(QualType T) {
4167 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4168 return !Record->isInvalidDecl();
4173 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4174 /// determine whether they are reference-related,
4175 /// reference-compatible, reference-compatible with added
4176 /// qualification, or incompatible, for use in C++ initialization by
4177 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4178 /// type, and the first type (T1) is the pointee type of the reference
4179 /// type being initialized.
4180 Sema::ReferenceCompareResult
4181 Sema::CompareReferenceRelationship(SourceLocation Loc,
4182 QualType OrigT1, QualType OrigT2,
4183 bool &DerivedToBase,
4184 bool &ObjCConversion,
4185 bool &ObjCLifetimeConversion) {
4186 assert(!OrigT1->isReferenceType() &&
4187 "T1 must be the pointee type of the reference type");
4188 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4190 QualType T1 = Context.getCanonicalType(OrigT1);
4191 QualType T2 = Context.getCanonicalType(OrigT2);
4192 Qualifiers T1Quals, T2Quals;
4193 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4194 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4196 // C++ [dcl.init.ref]p4:
4197 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4198 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4199 // T1 is a base class of T2.
4200 DerivedToBase = false;
4201 ObjCConversion = false;
4202 ObjCLifetimeConversion = false;
4203 QualType ConvertedT2;
4204 if (UnqualT1 == UnqualT2) {
4206 } else if (isCompleteType(Loc, OrigT2) &&
4207 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4208 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4209 DerivedToBase = true;
4210 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4211 UnqualT2->isObjCObjectOrInterfaceType() &&
4212 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4213 ObjCConversion = true;
4214 else if (UnqualT2->isFunctionType() &&
4215 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4216 // C++1z [dcl.init.ref]p4:
4217 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4218 // function" and T1 is "function"
4220 // We extend this to also apply to 'noreturn', so allow any function
4221 // conversion between function types.
4222 return Ref_Compatible;
4224 return Ref_Incompatible;
4226 // At this point, we know that T1 and T2 are reference-related (at
4229 // If the type is an array type, promote the element qualifiers to the type
4231 if (isa<ArrayType>(T1) && T1Quals)
4232 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4233 if (isa<ArrayType>(T2) && T2Quals)
4234 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4236 // C++ [dcl.init.ref]p4:
4237 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4238 // reference-related to T2 and cv1 is the same cv-qualification
4239 // as, or greater cv-qualification than, cv2. For purposes of
4240 // overload resolution, cases for which cv1 is greater
4241 // cv-qualification than cv2 are identified as
4242 // reference-compatible with added qualification (see 13.3.3.2).
4244 // Note that we also require equivalence of Objective-C GC and address-space
4245 // qualifiers when performing these computations, so that e.g., an int in
4246 // address space 1 is not reference-compatible with an int in address
4248 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4249 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4250 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4251 ObjCLifetimeConversion = true;
4253 T1Quals.removeObjCLifetime();
4254 T2Quals.removeObjCLifetime();
4257 // MS compiler ignores __unaligned qualifier for references; do the same.
4258 T1Quals.removeUnaligned();
4259 T2Quals.removeUnaligned();
4261 if (T1Quals.compatiblyIncludes(T2Quals))
4262 return Ref_Compatible;
4267 /// \brief Look for a user-defined conversion to an value reference-compatible
4268 /// with DeclType. Return true if something definite is found.
4270 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4271 QualType DeclType, SourceLocation DeclLoc,
4272 Expr *Init, QualType T2, bool AllowRvalues,
4273 bool AllowExplicit) {
4274 assert(T2->isRecordType() && "Can only find conversions of record types.");
4275 CXXRecordDecl *T2RecordDecl
4276 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4278 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4279 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4280 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4282 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4283 if (isa<UsingShadowDecl>(D))
4284 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4286 FunctionTemplateDecl *ConvTemplate
4287 = dyn_cast<FunctionTemplateDecl>(D);
4288 CXXConversionDecl *Conv;
4290 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4292 Conv = cast<CXXConversionDecl>(D);
4294 // If this is an explicit conversion, and we're not allowed to consider
4295 // explicit conversions, skip it.
4296 if (!AllowExplicit && Conv->isExplicit())
4300 bool DerivedToBase = false;
4301 bool ObjCConversion = false;
4302 bool ObjCLifetimeConversion = false;
4304 // If we are initializing an rvalue reference, don't permit conversion
4305 // functions that return lvalues.
4306 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4307 const ReferenceType *RefType
4308 = Conv->getConversionType()->getAs<LValueReferenceType>();
4309 if (RefType && !RefType->getPointeeType()->isFunctionType())
4313 if (!ConvTemplate &&
4314 S.CompareReferenceRelationship(
4316 Conv->getConversionType().getNonReferenceType()
4317 .getUnqualifiedType(),
4318 DeclType.getNonReferenceType().getUnqualifiedType(),
4319 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4320 Sema::Ref_Incompatible)
4323 // If the conversion function doesn't return a reference type,
4324 // it can't be considered for this conversion. An rvalue reference
4325 // is only acceptable if its referencee is a function type.
4327 const ReferenceType *RefType =
4328 Conv->getConversionType()->getAs<ReferenceType>();
4330 (!RefType->isLValueReferenceType() &&
4331 !RefType->getPointeeType()->isFunctionType()))
4336 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4337 Init, DeclType, CandidateSet,
4338 /*AllowObjCConversionOnExplicit=*/false);
4340 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4341 DeclType, CandidateSet,
4342 /*AllowObjCConversionOnExplicit=*/false);
4345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4347 OverloadCandidateSet::iterator Best;
4348 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4350 // C++ [over.ics.ref]p1:
4352 // [...] If the parameter binds directly to the result of
4353 // applying a conversion function to the argument
4354 // expression, the implicit conversion sequence is a
4355 // user-defined conversion sequence (13.3.3.1.2), with the
4356 // second standard conversion sequence either an identity
4357 // conversion or, if the conversion function returns an
4358 // entity of a type that is a derived class of the parameter
4359 // type, a derived-to-base Conversion.
4360 if (!Best->FinalConversion.DirectBinding)
4363 ICS.setUserDefined();
4364 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4365 ICS.UserDefined.After = Best->FinalConversion;
4366 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4367 ICS.UserDefined.ConversionFunction = Best->Function;
4368 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4369 ICS.UserDefined.EllipsisConversion = false;
4370 assert(ICS.UserDefined.After.ReferenceBinding &&
4371 ICS.UserDefined.After.DirectBinding &&
4372 "Expected a direct reference binding!");
4377 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4378 Cand != CandidateSet.end(); ++Cand)
4380 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4383 case OR_No_Viable_Function:
4385 // There was no suitable conversion, or we found a deleted
4386 // conversion; continue with other checks.
4390 llvm_unreachable("Invalid OverloadResult!");
4393 /// \brief Compute an implicit conversion sequence for reference
4395 static ImplicitConversionSequence
4396 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4397 SourceLocation DeclLoc,
4398 bool SuppressUserConversions,
4399 bool AllowExplicit) {
4400 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4402 // Most paths end in a failed conversion.
4403 ImplicitConversionSequence ICS;
4404 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4406 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4407 QualType T2 = Init->getType();
4409 // If the initializer is the address of an overloaded function, try
4410 // to resolve the overloaded function. If all goes well, T2 is the
4411 // type of the resulting function.
4412 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4413 DeclAccessPair Found;
4414 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4419 // Compute some basic properties of the types and the initializer.
4420 bool isRValRef = DeclType->isRValueReferenceType();
4421 bool DerivedToBase = false;
4422 bool ObjCConversion = false;
4423 bool ObjCLifetimeConversion = false;
4424 Expr::Classification InitCategory = Init->Classify(S.Context);
4425 Sema::ReferenceCompareResult RefRelationship
4426 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4427 ObjCConversion, ObjCLifetimeConversion);
4430 // C++0x [dcl.init.ref]p5:
4431 // A reference to type "cv1 T1" is initialized by an expression
4432 // of type "cv2 T2" as follows:
4434 // -- If reference is an lvalue reference and the initializer expression
4436 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4437 // reference-compatible with "cv2 T2," or
4439 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4440 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4441 // C++ [over.ics.ref]p1:
4442 // When a parameter of reference type binds directly (8.5.3)
4443 // to an argument expression, the implicit conversion sequence
4444 // is the identity conversion, unless the argument expression
4445 // has a type that is a derived class of the parameter type,
4446 // in which case the implicit conversion sequence is a
4447 // derived-to-base Conversion (13.3.3.1).
4449 ICS.Standard.First = ICK_Identity;
4450 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4451 : ObjCConversion? ICK_Compatible_Conversion
4453 ICS.Standard.Third = ICK_Identity;
4454 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4455 ICS.Standard.setToType(0, T2);
4456 ICS.Standard.setToType(1, T1);
4457 ICS.Standard.setToType(2, T1);
4458 ICS.Standard.ReferenceBinding = true;
4459 ICS.Standard.DirectBinding = true;
4460 ICS.Standard.IsLvalueReference = !isRValRef;
4461 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4462 ICS.Standard.BindsToRvalue = false;
4463 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4464 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4465 ICS.Standard.CopyConstructor = nullptr;
4466 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4468 // Nothing more to do: the inaccessibility/ambiguity check for
4469 // derived-to-base conversions is suppressed when we're
4470 // computing the implicit conversion sequence (C++
4471 // [over.best.ics]p2).
4475 // -- has a class type (i.e., T2 is a class type), where T1 is
4476 // not reference-related to T2, and can be implicitly
4477 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4478 // is reference-compatible with "cv3 T3" 92) (this
4479 // conversion is selected by enumerating the applicable
4480 // conversion functions (13.3.1.6) and choosing the best
4481 // one through overload resolution (13.3)),
4482 if (!SuppressUserConversions && T2->isRecordType() &&
4483 S.isCompleteType(DeclLoc, T2) &&
4484 RefRelationship == Sema::Ref_Incompatible) {
4485 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4486 Init, T2, /*AllowRvalues=*/false,
4492 // -- Otherwise, the reference shall be an lvalue reference to a
4493 // non-volatile const type (i.e., cv1 shall be const), or the reference
4494 // shall be an rvalue reference.
4495 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4498 // -- If the initializer expression
4500 // -- is an xvalue, class prvalue, array prvalue or function
4501 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4502 if (RefRelationship == Sema::Ref_Compatible &&
4503 (InitCategory.isXValue() ||
4504 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4505 (InitCategory.isLValue() && T2->isFunctionType()))) {
4507 ICS.Standard.First = ICK_Identity;
4508 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4509 : ObjCConversion? ICK_Compatible_Conversion
4511 ICS.Standard.Third = ICK_Identity;
4512 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4513 ICS.Standard.setToType(0, T2);
4514 ICS.Standard.setToType(1, T1);
4515 ICS.Standard.setToType(2, T1);
4516 ICS.Standard.ReferenceBinding = true;
4517 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4518 // binding unless we're binding to a class prvalue.
4519 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4520 // allow the use of rvalue references in C++98/03 for the benefit of
4521 // standard library implementors; therefore, we need the xvalue check here.
4522 ICS.Standard.DirectBinding =
4523 S.getLangOpts().CPlusPlus11 ||
4524 !(InitCategory.isPRValue() || T2->isRecordType());
4525 ICS.Standard.IsLvalueReference = !isRValRef;
4526 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4527 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4528 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4529 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4530 ICS.Standard.CopyConstructor = nullptr;
4531 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4535 // -- has a class type (i.e., T2 is a class type), where T1 is not
4536 // reference-related to T2, and can be implicitly converted to
4537 // an xvalue, class prvalue, or function lvalue of type
4538 // "cv3 T3", where "cv1 T1" is reference-compatible with
4541 // then the reference is bound to the value of the initializer
4542 // expression in the first case and to the result of the conversion
4543 // in the second case (or, in either case, to an appropriate base
4544 // class subobject).
4545 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4546 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4547 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4548 Init, T2, /*AllowRvalues=*/true,
4550 // In the second case, if the reference is an rvalue reference
4551 // and the second standard conversion sequence of the
4552 // user-defined conversion sequence includes an lvalue-to-rvalue
4553 // conversion, the program is ill-formed.
4554 if (ICS.isUserDefined() && isRValRef &&
4555 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4556 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4561 // A temporary of function type cannot be created; don't even try.
4562 if (T1->isFunctionType())
4565 // -- Otherwise, a temporary of type "cv1 T1" is created and
4566 // initialized from the initializer expression using the
4567 // rules for a non-reference copy initialization (8.5). The
4568 // reference is then bound to the temporary. If T1 is
4569 // reference-related to T2, cv1 must be the same
4570 // cv-qualification as, or greater cv-qualification than,
4571 // cv2; otherwise, the program is ill-formed.
4572 if (RefRelationship == Sema::Ref_Related) {
4573 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4574 // we would be reference-compatible or reference-compatible with
4575 // added qualification. But that wasn't the case, so the reference
4576 // initialization fails.
4578 // Note that we only want to check address spaces and cvr-qualifiers here.
4579 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4580 Qualifiers T1Quals = T1.getQualifiers();
4581 Qualifiers T2Quals = T2.getQualifiers();
4582 T1Quals.removeObjCGCAttr();
4583 T1Quals.removeObjCLifetime();
4584 T2Quals.removeObjCGCAttr();
4585 T2Quals.removeObjCLifetime();
4586 // MS compiler ignores __unaligned qualifier for references; do the same.
4587 T1Quals.removeUnaligned();
4588 T2Quals.removeUnaligned();
4589 if (!T1Quals.compatiblyIncludes(T2Quals))
4593 // If at least one of the types is a class type, the types are not
4594 // related, and we aren't allowed any user conversions, the
4595 // reference binding fails. This case is important for breaking
4596 // recursion, since TryImplicitConversion below will attempt to
4597 // create a temporary through the use of a copy constructor.
4598 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4599 (T1->isRecordType() || T2->isRecordType()))
4602 // If T1 is reference-related to T2 and the reference is an rvalue
4603 // reference, the initializer expression shall not be an lvalue.
4604 if (RefRelationship >= Sema::Ref_Related &&
4605 isRValRef && Init->Classify(S.Context).isLValue())
4608 // C++ [over.ics.ref]p2:
4609 // When a parameter of reference type is not bound directly to
4610 // an argument expression, the conversion sequence is the one
4611 // required to convert the argument expression to the
4612 // underlying type of the reference according to
4613 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4614 // to copy-initializing a temporary of the underlying type with
4615 // the argument expression. Any difference in top-level
4616 // cv-qualification is subsumed by the initialization itself
4617 // and does not constitute a conversion.
4618 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4619 /*AllowExplicit=*/false,
4620 /*InOverloadResolution=*/false,
4622 /*AllowObjCWritebackConversion=*/false,
4623 /*AllowObjCConversionOnExplicit=*/false);
4625 // Of course, that's still a reference binding.
4626 if (ICS.isStandard()) {
4627 ICS.Standard.ReferenceBinding = true;
4628 ICS.Standard.IsLvalueReference = !isRValRef;
4629 ICS.Standard.BindsToFunctionLvalue = false;
4630 ICS.Standard.BindsToRvalue = true;
4631 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4632 ICS.Standard.ObjCLifetimeConversionBinding = false;
4633 } else if (ICS.isUserDefined()) {
4634 const ReferenceType *LValRefType =
4635 ICS.UserDefined.ConversionFunction->getReturnType()
4636 ->getAs<LValueReferenceType>();
4638 // C++ [over.ics.ref]p3:
4639 // Except for an implicit object parameter, for which see 13.3.1, a
4640 // standard conversion sequence cannot be formed if it requires [...]
4641 // binding an rvalue reference to an lvalue other than a function
4643 // Note that the function case is not possible here.
4644 if (DeclType->isRValueReferenceType() && LValRefType) {
4645 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4646 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4647 // reference to an rvalue!
4648 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4652 ICS.UserDefined.After.ReferenceBinding = true;
4653 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4654 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4655 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4656 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4657 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4663 static ImplicitConversionSequence
4664 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4665 bool SuppressUserConversions,
4666 bool InOverloadResolution,
4667 bool AllowObjCWritebackConversion,
4668 bool AllowExplicit = false);
4670 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4671 /// initializer list From.
4672 static ImplicitConversionSequence
4673 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4674 bool SuppressUserConversions,
4675 bool InOverloadResolution,
4676 bool AllowObjCWritebackConversion) {
4677 // C++11 [over.ics.list]p1:
4678 // When an argument is an initializer list, it is not an expression and
4679 // special rules apply for converting it to a parameter type.
4681 ImplicitConversionSequence Result;
4682 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4684 // We need a complete type for what follows. Incomplete types can never be
4685 // initialized from init lists.
4686 if (!S.isCompleteType(From->getLocStart(), ToType))
4690 // If the parameter type is a class X and the initializer list has a single
4691 // element of type cv U, where U is X or a class derived from X, the
4692 // implicit conversion sequence is the one required to convert the element
4693 // to the parameter type.
4695 // Otherwise, if the parameter type is a character array [... ]
4696 // and the initializer list has a single element that is an
4697 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4698 // implicit conversion sequence is the identity conversion.
4699 if (From->getNumInits() == 1) {
4700 if (ToType->isRecordType()) {
4701 QualType InitType = From->getInit(0)->getType();
4702 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4703 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4704 return TryCopyInitialization(S, From->getInit(0), ToType,
4705 SuppressUserConversions,
4706 InOverloadResolution,
4707 AllowObjCWritebackConversion);
4709 // FIXME: Check the other conditions here: array of character type,
4710 // initializer is a string literal.
4711 if (ToType->isArrayType()) {
4712 InitializedEntity Entity =
4713 InitializedEntity::InitializeParameter(S.Context, ToType,
4714 /*Consumed=*/false);
4715 if (S.CanPerformCopyInitialization(Entity, From)) {
4716 Result.setStandard();
4717 Result.Standard.setAsIdentityConversion();
4718 Result.Standard.setFromType(ToType);
4719 Result.Standard.setAllToTypes(ToType);
4725 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4726 // C++11 [over.ics.list]p2:
4727 // If the parameter type is std::initializer_list<X> or "array of X" and
4728 // all the elements can be implicitly converted to X, the implicit
4729 // conversion sequence is the worst conversion necessary to convert an
4730 // element of the list to X.
4732 // C++14 [over.ics.list]p3:
4733 // Otherwise, if the parameter type is "array of N X", if the initializer
4734 // list has exactly N elements or if it has fewer than N elements and X is
4735 // default-constructible, and if all the elements of the initializer list
4736 // can be implicitly converted to X, the implicit conversion sequence is
4737 // the worst conversion necessary to convert an element of the list to X.
4739 // FIXME: We're missing a lot of these checks.
4740 bool toStdInitializerList = false;
4742 if (ToType->isArrayType())
4743 X = S.Context.getAsArrayType(ToType)->getElementType();
4745 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4747 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4748 Expr *Init = From->getInit(i);
4749 ImplicitConversionSequence ICS =
4750 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4751 InOverloadResolution,
4752 AllowObjCWritebackConversion);
4753 // If a single element isn't convertible, fail.
4758 // Otherwise, look for the worst conversion.
4759 if (Result.isBad() ||
4760 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4762 ImplicitConversionSequence::Worse)
4766 // For an empty list, we won't have computed any conversion sequence.
4767 // Introduce the identity conversion sequence.
4768 if (From->getNumInits() == 0) {
4769 Result.setStandard();
4770 Result.Standard.setAsIdentityConversion();
4771 Result.Standard.setFromType(ToType);
4772 Result.Standard.setAllToTypes(ToType);
4775 Result.setStdInitializerListElement(toStdInitializerList);
4779 // C++14 [over.ics.list]p4:
4780 // C++11 [over.ics.list]p3:
4781 // Otherwise, if the parameter is a non-aggregate class X and overload
4782 // resolution chooses a single best constructor [...] the implicit
4783 // conversion sequence is a user-defined conversion sequence. If multiple
4784 // constructors are viable but none is better than the others, the
4785 // implicit conversion sequence is a user-defined conversion sequence.
4786 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4787 // This function can deal with initializer lists.
4788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4789 /*AllowExplicit=*/false,
4790 InOverloadResolution, /*CStyle=*/false,
4791 AllowObjCWritebackConversion,
4792 /*AllowObjCConversionOnExplicit=*/false);
4795 // C++14 [over.ics.list]p5:
4796 // C++11 [over.ics.list]p4:
4797 // Otherwise, if the parameter has an aggregate type which can be
4798 // initialized from the initializer list [...] the implicit conversion
4799 // sequence is a user-defined conversion sequence.
4800 if (ToType->isAggregateType()) {
4801 // Type is an aggregate, argument is an init list. At this point it comes
4802 // down to checking whether the initialization works.
4803 // FIXME: Find out whether this parameter is consumed or not.
4804 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4805 // need to call into the initialization code here; overload resolution
4806 // should not be doing that.
4807 InitializedEntity Entity =
4808 InitializedEntity::InitializeParameter(S.Context, ToType,
4809 /*Consumed=*/false);
4810 if (S.CanPerformCopyInitialization(Entity, From)) {
4811 Result.setUserDefined();
4812 Result.UserDefined.Before.setAsIdentityConversion();
4813 // Initializer lists don't have a type.
4814 Result.UserDefined.Before.setFromType(QualType());
4815 Result.UserDefined.Before.setAllToTypes(QualType());
4817 Result.UserDefined.After.setAsIdentityConversion();
4818 Result.UserDefined.After.setFromType(ToType);
4819 Result.UserDefined.After.setAllToTypes(ToType);
4820 Result.UserDefined.ConversionFunction = nullptr;
4825 // C++14 [over.ics.list]p6:
4826 // C++11 [over.ics.list]p5:
4827 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4828 if (ToType->isReferenceType()) {
4829 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4830 // mention initializer lists in any way. So we go by what list-
4831 // initialization would do and try to extrapolate from that.
4833 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4835 // If the initializer list has a single element that is reference-related
4836 // to the parameter type, we initialize the reference from that.
4837 if (From->getNumInits() == 1) {
4838 Expr *Init = From->getInit(0);
4840 QualType T2 = Init->getType();
4842 // If the initializer is the address of an overloaded function, try
4843 // to resolve the overloaded function. If all goes well, T2 is the
4844 // type of the resulting function.
4845 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4846 DeclAccessPair Found;
4847 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4848 Init, ToType, false, Found))
4852 // Compute some basic properties of the types and the initializer.
4853 bool dummy1 = false;
4854 bool dummy2 = false;
4855 bool dummy3 = false;
4856 Sema::ReferenceCompareResult RefRelationship
4857 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4860 if (RefRelationship >= Sema::Ref_Related) {
4861 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4862 SuppressUserConversions,
4863 /*AllowExplicit=*/false);
4867 // Otherwise, we bind the reference to a temporary created from the
4868 // initializer list.
4869 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4870 InOverloadResolution,
4871 AllowObjCWritebackConversion);
4872 if (Result.isFailure())
4874 assert(!Result.isEllipsis() &&
4875 "Sub-initialization cannot result in ellipsis conversion.");
4877 // Can we even bind to a temporary?
4878 if (ToType->isRValueReferenceType() ||
4879 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4880 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4881 Result.UserDefined.After;
4882 SCS.ReferenceBinding = true;
4883 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4884 SCS.BindsToRvalue = true;
4885 SCS.BindsToFunctionLvalue = false;
4886 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4887 SCS.ObjCLifetimeConversionBinding = false;
4889 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4894 // C++14 [over.ics.list]p7:
4895 // C++11 [over.ics.list]p6:
4896 // Otherwise, if the parameter type is not a class:
4897 if (!ToType->isRecordType()) {
4898 // - if the initializer list has one element that is not itself an
4899 // initializer list, the implicit conversion sequence is the one
4900 // required to convert the element to the parameter type.
4901 unsigned NumInits = From->getNumInits();
4902 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4903 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4904 SuppressUserConversions,
4905 InOverloadResolution,
4906 AllowObjCWritebackConversion);
4907 // - if the initializer list has no elements, the implicit conversion
4908 // sequence is the identity conversion.
4909 else if (NumInits == 0) {
4910 Result.setStandard();
4911 Result.Standard.setAsIdentityConversion();
4912 Result.Standard.setFromType(ToType);
4913 Result.Standard.setAllToTypes(ToType);
4918 // C++14 [over.ics.list]p8:
4919 // C++11 [over.ics.list]p7:
4920 // In all cases other than those enumerated above, no conversion is possible
4924 /// TryCopyInitialization - Try to copy-initialize a value of type
4925 /// ToType from the expression From. Return the implicit conversion
4926 /// sequence required to pass this argument, which may be a bad
4927 /// conversion sequence (meaning that the argument cannot be passed to
4928 /// a parameter of this type). If @p SuppressUserConversions, then we
4929 /// do not permit any user-defined conversion sequences.
4930 static ImplicitConversionSequence
4931 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4932 bool SuppressUserConversions,
4933 bool InOverloadResolution,
4934 bool AllowObjCWritebackConversion,
4935 bool AllowExplicit) {
4936 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4937 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4938 InOverloadResolution,AllowObjCWritebackConversion);
4940 if (ToType->isReferenceType())
4941 return TryReferenceInit(S, From, ToType,
4942 /*FIXME:*/From->getLocStart(),
4943 SuppressUserConversions,
4946 return TryImplicitConversion(S, From, ToType,
4947 SuppressUserConversions,
4948 /*AllowExplicit=*/false,
4949 InOverloadResolution,
4951 AllowObjCWritebackConversion,
4952 /*AllowObjCConversionOnExplicit=*/false);
4955 static bool TryCopyInitialization(const CanQualType FromQTy,
4956 const CanQualType ToQTy,
4959 ExprValueKind FromVK) {
4960 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4961 ImplicitConversionSequence ICS =
4962 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4964 return !ICS.isBad();
4967 /// TryObjectArgumentInitialization - Try to initialize the object
4968 /// parameter of the given member function (@c Method) from the
4969 /// expression @p From.
4970 static ImplicitConversionSequence
4971 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4972 Expr::Classification FromClassification,
4973 CXXMethodDecl *Method,
4974 CXXRecordDecl *ActingContext) {
4975 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4976 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4977 // const volatile object.
4978 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4979 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4980 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4982 // Set up the conversion sequence as a "bad" conversion, to allow us
4984 ImplicitConversionSequence ICS;
4986 // We need to have an object of class type.
4987 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4988 FromType = PT->getPointeeType();
4990 // When we had a pointer, it's implicitly dereferenced, so we
4991 // better have an lvalue.
4992 assert(FromClassification.isLValue());
4995 assert(FromType->isRecordType());
4997 // C++0x [over.match.funcs]p4:
4998 // For non-static member functions, the type of the implicit object
5001 // - "lvalue reference to cv X" for functions declared without a
5002 // ref-qualifier or with the & ref-qualifier
5003 // - "rvalue reference to cv X" for functions declared with the &&
5006 // where X is the class of which the function is a member and cv is the
5007 // cv-qualification on the member function declaration.
5009 // However, when finding an implicit conversion sequence for the argument, we
5010 // are not allowed to perform user-defined conversions
5011 // (C++ [over.match.funcs]p5). We perform a simplified version of
5012 // reference binding here, that allows class rvalues to bind to
5013 // non-constant references.
5015 // First check the qualifiers.
5016 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5017 if (ImplicitParamType.getCVRQualifiers()
5018 != FromTypeCanon.getLocalCVRQualifiers() &&
5019 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5020 ICS.setBad(BadConversionSequence::bad_qualifiers,
5021 FromType, ImplicitParamType);
5025 // Check that we have either the same type or a derived type. It
5026 // affects the conversion rank.
5027 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5028 ImplicitConversionKind SecondKind;
5029 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5030 SecondKind = ICK_Identity;
5031 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5032 SecondKind = ICK_Derived_To_Base;
5034 ICS.setBad(BadConversionSequence::unrelated_class,
5035 FromType, ImplicitParamType);
5039 // Check the ref-qualifier.
5040 switch (Method->getRefQualifier()) {
5042 // Do nothing; we don't care about lvalueness or rvalueness.
5046 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5047 // non-const lvalue reference cannot bind to an rvalue
5048 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5055 if (!FromClassification.isRValue()) {
5056 // rvalue reference cannot bind to an lvalue
5057 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5064 // Success. Mark this as a reference binding.
5066 ICS.Standard.setAsIdentityConversion();
5067 ICS.Standard.Second = SecondKind;
5068 ICS.Standard.setFromType(FromType);
5069 ICS.Standard.setAllToTypes(ImplicitParamType);
5070 ICS.Standard.ReferenceBinding = true;
5071 ICS.Standard.DirectBinding = true;
5072 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5073 ICS.Standard.BindsToFunctionLvalue = false;
5074 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5075 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5076 = (Method->getRefQualifier() == RQ_None);
5080 /// PerformObjectArgumentInitialization - Perform initialization of
5081 /// the implicit object parameter for the given Method with the given
5084 Sema::PerformObjectArgumentInitialization(Expr *From,
5085 NestedNameSpecifier *Qualifier,
5086 NamedDecl *FoundDecl,
5087 CXXMethodDecl *Method) {
5088 QualType FromRecordType, DestType;
5089 QualType ImplicitParamRecordType =
5090 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5092 Expr::Classification FromClassification;
5093 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5094 FromRecordType = PT->getPointeeType();
5095 DestType = Method->getThisType(Context);
5096 FromClassification = Expr::Classification::makeSimpleLValue();
5098 FromRecordType = From->getType();
5099 DestType = ImplicitParamRecordType;
5100 FromClassification = From->Classify(Context);
5103 // Note that we always use the true parent context when performing
5104 // the actual argument initialization.
5105 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5106 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5107 Method->getParent());
5109 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5110 Qualifiers FromQs = FromRecordType.getQualifiers();
5111 Qualifiers ToQs = DestType.getQualifiers();
5112 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5114 Diag(From->getLocStart(),
5115 diag::err_member_function_call_bad_cvr)
5116 << Method->getDeclName() << FromRecordType << (CVR - 1)
5117 << From->getSourceRange();
5118 Diag(Method->getLocation(), diag::note_previous_decl)
5119 << Method->getDeclName();
5124 return Diag(From->getLocStart(),
5125 diag::err_implicit_object_parameter_init)
5126 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5129 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5130 ExprResult FromRes =
5131 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5132 if (FromRes.isInvalid())
5134 From = FromRes.get();
5137 if (!Context.hasSameType(From->getType(), DestType))
5138 From = ImpCastExprToType(From, DestType, CK_NoOp,
5139 From->getValueKind()).get();
5143 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5144 /// expression From to bool (C++0x [conv]p3).
5145 static ImplicitConversionSequence
5146 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5147 return TryImplicitConversion(S, From, S.Context.BoolTy,
5148 /*SuppressUserConversions=*/false,
5149 /*AllowExplicit=*/true,
5150 /*InOverloadResolution=*/false,
5152 /*AllowObjCWritebackConversion=*/false,
5153 /*AllowObjCConversionOnExplicit=*/false);
5156 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5157 /// of the expression From to bool (C++0x [conv]p3).
5158 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5159 if (checkPlaceholderForOverload(*this, From))
5162 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5164 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5166 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5167 return Diag(From->getLocStart(),
5168 diag::err_typecheck_bool_condition)
5169 << From->getType() << From->getSourceRange();
5173 /// Check that the specified conversion is permitted in a converted constant
5174 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5176 static bool CheckConvertedConstantConversions(Sema &S,
5177 StandardConversionSequence &SCS) {
5178 // Since we know that the target type is an integral or unscoped enumeration
5179 // type, most conversion kinds are impossible. All possible First and Third
5180 // conversions are fine.
5181 switch (SCS.Second) {
5183 case ICK_Function_Conversion:
5184 case ICK_Integral_Promotion:
5185 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5186 case ICK_Zero_Queue_Conversion:
5189 case ICK_Boolean_Conversion:
5190 // Conversion from an integral or unscoped enumeration type to bool is
5191 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5192 // conversion, so we allow it in a converted constant expression.
5194 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5195 // a lot of popular code. We should at least add a warning for this
5196 // (non-conforming) extension.
5197 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5198 SCS.getToType(2)->isBooleanType();
5200 case ICK_Pointer_Conversion:
5201 case ICK_Pointer_Member:
5202 // C++1z: null pointer conversions and null member pointer conversions are
5203 // only permitted if the source type is std::nullptr_t.
5204 return SCS.getFromType()->isNullPtrType();
5206 case ICK_Floating_Promotion:
5207 case ICK_Complex_Promotion:
5208 case ICK_Floating_Conversion:
5209 case ICK_Complex_Conversion:
5210 case ICK_Floating_Integral:
5211 case ICK_Compatible_Conversion:
5212 case ICK_Derived_To_Base:
5213 case ICK_Vector_Conversion:
5214 case ICK_Vector_Splat:
5215 case ICK_Complex_Real:
5216 case ICK_Block_Pointer_Conversion:
5217 case ICK_TransparentUnionConversion:
5218 case ICK_Writeback_Conversion:
5219 case ICK_Zero_Event_Conversion:
5220 case ICK_C_Only_Conversion:
5221 case ICK_Incompatible_Pointer_Conversion:
5224 case ICK_Lvalue_To_Rvalue:
5225 case ICK_Array_To_Pointer:
5226 case ICK_Function_To_Pointer:
5227 llvm_unreachable("found a first conversion kind in Second");
5229 case ICK_Qualification:
5230 llvm_unreachable("found a third conversion kind in Second");
5232 case ICK_Num_Conversion_Kinds:
5236 llvm_unreachable("unknown conversion kind");
5239 /// CheckConvertedConstantExpression - Check that the expression From is a
5240 /// converted constant expression of type T, perform the conversion and produce
5241 /// the converted expression, per C++11 [expr.const]p3.
5242 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5243 QualType T, APValue &Value,
5246 assert(S.getLangOpts().CPlusPlus11 &&
5247 "converted constant expression outside C++11");
5249 if (checkPlaceholderForOverload(S, From))
5252 // C++1z [expr.const]p3:
5253 // A converted constant expression of type T is an expression,
5254 // implicitly converted to type T, where the converted
5255 // expression is a constant expression and the implicit conversion
5256 // sequence contains only [... list of conversions ...].
5257 // C++1z [stmt.if]p2:
5258 // If the if statement is of the form if constexpr, the value of the
5259 // condition shall be a contextually converted constant expression of type
5261 ImplicitConversionSequence ICS =
5262 CCE == Sema::CCEK_ConstexprIf
5263 ? TryContextuallyConvertToBool(S, From)
5264 : TryCopyInitialization(S, From, T,
5265 /*SuppressUserConversions=*/false,
5266 /*InOverloadResolution=*/false,
5267 /*AllowObjcWritebackConversion=*/false,
5268 /*AllowExplicit=*/false);
5269 StandardConversionSequence *SCS = nullptr;
5270 switch (ICS.getKind()) {
5271 case ImplicitConversionSequence::StandardConversion:
5272 SCS = &ICS.Standard;
5274 case ImplicitConversionSequence::UserDefinedConversion:
5275 // We are converting to a non-class type, so the Before sequence
5277 SCS = &ICS.UserDefined.After;
5279 case ImplicitConversionSequence::AmbiguousConversion:
5280 case ImplicitConversionSequence::BadConversion:
5281 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5282 return S.Diag(From->getLocStart(),
5283 diag::err_typecheck_converted_constant_expression)
5284 << From->getType() << From->getSourceRange() << T;
5287 case ImplicitConversionSequence::EllipsisConversion:
5288 llvm_unreachable("ellipsis conversion in converted constant expression");
5291 // Check that we would only use permitted conversions.
5292 if (!CheckConvertedConstantConversions(S, *SCS)) {
5293 return S.Diag(From->getLocStart(),
5294 diag::err_typecheck_converted_constant_expression_disallowed)
5295 << From->getType() << From->getSourceRange() << T;
5297 // [...] and where the reference binding (if any) binds directly.
5298 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5299 return S.Diag(From->getLocStart(),
5300 diag::err_typecheck_converted_constant_expression_indirect)
5301 << From->getType() << From->getSourceRange() << T;
5305 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5306 if (Result.isInvalid())
5309 // Check for a narrowing implicit conversion.
5310 APValue PreNarrowingValue;
5311 QualType PreNarrowingType;
5312 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5313 PreNarrowingType)) {
5314 case NK_Dependent_Narrowing:
5315 // Implicit conversion to a narrower type, but the expression is
5316 // value-dependent so we can't tell whether it's actually narrowing.
5317 case NK_Variable_Narrowing:
5318 // Implicit conversion to a narrower type, and the value is not a constant
5319 // expression. We'll diagnose this in a moment.
5320 case NK_Not_Narrowing:
5323 case NK_Constant_Narrowing:
5324 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5325 << CCE << /*Constant*/1
5326 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5329 case NK_Type_Narrowing:
5330 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5331 << CCE << /*Constant*/0 << From->getType() << T;
5335 if (Result.get()->isValueDependent()) {
5340 // Check the expression is a constant expression.
5341 SmallVector<PartialDiagnosticAt, 8> Notes;
5342 Expr::EvalResult Eval;
5345 if ((T->isReferenceType()
5346 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5347 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5348 (RequireInt && !Eval.Val.isInt())) {
5349 // The expression can't be folded, so we can't keep it at this position in
5351 Result = ExprError();
5355 if (Notes.empty()) {
5356 // It's a constant expression.
5361 // It's not a constant expression. Produce an appropriate diagnostic.
5362 if (Notes.size() == 1 &&
5363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5364 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5366 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5367 << CCE << From->getSourceRange();
5368 for (unsigned I = 0; I < Notes.size(); ++I)
5369 S.Diag(Notes[I].first, Notes[I].second);
5374 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5375 APValue &Value, CCEKind CCE) {
5376 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5379 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5380 llvm::APSInt &Value,
5382 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5385 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5386 if (!R.isInvalid() && !R.get()->isValueDependent())
5392 /// dropPointerConversions - If the given standard conversion sequence
5393 /// involves any pointer conversions, remove them. This may change
5394 /// the result type of the conversion sequence.
5395 static void dropPointerConversion(StandardConversionSequence &SCS) {
5396 if (SCS.Second == ICK_Pointer_Conversion) {
5397 SCS.Second = ICK_Identity;
5398 SCS.Third = ICK_Identity;
5399 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5403 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5404 /// convert the expression From to an Objective-C pointer type.
5405 static ImplicitConversionSequence
5406 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5407 // Do an implicit conversion to 'id'.
5408 QualType Ty = S.Context.getObjCIdType();
5409 ImplicitConversionSequence ICS
5410 = TryImplicitConversion(S, From, Ty,
5411 // FIXME: Are these flags correct?
5412 /*SuppressUserConversions=*/false,
5413 /*AllowExplicit=*/true,
5414 /*InOverloadResolution=*/false,
5416 /*AllowObjCWritebackConversion=*/false,
5417 /*AllowObjCConversionOnExplicit=*/true);
5419 // Strip off any final conversions to 'id'.
5420 switch (ICS.getKind()) {
5421 case ImplicitConversionSequence::BadConversion:
5422 case ImplicitConversionSequence::AmbiguousConversion:
5423 case ImplicitConversionSequence::EllipsisConversion:
5426 case ImplicitConversionSequence::UserDefinedConversion:
5427 dropPointerConversion(ICS.UserDefined.After);
5430 case ImplicitConversionSequence::StandardConversion:
5431 dropPointerConversion(ICS.Standard);
5438 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5439 /// conversion of the expression From to an Objective-C pointer type.
5440 /// Returns a valid but null ExprResult if no conversion sequence exists.
5441 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5442 if (checkPlaceholderForOverload(*this, From))
5445 QualType Ty = Context.getObjCIdType();
5446 ImplicitConversionSequence ICS =
5447 TryContextuallyConvertToObjCPointer(*this, From);
5449 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5450 return ExprResult();
5453 /// Determine whether the provided type is an integral type, or an enumeration
5454 /// type of a permitted flavor.
5455 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5456 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5457 : T->isIntegralOrUnscopedEnumerationType();
5461 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5462 Sema::ContextualImplicitConverter &Converter,
5463 QualType T, UnresolvedSetImpl &ViableConversions) {
5465 if (Converter.Suppress)
5468 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5470 CXXConversionDecl *Conv =
5471 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5472 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5473 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5479 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5480 Sema::ContextualImplicitConverter &Converter,
5481 QualType T, bool HadMultipleCandidates,
5482 UnresolvedSetImpl &ExplicitConversions) {
5483 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5484 DeclAccessPair Found = ExplicitConversions[0];
5485 CXXConversionDecl *Conversion =
5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5488 // The user probably meant to invoke the given explicit
5489 // conversion; use it.
5490 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5491 std::string TypeStr;
5492 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5494 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5495 << FixItHint::CreateInsertion(From->getLocStart(),
5496 "static_cast<" + TypeStr + ">(")
5497 << FixItHint::CreateInsertion(
5498 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5499 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5501 // If we aren't in a SFINAE context, build a call to the
5502 // explicit conversion function.
5503 if (SemaRef.isSFINAEContext())
5506 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5507 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5508 HadMultipleCandidates);
5509 if (Result.isInvalid())
5511 // Record usage of conversion in an implicit cast.
5512 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5513 CK_UserDefinedConversion, Result.get(),
5514 nullptr, Result.get()->getValueKind());
5519 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5520 Sema::ContextualImplicitConverter &Converter,
5521 QualType T, bool HadMultipleCandidates,
5522 DeclAccessPair &Found) {
5523 CXXConversionDecl *Conversion =
5524 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5525 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5527 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5528 if (!Converter.SuppressConversion) {
5529 if (SemaRef.isSFINAEContext())
5532 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5533 << From->getSourceRange();
5536 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5537 HadMultipleCandidates);
5538 if (Result.isInvalid())
5540 // Record usage of conversion in an implicit cast.
5541 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5542 CK_UserDefinedConversion, Result.get(),
5543 nullptr, Result.get()->getValueKind());
5547 static ExprResult finishContextualImplicitConversion(
5548 Sema &SemaRef, SourceLocation Loc, Expr *From,
5549 Sema::ContextualImplicitConverter &Converter) {
5550 if (!Converter.match(From->getType()) && !Converter.Suppress)
5551 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5552 << From->getSourceRange();
5554 return SemaRef.DefaultLvalueConversion(From);
5558 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5559 UnresolvedSetImpl &ViableConversions,
5560 OverloadCandidateSet &CandidateSet) {
5561 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5562 DeclAccessPair FoundDecl = ViableConversions[I];
5563 NamedDecl *D = FoundDecl.getDecl();
5564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5565 if (isa<UsingShadowDecl>(D))
5566 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5568 CXXConversionDecl *Conv;
5569 FunctionTemplateDecl *ConvTemplate;
5570 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5571 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5573 Conv = cast<CXXConversionDecl>(D);
5576 SemaRef.AddTemplateConversionCandidate(
5577 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5578 /*AllowObjCConversionOnExplicit=*/false);
5580 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5581 ToType, CandidateSet,
5582 /*AllowObjCConversionOnExplicit=*/false);
5586 /// \brief Attempt to convert the given expression to a type which is accepted
5587 /// by the given converter.
5589 /// This routine will attempt to convert an expression of class type to a
5590 /// type accepted by the specified converter. In C++11 and before, the class
5591 /// must have a single non-explicit conversion function converting to a matching
5592 /// type. In C++1y, there can be multiple such conversion functions, but only
5593 /// one target type.
5595 /// \param Loc The source location of the construct that requires the
5598 /// \param From The expression we're converting from.
5600 /// \param Converter Used to control and diagnose the conversion process.
5602 /// \returns The expression, converted to an integral or enumeration type if
5604 ExprResult Sema::PerformContextualImplicitConversion(
5605 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5606 // We can't perform any more checking for type-dependent expressions.
5607 if (From->isTypeDependent())
5610 // Process placeholders immediately.
5611 if (From->hasPlaceholderType()) {
5612 ExprResult result = CheckPlaceholderExpr(From);
5613 if (result.isInvalid())
5615 From = result.get();
5618 // If the expression already has a matching type, we're golden.
5619 QualType T = From->getType();
5620 if (Converter.match(T))
5621 return DefaultLvalueConversion(From);
5623 // FIXME: Check for missing '()' if T is a function type?
5625 // We can only perform contextual implicit conversions on objects of class
5627 const RecordType *RecordTy = T->getAs<RecordType>();
5628 if (!RecordTy || !getLangOpts().CPlusPlus) {
5629 if (!Converter.Suppress)
5630 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5634 // We must have a complete class type.
5635 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5636 ContextualImplicitConverter &Converter;
5639 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5640 : Converter(Converter), From(From) {}
5642 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5643 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5645 } IncompleteDiagnoser(Converter, From);
5647 if (Converter.Suppress ? !isCompleteType(Loc, T)
5648 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5651 // Look for a conversion to an integral or enumeration type.
5653 ViableConversions; // These are *potentially* viable in C++1y.
5654 UnresolvedSet<4> ExplicitConversions;
5655 const auto &Conversions =
5656 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5658 bool HadMultipleCandidates =
5659 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5661 // To check that there is only one target type, in C++1y:
5663 bool HasUniqueTargetType = true;
5665 // Collect explicit or viable (potentially in C++1y) conversions.
5666 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5667 NamedDecl *D = (*I)->getUnderlyingDecl();
5668 CXXConversionDecl *Conversion;
5669 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5671 if (getLangOpts().CPlusPlus14)
5672 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5674 continue; // C++11 does not consider conversion operator templates(?).
5676 Conversion = cast<CXXConversionDecl>(D);
5678 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5679 "Conversion operator templates are considered potentially "
5682 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5683 if (Converter.match(CurToType) || ConvTemplate) {
5685 if (Conversion->isExplicit()) {
5686 // FIXME: For C++1y, do we need this restriction?
5687 // cf. diagnoseNoViableConversion()
5689 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5691 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5692 if (ToType.isNull())
5693 ToType = CurToType.getUnqualifiedType();
5694 else if (HasUniqueTargetType &&
5695 (CurToType.getUnqualifiedType() != ToType))
5696 HasUniqueTargetType = false;
5698 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5703 if (getLangOpts().CPlusPlus14) {
5705 // ... An expression e of class type E appearing in such a context
5706 // is said to be contextually implicitly converted to a specified
5707 // type T and is well-formed if and only if e can be implicitly
5708 // converted to a type T that is determined as follows: E is searched
5709 // for conversion functions whose return type is cv T or reference to
5710 // cv T such that T is allowed by the context. There shall be
5711 // exactly one such T.
5713 // If no unique T is found:
5714 if (ToType.isNull()) {
5715 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5716 HadMultipleCandidates,
5717 ExplicitConversions))
5719 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5722 // If more than one unique Ts are found:
5723 if (!HasUniqueTargetType)
5724 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5727 // If one unique T is found:
5728 // First, build a candidate set from the previously recorded
5729 // potentially viable conversions.
5730 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5731 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5734 // Then, perform overload resolution over the candidate set.
5735 OverloadCandidateSet::iterator Best;
5736 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5738 // Apply this conversion.
5739 DeclAccessPair Found =
5740 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5741 if (recordConversion(*this, Loc, From, Converter, T,
5742 HadMultipleCandidates, Found))
5747 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5749 case OR_No_Viable_Function:
5750 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5751 HadMultipleCandidates,
5752 ExplicitConversions))
5754 // fall through 'OR_Deleted' case.
5756 // We'll complain below about a non-integral condition type.
5760 switch (ViableConversions.size()) {
5762 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5763 HadMultipleCandidates,
5764 ExplicitConversions))
5767 // We'll complain below about a non-integral condition type.
5771 // Apply this conversion.
5772 DeclAccessPair Found = ViableConversions[0];
5773 if (recordConversion(*this, Loc, From, Converter, T,
5774 HadMultipleCandidates, Found))
5779 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5784 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5787 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5788 /// an acceptable non-member overloaded operator for a call whose
5789 /// arguments have types T1 (and, if non-empty, T2). This routine
5790 /// implements the check in C++ [over.match.oper]p3b2 concerning
5791 /// enumeration types.
5792 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5794 ArrayRef<Expr *> Args) {
5795 QualType T1 = Args[0]->getType();
5796 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5798 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5801 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5804 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5805 if (Proto->getNumParams() < 1)
5808 if (T1->isEnumeralType()) {
5809 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5810 if (Context.hasSameUnqualifiedType(T1, ArgType))
5814 if (Proto->getNumParams() < 2)
5817 if (!T2.isNull() && T2->isEnumeralType()) {
5818 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5819 if (Context.hasSameUnqualifiedType(T2, ArgType))
5826 /// AddOverloadCandidate - Adds the given function to the set of
5827 /// candidate functions, using the given function call arguments. If
5828 /// @p SuppressUserConversions, then don't allow user-defined
5829 /// conversions via constructors or conversion operators.
5831 /// \param PartialOverloading true if we are performing "partial" overloading
5832 /// based on an incomplete set of function arguments. This feature is used by
5833 /// code completion.
5835 Sema::AddOverloadCandidate(FunctionDecl *Function,
5836 DeclAccessPair FoundDecl,
5837 ArrayRef<Expr *> Args,
5838 OverloadCandidateSet &CandidateSet,
5839 bool SuppressUserConversions,
5840 bool PartialOverloading,
5842 ConversionSequenceList EarlyConversions) {
5843 const FunctionProtoType *Proto
5844 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5845 assert(Proto && "Functions without a prototype cannot be overloaded");
5846 assert(!Function->getDescribedFunctionTemplate() &&
5847 "Use AddTemplateOverloadCandidate for function templates");
5849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5850 if (!isa<CXXConstructorDecl>(Method)) {
5851 // If we get here, it's because we're calling a member function
5852 // that is named without a member access expression (e.g.,
5853 // "this->f") that was either written explicitly or created
5854 // implicitly. This can happen with a qualified call to a member
5855 // function, e.g., X::f(). We use an empty type for the implied
5856 // object argument (C++ [over.call.func]p3), and the acting context
5858 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5859 Expr::Classification::makeSimpleLValue(), Args,
5860 CandidateSet, SuppressUserConversions,
5861 PartialOverloading, EarlyConversions);
5864 // We treat a constructor like a non-member function, since its object
5865 // argument doesn't participate in overload resolution.
5868 if (!CandidateSet.isNewCandidate(Function))
5871 // C++ [over.match.oper]p3:
5872 // if no operand has a class type, only those non-member functions in the
5873 // lookup set that have a first parameter of type T1 or "reference to
5874 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5875 // is a right operand) a second parameter of type T2 or "reference to
5876 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5877 // candidate functions.
5878 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5879 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5882 // C++11 [class.copy]p11: [DR1402]
5883 // A defaulted move constructor that is defined as deleted is ignored by
5884 // overload resolution.
5885 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5886 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5887 Constructor->isMoveConstructor())
5890 // Overload resolution is always an unevaluated context.
5891 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5893 // Add this candidate
5894 OverloadCandidate &Candidate =
5895 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5896 Candidate.FoundDecl = FoundDecl;
5897 Candidate.Function = Function;
5898 Candidate.Viable = true;
5899 Candidate.IsSurrogate = false;
5900 Candidate.IgnoreObjectArgument = false;
5901 Candidate.ExplicitCallArguments = Args.size();
5904 // C++ [class.copy]p3:
5905 // A member function template is never instantiated to perform the copy
5906 // of a class object to an object of its class type.
5907 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5908 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5909 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5910 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5912 Candidate.Viable = false;
5913 Candidate.FailureKind = ovl_fail_illegal_constructor;
5917 // C++ [over.match.funcs]p8: (proposed DR resolution)
5918 // A constructor inherited from class type C that has a first parameter
5919 // of type "reference to P" (including such a constructor instantiated
5920 // from a template) is excluded from the set of candidate functions when
5921 // constructing an object of type cv D if the argument list has exactly
5922 // one argument and D is reference-related to P and P is reference-related
5924 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5925 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5926 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5927 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5928 QualType C = Context.getRecordType(Constructor->getParent());
5929 QualType D = Context.getRecordType(Shadow->getParent());
5930 SourceLocation Loc = Args.front()->getExprLoc();
5931 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5932 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5933 Candidate.Viable = false;
5934 Candidate.FailureKind = ovl_fail_inhctor_slice;
5940 unsigned NumParams = Proto->getNumParams();
5942 // (C++ 13.3.2p2): A candidate function having fewer than m
5943 // parameters is viable only if it has an ellipsis in its parameter
5945 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5946 !Proto->isVariadic()) {
5947 Candidate.Viable = false;
5948 Candidate.FailureKind = ovl_fail_too_many_arguments;
5952 // (C++ 13.3.2p2): A candidate function having more than m parameters
5953 // is viable only if the (m+1)st parameter has a default argument
5954 // (8.3.6). For the purposes of overload resolution, the
5955 // parameter list is truncated on the right, so that there are
5956 // exactly m parameters.
5957 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5958 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5959 // Not enough arguments.
5960 Candidate.Viable = false;
5961 Candidate.FailureKind = ovl_fail_too_few_arguments;
5965 // (CUDA B.1): Check for invalid calls between targets.
5966 if (getLangOpts().CUDA)
5967 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5968 // Skip the check for callers that are implicit members, because in this
5969 // case we may not yet know what the member's target is; the target is
5970 // inferred for the member automatically, based on the bases and fields of
5972 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5973 Candidate.Viable = false;
5974 Candidate.FailureKind = ovl_fail_bad_target;
5978 // Determine the implicit conversion sequences for each of the
5980 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5981 if (Candidate.Conversions[ArgIdx].isInitialized()) {
5982 // We already formed a conversion sequence for this parameter during
5983 // template argument deduction.
5984 } else if (ArgIdx < NumParams) {
5985 // (C++ 13.3.2p3): for F to be a viable function, there shall
5986 // exist for each argument an implicit conversion sequence
5987 // (13.3.3.1) that converts that argument to the corresponding
5989 QualType ParamType = Proto->getParamType(ArgIdx);
5990 Candidate.Conversions[ArgIdx]
5991 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5992 SuppressUserConversions,
5993 /*InOverloadResolution=*/true,
5994 /*AllowObjCWritebackConversion=*/
5995 getLangOpts().ObjCAutoRefCount,
5997 if (Candidate.Conversions[ArgIdx].isBad()) {
5998 Candidate.Viable = false;
5999 Candidate.FailureKind = ovl_fail_bad_conversion;
6003 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6004 // argument for which there is no corresponding parameter is
6005 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6006 Candidate.Conversions[ArgIdx].setEllipsis();
6010 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6011 Candidate.Viable = false;
6012 Candidate.FailureKind = ovl_fail_enable_if;
6013 Candidate.DeductionFailure.Data = FailedAttr;
6017 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6018 Candidate.Viable = false;
6019 Candidate.FailureKind = ovl_fail_ext_disabled;
6025 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6026 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6027 if (Methods.size() <= 1)
6030 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6032 ObjCMethodDecl *Method = Methods[b];
6033 unsigned NumNamedArgs = Sel.getNumArgs();
6034 // Method might have more arguments than selector indicates. This is due
6035 // to addition of c-style arguments in method.
6036 if (Method->param_size() > NumNamedArgs)
6037 NumNamedArgs = Method->param_size();
6038 if (Args.size() < NumNamedArgs)
6041 for (unsigned i = 0; i < NumNamedArgs; i++) {
6042 // We can't do any type-checking on a type-dependent argument.
6043 if (Args[i]->isTypeDependent()) {
6048 ParmVarDecl *param = Method->parameters()[i];
6049 Expr *argExpr = Args[i];
6050 assert(argExpr && "SelectBestMethod(): missing expression");
6052 // Strip the unbridged-cast placeholder expression off unless it's
6053 // a consumed argument.
6054 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6055 !param->hasAttr<CFConsumedAttr>())
6056 argExpr = stripARCUnbridgedCast(argExpr);
6058 // If the parameter is __unknown_anytype, move on to the next method.
6059 if (param->getType() == Context.UnknownAnyTy) {
6064 ImplicitConversionSequence ConversionState
6065 = TryCopyInitialization(*this, argExpr, param->getType(),
6066 /*SuppressUserConversions*/false,
6067 /*InOverloadResolution=*/true,
6068 /*AllowObjCWritebackConversion=*/
6069 getLangOpts().ObjCAutoRefCount,
6070 /*AllowExplicit*/false);
6071 // This function looks for a reasonably-exact match, so we consider
6072 // incompatible pointer conversions to be a failure here.
6073 if (ConversionState.isBad() ||
6074 (ConversionState.isStandard() &&
6075 ConversionState.Standard.Second ==
6076 ICK_Incompatible_Pointer_Conversion)) {
6081 // Promote additional arguments to variadic methods.
6082 if (Match && Method->isVariadic()) {
6083 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6084 if (Args[i]->isTypeDependent()) {
6088 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6090 if (Arg.isInvalid()) {
6096 // Check for extra arguments to non-variadic methods.
6097 if (Args.size() != NumNamedArgs)
6099 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6100 // Special case when selectors have no argument. In this case, select
6101 // one with the most general result type of 'id'.
6102 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6103 QualType ReturnT = Methods[b]->getReturnType();
6104 if (ReturnT->isObjCIdType())
6116 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6117 // enable_if is order-sensitive. As a result, we need to reverse things
6118 // sometimes. Size of 4 elements is arbitrary.
6119 static SmallVector<EnableIfAttr *, 4>
6120 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6121 SmallVector<EnableIfAttr *, 4> Result;
6122 if (!Function->hasAttrs())
6125 const auto &FuncAttrs = Function->getAttrs();
6126 for (Attr *Attr : FuncAttrs)
6127 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6128 Result.push_back(EnableIf);
6130 std::reverse(Result.begin(), Result.end());
6135 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6136 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6137 bool MissingImplicitThis, Expr *&ConvertedThis,
6138 SmallVectorImpl<Expr *> &ConvertedArgs) {
6140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6141 assert(!isa<CXXConstructorDecl>(Method) &&
6142 "Shouldn't have `this` for ctors!");
6143 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6144 ExprResult R = S.PerformObjectArgumentInitialization(
6145 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6148 ConvertedThis = R.get();
6150 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6152 assert((MissingImplicitThis || MD->isStatic() ||
6153 isa<CXXConstructorDecl>(MD)) &&
6154 "Expected `this` for non-ctor instance methods");
6156 ConvertedThis = nullptr;
6159 // Ignore any variadic arguments. Converting them is pointless, since the
6160 // user can't refer to them in the function condition.
6161 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6163 // Convert the arguments.
6164 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6166 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6167 S.Context, Function->getParamDecl(I)),
6168 SourceLocation(), Args[I]);
6173 ConvertedArgs.push_back(R.get());
6176 if (Trap.hasErrorOccurred())
6179 // Push default arguments if needed.
6180 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6181 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6182 ParmVarDecl *P = Function->getParamDecl(i);
6183 ExprResult R = S.PerformCopyInitialization(
6184 InitializedEntity::InitializeParameter(S.Context,
6185 Function->getParamDecl(i)),
6187 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6188 : P->getDefaultArg());
6191 ConvertedArgs.push_back(R.get());
6194 if (Trap.hasErrorOccurred())
6200 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6201 bool MissingImplicitThis) {
6202 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6203 getOrderedEnableIfAttrs(Function);
6204 if (EnableIfAttrs.empty())
6207 SFINAETrap Trap(*this);
6208 SmallVector<Expr *, 16> ConvertedArgs;
6209 // FIXME: We should look into making enable_if late-parsed.
6210 Expr *DiscardedThis;
6211 if (!convertArgsForAvailabilityChecks(
6212 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6213 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6214 return EnableIfAttrs[0];
6216 for (auto *EIA : EnableIfAttrs) {
6218 // FIXME: This doesn't consider value-dependent cases, because doing so is
6219 // very difficult. Ideally, we should handle them more gracefully.
6220 if (!EIA->getCond()->EvaluateWithSubstitution(
6221 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6224 if (!Result.isInt() || !Result.getInt().getBoolValue())
6230 template <typename CheckFn>
6231 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD,
6232 bool ArgDependent, SourceLocation Loc,
6233 CheckFn &&IsSuccessful) {
6234 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6235 for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) {
6236 if (ArgDependent == DIA->getArgDependent())
6237 Attrs.push_back(DIA);
6240 // Common case: No diagnose_if attributes, so we can quit early.
6244 auto WarningBegin = std::stable_partition(
6245 Attrs.begin(), Attrs.end(),
6246 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6248 // Note that diagnose_if attributes are late-parsed, so they appear in the
6249 // correct order (unlike enable_if attributes).
6250 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6252 if (ErrAttr != WarningBegin) {
6253 const DiagnoseIfAttr *DIA = *ErrAttr;
6254 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6255 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6256 << DIA->getParent() << DIA->getCond()->getSourceRange();
6260 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6261 if (IsSuccessful(DIA)) {
6262 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6263 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6264 << DIA->getParent() << DIA->getCond()->getSourceRange();
6270 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6271 const Expr *ThisArg,
6272 ArrayRef<const Expr *> Args,
6273 SourceLocation Loc) {
6274 return diagnoseDiagnoseIfAttrsWith(
6275 *this, Function, /*ArgDependent=*/true, Loc,
6276 [&](const DiagnoseIfAttr *DIA) {
6278 // It's sane to use the same Args for any redecl of this function, since
6279 // EvaluateWithSubstitution only cares about the position of each
6280 // argument in the arg list, not the ParmVarDecl* it maps to.
6281 if (!DIA->getCond()->EvaluateWithSubstitution(
6282 Result, Context, DIA->getParent(), Args, ThisArg))
6284 return Result.isInt() && Result.getInt().getBoolValue();
6288 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
6289 SourceLocation Loc) {
6290 return diagnoseDiagnoseIfAttrsWith(
6291 *this, Function, /*ArgDependent=*/false, Loc,
6292 [&](const DiagnoseIfAttr *DIA) {
6294 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6299 /// \brief Add all of the function declarations in the given function set to
6300 /// the overload candidate set.
6301 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6302 ArrayRef<Expr *> Args,
6303 OverloadCandidateSet& CandidateSet,
6304 TemplateArgumentListInfo *ExplicitTemplateArgs,
6305 bool SuppressUserConversions,
6306 bool PartialOverloading) {
6307 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6308 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6310 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6311 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6312 cast<CXXMethodDecl>(FD)->getParent(),
6313 Args[0]->getType(), Args[0]->Classify(Context),
6314 Args.slice(1), CandidateSet, SuppressUserConversions,
6315 PartialOverloading);
6317 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6318 SuppressUserConversions, PartialOverloading);
6320 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6321 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6322 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6323 AddMethodTemplateCandidate(
6324 FunTmpl, F.getPair(),
6325 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6326 ExplicitTemplateArgs, Args[0]->getType(),
6327 Args[0]->Classify(Context), Args.slice(1), CandidateSet,
6328 SuppressUserConversions, PartialOverloading);
6330 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6331 ExplicitTemplateArgs, Args,
6332 CandidateSet, SuppressUserConversions,
6333 PartialOverloading);
6338 /// AddMethodCandidate - Adds a named decl (which is some kind of
6339 /// method) as a method candidate to the given overload set.
6340 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6341 QualType ObjectType,
6342 Expr::Classification ObjectClassification,
6343 ArrayRef<Expr *> Args,
6344 OverloadCandidateSet& CandidateSet,
6345 bool SuppressUserConversions) {
6346 NamedDecl *Decl = FoundDecl.getDecl();
6347 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6349 if (isa<UsingShadowDecl>(Decl))
6350 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6352 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6353 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6354 "Expected a member function template");
6355 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6356 /*ExplicitArgs*/ nullptr, ObjectType,
6357 ObjectClassification, Args, CandidateSet,
6358 SuppressUserConversions);
6360 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6361 ObjectType, ObjectClassification, Args, CandidateSet,
6362 SuppressUserConversions);
6366 /// AddMethodCandidate - Adds the given C++ member function to the set
6367 /// of candidate functions, using the given function call arguments
6368 /// and the object argument (@c Object). For example, in a call
6369 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6370 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6371 /// allow user-defined conversions via constructors or conversion
6374 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6375 CXXRecordDecl *ActingContext, QualType ObjectType,
6376 Expr::Classification ObjectClassification,
6377 ArrayRef<Expr *> Args,
6378 OverloadCandidateSet &CandidateSet,
6379 bool SuppressUserConversions,
6380 bool PartialOverloading,
6381 ConversionSequenceList EarlyConversions) {
6382 const FunctionProtoType *Proto
6383 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6384 assert(Proto && "Methods without a prototype cannot be overloaded");
6385 assert(!isa<CXXConstructorDecl>(Method) &&
6386 "Use AddOverloadCandidate for constructors");
6388 if (!CandidateSet.isNewCandidate(Method))
6391 // C++11 [class.copy]p23: [DR1402]
6392 // A defaulted move assignment operator that is defined as deleted is
6393 // ignored by overload resolution.
6394 if (Method->isDefaulted() && Method->isDeleted() &&
6395 Method->isMoveAssignmentOperator())
6398 // Overload resolution is always an unevaluated context.
6399 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6401 // Add this candidate
6402 OverloadCandidate &Candidate =
6403 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6404 Candidate.FoundDecl = FoundDecl;
6405 Candidate.Function = Method;
6406 Candidate.IsSurrogate = false;
6407 Candidate.IgnoreObjectArgument = false;
6408 Candidate.ExplicitCallArguments = Args.size();
6410 unsigned NumParams = Proto->getNumParams();
6412 // (C++ 13.3.2p2): A candidate function having fewer than m
6413 // parameters is viable only if it has an ellipsis in its parameter
6415 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6416 !Proto->isVariadic()) {
6417 Candidate.Viable = false;
6418 Candidate.FailureKind = ovl_fail_too_many_arguments;
6422 // (C++ 13.3.2p2): A candidate function having more than m parameters
6423 // is viable only if the (m+1)st parameter has a default argument
6424 // (8.3.6). For the purposes of overload resolution, the
6425 // parameter list is truncated on the right, so that there are
6426 // exactly m parameters.
6427 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6428 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6429 // Not enough arguments.
6430 Candidate.Viable = false;
6431 Candidate.FailureKind = ovl_fail_too_few_arguments;
6435 Candidate.Viable = true;
6437 if (Method->isStatic() || ObjectType.isNull())
6438 // The implicit object argument is ignored.
6439 Candidate.IgnoreObjectArgument = true;
6441 // Determine the implicit conversion sequence for the object
6443 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6444 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6445 Method, ActingContext);
6446 if (Candidate.Conversions[0].isBad()) {
6447 Candidate.Viable = false;
6448 Candidate.FailureKind = ovl_fail_bad_conversion;
6453 // (CUDA B.1): Check for invalid calls between targets.
6454 if (getLangOpts().CUDA)
6455 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6456 if (!IsAllowedCUDACall(Caller, Method)) {
6457 Candidate.Viable = false;
6458 Candidate.FailureKind = ovl_fail_bad_target;
6462 // Determine the implicit conversion sequences for each of the
6464 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6465 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6466 // We already formed a conversion sequence for this parameter during
6467 // template argument deduction.
6468 } else if (ArgIdx < NumParams) {
6469 // (C++ 13.3.2p3): for F to be a viable function, there shall
6470 // exist for each argument an implicit conversion sequence
6471 // (13.3.3.1) that converts that argument to the corresponding
6473 QualType ParamType = Proto->getParamType(ArgIdx);
6474 Candidate.Conversions[ArgIdx + 1]
6475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6476 SuppressUserConversions,
6477 /*InOverloadResolution=*/true,
6478 /*AllowObjCWritebackConversion=*/
6479 getLangOpts().ObjCAutoRefCount);
6480 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6481 Candidate.Viable = false;
6482 Candidate.FailureKind = ovl_fail_bad_conversion;
6486 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6487 // argument for which there is no corresponding parameter is
6488 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6489 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6494 Candidate.Viable = false;
6495 Candidate.FailureKind = ovl_fail_enable_if;
6496 Candidate.DeductionFailure.Data = FailedAttr;
6501 /// \brief Add a C++ member function template as a candidate to the candidate
6502 /// set, using template argument deduction to produce an appropriate member
6503 /// function template specialization.
6505 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6506 DeclAccessPair FoundDecl,
6507 CXXRecordDecl *ActingContext,
6508 TemplateArgumentListInfo *ExplicitTemplateArgs,
6509 QualType ObjectType,
6510 Expr::Classification ObjectClassification,
6511 ArrayRef<Expr *> Args,
6512 OverloadCandidateSet& CandidateSet,
6513 bool SuppressUserConversions,
6514 bool PartialOverloading) {
6515 if (!CandidateSet.isNewCandidate(MethodTmpl))
6518 // C++ [over.match.funcs]p7:
6519 // In each case where a candidate is a function template, candidate
6520 // function template specializations are generated using template argument
6521 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6522 // candidate functions in the usual way.113) A given name can refer to one
6523 // or more function templates and also to a set of overloaded non-template
6524 // functions. In such a case, the candidate functions generated from each
6525 // function template are combined with the set of non-template candidate
6527 TemplateDeductionInfo Info(CandidateSet.getLocation());
6528 FunctionDecl *Specialization = nullptr;
6529 ConversionSequenceList Conversions;
6530 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6531 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6532 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6533 return CheckNonDependentConversions(
6534 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6535 SuppressUserConversions, ActingContext, ObjectType,
6536 ObjectClassification);
6538 OverloadCandidate &Candidate =
6539 CandidateSet.addCandidate(Conversions.size(), Conversions);
6540 Candidate.FoundDecl = FoundDecl;
6541 Candidate.Function = MethodTmpl->getTemplatedDecl();
6542 Candidate.Viable = false;
6543 Candidate.IsSurrogate = false;
6544 Candidate.IgnoreObjectArgument =
6545 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6546 ObjectType.isNull();
6547 Candidate.ExplicitCallArguments = Args.size();
6548 if (Result == TDK_NonDependentConversionFailure)
6549 Candidate.FailureKind = ovl_fail_bad_conversion;
6551 Candidate.FailureKind = ovl_fail_bad_deduction;
6552 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6558 // Add the function template specialization produced by template argument
6559 // deduction as a candidate.
6560 assert(Specialization && "Missing member function template specialization?");
6561 assert(isa<CXXMethodDecl>(Specialization) &&
6562 "Specialization is not a member function?");
6563 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6564 ActingContext, ObjectType, ObjectClassification, Args,
6565 CandidateSet, SuppressUserConversions, PartialOverloading,
6569 /// \brief Add a C++ function template specialization as a candidate
6570 /// in the candidate set, using template argument deduction to produce
6571 /// an appropriate function template specialization.
6573 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6574 DeclAccessPair FoundDecl,
6575 TemplateArgumentListInfo *ExplicitTemplateArgs,
6576 ArrayRef<Expr *> Args,
6577 OverloadCandidateSet& CandidateSet,
6578 bool SuppressUserConversions,
6579 bool PartialOverloading) {
6580 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6583 // C++ [over.match.funcs]p7:
6584 // In each case where a candidate is a function template, candidate
6585 // function template specializations are generated using template argument
6586 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6587 // candidate functions in the usual way.113) A given name can refer to one
6588 // or more function templates and also to a set of overloaded non-template
6589 // functions. In such a case, the candidate functions generated from each
6590 // function template are combined with the set of non-template candidate
6592 TemplateDeductionInfo Info(CandidateSet.getLocation());
6593 FunctionDecl *Specialization = nullptr;
6594 ConversionSequenceList Conversions;
6595 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6596 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6597 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6598 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6599 Args, CandidateSet, Conversions,
6600 SuppressUserConversions);
6602 OverloadCandidate &Candidate =
6603 CandidateSet.addCandidate(Conversions.size(), Conversions);
6604 Candidate.FoundDecl = FoundDecl;
6605 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6606 Candidate.Viable = false;
6607 Candidate.IsSurrogate = false;
6608 // Ignore the object argument if there is one, since we don't have an object
6610 Candidate.IgnoreObjectArgument =
6611 isa<CXXMethodDecl>(Candidate.Function) &&
6612 !isa<CXXConstructorDecl>(Candidate.Function);
6613 Candidate.ExplicitCallArguments = Args.size();
6614 if (Result == TDK_NonDependentConversionFailure)
6615 Candidate.FailureKind = ovl_fail_bad_conversion;
6617 Candidate.FailureKind = ovl_fail_bad_deduction;
6618 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6624 // Add the function template specialization produced by template argument
6625 // deduction as a candidate.
6626 assert(Specialization && "Missing function template specialization?");
6627 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6628 SuppressUserConversions, PartialOverloading,
6629 /*AllowExplicit*/false, Conversions);
6632 /// Check that implicit conversion sequences can be formed for each argument
6633 /// whose corresponding parameter has a non-dependent type, per DR1391's
6634 /// [temp.deduct.call]p10.
6635 bool Sema::CheckNonDependentConversions(
6636 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6637 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6638 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6639 CXXRecordDecl *ActingContext, QualType ObjectType,
6640 Expr::Classification ObjectClassification) {
6641 // FIXME: The cases in which we allow explicit conversions for constructor
6642 // arguments never consider calling a constructor template. It's not clear
6644 const bool AllowExplicit = false;
6646 auto *FD = FunctionTemplate->getTemplatedDecl();
6647 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6648 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6649 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6652 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6654 // Overload resolution is always an unevaluated context.
6655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6657 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6658 // require that, but this check should never result in a hard error, and
6659 // overload resolution is permitted to sidestep instantiations.
6660 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6661 !ObjectType.isNull()) {
6662 Conversions[0] = TryObjectArgumentInitialization(
6663 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6664 Method, ActingContext);
6665 if (Conversions[0].isBad())
6669 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6671 QualType ParamType = ParamTypes[I];
6672 if (!ParamType->isDependentType()) {
6673 Conversions[ThisConversions + I]
6674 = TryCopyInitialization(*this, Args[I], ParamType,
6675 SuppressUserConversions,
6676 /*InOverloadResolution=*/true,
6677 /*AllowObjCWritebackConversion=*/
6678 getLangOpts().ObjCAutoRefCount,
6680 if (Conversions[ThisConversions + I].isBad())
6688 /// Determine whether this is an allowable conversion from the result
6689 /// of an explicit conversion operator to the expected type, per C++
6690 /// [over.match.conv]p1 and [over.match.ref]p1.
6692 /// \param ConvType The return type of the conversion function.
6694 /// \param ToType The type we are converting to.
6696 /// \param AllowObjCPointerConversion Allow a conversion from one
6697 /// Objective-C pointer to another.
6699 /// \returns true if the conversion is allowable, false otherwise.
6700 static bool isAllowableExplicitConversion(Sema &S,
6701 QualType ConvType, QualType ToType,
6702 bool AllowObjCPointerConversion) {
6703 QualType ToNonRefType = ToType.getNonReferenceType();
6705 // Easy case: the types are the same.
6706 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6709 // Allow qualification conversions.
6710 bool ObjCLifetimeConversion;
6711 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6712 ObjCLifetimeConversion))
6715 // If we're not allowed to consider Objective-C pointer conversions,
6717 if (!AllowObjCPointerConversion)
6720 // Is this an Objective-C pointer conversion?
6721 bool IncompatibleObjC = false;
6722 QualType ConvertedType;
6723 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6727 /// AddConversionCandidate - Add a C++ conversion function as a
6728 /// candidate in the candidate set (C++ [over.match.conv],
6729 /// C++ [over.match.copy]). From is the expression we're converting from,
6730 /// and ToType is the type that we're eventually trying to convert to
6731 /// (which may or may not be the same type as the type that the
6732 /// conversion function produces).
6734 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6735 DeclAccessPair FoundDecl,
6736 CXXRecordDecl *ActingContext,
6737 Expr *From, QualType ToType,
6738 OverloadCandidateSet& CandidateSet,
6739 bool AllowObjCConversionOnExplicit) {
6740 assert(!Conversion->getDescribedFunctionTemplate() &&
6741 "Conversion function templates use AddTemplateConversionCandidate");
6742 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6743 if (!CandidateSet.isNewCandidate(Conversion))
6746 // If the conversion function has an undeduced return type, trigger its
6748 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6749 if (DeduceReturnType(Conversion, From->getExprLoc()))
6751 ConvType = Conversion->getConversionType().getNonReferenceType();
6754 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6755 // operator is only a candidate if its return type is the target type or
6756 // can be converted to the target type with a qualification conversion.
6757 if (Conversion->isExplicit() &&
6758 !isAllowableExplicitConversion(*this, ConvType, ToType,
6759 AllowObjCConversionOnExplicit))
6762 // Overload resolution is always an unevaluated context.
6763 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6765 // Add this candidate
6766 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6767 Candidate.FoundDecl = FoundDecl;
6768 Candidate.Function = Conversion;
6769 Candidate.IsSurrogate = false;
6770 Candidate.IgnoreObjectArgument = false;
6771 Candidate.FinalConversion.setAsIdentityConversion();
6772 Candidate.FinalConversion.setFromType(ConvType);
6773 Candidate.FinalConversion.setAllToTypes(ToType);
6774 Candidate.Viable = true;
6775 Candidate.ExplicitCallArguments = 1;
6777 // C++ [over.match.funcs]p4:
6778 // For conversion functions, the function is considered to be a member of
6779 // the class of the implicit implied object argument for the purpose of
6780 // defining the type of the implicit object parameter.
6782 // Determine the implicit conversion sequence for the implicit
6783 // object parameter.
6784 QualType ImplicitParamType = From->getType();
6785 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6786 ImplicitParamType = FromPtrType->getPointeeType();
6787 CXXRecordDecl *ConversionContext
6788 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6790 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6791 *this, CandidateSet.getLocation(), From->getType(),
6792 From->Classify(Context), Conversion, ConversionContext);
6794 if (Candidate.Conversions[0].isBad()) {
6795 Candidate.Viable = false;
6796 Candidate.FailureKind = ovl_fail_bad_conversion;
6800 // We won't go through a user-defined type conversion function to convert a
6801 // derived to base as such conversions are given Conversion Rank. They only
6802 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6804 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6805 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6806 if (FromCanon == ToCanon ||
6807 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6808 Candidate.Viable = false;
6809 Candidate.FailureKind = ovl_fail_trivial_conversion;
6813 // To determine what the conversion from the result of calling the
6814 // conversion function to the type we're eventually trying to
6815 // convert to (ToType), we need to synthesize a call to the
6816 // conversion function and attempt copy initialization from it. This
6817 // makes sure that we get the right semantics with respect to
6818 // lvalues/rvalues and the type. Fortunately, we can allocate this
6819 // call on the stack and we don't need its arguments to be
6821 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6822 VK_LValue, From->getLocStart());
6823 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6824 Context.getPointerType(Conversion->getType()),
6825 CK_FunctionToPointerDecay,
6826 &ConversionRef, VK_RValue);
6828 QualType ConversionType = Conversion->getConversionType();
6829 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6830 Candidate.Viable = false;
6831 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6835 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6837 // Note that it is safe to allocate CallExpr on the stack here because
6838 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6840 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6841 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6842 From->getLocStart());
6843 ImplicitConversionSequence ICS =
6844 TryCopyInitialization(*this, &Call, ToType,
6845 /*SuppressUserConversions=*/true,
6846 /*InOverloadResolution=*/false,
6847 /*AllowObjCWritebackConversion=*/false);
6849 switch (ICS.getKind()) {
6850 case ImplicitConversionSequence::StandardConversion:
6851 Candidate.FinalConversion = ICS.Standard;
6853 // C++ [over.ics.user]p3:
6854 // If the user-defined conversion is specified by a specialization of a
6855 // conversion function template, the second standard conversion sequence
6856 // shall have exact match rank.
6857 if (Conversion->getPrimaryTemplate() &&
6858 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6859 Candidate.Viable = false;
6860 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6864 // C++0x [dcl.init.ref]p5:
6865 // In the second case, if the reference is an rvalue reference and
6866 // the second standard conversion sequence of the user-defined
6867 // conversion sequence includes an lvalue-to-rvalue conversion, the
6868 // program is ill-formed.
6869 if (ToType->isRValueReferenceType() &&
6870 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6871 Candidate.Viable = false;
6872 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6877 case ImplicitConversionSequence::BadConversion:
6878 Candidate.Viable = false;
6879 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6884 "Can only end up with a standard conversion sequence or failure");
6887 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6888 Candidate.Viable = false;
6889 Candidate.FailureKind = ovl_fail_enable_if;
6890 Candidate.DeductionFailure.Data = FailedAttr;
6895 /// \brief Adds a conversion function template specialization
6896 /// candidate to the overload set, using template argument deduction
6897 /// to deduce the template arguments of the conversion function
6898 /// template from the type that we are converting to (C++
6899 /// [temp.deduct.conv]).
6901 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6902 DeclAccessPair FoundDecl,
6903 CXXRecordDecl *ActingDC,
6904 Expr *From, QualType ToType,
6905 OverloadCandidateSet &CandidateSet,
6906 bool AllowObjCConversionOnExplicit) {
6907 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6908 "Only conversion function templates permitted here");
6910 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6913 TemplateDeductionInfo Info(CandidateSet.getLocation());
6914 CXXConversionDecl *Specialization = nullptr;
6915 if (TemplateDeductionResult Result
6916 = DeduceTemplateArguments(FunctionTemplate, ToType,
6917 Specialization, Info)) {
6918 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6919 Candidate.FoundDecl = FoundDecl;
6920 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6921 Candidate.Viable = false;
6922 Candidate.FailureKind = ovl_fail_bad_deduction;
6923 Candidate.IsSurrogate = false;
6924 Candidate.IgnoreObjectArgument = false;
6925 Candidate.ExplicitCallArguments = 1;
6926 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6931 // Add the conversion function template specialization produced by
6932 // template argument deduction as a candidate.
6933 assert(Specialization && "Missing function template specialization?");
6934 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6935 CandidateSet, AllowObjCConversionOnExplicit);
6938 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6939 /// converts the given @c Object to a function pointer via the
6940 /// conversion function @c Conversion, and then attempts to call it
6941 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6942 /// the type of function that we'll eventually be calling.
6943 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6944 DeclAccessPair FoundDecl,
6945 CXXRecordDecl *ActingContext,
6946 const FunctionProtoType *Proto,
6948 ArrayRef<Expr *> Args,
6949 OverloadCandidateSet& CandidateSet) {
6950 if (!CandidateSet.isNewCandidate(Conversion))
6953 // Overload resolution is always an unevaluated context.
6954 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6956 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6957 Candidate.FoundDecl = FoundDecl;
6958 Candidate.Function = nullptr;
6959 Candidate.Surrogate = Conversion;
6960 Candidate.Viable = true;
6961 Candidate.IsSurrogate = true;
6962 Candidate.IgnoreObjectArgument = false;
6963 Candidate.ExplicitCallArguments = Args.size();
6965 // Determine the implicit conversion sequence for the implicit
6966 // object parameter.
6967 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6968 *this, CandidateSet.getLocation(), Object->getType(),
6969 Object->Classify(Context), Conversion, ActingContext);
6970 if (ObjectInit.isBad()) {
6971 Candidate.Viable = false;
6972 Candidate.FailureKind = ovl_fail_bad_conversion;
6973 Candidate.Conversions[0] = ObjectInit;
6977 // The first conversion is actually a user-defined conversion whose
6978 // first conversion is ObjectInit's standard conversion (which is
6979 // effectively a reference binding). Record it as such.
6980 Candidate.Conversions[0].setUserDefined();
6981 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6982 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6983 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6984 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6985 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6986 Candidate.Conversions[0].UserDefined.After
6987 = Candidate.Conversions[0].UserDefined.Before;
6988 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6991 unsigned NumParams = Proto->getNumParams();
6993 // (C++ 13.3.2p2): A candidate function having fewer than m
6994 // parameters is viable only if it has an ellipsis in its parameter
6996 if (Args.size() > NumParams && !Proto->isVariadic()) {
6997 Candidate.Viable = false;
6998 Candidate.FailureKind = ovl_fail_too_many_arguments;
7002 // Function types don't have any default arguments, so just check if
7003 // we have enough arguments.
7004 if (Args.size() < NumParams) {
7005 // Not enough arguments.
7006 Candidate.Viable = false;
7007 Candidate.FailureKind = ovl_fail_too_few_arguments;
7011 // Determine the implicit conversion sequences for each of the
7013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7014 if (ArgIdx < NumParams) {
7015 // (C++ 13.3.2p3): for F to be a viable function, there shall
7016 // exist for each argument an implicit conversion sequence
7017 // (13.3.3.1) that converts that argument to the corresponding
7019 QualType ParamType = Proto->getParamType(ArgIdx);
7020 Candidate.Conversions[ArgIdx + 1]
7021 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7022 /*SuppressUserConversions=*/false,
7023 /*InOverloadResolution=*/false,
7024 /*AllowObjCWritebackConversion=*/
7025 getLangOpts().ObjCAutoRefCount);
7026 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7027 Candidate.Viable = false;
7028 Candidate.FailureKind = ovl_fail_bad_conversion;
7032 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7033 // argument for which there is no corresponding parameter is
7034 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7035 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7039 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7040 Candidate.Viable = false;
7041 Candidate.FailureKind = ovl_fail_enable_if;
7042 Candidate.DeductionFailure.Data = FailedAttr;
7047 /// \brief Add overload candidates for overloaded operators that are
7048 /// member functions.
7050 /// Add the overloaded operator candidates that are member functions
7051 /// for the operator Op that was used in an operator expression such
7052 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7053 /// CandidateSet will store the added overload candidates. (C++
7054 /// [over.match.oper]).
7055 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7056 SourceLocation OpLoc,
7057 ArrayRef<Expr *> Args,
7058 OverloadCandidateSet& CandidateSet,
7059 SourceRange OpRange) {
7060 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7062 // C++ [over.match.oper]p3:
7063 // For a unary operator @ with an operand of a type whose
7064 // cv-unqualified version is T1, and for a binary operator @ with
7065 // a left operand of a type whose cv-unqualified version is T1 and
7066 // a right operand of a type whose cv-unqualified version is T2,
7067 // three sets of candidate functions, designated member
7068 // candidates, non-member candidates and built-in candidates, are
7069 // constructed as follows:
7070 QualType T1 = Args[0]->getType();
7072 // -- If T1 is a complete class type or a class currently being
7073 // defined, the set of member candidates is the result of the
7074 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7075 // the set of member candidates is empty.
7076 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7077 // Complete the type if it can be completed.
7078 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7080 // If the type is neither complete nor being defined, bail out now.
7081 if (!T1Rec->getDecl()->getDefinition())
7084 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7085 LookupQualifiedName(Operators, T1Rec->getDecl());
7086 Operators.suppressDiagnostics();
7088 for (LookupResult::iterator Oper = Operators.begin(),
7089 OperEnd = Operators.end();
7092 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7093 Args[0]->Classify(Context), Args.slice(1),
7094 CandidateSet, /*SuppressUserConversions=*/false);
7098 /// AddBuiltinCandidate - Add a candidate for a built-in
7099 /// operator. ResultTy and ParamTys are the result and parameter types
7100 /// of the built-in candidate, respectively. Args and NumArgs are the
7101 /// arguments being passed to the candidate. IsAssignmentOperator
7102 /// should be true when this built-in candidate is an assignment
7103 /// operator. NumContextualBoolArguments is the number of arguments
7104 /// (at the beginning of the argument list) that will be contextually
7105 /// converted to bool.
7106 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
7107 ArrayRef<Expr *> Args,
7108 OverloadCandidateSet& CandidateSet,
7109 bool IsAssignmentOperator,
7110 unsigned NumContextualBoolArguments) {
7111 // Overload resolution is always an unevaluated context.
7112 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
7114 // Add this candidate
7115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7116 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7117 Candidate.Function = nullptr;
7118 Candidate.IsSurrogate = false;
7119 Candidate.IgnoreObjectArgument = false;
7120 Candidate.BuiltinTypes.ResultTy = ResultTy;
7121 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7122 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7124 // Determine the implicit conversion sequences for each of the
7126 Candidate.Viable = true;
7127 Candidate.ExplicitCallArguments = Args.size();
7128 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7129 // C++ [over.match.oper]p4:
7130 // For the built-in assignment operators, conversions of the
7131 // left operand are restricted as follows:
7132 // -- no temporaries are introduced to hold the left operand, and
7133 // -- no user-defined conversions are applied to the left
7134 // operand to achieve a type match with the left-most
7135 // parameter of a built-in candidate.
7137 // We block these conversions by turning off user-defined
7138 // conversions, since that is the only way that initialization of
7139 // a reference to a non-class type can occur from something that
7140 // is not of the same type.
7141 if (ArgIdx < NumContextualBoolArguments) {
7142 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7143 "Contextual conversion to bool requires bool type");
7144 Candidate.Conversions[ArgIdx]
7145 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7147 Candidate.Conversions[ArgIdx]
7148 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7149 ArgIdx == 0 && IsAssignmentOperator,
7150 /*InOverloadResolution=*/false,
7151 /*AllowObjCWritebackConversion=*/
7152 getLangOpts().ObjCAutoRefCount);
7154 if (Candidate.Conversions[ArgIdx].isBad()) {
7155 Candidate.Viable = false;
7156 Candidate.FailureKind = ovl_fail_bad_conversion;
7164 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7165 /// candidate operator functions for built-in operators (C++
7166 /// [over.built]). The types are separated into pointer types and
7167 /// enumeration types.
7168 class BuiltinCandidateTypeSet {
7169 /// TypeSet - A set of types.
7170 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7171 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7173 /// PointerTypes - The set of pointer types that will be used in the
7174 /// built-in candidates.
7175 TypeSet PointerTypes;
7177 /// MemberPointerTypes - The set of member pointer types that will be
7178 /// used in the built-in candidates.
7179 TypeSet MemberPointerTypes;
7181 /// EnumerationTypes - The set of enumeration types that will be
7182 /// used in the built-in candidates.
7183 TypeSet EnumerationTypes;
7185 /// \brief The set of vector types that will be used in the built-in
7187 TypeSet VectorTypes;
7189 /// \brief A flag indicating non-record types are viable candidates
7190 bool HasNonRecordTypes;
7192 /// \brief A flag indicating whether either arithmetic or enumeration types
7193 /// were present in the candidate set.
7194 bool HasArithmeticOrEnumeralTypes;
7196 /// \brief A flag indicating whether the nullptr type was present in the
7198 bool HasNullPtrType;
7200 /// Sema - The semantic analysis instance where we are building the
7201 /// candidate type set.
7204 /// Context - The AST context in which we will build the type sets.
7205 ASTContext &Context;
7207 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7208 const Qualifiers &VisibleQuals);
7209 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7212 /// iterator - Iterates through the types that are part of the set.
7213 typedef TypeSet::iterator iterator;
7215 BuiltinCandidateTypeSet(Sema &SemaRef)
7216 : HasNonRecordTypes(false),
7217 HasArithmeticOrEnumeralTypes(false),
7218 HasNullPtrType(false),
7220 Context(SemaRef.Context) { }
7222 void AddTypesConvertedFrom(QualType Ty,
7224 bool AllowUserConversions,
7225 bool AllowExplicitConversions,
7226 const Qualifiers &VisibleTypeConversionsQuals);
7228 /// pointer_begin - First pointer type found;
7229 iterator pointer_begin() { return PointerTypes.begin(); }
7231 /// pointer_end - Past the last pointer type found;
7232 iterator pointer_end() { return PointerTypes.end(); }
7234 /// member_pointer_begin - First member pointer type found;
7235 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7237 /// member_pointer_end - Past the last member pointer type found;
7238 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7240 /// enumeration_begin - First enumeration type found;
7241 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7243 /// enumeration_end - Past the last enumeration type found;
7244 iterator enumeration_end() { return EnumerationTypes.end(); }
7246 iterator vector_begin() { return VectorTypes.begin(); }
7247 iterator vector_end() { return VectorTypes.end(); }
7249 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7250 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7251 bool hasNullPtrType() const { return HasNullPtrType; }
7254 } // end anonymous namespace
7256 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7257 /// the set of pointer types along with any more-qualified variants of
7258 /// that type. For example, if @p Ty is "int const *", this routine
7259 /// will add "int const *", "int const volatile *", "int const
7260 /// restrict *", and "int const volatile restrict *" to the set of
7261 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7262 /// false otherwise.
7264 /// FIXME: what to do about extended qualifiers?
7266 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7267 const Qualifiers &VisibleQuals) {
7269 // Insert this type.
7270 if (!PointerTypes.insert(Ty))
7274 const PointerType *PointerTy = Ty->getAs<PointerType>();
7275 bool buildObjCPtr = false;
7277 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7278 PointeeTy = PTy->getPointeeType();
7279 buildObjCPtr = true;
7281 PointeeTy = PointerTy->getPointeeType();
7284 // Don't add qualified variants of arrays. For one, they're not allowed
7285 // (the qualifier would sink to the element type), and for another, the
7286 // only overload situation where it matters is subscript or pointer +- int,
7287 // and those shouldn't have qualifier variants anyway.
7288 if (PointeeTy->isArrayType())
7291 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7292 bool hasVolatile = VisibleQuals.hasVolatile();
7293 bool hasRestrict = VisibleQuals.hasRestrict();
7295 // Iterate through all strict supersets of BaseCVR.
7296 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7297 if ((CVR | BaseCVR) != CVR) continue;
7298 // Skip over volatile if no volatile found anywhere in the types.
7299 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7301 // Skip over restrict if no restrict found anywhere in the types, or if
7302 // the type cannot be restrict-qualified.
7303 if ((CVR & Qualifiers::Restrict) &&
7305 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7308 // Build qualified pointee type.
7309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7311 // Build qualified pointer type.
7312 QualType QPointerTy;
7314 QPointerTy = Context.getPointerType(QPointeeTy);
7316 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7318 // Insert qualified pointer type.
7319 PointerTypes.insert(QPointerTy);
7325 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7326 /// to the set of pointer types along with any more-qualified variants of
7327 /// that type. For example, if @p Ty is "int const *", this routine
7328 /// will add "int const *", "int const volatile *", "int const
7329 /// restrict *", and "int const volatile restrict *" to the set of
7330 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7331 /// false otherwise.
7333 /// FIXME: what to do about extended qualifiers?
7335 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7337 // Insert this type.
7338 if (!MemberPointerTypes.insert(Ty))
7341 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7342 assert(PointerTy && "type was not a member pointer type!");
7344 QualType PointeeTy = PointerTy->getPointeeType();
7345 // Don't add qualified variants of arrays. For one, they're not allowed
7346 // (the qualifier would sink to the element type), and for another, the
7347 // only overload situation where it matters is subscript or pointer +- int,
7348 // and those shouldn't have qualifier variants anyway.
7349 if (PointeeTy->isArrayType())
7351 const Type *ClassTy = PointerTy->getClass();
7353 // Iterate through all strict supersets of the pointee type's CVR
7355 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7356 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7357 if ((CVR | BaseCVR) != CVR) continue;
7359 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7360 MemberPointerTypes.insert(
7361 Context.getMemberPointerType(QPointeeTy, ClassTy));
7367 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7368 /// Ty can be implicit converted to the given set of @p Types. We're
7369 /// primarily interested in pointer types and enumeration types. We also
7370 /// take member pointer types, for the conditional operator.
7371 /// AllowUserConversions is true if we should look at the conversion
7372 /// functions of a class type, and AllowExplicitConversions if we
7373 /// should also include the explicit conversion functions of a class
7376 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7378 bool AllowUserConversions,
7379 bool AllowExplicitConversions,
7380 const Qualifiers &VisibleQuals) {
7381 // Only deal with canonical types.
7382 Ty = Context.getCanonicalType(Ty);
7384 // Look through reference types; they aren't part of the type of an
7385 // expression for the purposes of conversions.
7386 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7387 Ty = RefTy->getPointeeType();
7389 // If we're dealing with an array type, decay to the pointer.
7390 if (Ty->isArrayType())
7391 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7393 // Otherwise, we don't care about qualifiers on the type.
7394 Ty = Ty.getLocalUnqualifiedType();
7396 // Flag if we ever add a non-record type.
7397 const RecordType *TyRec = Ty->getAs<RecordType>();
7398 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7400 // Flag if we encounter an arithmetic type.
7401 HasArithmeticOrEnumeralTypes =
7402 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7404 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7405 PointerTypes.insert(Ty);
7406 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7407 // Insert our type, and its more-qualified variants, into the set
7409 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7411 } else if (Ty->isMemberPointerType()) {
7412 // Member pointers are far easier, since the pointee can't be converted.
7413 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7415 } else if (Ty->isEnumeralType()) {
7416 HasArithmeticOrEnumeralTypes = true;
7417 EnumerationTypes.insert(Ty);
7418 } else if (Ty->isVectorType()) {
7419 // We treat vector types as arithmetic types in many contexts as an
7421 HasArithmeticOrEnumeralTypes = true;
7422 VectorTypes.insert(Ty);
7423 } else if (Ty->isNullPtrType()) {
7424 HasNullPtrType = true;
7425 } else if (AllowUserConversions && TyRec) {
7426 // No conversion functions in incomplete types.
7427 if (!SemaRef.isCompleteType(Loc, Ty))
7430 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7431 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7432 if (isa<UsingShadowDecl>(D))
7433 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7435 // Skip conversion function templates; they don't tell us anything
7436 // about which builtin types we can convert to.
7437 if (isa<FunctionTemplateDecl>(D))
7440 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7441 if (AllowExplicitConversions || !Conv->isExplicit()) {
7442 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7449 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7450 /// the volatile- and non-volatile-qualified assignment operators for the
7451 /// given type to the candidate set.
7452 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7454 ArrayRef<Expr *> Args,
7455 OverloadCandidateSet &CandidateSet) {
7456 QualType ParamTypes[2];
7458 // T& operator=(T&, T)
7459 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7462 /*IsAssignmentOperator=*/true);
7464 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7465 // volatile T& operator=(volatile T&, T)
7467 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7470 /*IsAssignmentOperator=*/true);
7474 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7475 /// if any, found in visible type conversion functions found in ArgExpr's type.
7476 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7478 const RecordType *TyRec;
7479 if (const MemberPointerType *RHSMPType =
7480 ArgExpr->getType()->getAs<MemberPointerType>())
7481 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7483 TyRec = ArgExpr->getType()->getAs<RecordType>();
7485 // Just to be safe, assume the worst case.
7486 VRQuals.addVolatile();
7487 VRQuals.addRestrict();
7491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7492 if (!ClassDecl->hasDefinition())
7495 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7496 if (isa<UsingShadowDecl>(D))
7497 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7498 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7499 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7500 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7501 CanTy = ResTypeRef->getPointeeType();
7502 // Need to go down the pointer/mempointer chain and add qualifiers
7506 if (CanTy.isRestrictQualified())
7507 VRQuals.addRestrict();
7508 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7509 CanTy = ResTypePtr->getPointeeType();
7510 else if (const MemberPointerType *ResTypeMPtr =
7511 CanTy->getAs<MemberPointerType>())
7512 CanTy = ResTypeMPtr->getPointeeType();
7515 if (CanTy.isVolatileQualified())
7516 VRQuals.addVolatile();
7517 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7527 /// \brief Helper class to manage the addition of builtin operator overload
7528 /// candidates. It provides shared state and utility methods used throughout
7529 /// the process, as well as a helper method to add each group of builtin
7530 /// operator overloads from the standard to a candidate set.
7531 class BuiltinOperatorOverloadBuilder {
7532 // Common instance state available to all overload candidate addition methods.
7534 ArrayRef<Expr *> Args;
7535 Qualifiers VisibleTypeConversionsQuals;
7536 bool HasArithmeticOrEnumeralCandidateType;
7537 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7538 OverloadCandidateSet &CandidateSet;
7540 // Define some constants used to index and iterate over the arithemetic types
7541 // provided via the getArithmeticType() method below.
7542 // The "promoted arithmetic types" are the arithmetic
7543 // types are that preserved by promotion (C++ [over.built]p2).
7544 static const unsigned FirstIntegralType = 4;
7545 static const unsigned LastIntegralType = 21;
7546 static const unsigned FirstPromotedIntegralType = 4,
7547 LastPromotedIntegralType = 12;
7548 static const unsigned FirstPromotedArithmeticType = 0,
7549 LastPromotedArithmeticType = 12;
7550 static const unsigned NumArithmeticTypes = 21;
7552 /// \brief Get the canonical type for a given arithmetic type index.
7553 CanQualType getArithmeticType(unsigned index) {
7554 assert(index < NumArithmeticTypes);
7555 static CanQualType ASTContext::* const
7556 ArithmeticTypes[NumArithmeticTypes] = {
7557 // Start of promoted types.
7558 &ASTContext::FloatTy,
7559 &ASTContext::DoubleTy,
7560 &ASTContext::LongDoubleTy,
7561 &ASTContext::Float128Ty,
7563 // Start of integral types.
7565 &ASTContext::LongTy,
7566 &ASTContext::LongLongTy,
7567 &ASTContext::Int128Ty,
7568 &ASTContext::UnsignedIntTy,
7569 &ASTContext::UnsignedLongTy,
7570 &ASTContext::UnsignedLongLongTy,
7571 &ASTContext::UnsignedInt128Ty,
7572 // End of promoted types.
7574 &ASTContext::BoolTy,
7575 &ASTContext::CharTy,
7576 &ASTContext::WCharTy,
7577 &ASTContext::Char16Ty,
7578 &ASTContext::Char32Ty,
7579 &ASTContext::SignedCharTy,
7580 &ASTContext::ShortTy,
7581 &ASTContext::UnsignedCharTy,
7582 &ASTContext::UnsignedShortTy,
7583 // End of integral types.
7584 // FIXME: What about complex? What about half?
7586 return S.Context.*ArithmeticTypes[index];
7589 /// \brief Gets the canonical type resulting from the usual arithemetic
7590 /// converions for the given arithmetic types.
7591 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7592 // Accelerator table for performing the usual arithmetic conversions.
7593 // The rules are basically:
7594 // - if either is floating-point, use the wider floating-point
7595 // - if same signedness, use the higher rank
7596 // - if same size, use unsigned of the higher rank
7597 // - use the larger type
7598 // These rules, together with the axiom that higher ranks are
7599 // never smaller, are sufficient to precompute all of these results
7600 // *except* when dealing with signed types of higher rank.
7601 // (we could precompute SLL x UI for all known platforms, but it's
7602 // better not to make any assumptions).
7603 // We assume that int128 has a higher rank than long long on all platforms.
7604 enum PromotedType : int8_t {
7606 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7608 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7609 [LastPromotedArithmeticType] = {
7610 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7611 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7612 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7613 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7614 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7615 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7616 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7617 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7618 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7619 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7620 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7623 assert(L < LastPromotedArithmeticType);
7624 assert(R < LastPromotedArithmeticType);
7625 int Idx = ConversionsTable[L][R];
7627 // Fast path: the table gives us a concrete answer.
7628 if (Idx != Dep) return getArithmeticType(Idx);
7630 // Slow path: we need to compare widths.
7631 // An invariant is that the signed type has higher rank.
7632 CanQualType LT = getArithmeticType(L),
7633 RT = getArithmeticType(R);
7634 unsigned LW = S.Context.getIntWidth(LT),
7635 RW = S.Context.getIntWidth(RT);
7637 // If they're different widths, use the signed type.
7638 if (LW > RW) return LT;
7639 else if (LW < RW) return RT;
7641 // Otherwise, use the unsigned type of the signed type's rank.
7642 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7643 assert(L == SLL || R == SLL);
7644 return S.Context.UnsignedLongLongTy;
7647 /// \brief Helper method to factor out the common pattern of adding overloads
7648 /// for '++' and '--' builtin operators.
7649 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7652 QualType ParamTypes[2] = {
7653 S.Context.getLValueReferenceType(CandidateTy),
7657 // Non-volatile version.
7658 if (Args.size() == 1)
7659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7661 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7663 // Use a heuristic to reduce number of builtin candidates in the set:
7664 // add volatile version only if there are conversions to a volatile type.
7667 S.Context.getLValueReferenceType(
7668 S.Context.getVolatileType(CandidateTy));
7669 if (Args.size() == 1)
7670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7672 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7675 // Add restrict version only if there are conversions to a restrict type
7676 // and our candidate type is a non-restrict-qualified pointer.
7677 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7678 !CandidateTy.isRestrictQualified()) {
7680 = S.Context.getLValueReferenceType(
7681 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7682 if (Args.size() == 1)
7683 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7685 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7689 = S.Context.getLValueReferenceType(
7690 S.Context.getCVRQualifiedType(CandidateTy,
7691 (Qualifiers::Volatile |
7692 Qualifiers::Restrict)));
7693 if (Args.size() == 1)
7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7696 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7703 BuiltinOperatorOverloadBuilder(
7704 Sema &S, ArrayRef<Expr *> Args,
7705 Qualifiers VisibleTypeConversionsQuals,
7706 bool HasArithmeticOrEnumeralCandidateType,
7707 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7708 OverloadCandidateSet &CandidateSet)
7710 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7711 HasArithmeticOrEnumeralCandidateType(
7712 HasArithmeticOrEnumeralCandidateType),
7713 CandidateTypes(CandidateTypes),
7714 CandidateSet(CandidateSet) {
7715 // Validate some of our static helper constants in debug builds.
7716 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7717 "Invalid first promoted integral type");
7718 assert(getArithmeticType(LastPromotedIntegralType - 1)
7719 == S.Context.UnsignedInt128Ty &&
7720 "Invalid last promoted integral type");
7721 assert(getArithmeticType(FirstPromotedArithmeticType)
7722 == S.Context.FloatTy &&
7723 "Invalid first promoted arithmetic type");
7724 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7725 == S.Context.UnsignedInt128Ty &&
7726 "Invalid last promoted arithmetic type");
7729 // C++ [over.built]p3:
7731 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7732 // is either volatile or empty, there exist candidate operator
7733 // functions of the form
7735 // VQ T& operator++(VQ T&);
7736 // T operator++(VQ T&, int);
7738 // C++ [over.built]p4:
7740 // For every pair (T, VQ), where T is an arithmetic type other
7741 // than bool, and VQ is either volatile or empty, there exist
7742 // candidate operator functions of the form
7744 // VQ T& operator--(VQ T&);
7745 // T operator--(VQ T&, int);
7746 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7747 if (!HasArithmeticOrEnumeralCandidateType)
7750 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7751 Arith < NumArithmeticTypes; ++Arith) {
7752 addPlusPlusMinusMinusStyleOverloads(
7753 getArithmeticType(Arith),
7754 VisibleTypeConversionsQuals.hasVolatile(),
7755 VisibleTypeConversionsQuals.hasRestrict());
7759 // C++ [over.built]p5:
7761 // For every pair (T, VQ), where T is a cv-qualified or
7762 // cv-unqualified object type, and VQ is either volatile or
7763 // empty, there exist candidate operator functions of the form
7765 // T*VQ& operator++(T*VQ&);
7766 // T*VQ& operator--(T*VQ&);
7767 // T* operator++(T*VQ&, int);
7768 // T* operator--(T*VQ&, int);
7769 void addPlusPlusMinusMinusPointerOverloads() {
7770 for (BuiltinCandidateTypeSet::iterator
7771 Ptr = CandidateTypes[0].pointer_begin(),
7772 PtrEnd = CandidateTypes[0].pointer_end();
7773 Ptr != PtrEnd; ++Ptr) {
7774 // Skip pointer types that aren't pointers to object types.
7775 if (!(*Ptr)->getPointeeType()->isObjectType())
7778 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7779 (!(*Ptr).isVolatileQualified() &&
7780 VisibleTypeConversionsQuals.hasVolatile()),
7781 (!(*Ptr).isRestrictQualified() &&
7782 VisibleTypeConversionsQuals.hasRestrict()));
7786 // C++ [over.built]p6:
7787 // For every cv-qualified or cv-unqualified object type T, there
7788 // exist candidate operator functions of the form
7790 // T& operator*(T*);
7792 // C++ [over.built]p7:
7793 // For every function type T that does not have cv-qualifiers or a
7794 // ref-qualifier, there exist candidate operator functions of the form
7795 // T& operator*(T*);
7796 void addUnaryStarPointerOverloads() {
7797 for (BuiltinCandidateTypeSet::iterator
7798 Ptr = CandidateTypes[0].pointer_begin(),
7799 PtrEnd = CandidateTypes[0].pointer_end();
7800 Ptr != PtrEnd; ++Ptr) {
7801 QualType ParamTy = *Ptr;
7802 QualType PointeeTy = ParamTy->getPointeeType();
7803 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7806 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7807 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7810 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7811 &ParamTy, Args, CandidateSet);
7815 // C++ [over.built]p9:
7816 // For every promoted arithmetic type T, there exist candidate
7817 // operator functions of the form
7821 void addUnaryPlusOrMinusArithmeticOverloads() {
7822 if (!HasArithmeticOrEnumeralCandidateType)
7825 for (unsigned Arith = FirstPromotedArithmeticType;
7826 Arith < LastPromotedArithmeticType; ++Arith) {
7827 QualType ArithTy = getArithmeticType(Arith);
7828 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7831 // Extension: We also add these operators for vector types.
7832 for (BuiltinCandidateTypeSet::iterator
7833 Vec = CandidateTypes[0].vector_begin(),
7834 VecEnd = CandidateTypes[0].vector_end();
7835 Vec != VecEnd; ++Vec) {
7836 QualType VecTy = *Vec;
7837 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7841 // C++ [over.built]p8:
7842 // For every type T, there exist candidate operator functions of
7845 // T* operator+(T*);
7846 void addUnaryPlusPointerOverloads() {
7847 for (BuiltinCandidateTypeSet::iterator
7848 Ptr = CandidateTypes[0].pointer_begin(),
7849 PtrEnd = CandidateTypes[0].pointer_end();
7850 Ptr != PtrEnd; ++Ptr) {
7851 QualType ParamTy = *Ptr;
7852 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7856 // C++ [over.built]p10:
7857 // For every promoted integral type T, there exist candidate
7858 // operator functions of the form
7861 void addUnaryTildePromotedIntegralOverloads() {
7862 if (!HasArithmeticOrEnumeralCandidateType)
7865 for (unsigned Int = FirstPromotedIntegralType;
7866 Int < LastPromotedIntegralType; ++Int) {
7867 QualType IntTy = getArithmeticType(Int);
7868 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7871 // Extension: We also add this operator for vector types.
7872 for (BuiltinCandidateTypeSet::iterator
7873 Vec = CandidateTypes[0].vector_begin(),
7874 VecEnd = CandidateTypes[0].vector_end();
7875 Vec != VecEnd; ++Vec) {
7876 QualType VecTy = *Vec;
7877 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7881 // C++ [over.match.oper]p16:
7882 // For every pointer to member type T or type std::nullptr_t, there
7883 // exist candidate operator functions of the form
7885 // bool operator==(T,T);
7886 // bool operator!=(T,T);
7887 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7888 /// Set of (canonical) types that we've already handled.
7889 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7892 for (BuiltinCandidateTypeSet::iterator
7893 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7894 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7895 MemPtr != MemPtrEnd;
7897 // Don't add the same builtin candidate twice.
7898 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7901 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7902 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7905 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7906 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7907 if (AddedTypes.insert(NullPtrTy).second) {
7908 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7909 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7916 // C++ [over.built]p15:
7918 // For every T, where T is an enumeration type or a pointer type,
7919 // there exist candidate operator functions of the form
7921 // bool operator<(T, T);
7922 // bool operator>(T, T);
7923 // bool operator<=(T, T);
7924 // bool operator>=(T, T);
7925 // bool operator==(T, T);
7926 // bool operator!=(T, T);
7927 void addRelationalPointerOrEnumeralOverloads() {
7928 // C++ [over.match.oper]p3:
7929 // [...]the built-in candidates include all of the candidate operator
7930 // functions defined in 13.6 that, compared to the given operator, [...]
7931 // do not have the same parameter-type-list as any non-template non-member
7934 // Note that in practice, this only affects enumeration types because there
7935 // aren't any built-in candidates of record type, and a user-defined operator
7936 // must have an operand of record or enumeration type. Also, the only other
7937 // overloaded operator with enumeration arguments, operator=,
7938 // cannot be overloaded for enumeration types, so this is the only place
7939 // where we must suppress candidates like this.
7940 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7941 UserDefinedBinaryOperators;
7943 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7944 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7945 CandidateTypes[ArgIdx].enumeration_end()) {
7946 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7947 CEnd = CandidateSet.end();
7949 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7952 if (C->Function->isFunctionTemplateSpecialization())
7955 QualType FirstParamType =
7956 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7957 QualType SecondParamType =
7958 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7960 // Skip if either parameter isn't of enumeral type.
7961 if (!FirstParamType->isEnumeralType() ||
7962 !SecondParamType->isEnumeralType())
7965 // Add this operator to the set of known user-defined operators.
7966 UserDefinedBinaryOperators.insert(
7967 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7968 S.Context.getCanonicalType(SecondParamType)));
7973 /// Set of (canonical) types that we've already handled.
7974 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7976 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7977 for (BuiltinCandidateTypeSet::iterator
7978 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7979 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7980 Ptr != PtrEnd; ++Ptr) {
7981 // Don't add the same builtin candidate twice.
7982 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7985 QualType ParamTypes[2] = { *Ptr, *Ptr };
7986 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7988 for (BuiltinCandidateTypeSet::iterator
7989 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7990 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7991 Enum != EnumEnd; ++Enum) {
7992 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7994 // Don't add the same builtin candidate twice, or if a user defined
7995 // candidate exists.
7996 if (!AddedTypes.insert(CanonType).second ||
7997 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8001 QualType ParamTypes[2] = { *Enum, *Enum };
8002 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
8007 // C++ [over.built]p13:
8009 // For every cv-qualified or cv-unqualified object type T
8010 // there exist candidate operator functions of the form
8012 // T* operator+(T*, ptrdiff_t);
8013 // T& operator[](T*, ptrdiff_t); [BELOW]
8014 // T* operator-(T*, ptrdiff_t);
8015 // T* operator+(ptrdiff_t, T*);
8016 // T& operator[](ptrdiff_t, T*); [BELOW]
8018 // C++ [over.built]p14:
8020 // For every T, where T is a pointer to object type, there
8021 // exist candidate operator functions of the form
8023 // ptrdiff_t operator-(T, T);
8024 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8025 /// Set of (canonical) types that we've already handled.
8026 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8028 for (int Arg = 0; Arg < 2; ++Arg) {
8029 QualType AsymmetricParamTypes[2] = {
8030 S.Context.getPointerDiffType(),
8031 S.Context.getPointerDiffType(),
8033 for (BuiltinCandidateTypeSet::iterator
8034 Ptr = CandidateTypes[Arg].pointer_begin(),
8035 PtrEnd = CandidateTypes[Arg].pointer_end();
8036 Ptr != PtrEnd; ++Ptr) {
8037 QualType PointeeTy = (*Ptr)->getPointeeType();
8038 if (!PointeeTy->isObjectType())
8041 AsymmetricParamTypes[Arg] = *Ptr;
8042 if (Arg == 0 || Op == OO_Plus) {
8043 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8044 // T* operator+(ptrdiff_t, T*);
8045 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
8047 if (Op == OO_Minus) {
8048 // ptrdiff_t operator-(T, T);
8049 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8052 QualType ParamTypes[2] = { *Ptr, *Ptr };
8053 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
8054 Args, CandidateSet);
8060 // C++ [over.built]p12:
8062 // For every pair of promoted arithmetic types L and R, there
8063 // exist candidate operator functions of the form
8065 // LR operator*(L, R);
8066 // LR operator/(L, R);
8067 // LR operator+(L, R);
8068 // LR operator-(L, R);
8069 // bool operator<(L, R);
8070 // bool operator>(L, R);
8071 // bool operator<=(L, R);
8072 // bool operator>=(L, R);
8073 // bool operator==(L, R);
8074 // bool operator!=(L, R);
8076 // where LR is the result of the usual arithmetic conversions
8077 // between types L and R.
8079 // C++ [over.built]p24:
8081 // For every pair of promoted arithmetic types L and R, there exist
8082 // candidate operator functions of the form
8084 // LR operator?(bool, L, R);
8086 // where LR is the result of the usual arithmetic conversions
8087 // between types L and R.
8088 // Our candidates ignore the first parameter.
8089 void addGenericBinaryArithmeticOverloads(bool isComparison) {
8090 if (!HasArithmeticOrEnumeralCandidateType)
8093 for (unsigned Left = FirstPromotedArithmeticType;
8094 Left < LastPromotedArithmeticType; ++Left) {
8095 for (unsigned Right = FirstPromotedArithmeticType;
8096 Right < LastPromotedArithmeticType; ++Right) {
8097 QualType LandR[2] = { getArithmeticType(Left),
8098 getArithmeticType(Right) };
8100 isComparison ? S.Context.BoolTy
8101 : getUsualArithmeticConversions(Left, Right);
8102 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8106 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8107 // conditional operator for vector types.
8108 for (BuiltinCandidateTypeSet::iterator
8109 Vec1 = CandidateTypes[0].vector_begin(),
8110 Vec1End = CandidateTypes[0].vector_end();
8111 Vec1 != Vec1End; ++Vec1) {
8112 for (BuiltinCandidateTypeSet::iterator
8113 Vec2 = CandidateTypes[1].vector_begin(),
8114 Vec2End = CandidateTypes[1].vector_end();
8115 Vec2 != Vec2End; ++Vec2) {
8116 QualType LandR[2] = { *Vec1, *Vec2 };
8117 QualType Result = S.Context.BoolTy;
8118 if (!isComparison) {
8119 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8125 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8130 // C++ [over.built]p17:
8132 // For every pair of promoted integral types L and R, there
8133 // exist candidate operator functions of the form
8135 // LR operator%(L, R);
8136 // LR operator&(L, R);
8137 // LR operator^(L, R);
8138 // LR operator|(L, R);
8139 // L operator<<(L, R);
8140 // L operator>>(L, R);
8142 // where LR is the result of the usual arithmetic conversions
8143 // between types L and R.
8144 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8145 if (!HasArithmeticOrEnumeralCandidateType)
8148 for (unsigned Left = FirstPromotedIntegralType;
8149 Left < LastPromotedIntegralType; ++Left) {
8150 for (unsigned Right = FirstPromotedIntegralType;
8151 Right < LastPromotedIntegralType; ++Right) {
8152 QualType LandR[2] = { getArithmeticType(Left),
8153 getArithmeticType(Right) };
8154 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8156 : getUsualArithmeticConversions(Left, Right);
8157 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
8162 // C++ [over.built]p20:
8164 // For every pair (T, VQ), where T is an enumeration or
8165 // pointer to member type and VQ is either volatile or
8166 // empty, there exist candidate operator functions of the form
8168 // VQ T& operator=(VQ T&, T);
8169 void addAssignmentMemberPointerOrEnumeralOverloads() {
8170 /// Set of (canonical) types that we've already handled.
8171 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8173 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8174 for (BuiltinCandidateTypeSet::iterator
8175 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8176 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8177 Enum != EnumEnd; ++Enum) {
8178 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8181 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8184 for (BuiltinCandidateTypeSet::iterator
8185 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8186 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8187 MemPtr != MemPtrEnd; ++MemPtr) {
8188 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8191 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8196 // C++ [over.built]p19:
8198 // For every pair (T, VQ), where T is any type and VQ is either
8199 // volatile or empty, there exist candidate operator functions
8202 // T*VQ& operator=(T*VQ&, T*);
8204 // C++ [over.built]p21:
8206 // For every pair (T, VQ), where T is a cv-qualified or
8207 // cv-unqualified object type and VQ is either volatile or
8208 // empty, there exist candidate operator functions of the form
8210 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8211 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8212 void addAssignmentPointerOverloads(bool isEqualOp) {
8213 /// Set of (canonical) types that we've already handled.
8214 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8216 for (BuiltinCandidateTypeSet::iterator
8217 Ptr = CandidateTypes[0].pointer_begin(),
8218 PtrEnd = CandidateTypes[0].pointer_end();
8219 Ptr != PtrEnd; ++Ptr) {
8220 // If this is operator=, keep track of the builtin candidates we added.
8222 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8223 else if (!(*Ptr)->getPointeeType()->isObjectType())
8226 // non-volatile version
8227 QualType ParamTypes[2] = {
8228 S.Context.getLValueReferenceType(*Ptr),
8229 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8231 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8232 /*IsAssigmentOperator=*/ isEqualOp);
8234 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8235 VisibleTypeConversionsQuals.hasVolatile();
8239 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8241 /*IsAssigmentOperator=*/isEqualOp);
8244 if (!(*Ptr).isRestrictQualified() &&
8245 VisibleTypeConversionsQuals.hasRestrict()) {
8248 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8250 /*IsAssigmentOperator=*/isEqualOp);
8253 // volatile restrict version
8255 = S.Context.getLValueReferenceType(
8256 S.Context.getCVRQualifiedType(*Ptr,
8257 (Qualifiers::Volatile |
8258 Qualifiers::Restrict)));
8259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8260 /*IsAssigmentOperator=*/isEqualOp);
8266 for (BuiltinCandidateTypeSet::iterator
8267 Ptr = CandidateTypes[1].pointer_begin(),
8268 PtrEnd = CandidateTypes[1].pointer_end();
8269 Ptr != PtrEnd; ++Ptr) {
8270 // Make sure we don't add the same candidate twice.
8271 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8274 QualType ParamTypes[2] = {
8275 S.Context.getLValueReferenceType(*Ptr),
8279 // non-volatile version
8280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8281 /*IsAssigmentOperator=*/true);
8283 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8284 VisibleTypeConversionsQuals.hasVolatile();
8288 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8290 /*IsAssigmentOperator=*/true);
8293 if (!(*Ptr).isRestrictQualified() &&
8294 VisibleTypeConversionsQuals.hasRestrict()) {
8297 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8299 /*IsAssigmentOperator=*/true);
8302 // volatile restrict version
8304 = S.Context.getLValueReferenceType(
8305 S.Context.getCVRQualifiedType(*Ptr,
8306 (Qualifiers::Volatile |
8307 Qualifiers::Restrict)));
8308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8309 /*IsAssigmentOperator=*/true);
8316 // C++ [over.built]p18:
8318 // For every triple (L, VQ, R), where L is an arithmetic type,
8319 // VQ is either volatile or empty, and R is a promoted
8320 // arithmetic type, there exist candidate operator functions of
8323 // VQ L& operator=(VQ L&, R);
8324 // VQ L& operator*=(VQ L&, R);
8325 // VQ L& operator/=(VQ L&, R);
8326 // VQ L& operator+=(VQ L&, R);
8327 // VQ L& operator-=(VQ L&, R);
8328 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8329 if (!HasArithmeticOrEnumeralCandidateType)
8332 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8333 for (unsigned Right = FirstPromotedArithmeticType;
8334 Right < LastPromotedArithmeticType; ++Right) {
8335 QualType ParamTypes[2];
8336 ParamTypes[1] = getArithmeticType(Right);
8338 // Add this built-in operator as a candidate (VQ is empty).
8340 S.Context.getLValueReferenceType(getArithmeticType(Left));
8341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8342 /*IsAssigmentOperator=*/isEqualOp);
8344 // Add this built-in operator as a candidate (VQ is 'volatile').
8345 if (VisibleTypeConversionsQuals.hasVolatile()) {
8347 S.Context.getVolatileType(getArithmeticType(Left));
8348 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8350 /*IsAssigmentOperator=*/isEqualOp);
8355 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8356 for (BuiltinCandidateTypeSet::iterator
8357 Vec1 = CandidateTypes[0].vector_begin(),
8358 Vec1End = CandidateTypes[0].vector_end();
8359 Vec1 != Vec1End; ++Vec1) {
8360 for (BuiltinCandidateTypeSet::iterator
8361 Vec2 = CandidateTypes[1].vector_begin(),
8362 Vec2End = CandidateTypes[1].vector_end();
8363 Vec2 != Vec2End; ++Vec2) {
8364 QualType ParamTypes[2];
8365 ParamTypes[1] = *Vec2;
8366 // Add this built-in operator as a candidate (VQ is empty).
8367 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8368 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8369 /*IsAssigmentOperator=*/isEqualOp);
8371 // Add this built-in operator as a candidate (VQ is 'volatile').
8372 if (VisibleTypeConversionsQuals.hasVolatile()) {
8373 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8374 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8376 /*IsAssigmentOperator=*/isEqualOp);
8382 // C++ [over.built]p22:
8384 // For every triple (L, VQ, R), where L is an integral type, VQ
8385 // is either volatile or empty, and R is a promoted integral
8386 // type, there exist candidate operator functions of the form
8388 // VQ L& operator%=(VQ L&, R);
8389 // VQ L& operator<<=(VQ L&, R);
8390 // VQ L& operator>>=(VQ L&, R);
8391 // VQ L& operator&=(VQ L&, R);
8392 // VQ L& operator^=(VQ L&, R);
8393 // VQ L& operator|=(VQ L&, R);
8394 void addAssignmentIntegralOverloads() {
8395 if (!HasArithmeticOrEnumeralCandidateType)
8398 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8399 for (unsigned Right = FirstPromotedIntegralType;
8400 Right < LastPromotedIntegralType; ++Right) {
8401 QualType ParamTypes[2];
8402 ParamTypes[1] = getArithmeticType(Right);
8404 // Add this built-in operator as a candidate (VQ is empty).
8406 S.Context.getLValueReferenceType(getArithmeticType(Left));
8407 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8408 if (VisibleTypeConversionsQuals.hasVolatile()) {
8409 // Add this built-in operator as a candidate (VQ is 'volatile').
8410 ParamTypes[0] = getArithmeticType(Left);
8411 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8412 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8419 // C++ [over.operator]p23:
8421 // There also exist candidate operator functions of the form
8423 // bool operator!(bool);
8424 // bool operator&&(bool, bool);
8425 // bool operator||(bool, bool);
8426 void addExclaimOverload() {
8427 QualType ParamTy = S.Context.BoolTy;
8428 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8429 /*IsAssignmentOperator=*/false,
8430 /*NumContextualBoolArguments=*/1);
8432 void addAmpAmpOrPipePipeOverload() {
8433 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8434 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8435 /*IsAssignmentOperator=*/false,
8436 /*NumContextualBoolArguments=*/2);
8439 // C++ [over.built]p13:
8441 // For every cv-qualified or cv-unqualified object type T there
8442 // exist candidate operator functions of the form
8444 // T* operator+(T*, ptrdiff_t); [ABOVE]
8445 // T& operator[](T*, ptrdiff_t);
8446 // T* operator-(T*, ptrdiff_t); [ABOVE]
8447 // T* operator+(ptrdiff_t, T*); [ABOVE]
8448 // T& operator[](ptrdiff_t, T*);
8449 void addSubscriptOverloads() {
8450 for (BuiltinCandidateTypeSet::iterator
8451 Ptr = CandidateTypes[0].pointer_begin(),
8452 PtrEnd = CandidateTypes[0].pointer_end();
8453 Ptr != PtrEnd; ++Ptr) {
8454 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8455 QualType PointeeType = (*Ptr)->getPointeeType();
8456 if (!PointeeType->isObjectType())
8459 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8461 // T& operator[](T*, ptrdiff_t)
8462 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8465 for (BuiltinCandidateTypeSet::iterator
8466 Ptr = CandidateTypes[1].pointer_begin(),
8467 PtrEnd = CandidateTypes[1].pointer_end();
8468 Ptr != PtrEnd; ++Ptr) {
8469 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8470 QualType PointeeType = (*Ptr)->getPointeeType();
8471 if (!PointeeType->isObjectType())
8474 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8476 // T& operator[](ptrdiff_t, T*)
8477 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8481 // C++ [over.built]p11:
8482 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8483 // C1 is the same type as C2 or is a derived class of C2, T is an object
8484 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8485 // there exist candidate operator functions of the form
8487 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8489 // where CV12 is the union of CV1 and CV2.
8490 void addArrowStarOverloads() {
8491 for (BuiltinCandidateTypeSet::iterator
8492 Ptr = CandidateTypes[0].pointer_begin(),
8493 PtrEnd = CandidateTypes[0].pointer_end();
8494 Ptr != PtrEnd; ++Ptr) {
8495 QualType C1Ty = (*Ptr);
8497 QualifierCollector Q1;
8498 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8499 if (!isa<RecordType>(C1))
8501 // heuristic to reduce number of builtin candidates in the set.
8502 // Add volatile/restrict version only if there are conversions to a
8503 // volatile/restrict type.
8504 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8506 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8508 for (BuiltinCandidateTypeSet::iterator
8509 MemPtr = CandidateTypes[1].member_pointer_begin(),
8510 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8511 MemPtr != MemPtrEnd; ++MemPtr) {
8512 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8513 QualType C2 = QualType(mptr->getClass(), 0);
8514 C2 = C2.getUnqualifiedType();
8515 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8517 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8519 QualType T = mptr->getPointeeType();
8520 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8521 T.isVolatileQualified())
8523 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8524 T.isRestrictQualified())
8526 T = Q1.apply(S.Context, T);
8527 QualType ResultTy = S.Context.getLValueReferenceType(T);
8528 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8533 // Note that we don't consider the first argument, since it has been
8534 // contextually converted to bool long ago. The candidates below are
8535 // therefore added as binary.
8537 // C++ [over.built]p25:
8538 // For every type T, where T is a pointer, pointer-to-member, or scoped
8539 // enumeration type, there exist candidate operator functions of the form
8541 // T operator?(bool, T, T);
8543 void addConditionalOperatorOverloads() {
8544 /// Set of (canonical) types that we've already handled.
8545 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8548 for (BuiltinCandidateTypeSet::iterator
8549 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8550 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8551 Ptr != PtrEnd; ++Ptr) {
8552 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8555 QualType ParamTypes[2] = { *Ptr, *Ptr };
8556 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8559 for (BuiltinCandidateTypeSet::iterator
8560 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8561 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8562 MemPtr != MemPtrEnd; ++MemPtr) {
8563 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8566 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8567 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8570 if (S.getLangOpts().CPlusPlus11) {
8571 for (BuiltinCandidateTypeSet::iterator
8572 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8573 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8574 Enum != EnumEnd; ++Enum) {
8575 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8578 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8581 QualType ParamTypes[2] = { *Enum, *Enum };
8582 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8589 } // end anonymous namespace
8591 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8592 /// operator overloads to the candidate set (C++ [over.built]), based
8593 /// on the operator @p Op and the arguments given. For example, if the
8594 /// operator is a binary '+', this routine might add "int
8595 /// operator+(int, int)" to cover integer addition.
8596 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8597 SourceLocation OpLoc,
8598 ArrayRef<Expr *> Args,
8599 OverloadCandidateSet &CandidateSet) {
8600 // Find all of the types that the arguments can convert to, but only
8601 // if the operator we're looking at has built-in operator candidates
8602 // that make use of these types. Also record whether we encounter non-record
8603 // candidate types or either arithmetic or enumeral candidate types.
8604 Qualifiers VisibleTypeConversionsQuals;
8605 VisibleTypeConversionsQuals.addConst();
8606 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8609 bool HasNonRecordCandidateType = false;
8610 bool HasArithmeticOrEnumeralCandidateType = false;
8611 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8613 CandidateTypes.emplace_back(*this);
8614 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8617 (Op == OO_Exclaim ||
8620 VisibleTypeConversionsQuals);
8621 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8622 CandidateTypes[ArgIdx].hasNonRecordTypes();
8623 HasArithmeticOrEnumeralCandidateType =
8624 HasArithmeticOrEnumeralCandidateType ||
8625 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8628 // Exit early when no non-record types have been added to the candidate set
8629 // for any of the arguments to the operator.
8631 // We can't exit early for !, ||, or &&, since there we have always have
8632 // 'bool' overloads.
8633 if (!HasNonRecordCandidateType &&
8634 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8637 // Setup an object to manage the common state for building overloads.
8638 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8639 VisibleTypeConversionsQuals,
8640 HasArithmeticOrEnumeralCandidateType,
8641 CandidateTypes, CandidateSet);
8643 // Dispatch over the operation to add in only those overloads which apply.
8646 case NUM_OVERLOADED_OPERATORS:
8647 llvm_unreachable("Expected an overloaded operator");
8652 case OO_Array_Delete:
8655 "Special operators don't use AddBuiltinOperatorCandidates");
8660 // C++ [over.match.oper]p3:
8661 // -- For the operator ',', the unary operator '&', the
8662 // operator '->', or the operator 'co_await', the
8663 // built-in candidates set is empty.
8666 case OO_Plus: // '+' is either unary or binary
8667 if (Args.size() == 1)
8668 OpBuilder.addUnaryPlusPointerOverloads();
8671 case OO_Minus: // '-' is either unary or binary
8672 if (Args.size() == 1) {
8673 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8675 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8676 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8680 case OO_Star: // '*' is either unary or binary
8681 if (Args.size() == 1)
8682 OpBuilder.addUnaryStarPointerOverloads();
8684 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8688 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8693 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8694 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8698 case OO_ExclaimEqual:
8699 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8705 case OO_GreaterEqual:
8706 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8707 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8714 case OO_GreaterGreater:
8715 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8718 case OO_Amp: // '&' is either unary or binary
8719 if (Args.size() == 1)
8720 // C++ [over.match.oper]p3:
8721 // -- For the operator ',', the unary operator '&', or the
8722 // operator '->', the built-in candidates set is empty.
8725 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8729 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8733 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8738 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8743 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8746 case OO_PercentEqual:
8747 case OO_LessLessEqual:
8748 case OO_GreaterGreaterEqual:
8752 OpBuilder.addAssignmentIntegralOverloads();
8756 OpBuilder.addExclaimOverload();
8761 OpBuilder.addAmpAmpOrPipePipeOverload();
8765 OpBuilder.addSubscriptOverloads();
8769 OpBuilder.addArrowStarOverloads();
8772 case OO_Conditional:
8773 OpBuilder.addConditionalOperatorOverloads();
8774 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8779 /// \brief Add function candidates found via argument-dependent lookup
8780 /// to the set of overloading candidates.
8782 /// This routine performs argument-dependent name lookup based on the
8783 /// given function name (which may also be an operator name) and adds
8784 /// all of the overload candidates found by ADL to the overload
8785 /// candidate set (C++ [basic.lookup.argdep]).
8787 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8789 ArrayRef<Expr *> Args,
8790 TemplateArgumentListInfo *ExplicitTemplateArgs,
8791 OverloadCandidateSet& CandidateSet,
8792 bool PartialOverloading) {
8795 // FIXME: This approach for uniquing ADL results (and removing
8796 // redundant candidates from the set) relies on pointer-equality,
8797 // which means we need to key off the canonical decl. However,
8798 // always going back to the canonical decl might not get us the
8799 // right set of default arguments. What default arguments are
8800 // we supposed to consider on ADL candidates, anyway?
8802 // FIXME: Pass in the explicit template arguments?
8803 ArgumentDependentLookup(Name, Loc, Args, Fns);
8805 // Erase all of the candidates we already knew about.
8806 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8807 CandEnd = CandidateSet.end();
8808 Cand != CandEnd; ++Cand)
8809 if (Cand->Function) {
8810 Fns.erase(Cand->Function);
8811 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8815 // For each of the ADL candidates we found, add it to the overload
8817 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8818 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8819 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8820 if (ExplicitTemplateArgs)
8823 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8824 PartialOverloading);
8826 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8827 FoundDecl, ExplicitTemplateArgs,
8828 Args, CandidateSet, PartialOverloading);
8833 enum class Comparison { Equal, Better, Worse };
8836 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8837 /// overload resolution.
8839 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8840 /// Cand1's first N enable_if attributes have precisely the same conditions as
8841 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8842 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8844 /// Note that you can have a pair of candidates such that Cand1's enable_if
8845 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8846 /// worse than Cand1's.
8847 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8848 const FunctionDecl *Cand2) {
8849 // Common case: One (or both) decls don't have enable_if attrs.
8850 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8851 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8852 if (!Cand1Attr || !Cand2Attr) {
8853 if (Cand1Attr == Cand2Attr)
8854 return Comparison::Equal;
8855 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8858 // FIXME: The next several lines are just
8859 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8860 // instead of reverse order which is how they're stored in the AST.
8861 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8862 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8864 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8865 // has fewer enable_if attributes than Cand2.
8866 if (Cand1Attrs.size() < Cand2Attrs.size())
8867 return Comparison::Worse;
8869 auto Cand1I = Cand1Attrs.begin();
8870 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8871 for (auto &Cand2A : Cand2Attrs) {
8875 auto &Cand1A = *Cand1I++;
8876 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8877 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8878 if (Cand1ID != Cand2ID)
8879 return Comparison::Worse;
8882 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8885 /// isBetterOverloadCandidate - Determines whether the first overload
8886 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8887 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8888 const OverloadCandidate &Cand2,
8890 bool UserDefinedConversion) {
8891 // Define viable functions to be better candidates than non-viable
8894 return Cand1.Viable;
8895 else if (!Cand1.Viable)
8898 // C++ [over.match.best]p1:
8900 // -- if F is a static member function, ICS1(F) is defined such
8901 // that ICS1(F) is neither better nor worse than ICS1(G) for
8902 // any function G, and, symmetrically, ICS1(G) is neither
8903 // better nor worse than ICS1(F).
8904 unsigned StartArg = 0;
8905 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8908 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8909 // We don't allow incompatible pointer conversions in C++.
8910 if (!S.getLangOpts().CPlusPlus)
8911 return ICS.isStandard() &&
8912 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8914 // The only ill-formed conversion we allow in C++ is the string literal to
8915 // char* conversion, which is only considered ill-formed after C++11.
8916 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8917 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8920 // Define functions that don't require ill-formed conversions for a given
8921 // argument to be better candidates than functions that do.
8922 unsigned NumArgs = Cand1.Conversions.size();
8923 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
8924 bool HasBetterConversion = false;
8925 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8926 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8927 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8928 if (Cand1Bad != Cand2Bad) {
8931 HasBetterConversion = true;
8935 if (HasBetterConversion)
8938 // C++ [over.match.best]p1:
8939 // A viable function F1 is defined to be a better function than another
8940 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8941 // conversion sequence than ICSi(F2), and then...
8942 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8943 switch (CompareImplicitConversionSequences(S, Loc,
8944 Cand1.Conversions[ArgIdx],
8945 Cand2.Conversions[ArgIdx])) {
8946 case ImplicitConversionSequence::Better:
8947 // Cand1 has a better conversion sequence.
8948 HasBetterConversion = true;
8951 case ImplicitConversionSequence::Worse:
8952 // Cand1 can't be better than Cand2.
8955 case ImplicitConversionSequence::Indistinguishable:
8961 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8962 // ICSj(F2), or, if not that,
8963 if (HasBetterConversion)
8966 // -- the context is an initialization by user-defined conversion
8967 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8968 // from the return type of F1 to the destination type (i.e.,
8969 // the type of the entity being initialized) is a better
8970 // conversion sequence than the standard conversion sequence
8971 // from the return type of F2 to the destination type.
8972 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8973 isa<CXXConversionDecl>(Cand1.Function) &&
8974 isa<CXXConversionDecl>(Cand2.Function)) {
8975 // First check whether we prefer one of the conversion functions over the
8976 // other. This only distinguishes the results in non-standard, extension
8977 // cases such as the conversion from a lambda closure type to a function
8978 // pointer or block.
8979 ImplicitConversionSequence::CompareKind Result =
8980 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8981 if (Result == ImplicitConversionSequence::Indistinguishable)
8982 Result = CompareStandardConversionSequences(S, Loc,
8983 Cand1.FinalConversion,
8984 Cand2.FinalConversion);
8986 if (Result != ImplicitConversionSequence::Indistinguishable)
8987 return Result == ImplicitConversionSequence::Better;
8989 // FIXME: Compare kind of reference binding if conversion functions
8990 // convert to a reference type used in direct reference binding, per
8991 // C++14 [over.match.best]p1 section 2 bullet 3.
8994 // -- F1 is a non-template function and F2 is a function template
8995 // specialization, or, if not that,
8996 bool Cand1IsSpecialization = Cand1.Function &&
8997 Cand1.Function->getPrimaryTemplate();
8998 bool Cand2IsSpecialization = Cand2.Function &&
8999 Cand2.Function->getPrimaryTemplate();
9000 if (Cand1IsSpecialization != Cand2IsSpecialization)
9001 return Cand2IsSpecialization;
9003 // -- F1 and F2 are function template specializations, and the function
9004 // template for F1 is more specialized than the template for F2
9005 // according to the partial ordering rules described in 14.5.5.2, or,
9007 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9008 if (FunctionTemplateDecl *BetterTemplate
9009 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9010 Cand2.Function->getPrimaryTemplate(),
9012 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9014 Cand1.ExplicitCallArguments,
9015 Cand2.ExplicitCallArguments))
9016 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9019 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9020 // A derived-class constructor beats an (inherited) base class constructor.
9021 bool Cand1IsInherited =
9022 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9023 bool Cand2IsInherited =
9024 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9025 if (Cand1IsInherited != Cand2IsInherited)
9026 return Cand2IsInherited;
9027 else if (Cand1IsInherited) {
9028 assert(Cand2IsInherited);
9029 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9030 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9031 if (Cand1Class->isDerivedFrom(Cand2Class))
9033 if (Cand2Class->isDerivedFrom(Cand1Class))
9035 // Inherited from sibling base classes: still ambiguous.
9038 // Check for enable_if value-based overload resolution.
9039 if (Cand1.Function && Cand2.Function) {
9040 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9041 if (Cmp != Comparison::Equal)
9042 return Cmp == Comparison::Better;
9045 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9046 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9047 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9048 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9051 bool HasPS1 = Cand1.Function != nullptr &&
9052 functionHasPassObjectSizeParams(Cand1.Function);
9053 bool HasPS2 = Cand2.Function != nullptr &&
9054 functionHasPassObjectSizeParams(Cand2.Function);
9055 return HasPS1 != HasPS2 && HasPS1;
9058 /// Determine whether two declarations are "equivalent" for the purposes of
9059 /// name lookup and overload resolution. This applies when the same internal/no
9060 /// linkage entity is defined by two modules (probably by textually including
9061 /// the same header). In such a case, we don't consider the declarations to
9062 /// declare the same entity, but we also don't want lookups with both
9063 /// declarations visible to be ambiguous in some cases (this happens when using
9064 /// a modularized libstdc++).
9065 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9066 const NamedDecl *B) {
9067 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9068 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9072 // The declarations must be declaring the same name as an internal linkage
9073 // entity in different modules.
9074 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9075 VB->getDeclContext()->getRedeclContext()) ||
9076 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9077 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9078 VA->isExternallyVisible() || VB->isExternallyVisible())
9081 // Check that the declarations appear to be equivalent.
9083 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9084 // For constants and functions, we should check the initializer or body is
9085 // the same. For non-constant variables, we shouldn't allow it at all.
9086 if (Context.hasSameType(VA->getType(), VB->getType()))
9089 // Enum constants within unnamed enumerations will have different types, but
9090 // may still be similar enough to be interchangeable for our purposes.
9091 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9092 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9093 // Only handle anonymous enums. If the enumerations were named and
9094 // equivalent, they would have been merged to the same type.
9095 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9096 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9097 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9098 !Context.hasSameType(EnumA->getIntegerType(),
9099 EnumB->getIntegerType()))
9101 // Allow this only if the value is the same for both enumerators.
9102 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9106 // Nothing else is sufficiently similar.
9110 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9111 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9112 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9114 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9115 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9116 << !M << (M ? M->getFullModuleName() : "");
9118 for (auto *E : Equiv) {
9119 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9120 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9121 << !M << (M ? M->getFullModuleName() : "");
9125 /// \brief Computes the best viable function (C++ 13.3.3)
9126 /// within an overload candidate set.
9128 /// \param Loc The location of the function name (or operator symbol) for
9129 /// which overload resolution occurs.
9131 /// \param Best If overload resolution was successful or found a deleted
9132 /// function, \p Best points to the candidate function found.
9134 /// \returns The result of overload resolution.
9136 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9138 bool UserDefinedConversion) {
9139 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9140 std::transform(begin(), end(), std::back_inserter(Candidates),
9141 [](OverloadCandidate &Cand) { return &Cand; });
9143 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9144 // are accepted by both clang and NVCC. However, during a particular
9145 // compilation mode only one call variant is viable. We need to
9146 // exclude non-viable overload candidates from consideration based
9147 // only on their host/device attributes. Specifically, if one
9148 // candidate call is WrongSide and the other is SameSide, we ignore
9149 // the WrongSide candidate.
9150 if (S.getLangOpts().CUDA) {
9151 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9152 bool ContainsSameSideCandidate =
9153 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9154 return Cand->Function &&
9155 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9158 if (ContainsSameSideCandidate) {
9159 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9160 return Cand->Function &&
9161 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9162 Sema::CFP_WrongSide;
9164 llvm::erase_if(Candidates, IsWrongSideCandidate);
9168 // Find the best viable function.
9170 for (auto *Cand : Candidates)
9172 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
9173 UserDefinedConversion))
9176 // If we didn't find any viable functions, abort.
9178 return OR_No_Viable_Function;
9180 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9182 // Make sure that this function is better than every other viable
9183 // function. If not, we have an ambiguity.
9184 for (auto *Cand : Candidates) {
9187 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
9188 UserDefinedConversion)) {
9189 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9191 EquivalentCands.push_back(Cand->Function);
9196 return OR_Ambiguous;
9200 // Best is the best viable function.
9201 if (Best->Function &&
9202 (Best->Function->isDeleted() ||
9203 S.isFunctionConsideredUnavailable(Best->Function)))
9206 if (!EquivalentCands.empty())
9207 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9215 enum OverloadCandidateKind {
9219 oc_function_template,
9221 oc_constructor_template,
9222 oc_implicit_default_constructor,
9223 oc_implicit_copy_constructor,
9224 oc_implicit_move_constructor,
9225 oc_implicit_copy_assignment,
9226 oc_implicit_move_assignment,
9227 oc_inherited_constructor,
9228 oc_inherited_constructor_template
9231 static OverloadCandidateKind
9232 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9233 std::string &Description) {
9234 bool isTemplate = false;
9236 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9238 Description = S.getTemplateArgumentBindingsText(
9239 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9242 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9243 if (!Ctor->isImplicit()) {
9244 if (isa<ConstructorUsingShadowDecl>(Found))
9245 return isTemplate ? oc_inherited_constructor_template
9246 : oc_inherited_constructor;
9248 return isTemplate ? oc_constructor_template : oc_constructor;
9251 if (Ctor->isDefaultConstructor())
9252 return oc_implicit_default_constructor;
9254 if (Ctor->isMoveConstructor())
9255 return oc_implicit_move_constructor;
9257 assert(Ctor->isCopyConstructor() &&
9258 "unexpected sort of implicit constructor");
9259 return oc_implicit_copy_constructor;
9262 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9263 // This actually gets spelled 'candidate function' for now, but
9264 // it doesn't hurt to split it out.
9265 if (!Meth->isImplicit())
9266 return isTemplate ? oc_method_template : oc_method;
9268 if (Meth->isMoveAssignmentOperator())
9269 return oc_implicit_move_assignment;
9271 if (Meth->isCopyAssignmentOperator())
9272 return oc_implicit_copy_assignment;
9274 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9278 return isTemplate ? oc_function_template : oc_function;
9281 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9282 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9284 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9285 S.Diag(FoundDecl->getLocation(),
9286 diag::note_ovl_candidate_inherited_constructor)
9287 << Shadow->getNominatedBaseClass();
9290 } // end anonymous namespace
9292 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9293 const FunctionDecl *FD) {
9294 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9296 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9304 /// \brief Returns true if we can take the address of the function.
9306 /// \param Complain - If true, we'll emit a diagnostic
9307 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9308 /// we in overload resolution?
9309 /// \param Loc - The location of the statement we're complaining about. Ignored
9310 /// if we're not complaining, or if we're in overload resolution.
9311 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9313 bool InOverloadResolution,
9314 SourceLocation Loc) {
9315 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9317 if (InOverloadResolution)
9318 S.Diag(FD->getLocStart(),
9319 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9321 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9326 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9327 return P->hasAttr<PassObjectSizeAttr>();
9329 if (I == FD->param_end())
9333 // Add one to ParamNo because it's user-facing
9334 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9335 if (InOverloadResolution)
9336 S.Diag(FD->getLocation(),
9337 diag::note_ovl_candidate_has_pass_object_size_params)
9340 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9346 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9347 const FunctionDecl *FD) {
9348 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9349 /*InOverloadResolution=*/true,
9350 /*Loc=*/SourceLocation());
9353 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9355 SourceLocation Loc) {
9356 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9357 /*InOverloadResolution=*/false,
9361 // Notes the location of an overload candidate.
9362 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9363 QualType DestType, bool TakingAddress) {
9364 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9368 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9369 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9370 << (unsigned) K << Fn << FnDesc;
9372 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9373 Diag(Fn->getLocation(), PD);
9374 MaybeEmitInheritedConstructorNote(*this, Found);
9377 // Notes the location of all overload candidates designated through
9379 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9380 bool TakingAddress) {
9381 assert(OverloadedExpr->getType() == Context.OverloadTy);
9383 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9384 OverloadExpr *OvlExpr = Ovl.Expression;
9386 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9387 IEnd = OvlExpr->decls_end();
9389 if (FunctionTemplateDecl *FunTmpl =
9390 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9391 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9393 } else if (FunctionDecl *Fun
9394 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9395 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9400 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
9401 /// "lead" diagnostic; it will be given two arguments, the source and
9402 /// target types of the conversion.
9403 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9405 SourceLocation CaretLoc,
9406 const PartialDiagnostic &PDiag) const {
9407 S.Diag(CaretLoc, PDiag)
9408 << Ambiguous.getFromType() << Ambiguous.getToType();
9409 // FIXME: The note limiting machinery is borrowed from
9410 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9411 // refactoring here.
9412 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9413 unsigned CandsShown = 0;
9414 AmbiguousConversionSequence::const_iterator I, E;
9415 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9416 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9419 S.NoteOverloadCandidate(I->first, I->second);
9422 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9425 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9426 unsigned I, bool TakingCandidateAddress) {
9427 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9428 assert(Conv.isBad());
9429 assert(Cand->Function && "for now, candidate must be a function");
9430 FunctionDecl *Fn = Cand->Function;
9432 // There's a conversion slot for the object argument if this is a
9433 // non-constructor method. Note that 'I' corresponds the
9434 // conversion-slot index.
9435 bool isObjectArgument = false;
9436 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9438 isObjectArgument = true;
9444 OverloadCandidateKind FnKind =
9445 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9447 Expr *FromExpr = Conv.Bad.FromExpr;
9448 QualType FromTy = Conv.Bad.getFromType();
9449 QualType ToTy = Conv.Bad.getToType();
9451 if (FromTy == S.Context.OverloadTy) {
9452 assert(FromExpr && "overload set argument came from implicit argument?");
9453 Expr *E = FromExpr->IgnoreParens();
9454 if (isa<UnaryOperator>(E))
9455 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9456 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9459 << (unsigned) FnKind << FnDesc
9460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9461 << ToTy << Name << I+1;
9462 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9466 // Do some hand-waving analysis to see if the non-viability is due
9467 // to a qualifier mismatch.
9468 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9469 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9470 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9471 CToTy = RT->getPointeeType();
9473 // TODO: detect and diagnose the full richness of const mismatches.
9474 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9475 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9476 CFromTy = FromPT->getPointeeType();
9477 CToTy = ToPT->getPointeeType();
9481 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9482 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9483 Qualifiers FromQs = CFromTy.getQualifiers();
9484 Qualifiers ToQs = CToTy.getQualifiers();
9486 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9488 << (unsigned) FnKind << FnDesc
9489 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9491 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9492 << (unsigned) isObjectArgument << I+1;
9493 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9497 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9499 << (unsigned) FnKind << FnDesc
9500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9502 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9503 << (unsigned) isObjectArgument << I+1;
9504 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9508 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9510 << (unsigned) FnKind << FnDesc
9511 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9513 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9514 << (unsigned) isObjectArgument << I+1;
9515 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9519 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9521 << (unsigned) FnKind << FnDesc
9522 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9523 << FromTy << FromQs.hasUnaligned() << I+1;
9524 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9528 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9529 assert(CVR && "unexpected qualifiers mismatch");
9531 if (isObjectArgument) {
9532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9533 << (unsigned) FnKind << FnDesc
9534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9535 << FromTy << (CVR - 1);
9537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9538 << (unsigned) FnKind << FnDesc
9539 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9540 << FromTy << (CVR - 1) << I+1;
9542 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9546 // Special diagnostic for failure to convert an initializer list, since
9547 // telling the user that it has type void is not useful.
9548 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9550 << (unsigned) FnKind << FnDesc
9551 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9552 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9553 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9557 // Diagnose references or pointers to incomplete types differently,
9558 // since it's far from impossible that the incompleteness triggered
9560 QualType TempFromTy = FromTy.getNonReferenceType();
9561 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9562 TempFromTy = PTy->getPointeeType();
9563 if (TempFromTy->isIncompleteType()) {
9564 // Emit the generic diagnostic and, optionally, add the hints to it.
9565 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9566 << (unsigned) FnKind << FnDesc
9567 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9568 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9569 << (unsigned) (Cand->Fix.Kind);
9571 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9575 // Diagnose base -> derived pointer conversions.
9576 unsigned BaseToDerivedConversion = 0;
9577 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9578 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9579 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9580 FromPtrTy->getPointeeType()) &&
9581 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9582 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9583 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9584 FromPtrTy->getPointeeType()))
9585 BaseToDerivedConversion = 1;
9587 } else if (const ObjCObjectPointerType *FromPtrTy
9588 = FromTy->getAs<ObjCObjectPointerType>()) {
9589 if (const ObjCObjectPointerType *ToPtrTy
9590 = ToTy->getAs<ObjCObjectPointerType>())
9591 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9592 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9593 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9594 FromPtrTy->getPointeeType()) &&
9595 FromIface->isSuperClassOf(ToIface))
9596 BaseToDerivedConversion = 2;
9597 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9598 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9599 !FromTy->isIncompleteType() &&
9600 !ToRefTy->getPointeeType()->isIncompleteType() &&
9601 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9602 BaseToDerivedConversion = 3;
9603 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9604 ToTy.getNonReferenceType().getCanonicalType() ==
9605 FromTy.getNonReferenceType().getCanonicalType()) {
9606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9607 << (unsigned) FnKind << FnDesc
9608 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9609 << (unsigned) isObjectArgument << I + 1;
9610 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9615 if (BaseToDerivedConversion) {
9616 S.Diag(Fn->getLocation(),
9617 diag::note_ovl_candidate_bad_base_to_derived_conv)
9618 << (unsigned) FnKind << FnDesc
9619 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9620 << (BaseToDerivedConversion - 1)
9621 << FromTy << ToTy << I+1;
9622 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9626 if (isa<ObjCObjectPointerType>(CFromTy) &&
9627 isa<PointerType>(CToTy)) {
9628 Qualifiers FromQs = CFromTy.getQualifiers();
9629 Qualifiers ToQs = CToTy.getQualifiers();
9630 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9631 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9632 << (unsigned) FnKind << FnDesc
9633 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9634 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9635 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9640 if (TakingCandidateAddress &&
9641 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9644 // Emit the generic diagnostic and, optionally, add the hints to it.
9645 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9646 FDiag << (unsigned) FnKind << FnDesc
9647 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9648 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9649 << (unsigned) (Cand->Fix.Kind);
9651 // If we can fix the conversion, suggest the FixIts.
9652 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9653 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9655 S.Diag(Fn->getLocation(), FDiag);
9657 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9660 /// Additional arity mismatch diagnosis specific to a function overload
9661 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9662 /// over a candidate in any candidate set.
9663 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9665 FunctionDecl *Fn = Cand->Function;
9666 unsigned MinParams = Fn->getMinRequiredArguments();
9668 // With invalid overloaded operators, it's possible that we think we
9669 // have an arity mismatch when in fact it looks like we have the
9670 // right number of arguments, because only overloaded operators have
9671 // the weird behavior of overloading member and non-member functions.
9672 // Just don't report anything.
9673 if (Fn->isInvalidDecl() &&
9674 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9677 if (NumArgs < MinParams) {
9678 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9679 (Cand->FailureKind == ovl_fail_bad_deduction &&
9680 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9682 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9683 (Cand->FailureKind == ovl_fail_bad_deduction &&
9684 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9690 /// General arity mismatch diagnosis over a candidate in a candidate set.
9691 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9692 unsigned NumFormalArgs) {
9693 assert(isa<FunctionDecl>(D) &&
9694 "The templated declaration should at least be a function"
9695 " when diagnosing bad template argument deduction due to too many"
9696 " or too few arguments");
9698 FunctionDecl *Fn = cast<FunctionDecl>(D);
9700 // TODO: treat calls to a missing default constructor as a special case
9701 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9702 unsigned MinParams = Fn->getMinRequiredArguments();
9704 // at least / at most / exactly
9705 unsigned mode, modeCount;
9706 if (NumFormalArgs < MinParams) {
9707 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9708 FnTy->isTemplateVariadic())
9709 mode = 0; // "at least"
9711 mode = 2; // "exactly"
9712 modeCount = MinParams;
9714 if (MinParams != FnTy->getNumParams())
9715 mode = 1; // "at most"
9717 mode = 2; // "exactly"
9718 modeCount = FnTy->getNumParams();
9721 std::string Description;
9722 OverloadCandidateKind FnKind =
9723 ClassifyOverloadCandidate(S, Found, Fn, Description);
9725 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9726 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9727 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9728 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9731 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9732 << mode << modeCount << NumFormalArgs;
9733 MaybeEmitInheritedConstructorNote(S, Found);
9736 /// Arity mismatch diagnosis specific to a function overload candidate.
9737 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9738 unsigned NumFormalArgs) {
9739 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9740 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9743 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9744 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9746 llvm_unreachable("Unsupported: Getting the described template declaration"
9747 " for bad deduction diagnosis");
9750 /// Diagnose a failed template-argument deduction.
9751 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9752 DeductionFailureInfo &DeductionFailure,
9754 bool TakingCandidateAddress) {
9755 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9757 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9758 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9759 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9760 switch (DeductionFailure.Result) {
9761 case Sema::TDK_Success:
9762 llvm_unreachable("TDK_success while diagnosing bad deduction");
9764 case Sema::TDK_Incomplete: {
9765 assert(ParamD && "no parameter found for incomplete deduction result");
9766 S.Diag(Templated->getLocation(),
9767 diag::note_ovl_candidate_incomplete_deduction)
9768 << ParamD->getDeclName();
9769 MaybeEmitInheritedConstructorNote(S, Found);
9773 case Sema::TDK_Underqualified: {
9774 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9775 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9777 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9779 // Param will have been canonicalized, but it should just be a
9780 // qualified version of ParamD, so move the qualifiers to that.
9781 QualifierCollector Qs;
9783 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9784 assert(S.Context.hasSameType(Param, NonCanonParam));
9786 // Arg has also been canonicalized, but there's nothing we can do
9787 // about that. It also doesn't matter as much, because it won't
9788 // have any template parameters in it (because deduction isn't
9789 // done on dependent types).
9790 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9792 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9793 << ParamD->getDeclName() << Arg << NonCanonParam;
9794 MaybeEmitInheritedConstructorNote(S, Found);
9798 case Sema::TDK_Inconsistent: {
9799 assert(ParamD && "no parameter found for inconsistent deduction result");
9801 if (isa<TemplateTypeParmDecl>(ParamD))
9803 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9804 // Deduction might have failed because we deduced arguments of two
9805 // different types for a non-type template parameter.
9806 // FIXME: Use a different TDK value for this.
9808 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9810 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9811 if (!S.Context.hasSameType(T1, T2)) {
9812 S.Diag(Templated->getLocation(),
9813 diag::note_ovl_candidate_inconsistent_deduction_types)
9814 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9815 << *DeductionFailure.getSecondArg() << T2;
9816 MaybeEmitInheritedConstructorNote(S, Found);
9825 S.Diag(Templated->getLocation(),
9826 diag::note_ovl_candidate_inconsistent_deduction)
9827 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9828 << *DeductionFailure.getSecondArg();
9829 MaybeEmitInheritedConstructorNote(S, Found);
9833 case Sema::TDK_InvalidExplicitArguments:
9834 assert(ParamD && "no parameter found for invalid explicit arguments");
9835 if (ParamD->getDeclName())
9836 S.Diag(Templated->getLocation(),
9837 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9838 << ParamD->getDeclName();
9841 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9842 index = TTP->getIndex();
9843 else if (NonTypeTemplateParmDecl *NTTP
9844 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9845 index = NTTP->getIndex();
9847 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9848 S.Diag(Templated->getLocation(),
9849 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9852 MaybeEmitInheritedConstructorNote(S, Found);
9855 case Sema::TDK_TooManyArguments:
9856 case Sema::TDK_TooFewArguments:
9857 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9860 case Sema::TDK_InstantiationDepth:
9861 S.Diag(Templated->getLocation(),
9862 diag::note_ovl_candidate_instantiation_depth);
9863 MaybeEmitInheritedConstructorNote(S, Found);
9866 case Sema::TDK_SubstitutionFailure: {
9867 // Format the template argument list into the argument string.
9868 SmallString<128> TemplateArgString;
9869 if (TemplateArgumentList *Args =
9870 DeductionFailure.getTemplateArgumentList()) {
9871 TemplateArgString = " ";
9872 TemplateArgString += S.getTemplateArgumentBindingsText(
9873 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9876 // If this candidate was disabled by enable_if, say so.
9877 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9878 if (PDiag && PDiag->second.getDiagID() ==
9879 diag::err_typename_nested_not_found_enable_if) {
9880 // FIXME: Use the source range of the condition, and the fully-qualified
9881 // name of the enable_if template. These are both present in PDiag.
9882 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9883 << "'enable_if'" << TemplateArgString;
9887 // Format the SFINAE diagnostic into the argument string.
9888 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9889 // formatted message in another diagnostic.
9890 SmallString<128> SFINAEArgString;
9893 SFINAEArgString = ": ";
9894 R = SourceRange(PDiag->first, PDiag->first);
9895 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9898 S.Diag(Templated->getLocation(),
9899 diag::note_ovl_candidate_substitution_failure)
9900 << TemplateArgString << SFINAEArgString << R;
9901 MaybeEmitInheritedConstructorNote(S, Found);
9905 case Sema::TDK_DeducedMismatch:
9906 case Sema::TDK_DeducedMismatchNested: {
9907 // Format the template argument list into the argument string.
9908 SmallString<128> TemplateArgString;
9909 if (TemplateArgumentList *Args =
9910 DeductionFailure.getTemplateArgumentList()) {
9911 TemplateArgString = " ";
9912 TemplateArgString += S.getTemplateArgumentBindingsText(
9913 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9916 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9917 << (*DeductionFailure.getCallArgIndex() + 1)
9918 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9919 << TemplateArgString
9920 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
9924 case Sema::TDK_NonDeducedMismatch: {
9925 // FIXME: Provide a source location to indicate what we couldn't match.
9926 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9927 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9928 if (FirstTA.getKind() == TemplateArgument::Template &&
9929 SecondTA.getKind() == TemplateArgument::Template) {
9930 TemplateName FirstTN = FirstTA.getAsTemplate();
9931 TemplateName SecondTN = SecondTA.getAsTemplate();
9932 if (FirstTN.getKind() == TemplateName::Template &&
9933 SecondTN.getKind() == TemplateName::Template) {
9934 if (FirstTN.getAsTemplateDecl()->getName() ==
9935 SecondTN.getAsTemplateDecl()->getName()) {
9936 // FIXME: This fixes a bad diagnostic where both templates are named
9937 // the same. This particular case is a bit difficult since:
9938 // 1) It is passed as a string to the diagnostic printer.
9939 // 2) The diagnostic printer only attempts to find a better
9940 // name for types, not decls.
9941 // Ideally, this should folded into the diagnostic printer.
9942 S.Diag(Templated->getLocation(),
9943 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9944 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9950 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9951 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9954 // FIXME: For generic lambda parameters, check if the function is a lambda
9955 // call operator, and if so, emit a prettier and more informative
9956 // diagnostic that mentions 'auto' and lambda in addition to
9957 // (or instead of?) the canonical template type parameters.
9958 S.Diag(Templated->getLocation(),
9959 diag::note_ovl_candidate_non_deduced_mismatch)
9960 << FirstTA << SecondTA;
9963 // TODO: diagnose these individually, then kill off
9964 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9965 case Sema::TDK_MiscellaneousDeductionFailure:
9966 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9967 MaybeEmitInheritedConstructorNote(S, Found);
9969 case Sema::TDK_CUDATargetMismatch:
9970 S.Diag(Templated->getLocation(),
9971 diag::note_cuda_ovl_candidate_target_mismatch);
9976 /// Diagnose a failed template-argument deduction, for function calls.
9977 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9979 bool TakingCandidateAddress) {
9980 unsigned TDK = Cand->DeductionFailure.Result;
9981 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9982 if (CheckArityMismatch(S, Cand, NumArgs))
9985 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9986 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9989 /// CUDA: diagnose an invalid call across targets.
9990 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9991 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9992 FunctionDecl *Callee = Cand->Function;
9994 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9995 CalleeTarget = S.IdentifyCUDATarget(Callee);
9998 OverloadCandidateKind FnKind =
9999 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10001 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10002 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10004 // This could be an implicit constructor for which we could not infer the
10005 // target due to a collsion. Diagnose that case.
10006 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10007 if (Meth != nullptr && Meth->isImplicit()) {
10008 CXXRecordDecl *ParentClass = Meth->getParent();
10009 Sema::CXXSpecialMember CSM;
10014 case oc_implicit_default_constructor:
10015 CSM = Sema::CXXDefaultConstructor;
10017 case oc_implicit_copy_constructor:
10018 CSM = Sema::CXXCopyConstructor;
10020 case oc_implicit_move_constructor:
10021 CSM = Sema::CXXMoveConstructor;
10023 case oc_implicit_copy_assignment:
10024 CSM = Sema::CXXCopyAssignment;
10026 case oc_implicit_move_assignment:
10027 CSM = Sema::CXXMoveAssignment;
10031 bool ConstRHS = false;
10032 if (Meth->getNumParams()) {
10033 if (const ReferenceType *RT =
10034 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10035 ConstRHS = RT->getPointeeType().isConstQualified();
10039 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10040 /* ConstRHS */ ConstRHS,
10041 /* Diagnose */ true);
10045 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10046 FunctionDecl *Callee = Cand->Function;
10047 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10049 S.Diag(Callee->getLocation(),
10050 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10051 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10054 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10055 FunctionDecl *Callee = Cand->Function;
10057 S.Diag(Callee->getLocation(),
10058 diag::note_ovl_candidate_disabled_by_extension);
10061 /// Generates a 'note' diagnostic for an overload candidate. We've
10062 /// already generated a primary error at the call site.
10064 /// It really does need to be a single diagnostic with its caret
10065 /// pointed at the candidate declaration. Yes, this creates some
10066 /// major challenges of technical writing. Yes, this makes pointing
10067 /// out problems with specific arguments quite awkward. It's still
10068 /// better than generating twenty screens of text for every failed
10071 /// It would be great to be able to express per-candidate problems
10072 /// more richly for those diagnostic clients that cared, but we'd
10073 /// still have to be just as careful with the default diagnostics.
10074 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10076 bool TakingCandidateAddress) {
10077 FunctionDecl *Fn = Cand->Function;
10079 // Note deleted candidates, but only if they're viable.
10080 if (Cand->Viable) {
10081 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10082 std::string FnDesc;
10083 OverloadCandidateKind FnKind =
10084 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10087 << FnKind << FnDesc
10088 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10089 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10093 // We don't really have anything else to say about viable candidates.
10094 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10098 switch (Cand->FailureKind) {
10099 case ovl_fail_too_many_arguments:
10100 case ovl_fail_too_few_arguments:
10101 return DiagnoseArityMismatch(S, Cand, NumArgs);
10103 case ovl_fail_bad_deduction:
10104 return DiagnoseBadDeduction(S, Cand, NumArgs,
10105 TakingCandidateAddress);
10107 case ovl_fail_illegal_constructor: {
10108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10109 << (Fn->getPrimaryTemplate() ? 1 : 0);
10110 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10114 case ovl_fail_trivial_conversion:
10115 case ovl_fail_bad_final_conversion:
10116 case ovl_fail_final_conversion_not_exact:
10117 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10119 case ovl_fail_bad_conversion: {
10120 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10121 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10122 if (Cand->Conversions[I].isBad())
10123 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10125 // FIXME: this currently happens when we're called from SemaInit
10126 // when user-conversion overload fails. Figure out how to handle
10127 // those conditions and diagnose them well.
10128 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10131 case ovl_fail_bad_target:
10132 return DiagnoseBadTarget(S, Cand);
10134 case ovl_fail_enable_if:
10135 return DiagnoseFailedEnableIfAttr(S, Cand);
10137 case ovl_fail_ext_disabled:
10138 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10140 case ovl_fail_inhctor_slice:
10141 // It's generally not interesting to note copy/move constructors here.
10142 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10144 S.Diag(Fn->getLocation(),
10145 diag::note_ovl_candidate_inherited_constructor_slice)
10146 << (Fn->getPrimaryTemplate() ? 1 : 0)
10147 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10148 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10151 case ovl_fail_addr_not_available: {
10152 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10154 assert(!Available);
10160 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10161 // Desugar the type of the surrogate down to a function type,
10162 // retaining as many typedefs as possible while still showing
10163 // the function type (and, therefore, its parameter types).
10164 QualType FnType = Cand->Surrogate->getConversionType();
10165 bool isLValueReference = false;
10166 bool isRValueReference = false;
10167 bool isPointer = false;
10168 if (const LValueReferenceType *FnTypeRef =
10169 FnType->getAs<LValueReferenceType>()) {
10170 FnType = FnTypeRef->getPointeeType();
10171 isLValueReference = true;
10172 } else if (const RValueReferenceType *FnTypeRef =
10173 FnType->getAs<RValueReferenceType>()) {
10174 FnType = FnTypeRef->getPointeeType();
10175 isRValueReference = true;
10177 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10178 FnType = FnTypePtr->getPointeeType();
10181 // Desugar down to a function type.
10182 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10183 // Reconstruct the pointer/reference as appropriate.
10184 if (isPointer) FnType = S.Context.getPointerType(FnType);
10185 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10186 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10188 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10192 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10193 SourceLocation OpLoc,
10194 OverloadCandidate *Cand) {
10195 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10196 std::string TypeStr("operator");
10199 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
10200 if (Cand->Conversions.size() == 1) {
10202 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10205 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10207 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10211 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10212 OverloadCandidate *Cand) {
10213 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10214 if (ICS.isBad()) break; // all meaningless after first invalid
10215 if (!ICS.isAmbiguous()) continue;
10217 ICS.DiagnoseAmbiguousConversion(
10218 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10222 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10223 if (Cand->Function)
10224 return Cand->Function->getLocation();
10225 if (Cand->IsSurrogate)
10226 return Cand->Surrogate->getLocation();
10227 return SourceLocation();
10230 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10231 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10232 case Sema::TDK_Success:
10233 case Sema::TDK_NonDependentConversionFailure:
10234 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10236 case Sema::TDK_Invalid:
10237 case Sema::TDK_Incomplete:
10240 case Sema::TDK_Underqualified:
10241 case Sema::TDK_Inconsistent:
10244 case Sema::TDK_SubstitutionFailure:
10245 case Sema::TDK_DeducedMismatch:
10246 case Sema::TDK_DeducedMismatchNested:
10247 case Sema::TDK_NonDeducedMismatch:
10248 case Sema::TDK_MiscellaneousDeductionFailure:
10249 case Sema::TDK_CUDATargetMismatch:
10252 case Sema::TDK_InstantiationDepth:
10255 case Sema::TDK_InvalidExplicitArguments:
10258 case Sema::TDK_TooManyArguments:
10259 case Sema::TDK_TooFewArguments:
10262 llvm_unreachable("Unhandled deduction result");
10266 struct CompareOverloadCandidatesForDisplay {
10268 SourceLocation Loc;
10271 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10272 : S(S), NumArgs(nArgs) {}
10274 bool operator()(const OverloadCandidate *L,
10275 const OverloadCandidate *R) {
10276 // Fast-path this check.
10277 if (L == R) return false;
10279 // Order first by viability.
10281 if (!R->Viable) return true;
10283 // TODO: introduce a tri-valued comparison for overload
10284 // candidates. Would be more worthwhile if we had a sort
10285 // that could exploit it.
10286 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10287 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10288 } else if (R->Viable)
10291 assert(L->Viable == R->Viable);
10293 // Criteria by which we can sort non-viable candidates:
10295 // 1. Arity mismatches come after other candidates.
10296 if (L->FailureKind == ovl_fail_too_many_arguments ||
10297 L->FailureKind == ovl_fail_too_few_arguments) {
10298 if (R->FailureKind == ovl_fail_too_many_arguments ||
10299 R->FailureKind == ovl_fail_too_few_arguments) {
10300 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10301 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10302 if (LDist == RDist) {
10303 if (L->FailureKind == R->FailureKind)
10304 // Sort non-surrogates before surrogates.
10305 return !L->IsSurrogate && R->IsSurrogate;
10306 // Sort candidates requiring fewer parameters than there were
10307 // arguments given after candidates requiring more parameters
10308 // than there were arguments given.
10309 return L->FailureKind == ovl_fail_too_many_arguments;
10311 return LDist < RDist;
10315 if (R->FailureKind == ovl_fail_too_many_arguments ||
10316 R->FailureKind == ovl_fail_too_few_arguments)
10319 // 2. Bad conversions come first and are ordered by the number
10320 // of bad conversions and quality of good conversions.
10321 if (L->FailureKind == ovl_fail_bad_conversion) {
10322 if (R->FailureKind != ovl_fail_bad_conversion)
10325 // The conversion that can be fixed with a smaller number of changes,
10327 unsigned numLFixes = L->Fix.NumConversionsFixed;
10328 unsigned numRFixes = R->Fix.NumConversionsFixed;
10329 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10330 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10331 if (numLFixes != numRFixes) {
10332 return numLFixes < numRFixes;
10335 // If there's any ordering between the defined conversions...
10336 // FIXME: this might not be transitive.
10337 assert(L->Conversions.size() == R->Conversions.size());
10339 int leftBetter = 0;
10340 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10341 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10342 switch (CompareImplicitConversionSequences(S, Loc,
10344 R->Conversions[I])) {
10345 case ImplicitConversionSequence::Better:
10349 case ImplicitConversionSequence::Worse:
10353 case ImplicitConversionSequence::Indistinguishable:
10357 if (leftBetter > 0) return true;
10358 if (leftBetter < 0) return false;
10360 } else if (R->FailureKind == ovl_fail_bad_conversion)
10363 if (L->FailureKind == ovl_fail_bad_deduction) {
10364 if (R->FailureKind != ovl_fail_bad_deduction)
10367 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10368 return RankDeductionFailure(L->DeductionFailure)
10369 < RankDeductionFailure(R->DeductionFailure);
10370 } else if (R->FailureKind == ovl_fail_bad_deduction)
10376 // Sort everything else by location.
10377 SourceLocation LLoc = GetLocationForCandidate(L);
10378 SourceLocation RLoc = GetLocationForCandidate(R);
10380 // Put candidates without locations (e.g. builtins) at the end.
10381 if (LLoc.isInvalid()) return false;
10382 if (RLoc.isInvalid()) return true;
10384 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10389 /// CompleteNonViableCandidate - Normally, overload resolution only
10390 /// computes up to the first bad conversion. Produces the FixIt set if
10392 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10393 ArrayRef<Expr *> Args) {
10394 assert(!Cand->Viable);
10396 // Don't do anything on failures other than bad conversion.
10397 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10399 // We only want the FixIts if all the arguments can be corrected.
10400 bool Unfixable = false;
10401 // Use a implicit copy initialization to check conversion fixes.
10402 Cand->Fix.setConversionChecker(TryCopyInitialization);
10404 // Attempt to fix the bad conversion.
10405 unsigned ConvCount = Cand->Conversions.size();
10406 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10408 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10409 if (Cand->Conversions[ConvIdx].isInitialized() &&
10410 Cand->Conversions[ConvIdx].isBad()) {
10411 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10416 // FIXME: this should probably be preserved from the overload
10417 // operation somehow.
10418 bool SuppressUserConversions = false;
10420 unsigned ConvIdx = 0;
10421 ArrayRef<QualType> ParamTypes;
10423 if (Cand->IsSurrogate) {
10425 = Cand->Surrogate->getConversionType().getNonReferenceType();
10426 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10427 ConvType = ConvPtrType->getPointeeType();
10428 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10429 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10431 } else if (Cand->Function) {
10433 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10434 if (isa<CXXMethodDecl>(Cand->Function) &&
10435 !isa<CXXConstructorDecl>(Cand->Function)) {
10436 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10440 // Builtin operator.
10441 assert(ConvCount <= 3);
10442 ParamTypes = Cand->BuiltinTypes.ParamTypes;
10445 // Fill in the rest of the conversions.
10446 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10447 if (Cand->Conversions[ConvIdx].isInitialized()) {
10448 // We've already checked this conversion.
10449 } else if (ArgIdx < ParamTypes.size()) {
10450 if (ParamTypes[ArgIdx]->isDependentType())
10451 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10452 Args[ArgIdx]->getType());
10454 Cand->Conversions[ConvIdx] =
10455 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10456 SuppressUserConversions,
10457 /*InOverloadResolution=*/true,
10458 /*AllowObjCWritebackConversion=*/
10459 S.getLangOpts().ObjCAutoRefCount);
10460 // Store the FixIt in the candidate if it exists.
10461 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10462 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10465 Cand->Conversions[ConvIdx].setEllipsis();
10469 /// PrintOverloadCandidates - When overload resolution fails, prints
10470 /// diagnostic messages containing the candidates in the candidate
10472 void OverloadCandidateSet::NoteCandidates(
10473 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10474 StringRef Opc, SourceLocation OpLoc,
10475 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10476 // Sort the candidates by viability and position. Sorting directly would
10477 // be prohibitive, so we make a set of pointers and sort those.
10478 SmallVector<OverloadCandidate*, 32> Cands;
10479 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10480 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10481 if (!Filter(*Cand))
10484 Cands.push_back(Cand);
10485 else if (OCD == OCD_AllCandidates) {
10486 CompleteNonViableCandidate(S, Cand, Args);
10487 if (Cand->Function || Cand->IsSurrogate)
10488 Cands.push_back(Cand);
10489 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10490 // want to list every possible builtin candidate.
10494 std::sort(Cands.begin(), Cands.end(),
10495 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10497 bool ReportedAmbiguousConversions = false;
10499 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10500 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10501 unsigned CandsShown = 0;
10502 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10503 OverloadCandidate *Cand = *I;
10505 // Set an arbitrary limit on the number of candidate functions we'll spam
10506 // the user with. FIXME: This limit should depend on details of the
10508 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10513 if (Cand->Function)
10514 NoteFunctionCandidate(S, Cand, Args.size(),
10515 /*TakingCandidateAddress=*/false);
10516 else if (Cand->IsSurrogate)
10517 NoteSurrogateCandidate(S, Cand);
10519 assert(Cand->Viable &&
10520 "Non-viable built-in candidates are not added to Cands.");
10521 // Generally we only see ambiguities including viable builtin
10522 // operators if overload resolution got screwed up by an
10523 // ambiguous user-defined conversion.
10525 // FIXME: It's quite possible for different conversions to see
10526 // different ambiguities, though.
10527 if (!ReportedAmbiguousConversions) {
10528 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10529 ReportedAmbiguousConversions = true;
10532 // If this is a viable builtin, print it.
10533 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10538 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10541 static SourceLocation
10542 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10543 return Cand->Specialization ? Cand->Specialization->getLocation()
10544 : SourceLocation();
10548 struct CompareTemplateSpecCandidatesForDisplay {
10550 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10552 bool operator()(const TemplateSpecCandidate *L,
10553 const TemplateSpecCandidate *R) {
10554 // Fast-path this check.
10558 // Assuming that both candidates are not matches...
10560 // Sort by the ranking of deduction failures.
10561 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10562 return RankDeductionFailure(L->DeductionFailure) <
10563 RankDeductionFailure(R->DeductionFailure);
10565 // Sort everything else by location.
10566 SourceLocation LLoc = GetLocationForCandidate(L);
10567 SourceLocation RLoc = GetLocationForCandidate(R);
10569 // Put candidates without locations (e.g. builtins) at the end.
10570 if (LLoc.isInvalid())
10572 if (RLoc.isInvalid())
10575 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10580 /// Diagnose a template argument deduction failure.
10581 /// We are treating these failures as overload failures due to bad
10583 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10584 bool ForTakingAddress) {
10585 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10586 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10589 void TemplateSpecCandidateSet::destroyCandidates() {
10590 for (iterator i = begin(), e = end(); i != e; ++i) {
10591 i->DeductionFailure.Destroy();
10595 void TemplateSpecCandidateSet::clear() {
10596 destroyCandidates();
10597 Candidates.clear();
10600 /// NoteCandidates - When no template specialization match is found, prints
10601 /// diagnostic messages containing the non-matching specializations that form
10602 /// the candidate set.
10603 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10604 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10605 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10606 // Sort the candidates by position (assuming no candidate is a match).
10607 // Sorting directly would be prohibitive, so we make a set of pointers
10609 SmallVector<TemplateSpecCandidate *, 32> Cands;
10610 Cands.reserve(size());
10611 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10612 if (Cand->Specialization)
10613 Cands.push_back(Cand);
10614 // Otherwise, this is a non-matching builtin candidate. We do not,
10615 // in general, want to list every possible builtin candidate.
10618 std::sort(Cands.begin(), Cands.end(),
10619 CompareTemplateSpecCandidatesForDisplay(S));
10621 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10622 // for generalization purposes (?).
10623 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10625 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10626 unsigned CandsShown = 0;
10627 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10628 TemplateSpecCandidate *Cand = *I;
10630 // Set an arbitrary limit on the number of candidates we'll spam
10631 // the user with. FIXME: This limit should depend on details of the
10633 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10637 assert(Cand->Specialization &&
10638 "Non-matching built-in candidates are not added to Cands.");
10639 Cand->NoteDeductionFailure(S, ForTakingAddress);
10643 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10646 // [PossiblyAFunctionType] --> [Return]
10647 // NonFunctionType --> NonFunctionType
10649 // R (*)(A) --> R (A)
10650 // R (&)(A) --> R (A)
10651 // R (S::*)(A) --> R (A)
10652 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10653 QualType Ret = PossiblyAFunctionType;
10654 if (const PointerType *ToTypePtr =
10655 PossiblyAFunctionType->getAs<PointerType>())
10656 Ret = ToTypePtr->getPointeeType();
10657 else if (const ReferenceType *ToTypeRef =
10658 PossiblyAFunctionType->getAs<ReferenceType>())
10659 Ret = ToTypeRef->getPointeeType();
10660 else if (const MemberPointerType *MemTypePtr =
10661 PossiblyAFunctionType->getAs<MemberPointerType>())
10662 Ret = MemTypePtr->getPointeeType();
10664 Context.getCanonicalType(Ret).getUnqualifiedType();
10668 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10669 bool Complain = true) {
10670 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10671 S.DeduceReturnType(FD, Loc, Complain))
10674 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10675 if (S.getLangOpts().CPlusPlus1z &&
10676 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10677 !S.ResolveExceptionSpec(Loc, FPT))
10684 // A helper class to help with address of function resolution
10685 // - allows us to avoid passing around all those ugly parameters
10686 class AddressOfFunctionResolver {
10689 const QualType& TargetType;
10690 QualType TargetFunctionType; // Extracted function type from target type
10693 //DeclAccessPair& ResultFunctionAccessPair;
10694 ASTContext& Context;
10696 bool TargetTypeIsNonStaticMemberFunction;
10697 bool FoundNonTemplateFunction;
10698 bool StaticMemberFunctionFromBoundPointer;
10699 bool HasComplained;
10701 OverloadExpr::FindResult OvlExprInfo;
10702 OverloadExpr *OvlExpr;
10703 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10704 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10705 TemplateSpecCandidateSet FailedCandidates;
10708 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10709 const QualType &TargetType, bool Complain)
10710 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10711 Complain(Complain), Context(S.getASTContext()),
10712 TargetTypeIsNonStaticMemberFunction(
10713 !!TargetType->getAs<MemberPointerType>()),
10714 FoundNonTemplateFunction(false),
10715 StaticMemberFunctionFromBoundPointer(false),
10716 HasComplained(false),
10717 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10718 OvlExpr(OvlExprInfo.Expression),
10719 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10720 ExtractUnqualifiedFunctionTypeFromTargetType();
10722 if (TargetFunctionType->isFunctionType()) {
10723 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10724 if (!UME->isImplicitAccess() &&
10725 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10726 StaticMemberFunctionFromBoundPointer = true;
10727 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10728 DeclAccessPair dap;
10729 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10730 OvlExpr, false, &dap)) {
10731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10732 if (!Method->isStatic()) {
10733 // If the target type is a non-function type and the function found
10734 // is a non-static member function, pretend as if that was the
10735 // target, it's the only possible type to end up with.
10736 TargetTypeIsNonStaticMemberFunction = true;
10738 // And skip adding the function if its not in the proper form.
10739 // We'll diagnose this due to an empty set of functions.
10740 if (!OvlExprInfo.HasFormOfMemberPointer)
10744 Matches.push_back(std::make_pair(dap, Fn));
10749 if (OvlExpr->hasExplicitTemplateArgs())
10750 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10752 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10753 // C++ [over.over]p4:
10754 // If more than one function is selected, [...]
10755 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10756 if (FoundNonTemplateFunction)
10757 EliminateAllTemplateMatches();
10759 EliminateAllExceptMostSpecializedTemplate();
10763 if (S.getLangOpts().CUDA && Matches.size() > 1)
10764 EliminateSuboptimalCudaMatches();
10767 bool hasComplained() const { return HasComplained; }
10770 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10772 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10773 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10776 /// \return true if A is considered a better overload candidate for the
10777 /// desired type than B.
10778 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10779 // If A doesn't have exactly the correct type, we don't want to classify it
10780 // as "better" than anything else. This way, the user is required to
10781 // disambiguate for us if there are multiple candidates and no exact match.
10782 return candidateHasExactlyCorrectType(A) &&
10783 (!candidateHasExactlyCorrectType(B) ||
10784 compareEnableIfAttrs(S, A, B) == Comparison::Better);
10787 /// \return true if we were able to eliminate all but one overload candidate,
10788 /// false otherwise.
10789 bool eliminiateSuboptimalOverloadCandidates() {
10790 // Same algorithm as overload resolution -- one pass to pick the "best",
10791 // another pass to be sure that nothing is better than the best.
10792 auto Best = Matches.begin();
10793 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10794 if (isBetterCandidate(I->second, Best->second))
10797 const FunctionDecl *BestFn = Best->second;
10798 auto IsBestOrInferiorToBest = [this, BestFn](
10799 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10800 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10803 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10804 // option, so we can potentially give the user a better error
10805 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10807 Matches[0] = *Best;
10812 bool isTargetTypeAFunction() const {
10813 return TargetFunctionType->isFunctionType();
10816 // [ToType] [Return]
10818 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10819 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10820 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10821 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10822 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10825 // return true if any matching specializations were found
10826 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10827 const DeclAccessPair& CurAccessFunPair) {
10828 if (CXXMethodDecl *Method
10829 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10830 // Skip non-static function templates when converting to pointer, and
10831 // static when converting to member pointer.
10832 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10835 else if (TargetTypeIsNonStaticMemberFunction)
10838 // C++ [over.over]p2:
10839 // If the name is a function template, template argument deduction is
10840 // done (14.8.2.2), and if the argument deduction succeeds, the
10841 // resulting template argument list is used to generate a single
10842 // function template specialization, which is added to the set of
10843 // overloaded functions considered.
10844 FunctionDecl *Specialization = nullptr;
10845 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10846 if (Sema::TemplateDeductionResult Result
10847 = S.DeduceTemplateArguments(FunctionTemplate,
10848 &OvlExplicitTemplateArgs,
10849 TargetFunctionType, Specialization,
10850 Info, /*IsAddressOfFunction*/true)) {
10851 // Make a note of the failed deduction for diagnostics.
10852 FailedCandidates.addCandidate()
10853 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10854 MakeDeductionFailureInfo(Context, Result, Info));
10858 // Template argument deduction ensures that we have an exact match or
10859 // compatible pointer-to-function arguments that would be adjusted by ICS.
10860 // This function template specicalization works.
10861 assert(S.isSameOrCompatibleFunctionType(
10862 Context.getCanonicalType(Specialization->getType()),
10863 Context.getCanonicalType(TargetFunctionType)));
10865 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10868 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10872 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10873 const DeclAccessPair& CurAccessFunPair) {
10874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10875 // Skip non-static functions when converting to pointer, and static
10876 // when converting to member pointer.
10877 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10880 else if (TargetTypeIsNonStaticMemberFunction)
10883 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10884 if (S.getLangOpts().CUDA)
10885 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10886 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10889 // If any candidate has a placeholder return type, trigger its deduction
10891 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10893 HasComplained |= Complain;
10897 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10900 // If we're in C, we need to support types that aren't exactly identical.
10901 if (!S.getLangOpts().CPlusPlus ||
10902 candidateHasExactlyCorrectType(FunDecl)) {
10903 Matches.push_back(std::make_pair(
10904 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10905 FoundNonTemplateFunction = true;
10913 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10916 // If the overload expression doesn't have the form of a pointer to
10917 // member, don't try to convert it to a pointer-to-member type.
10918 if (IsInvalidFormOfPointerToMemberFunction())
10921 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10922 E = OvlExpr->decls_end();
10924 // Look through any using declarations to find the underlying function.
10925 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10927 // C++ [over.over]p3:
10928 // Non-member functions and static member functions match
10929 // targets of type "pointer-to-function" or "reference-to-function."
10930 // Nonstatic member functions match targets of
10931 // type "pointer-to-member-function."
10932 // Note that according to DR 247, the containing class does not matter.
10933 if (FunctionTemplateDecl *FunctionTemplate
10934 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10935 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10938 // If we have explicit template arguments supplied, skip non-templates.
10939 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10940 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10943 assert(Ret || Matches.empty());
10947 void EliminateAllExceptMostSpecializedTemplate() {
10948 // [...] and any given function template specialization F1 is
10949 // eliminated if the set contains a second function template
10950 // specialization whose function template is more specialized
10951 // than the function template of F1 according to the partial
10952 // ordering rules of 14.5.5.2.
10954 // The algorithm specified above is quadratic. We instead use a
10955 // two-pass algorithm (similar to the one used to identify the
10956 // best viable function in an overload set) that identifies the
10957 // best function template (if it exists).
10959 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10960 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10961 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10963 // TODO: It looks like FailedCandidates does not serve much purpose
10964 // here, since the no_viable diagnostic has index 0.
10965 UnresolvedSetIterator Result = S.getMostSpecialized(
10966 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10967 SourceExpr->getLocStart(), S.PDiag(),
10968 S.PDiag(diag::err_addr_ovl_ambiguous)
10969 << Matches[0].second->getDeclName(),
10970 S.PDiag(diag::note_ovl_candidate)
10971 << (unsigned)oc_function_template,
10972 Complain, TargetFunctionType);
10974 if (Result != MatchesCopy.end()) {
10975 // Make it the first and only element
10976 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10977 Matches[0].second = cast<FunctionDecl>(*Result);
10980 HasComplained |= Complain;
10983 void EliminateAllTemplateMatches() {
10984 // [...] any function template specializations in the set are
10985 // eliminated if the set also contains a non-template function, [...]
10986 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10987 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10990 Matches[I] = Matches[--N];
10996 void EliminateSuboptimalCudaMatches() {
10997 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11001 void ComplainNoMatchesFound() const {
11002 assert(Matches.empty());
11003 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11004 << OvlExpr->getName() << TargetFunctionType
11005 << OvlExpr->getSourceRange();
11006 if (FailedCandidates.empty())
11007 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11008 /*TakingAddress=*/true);
11010 // We have some deduction failure messages. Use them to diagnose
11011 // the function templates, and diagnose the non-template candidates
11013 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11014 IEnd = OvlExpr->decls_end();
11016 if (FunctionDecl *Fun =
11017 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11018 if (!functionHasPassObjectSizeParams(Fun))
11019 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11020 /*TakingAddress=*/true);
11021 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11025 bool IsInvalidFormOfPointerToMemberFunction() const {
11026 return TargetTypeIsNonStaticMemberFunction &&
11027 !OvlExprInfo.HasFormOfMemberPointer;
11030 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11031 // TODO: Should we condition this on whether any functions might
11032 // have matched, or is it more appropriate to do that in callers?
11033 // TODO: a fixit wouldn't hurt.
11034 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11035 << TargetType << OvlExpr->getSourceRange();
11038 bool IsStaticMemberFunctionFromBoundPointer() const {
11039 return StaticMemberFunctionFromBoundPointer;
11042 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11043 S.Diag(OvlExpr->getLocStart(),
11044 diag::err_invalid_form_pointer_member_function)
11045 << OvlExpr->getSourceRange();
11048 void ComplainOfInvalidConversion() const {
11049 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11050 << OvlExpr->getName() << TargetType;
11053 void ComplainMultipleMatchesFound() const {
11054 assert(Matches.size() > 1);
11055 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11056 << OvlExpr->getName()
11057 << OvlExpr->getSourceRange();
11058 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11059 /*TakingAddress=*/true);
11062 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11064 int getNumMatches() const { return Matches.size(); }
11066 FunctionDecl* getMatchingFunctionDecl() const {
11067 if (Matches.size() != 1) return nullptr;
11068 return Matches[0].second;
11071 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11072 if (Matches.size() != 1) return nullptr;
11073 return &Matches[0].first;
11078 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11079 /// an overloaded function (C++ [over.over]), where @p From is an
11080 /// expression with overloaded function type and @p ToType is the type
11081 /// we're trying to resolve to. For example:
11087 /// int (*pfd)(double) = f; // selects f(double)
11090 /// This routine returns the resulting FunctionDecl if it could be
11091 /// resolved, and NULL otherwise. When @p Complain is true, this
11092 /// routine will emit diagnostics if there is an error.
11094 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11095 QualType TargetType,
11097 DeclAccessPair &FoundResult,
11098 bool *pHadMultipleCandidates) {
11099 assert(AddressOfExpr->getType() == Context.OverloadTy);
11101 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11103 int NumMatches = Resolver.getNumMatches();
11104 FunctionDecl *Fn = nullptr;
11105 bool ShouldComplain = Complain && !Resolver.hasComplained();
11106 if (NumMatches == 0 && ShouldComplain) {
11107 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11108 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11110 Resolver.ComplainNoMatchesFound();
11112 else if (NumMatches > 1 && ShouldComplain)
11113 Resolver.ComplainMultipleMatchesFound();
11114 else if (NumMatches == 1) {
11115 Fn = Resolver.getMatchingFunctionDecl();
11117 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11118 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11119 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11121 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11122 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11124 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11128 if (pHadMultipleCandidates)
11129 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11133 /// \brief Given an expression that refers to an overloaded function, try to
11134 /// resolve that function to a single function that can have its address taken.
11135 /// This will modify `Pair` iff it returns non-null.
11137 /// This routine can only realistically succeed if all but one candidates in the
11138 /// overload set for SrcExpr cannot have their addresses taken.
11140 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11141 DeclAccessPair &Pair) {
11142 OverloadExpr::FindResult R = OverloadExpr::find(E);
11143 OverloadExpr *Ovl = R.Expression;
11144 FunctionDecl *Result = nullptr;
11145 DeclAccessPair DAP;
11146 // Don't use the AddressOfResolver because we're specifically looking for
11147 // cases where we have one overload candidate that lacks
11148 // enable_if/pass_object_size/...
11149 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11150 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11154 if (!checkAddressOfFunctionIsAvailable(FD))
11157 // We have more than one result; quit.
11169 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
11170 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11171 /// will perform access checks, diagnose the use of the resultant decl, and, if
11172 /// necessary, perform a function-to-pointer decay.
11174 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11175 /// Otherwise, returns true. This may emit diagnostics and return true.
11176 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11177 ExprResult &SrcExpr) {
11178 Expr *E = SrcExpr.get();
11179 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11181 DeclAccessPair DAP;
11182 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11186 // Emitting multiple diagnostics for a function that is both inaccessible and
11187 // unavailable is consistent with our behavior elsewhere. So, always check
11189 DiagnoseUseOfDecl(Found, E->getExprLoc());
11190 CheckAddressOfMemberAccess(E, DAP);
11191 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11192 if (Fixed->getType()->isFunctionType())
11193 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11199 /// \brief Given an expression that refers to an overloaded function, try to
11200 /// resolve that overloaded function expression down to a single function.
11202 /// This routine can only resolve template-ids that refer to a single function
11203 /// template, where that template-id refers to a single template whose template
11204 /// arguments are either provided by the template-id or have defaults,
11205 /// as described in C++0x [temp.arg.explicit]p3.
11207 /// If no template-ids are found, no diagnostics are emitted and NULL is
11210 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11212 DeclAccessPair *FoundResult) {
11213 // C++ [over.over]p1:
11214 // [...] [Note: any redundant set of parentheses surrounding the
11215 // overloaded function name is ignored (5.1). ]
11216 // C++ [over.over]p1:
11217 // [...] The overloaded function name can be preceded by the &
11220 // If we didn't actually find any template-ids, we're done.
11221 if (!ovl->hasExplicitTemplateArgs())
11224 TemplateArgumentListInfo ExplicitTemplateArgs;
11225 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11226 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11228 // Look through all of the overloaded functions, searching for one
11229 // whose type matches exactly.
11230 FunctionDecl *Matched = nullptr;
11231 for (UnresolvedSetIterator I = ovl->decls_begin(),
11232 E = ovl->decls_end(); I != E; ++I) {
11233 // C++0x [temp.arg.explicit]p3:
11234 // [...] In contexts where deduction is done and fails, or in contexts
11235 // where deduction is not done, if a template argument list is
11236 // specified and it, along with any default template arguments,
11237 // identifies a single function template specialization, then the
11238 // template-id is an lvalue for the function template specialization.
11239 FunctionTemplateDecl *FunctionTemplate
11240 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11242 // C++ [over.over]p2:
11243 // If the name is a function template, template argument deduction is
11244 // done (14.8.2.2), and if the argument deduction succeeds, the
11245 // resulting template argument list is used to generate a single
11246 // function template specialization, which is added to the set of
11247 // overloaded functions considered.
11248 FunctionDecl *Specialization = nullptr;
11249 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11250 if (TemplateDeductionResult Result
11251 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11252 Specialization, Info,
11253 /*IsAddressOfFunction*/true)) {
11254 // Make a note of the failed deduction for diagnostics.
11255 // TODO: Actually use the failed-deduction info?
11256 FailedCandidates.addCandidate()
11257 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11258 MakeDeductionFailureInfo(Context, Result, Info));
11262 assert(Specialization && "no specialization and no error?");
11264 // Multiple matches; we can't resolve to a single declaration.
11267 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11269 NoteAllOverloadCandidates(ovl);
11274 Matched = Specialization;
11275 if (FoundResult) *FoundResult = I.getPair();
11279 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11288 // Resolve and fix an overloaded expression that can be resolved
11289 // because it identifies a single function template specialization.
11291 // Last three arguments should only be supplied if Complain = true
11293 // Return true if it was logically possible to so resolve the
11294 // expression, regardless of whether or not it succeeded. Always
11295 // returns true if 'complain' is set.
11296 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11297 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11298 bool complain, SourceRange OpRangeForComplaining,
11299 QualType DestTypeForComplaining,
11300 unsigned DiagIDForComplaining) {
11301 assert(SrcExpr.get()->getType() == Context.OverloadTy);
11303 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11305 DeclAccessPair found;
11306 ExprResult SingleFunctionExpression;
11307 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11308 ovl.Expression, /*complain*/ false, &found)) {
11309 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11310 SrcExpr = ExprError();
11314 // It is only correct to resolve to an instance method if we're
11315 // resolving a form that's permitted to be a pointer to member.
11316 // Otherwise we'll end up making a bound member expression, which
11317 // is illegal in all the contexts we resolve like this.
11318 if (!ovl.HasFormOfMemberPointer &&
11319 isa<CXXMethodDecl>(fn) &&
11320 cast<CXXMethodDecl>(fn)->isInstance()) {
11321 if (!complain) return false;
11323 Diag(ovl.Expression->getExprLoc(),
11324 diag::err_bound_member_function)
11325 << 0 << ovl.Expression->getSourceRange();
11327 // TODO: I believe we only end up here if there's a mix of
11328 // static and non-static candidates (otherwise the expression
11329 // would have 'bound member' type, not 'overload' type).
11330 // Ideally we would note which candidate was chosen and why
11331 // the static candidates were rejected.
11332 SrcExpr = ExprError();
11336 // Fix the expression to refer to 'fn'.
11337 SingleFunctionExpression =
11338 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11340 // If desired, do function-to-pointer decay.
11341 if (doFunctionPointerConverion) {
11342 SingleFunctionExpression =
11343 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11344 if (SingleFunctionExpression.isInvalid()) {
11345 SrcExpr = ExprError();
11351 if (!SingleFunctionExpression.isUsable()) {
11353 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11354 << ovl.Expression->getName()
11355 << DestTypeForComplaining
11356 << OpRangeForComplaining
11357 << ovl.Expression->getQualifierLoc().getSourceRange();
11358 NoteAllOverloadCandidates(SrcExpr.get());
11360 SrcExpr = ExprError();
11367 SrcExpr = SingleFunctionExpression;
11371 /// \brief Add a single candidate to the overload set.
11372 static void AddOverloadedCallCandidate(Sema &S,
11373 DeclAccessPair FoundDecl,
11374 TemplateArgumentListInfo *ExplicitTemplateArgs,
11375 ArrayRef<Expr *> Args,
11376 OverloadCandidateSet &CandidateSet,
11377 bool PartialOverloading,
11379 NamedDecl *Callee = FoundDecl.getDecl();
11380 if (isa<UsingShadowDecl>(Callee))
11381 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11383 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11384 if (ExplicitTemplateArgs) {
11385 assert(!KnownValid && "Explicit template arguments?");
11388 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11389 /*SuppressUsedConversions=*/false,
11390 PartialOverloading);
11394 if (FunctionTemplateDecl *FuncTemplate
11395 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11396 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11397 ExplicitTemplateArgs, Args, CandidateSet,
11398 /*SuppressUsedConversions=*/false,
11399 PartialOverloading);
11403 assert(!KnownValid && "unhandled case in overloaded call candidate");
11406 /// \brief Add the overload candidates named by callee and/or found by argument
11407 /// dependent lookup to the given overload set.
11408 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11409 ArrayRef<Expr *> Args,
11410 OverloadCandidateSet &CandidateSet,
11411 bool PartialOverloading) {
11414 // Verify that ArgumentDependentLookup is consistent with the rules
11415 // in C++0x [basic.lookup.argdep]p3:
11417 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11418 // and let Y be the lookup set produced by argument dependent
11419 // lookup (defined as follows). If X contains
11421 // -- a declaration of a class member, or
11423 // -- a block-scope function declaration that is not a
11424 // using-declaration, or
11426 // -- a declaration that is neither a function or a function
11429 // then Y is empty.
11431 if (ULE->requiresADL()) {
11432 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11433 E = ULE->decls_end(); I != E; ++I) {
11434 assert(!(*I)->getDeclContext()->isRecord());
11435 assert(isa<UsingShadowDecl>(*I) ||
11436 !(*I)->getDeclContext()->isFunctionOrMethod());
11437 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11442 // It would be nice to avoid this copy.
11443 TemplateArgumentListInfo TABuffer;
11444 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11445 if (ULE->hasExplicitTemplateArgs()) {
11446 ULE->copyTemplateArgumentsInto(TABuffer);
11447 ExplicitTemplateArgs = &TABuffer;
11450 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11451 E = ULE->decls_end(); I != E; ++I)
11452 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11453 CandidateSet, PartialOverloading,
11454 /*KnownValid*/ true);
11456 if (ULE->requiresADL())
11457 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11458 Args, ExplicitTemplateArgs,
11459 CandidateSet, PartialOverloading);
11462 /// Determine whether a declaration with the specified name could be moved into
11463 /// a different namespace.
11464 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11465 switch (Name.getCXXOverloadedOperator()) {
11466 case OO_New: case OO_Array_New:
11467 case OO_Delete: case OO_Array_Delete:
11475 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11476 /// template, where the non-dependent name was declared after the template
11477 /// was defined. This is common in code written for a compilers which do not
11478 /// correctly implement two-stage name lookup.
11480 /// Returns true if a viable candidate was found and a diagnostic was issued.
11482 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11483 const CXXScopeSpec &SS, LookupResult &R,
11484 OverloadCandidateSet::CandidateSetKind CSK,
11485 TemplateArgumentListInfo *ExplicitTemplateArgs,
11486 ArrayRef<Expr *> Args,
11487 bool *DoDiagnoseEmptyLookup = nullptr) {
11488 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11491 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11492 if (DC->isTransparentContext())
11495 SemaRef.LookupQualifiedName(R, DC);
11498 R.suppressDiagnostics();
11500 if (isa<CXXRecordDecl>(DC)) {
11501 // Don't diagnose names we find in classes; we get much better
11502 // diagnostics for these from DiagnoseEmptyLookup.
11504 if (DoDiagnoseEmptyLookup)
11505 *DoDiagnoseEmptyLookup = true;
11509 OverloadCandidateSet Candidates(FnLoc, CSK);
11510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11511 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11512 ExplicitTemplateArgs, Args,
11513 Candidates, false, /*KnownValid*/ false);
11515 OverloadCandidateSet::iterator Best;
11516 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11517 // No viable functions. Don't bother the user with notes for functions
11518 // which don't work and shouldn't be found anyway.
11523 // Find the namespaces where ADL would have looked, and suggest
11524 // declaring the function there instead.
11525 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11526 Sema::AssociatedClassSet AssociatedClasses;
11527 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11528 AssociatedNamespaces,
11529 AssociatedClasses);
11530 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11531 if (canBeDeclaredInNamespace(R.getLookupName())) {
11532 DeclContext *Std = SemaRef.getStdNamespace();
11533 for (Sema::AssociatedNamespaceSet::iterator
11534 it = AssociatedNamespaces.begin(),
11535 end = AssociatedNamespaces.end(); it != end; ++it) {
11536 // Never suggest declaring a function within namespace 'std'.
11537 if (Std && Std->Encloses(*it))
11540 // Never suggest declaring a function within a namespace with a
11541 // reserved name, like __gnu_cxx.
11542 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11544 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11547 SuggestedNamespaces.insert(*it);
11551 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11552 << R.getLookupName();
11553 if (SuggestedNamespaces.empty()) {
11554 SemaRef.Diag(Best->Function->getLocation(),
11555 diag::note_not_found_by_two_phase_lookup)
11556 << R.getLookupName() << 0;
11557 } else if (SuggestedNamespaces.size() == 1) {
11558 SemaRef.Diag(Best->Function->getLocation(),
11559 diag::note_not_found_by_two_phase_lookup)
11560 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11562 // FIXME: It would be useful to list the associated namespaces here,
11563 // but the diagnostics infrastructure doesn't provide a way to produce
11564 // a localized representation of a list of items.
11565 SemaRef.Diag(Best->Function->getLocation(),
11566 diag::note_not_found_by_two_phase_lookup)
11567 << R.getLookupName() << 2;
11570 // Try to recover by calling this function.
11580 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11581 /// template, where the non-dependent operator was declared after the template
11584 /// Returns true if a viable candidate was found and a diagnostic was issued.
11586 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11587 SourceLocation OpLoc,
11588 ArrayRef<Expr *> Args) {
11589 DeclarationName OpName =
11590 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11591 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11592 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11593 OverloadCandidateSet::CSK_Operator,
11594 /*ExplicitTemplateArgs=*/nullptr, Args);
11598 class BuildRecoveryCallExprRAII {
11601 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11602 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11603 SemaRef.IsBuildingRecoveryCallExpr = true;
11606 ~BuildRecoveryCallExprRAII() {
11607 SemaRef.IsBuildingRecoveryCallExpr = false;
11613 static std::unique_ptr<CorrectionCandidateCallback>
11614 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11615 bool HasTemplateArgs, bool AllowTypoCorrection) {
11616 if (!AllowTypoCorrection)
11617 return llvm::make_unique<NoTypoCorrectionCCC>();
11618 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11619 HasTemplateArgs, ME);
11622 /// Attempts to recover from a call where no functions were found.
11624 /// Returns true if new candidates were found.
11626 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11627 UnresolvedLookupExpr *ULE,
11628 SourceLocation LParenLoc,
11629 MutableArrayRef<Expr *> Args,
11630 SourceLocation RParenLoc,
11631 bool EmptyLookup, bool AllowTypoCorrection) {
11632 // Do not try to recover if it is already building a recovery call.
11633 // This stops infinite loops for template instantiations like
11635 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11636 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11638 if (SemaRef.IsBuildingRecoveryCallExpr)
11639 return ExprError();
11640 BuildRecoveryCallExprRAII RCE(SemaRef);
11643 SS.Adopt(ULE->getQualifierLoc());
11644 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11646 TemplateArgumentListInfo TABuffer;
11647 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11648 if (ULE->hasExplicitTemplateArgs()) {
11649 ULE->copyTemplateArgumentsInto(TABuffer);
11650 ExplicitTemplateArgs = &TABuffer;
11653 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11654 Sema::LookupOrdinaryName);
11655 bool DoDiagnoseEmptyLookup = EmptyLookup;
11656 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11657 OverloadCandidateSet::CSK_Normal,
11658 ExplicitTemplateArgs, Args,
11659 &DoDiagnoseEmptyLookup) &&
11660 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11662 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11663 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11664 ExplicitTemplateArgs, Args)))
11665 return ExprError();
11667 assert(!R.empty() && "lookup results empty despite recovery");
11669 // If recovery created an ambiguity, just bail out.
11670 if (R.isAmbiguous()) {
11671 R.suppressDiagnostics();
11672 return ExprError();
11675 // Build an implicit member call if appropriate. Just drop the
11676 // casts and such from the call, we don't really care.
11677 ExprResult NewFn = ExprError();
11678 if ((*R.begin())->isCXXClassMember())
11679 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11680 ExplicitTemplateArgs, S);
11681 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11682 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11683 ExplicitTemplateArgs);
11685 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11687 if (NewFn.isInvalid())
11688 return ExprError();
11690 // This shouldn't cause an infinite loop because we're giving it
11691 // an expression with viable lookup results, which should never
11693 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11694 MultiExprArg(Args.data(), Args.size()),
11698 /// \brief Constructs and populates an OverloadedCandidateSet from
11699 /// the given function.
11700 /// \returns true when an the ExprResult output parameter has been set.
11701 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11702 UnresolvedLookupExpr *ULE,
11704 SourceLocation RParenLoc,
11705 OverloadCandidateSet *CandidateSet,
11706 ExprResult *Result) {
11708 if (ULE->requiresADL()) {
11709 // To do ADL, we must have found an unqualified name.
11710 assert(!ULE->getQualifier() && "qualified name with ADL");
11712 // We don't perform ADL for implicit declarations of builtins.
11713 // Verify that this was correctly set up.
11715 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11716 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11717 F->getBuiltinID() && F->isImplicit())
11718 llvm_unreachable("performing ADL for builtin");
11720 // We don't perform ADL in C.
11721 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11725 UnbridgedCastsSet UnbridgedCasts;
11726 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11727 *Result = ExprError();
11731 // Add the functions denoted by the callee to the set of candidate
11732 // functions, including those from argument-dependent lookup.
11733 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11735 if (getLangOpts().MSVCCompat &&
11736 CurContext->isDependentContext() && !isSFINAEContext() &&
11737 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11739 OverloadCandidateSet::iterator Best;
11740 if (CandidateSet->empty() ||
11741 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11742 OR_No_Viable_Function) {
11743 // In Microsoft mode, if we are inside a template class member function then
11744 // create a type dependent CallExpr. The goal is to postpone name lookup
11745 // to instantiation time to be able to search into type dependent base
11747 CallExpr *CE = new (Context) CallExpr(
11748 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11749 CE->setTypeDependent(true);
11750 CE->setValueDependent(true);
11751 CE->setInstantiationDependent(true);
11757 if (CandidateSet->empty())
11760 UnbridgedCasts.restore();
11764 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11765 /// the completed call expression. If overload resolution fails, emits
11766 /// diagnostics and returns ExprError()
11767 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11768 UnresolvedLookupExpr *ULE,
11769 SourceLocation LParenLoc,
11771 SourceLocation RParenLoc,
11773 OverloadCandidateSet *CandidateSet,
11774 OverloadCandidateSet::iterator *Best,
11775 OverloadingResult OverloadResult,
11776 bool AllowTypoCorrection) {
11777 if (CandidateSet->empty())
11778 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11779 RParenLoc, /*EmptyLookup=*/true,
11780 AllowTypoCorrection);
11782 switch (OverloadResult) {
11784 FunctionDecl *FDecl = (*Best)->Function;
11785 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11786 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11787 return ExprError();
11788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11793 case OR_No_Viable_Function: {
11794 // Try to recover by looking for viable functions which the user might
11795 // have meant to call.
11796 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11798 /*EmptyLookup=*/false,
11799 AllowTypoCorrection);
11800 if (!Recovery.isInvalid())
11803 // If the user passes in a function that we can't take the address of, we
11804 // generally end up emitting really bad error messages. Here, we attempt to
11805 // emit better ones.
11806 for (const Expr *Arg : Args) {
11807 if (!Arg->getType()->isFunctionType())
11809 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11810 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11812 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11813 Arg->getExprLoc()))
11814 return ExprError();
11818 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11819 << ULE->getName() << Fn->getSourceRange();
11820 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11825 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11826 << ULE->getName() << Fn->getSourceRange();
11827 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11831 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11832 << (*Best)->Function->isDeleted()
11834 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11835 << Fn->getSourceRange();
11836 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11838 // We emitted an error for the unvailable/deleted function call but keep
11839 // the call in the AST.
11840 FunctionDecl *FDecl = (*Best)->Function;
11841 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11842 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11847 // Overload resolution failed.
11848 return ExprError();
11851 static void markUnaddressableCandidatesUnviable(Sema &S,
11852 OverloadCandidateSet &CS) {
11853 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11855 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11857 I->FailureKind = ovl_fail_addr_not_available;
11862 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11863 /// (which eventually refers to the declaration Func) and the call
11864 /// arguments Args/NumArgs, attempt to resolve the function call down
11865 /// to a specific function. If overload resolution succeeds, returns
11866 /// the call expression produced by overload resolution.
11867 /// Otherwise, emits diagnostics and returns ExprError.
11868 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11869 UnresolvedLookupExpr *ULE,
11870 SourceLocation LParenLoc,
11872 SourceLocation RParenLoc,
11874 bool AllowTypoCorrection,
11875 bool CalleesAddressIsTaken) {
11876 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11877 OverloadCandidateSet::CSK_Normal);
11880 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11884 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11885 // functions that aren't addressible are considered unviable.
11886 if (CalleesAddressIsTaken)
11887 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11889 OverloadCandidateSet::iterator Best;
11890 OverloadingResult OverloadResult =
11891 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11893 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11894 RParenLoc, ExecConfig, &CandidateSet,
11895 &Best, OverloadResult,
11896 AllowTypoCorrection);
11899 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11900 return Functions.size() > 1 ||
11901 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11904 /// \brief Create a unary operation that may resolve to an overloaded
11907 /// \param OpLoc The location of the operator itself (e.g., '*').
11909 /// \param Opc The UnaryOperatorKind that describes this operator.
11911 /// \param Fns The set of non-member functions that will be
11912 /// considered by overload resolution. The caller needs to build this
11913 /// set based on the context using, e.g.,
11914 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11915 /// set should not contain any member functions; those will be added
11916 /// by CreateOverloadedUnaryOp().
11918 /// \param Input The input argument.
11920 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11921 const UnresolvedSetImpl &Fns,
11923 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11924 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11926 // TODO: provide better source location info.
11927 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11929 if (checkPlaceholderForOverload(*this, Input))
11930 return ExprError();
11932 Expr *Args[2] = { Input, nullptr };
11933 unsigned NumArgs = 1;
11935 // For post-increment and post-decrement, add the implicit '0' as
11936 // the second argument, so that we know this is a post-increment or
11938 if (Opc == UO_PostInc || Opc == UO_PostDec) {
11939 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11940 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11945 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11947 if (Input->isTypeDependent()) {
11949 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11950 VK_RValue, OK_Ordinary, OpLoc);
11952 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11953 UnresolvedLookupExpr *Fn
11954 = UnresolvedLookupExpr::Create(Context, NamingClass,
11955 NestedNameSpecifierLoc(), OpNameInfo,
11956 /*ADL*/ true, IsOverloaded(Fns),
11957 Fns.begin(), Fns.end());
11958 return new (Context)
11959 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11960 VK_RValue, OpLoc, false);
11963 // Build an empty overload set.
11964 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11966 // Add the candidates from the given function set.
11967 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11969 // Add operator candidates that are member functions.
11970 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11972 // Add candidates from ADL.
11973 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11974 /*ExplicitTemplateArgs*/nullptr,
11977 // Add builtin operator candidates.
11978 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11980 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11982 // Perform overload resolution.
11983 OverloadCandidateSet::iterator Best;
11984 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11986 // We found a built-in operator or an overloaded operator.
11987 FunctionDecl *FnDecl = Best->Function;
11990 // We matched an overloaded operator. Build a call to that
11993 // Convert the arguments.
11994 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11995 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11997 ExprResult InputRes =
11998 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11999 Best->FoundDecl, Method);
12000 if (InputRes.isInvalid())
12001 return ExprError();
12002 Input = InputRes.get();
12004 // Convert the arguments.
12005 ExprResult InputInit
12006 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12008 FnDecl->getParamDecl(0)),
12011 if (InputInit.isInvalid())
12012 return ExprError();
12013 Input = InputInit.get();
12016 // Build the actual expression node.
12017 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12018 HadMultipleCandidates, OpLoc);
12019 if (FnExpr.isInvalid())
12020 return ExprError();
12022 // Determine the result type.
12023 QualType ResultTy = FnDecl->getReturnType();
12024 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12025 ResultTy = ResultTy.getNonLValueExprType(Context);
12028 CallExpr *TheCall =
12029 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12030 ResultTy, VK, OpLoc, false);
12032 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12033 return ExprError();
12035 if (CheckFunctionCall(FnDecl, TheCall,
12036 FnDecl->getType()->castAs<FunctionProtoType>()))
12037 return ExprError();
12039 return MaybeBindToTemporary(TheCall);
12041 // We matched a built-in operator. Convert the arguments, then
12042 // break out so that we will build the appropriate built-in
12044 ExprResult InputRes =
12045 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12046 Best->Conversions[0], AA_Passing);
12047 if (InputRes.isInvalid())
12048 return ExprError();
12049 Input = InputRes.get();
12054 case OR_No_Viable_Function:
12055 // This is an erroneous use of an operator which can be overloaded by
12056 // a non-member function. Check for non-member operators which were
12057 // defined too late to be candidates.
12058 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12059 // FIXME: Recover by calling the found function.
12060 return ExprError();
12062 // No viable function; fall through to handling this as a
12063 // built-in operator, which will produce an error message for us.
12067 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12068 << UnaryOperator::getOpcodeStr(Opc)
12069 << Input->getType()
12070 << Input->getSourceRange();
12071 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12072 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12073 return ExprError();
12076 Diag(OpLoc, diag::err_ovl_deleted_oper)
12077 << Best->Function->isDeleted()
12078 << UnaryOperator::getOpcodeStr(Opc)
12079 << getDeletedOrUnavailableSuffix(Best->Function)
12080 << Input->getSourceRange();
12081 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12082 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12083 return ExprError();
12086 // Either we found no viable overloaded operator or we matched a
12087 // built-in operator. In either case, fall through to trying to
12088 // build a built-in operation.
12089 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12092 /// \brief Create a binary operation that may resolve to an overloaded
12095 /// \param OpLoc The location of the operator itself (e.g., '+').
12097 /// \param Opc The BinaryOperatorKind that describes this operator.
12099 /// \param Fns The set of non-member functions that will be
12100 /// considered by overload resolution. The caller needs to build this
12101 /// set based on the context using, e.g.,
12102 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12103 /// set should not contain any member functions; those will be added
12104 /// by CreateOverloadedBinOp().
12106 /// \param LHS Left-hand argument.
12107 /// \param RHS Right-hand argument.
12109 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12110 BinaryOperatorKind Opc,
12111 const UnresolvedSetImpl &Fns,
12112 Expr *LHS, Expr *RHS) {
12113 Expr *Args[2] = { LHS, RHS };
12114 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12116 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12117 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12119 // If either side is type-dependent, create an appropriate dependent
12121 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12123 // If there are no functions to store, just build a dependent
12124 // BinaryOperator or CompoundAssignment.
12125 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12126 return new (Context) BinaryOperator(
12127 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12128 OpLoc, FPFeatures.fp_contract);
12130 return new (Context) CompoundAssignOperator(
12131 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12132 Context.DependentTy, Context.DependentTy, OpLoc,
12133 FPFeatures.fp_contract);
12136 // FIXME: save results of ADL from here?
12137 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12138 // TODO: provide better source location info in DNLoc component.
12139 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12140 UnresolvedLookupExpr *Fn
12141 = UnresolvedLookupExpr::Create(Context, NamingClass,
12142 NestedNameSpecifierLoc(), OpNameInfo,
12143 /*ADL*/ true, IsOverloaded(Fns),
12144 Fns.begin(), Fns.end());
12145 return new (Context)
12146 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12147 VK_RValue, OpLoc, FPFeatures.fp_contract);
12150 // Always do placeholder-like conversions on the RHS.
12151 if (checkPlaceholderForOverload(*this, Args[1]))
12152 return ExprError();
12154 // Do placeholder-like conversion on the LHS; note that we should
12155 // not get here with a PseudoObject LHS.
12156 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12157 if (checkPlaceholderForOverload(*this, Args[0]))
12158 return ExprError();
12160 // If this is the assignment operator, we only perform overload resolution
12161 // if the left-hand side is a class or enumeration type. This is actually
12162 // a hack. The standard requires that we do overload resolution between the
12163 // various built-in candidates, but as DR507 points out, this can lead to
12164 // problems. So we do it this way, which pretty much follows what GCC does.
12165 // Note that we go the traditional code path for compound assignment forms.
12166 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12167 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12169 // If this is the .* operator, which is not overloadable, just
12170 // create a built-in binary operator.
12171 if (Opc == BO_PtrMemD)
12172 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12174 // Build an empty overload set.
12175 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12177 // Add the candidates from the given function set.
12178 AddFunctionCandidates(Fns, Args, CandidateSet);
12180 // Add operator candidates that are member functions.
12181 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12183 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12184 // performed for an assignment operator (nor for operator[] nor operator->,
12185 // which don't get here).
12186 if (Opc != BO_Assign)
12187 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12188 /*ExplicitTemplateArgs*/ nullptr,
12191 // Add builtin operator candidates.
12192 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12194 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12196 // Perform overload resolution.
12197 OverloadCandidateSet::iterator Best;
12198 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12200 // We found a built-in operator or an overloaded operator.
12201 FunctionDecl *FnDecl = Best->Function;
12204 // We matched an overloaded operator. Build a call to that
12207 // Convert the arguments.
12208 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12209 // Best->Access is only meaningful for class members.
12210 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12213 PerformCopyInitialization(
12214 InitializedEntity::InitializeParameter(Context,
12215 FnDecl->getParamDecl(0)),
12216 SourceLocation(), Args[1]);
12217 if (Arg1.isInvalid())
12218 return ExprError();
12221 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12222 Best->FoundDecl, Method);
12223 if (Arg0.isInvalid())
12224 return ExprError();
12225 Args[0] = Arg0.getAs<Expr>();
12226 Args[1] = RHS = Arg1.getAs<Expr>();
12228 // Convert the arguments.
12229 ExprResult Arg0 = PerformCopyInitialization(
12230 InitializedEntity::InitializeParameter(Context,
12231 FnDecl->getParamDecl(0)),
12232 SourceLocation(), Args[0]);
12233 if (Arg0.isInvalid())
12234 return ExprError();
12237 PerformCopyInitialization(
12238 InitializedEntity::InitializeParameter(Context,
12239 FnDecl->getParamDecl(1)),
12240 SourceLocation(), Args[1]);
12241 if (Arg1.isInvalid())
12242 return ExprError();
12243 Args[0] = LHS = Arg0.getAs<Expr>();
12244 Args[1] = RHS = Arg1.getAs<Expr>();
12247 // Build the actual expression node.
12248 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12250 HadMultipleCandidates, OpLoc);
12251 if (FnExpr.isInvalid())
12252 return ExprError();
12254 // Determine the result type.
12255 QualType ResultTy = FnDecl->getReturnType();
12256 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12257 ResultTy = ResultTy.getNonLValueExprType(Context);
12259 CXXOperatorCallExpr *TheCall =
12260 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12261 Args, ResultTy, VK, OpLoc,
12262 FPFeatures.fp_contract);
12264 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12266 return ExprError();
12268 ArrayRef<const Expr *> ArgsArray(Args, 2);
12269 const Expr *ImplicitThis = nullptr;
12270 // Cut off the implicit 'this'.
12271 if (isa<CXXMethodDecl>(FnDecl)) {
12272 ImplicitThis = ArgsArray[0];
12273 ArgsArray = ArgsArray.slice(1);
12276 // Check for a self move.
12277 if (Op == OO_Equal)
12278 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12280 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12281 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12282 VariadicDoesNotApply);
12284 return MaybeBindToTemporary(TheCall);
12286 // We matched a built-in operator. Convert the arguments, then
12287 // break out so that we will build the appropriate built-in
12289 ExprResult ArgsRes0 =
12290 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12291 Best->Conversions[0], AA_Passing);
12292 if (ArgsRes0.isInvalid())
12293 return ExprError();
12294 Args[0] = ArgsRes0.get();
12296 ExprResult ArgsRes1 =
12297 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12298 Best->Conversions[1], AA_Passing);
12299 if (ArgsRes1.isInvalid())
12300 return ExprError();
12301 Args[1] = ArgsRes1.get();
12306 case OR_No_Viable_Function: {
12307 // C++ [over.match.oper]p9:
12308 // If the operator is the operator , [...] and there are no
12309 // viable functions, then the operator is assumed to be the
12310 // built-in operator and interpreted according to clause 5.
12311 if (Opc == BO_Comma)
12314 // For class as left operand for assignment or compound assigment
12315 // operator do not fall through to handling in built-in, but report that
12316 // no overloaded assignment operator found
12317 ExprResult Result = ExprError();
12318 if (Args[0]->getType()->isRecordType() &&
12319 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12320 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12321 << BinaryOperator::getOpcodeStr(Opc)
12322 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12323 if (Args[0]->getType()->isIncompleteType()) {
12324 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12325 << Args[0]->getType()
12326 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12329 // This is an erroneous use of an operator which can be overloaded by
12330 // a non-member function. Check for non-member operators which were
12331 // defined too late to be candidates.
12332 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12333 // FIXME: Recover by calling the found function.
12334 return ExprError();
12336 // No viable function; try to create a built-in operation, which will
12337 // produce an error. Then, show the non-viable candidates.
12338 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12340 assert(Result.isInvalid() &&
12341 "C++ binary operator overloading is missing candidates!");
12342 if (Result.isInvalid())
12343 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12344 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12349 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12350 << BinaryOperator::getOpcodeStr(Opc)
12351 << Args[0]->getType() << Args[1]->getType()
12352 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12353 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12354 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12355 return ExprError();
12358 if (isImplicitlyDeleted(Best->Function)) {
12359 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12360 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12361 << Context.getRecordType(Method->getParent())
12362 << getSpecialMember(Method);
12364 // The user probably meant to call this special member. Just
12365 // explain why it's deleted.
12366 NoteDeletedFunction(Method);
12367 return ExprError();
12369 Diag(OpLoc, diag::err_ovl_deleted_oper)
12370 << Best->Function->isDeleted()
12371 << BinaryOperator::getOpcodeStr(Opc)
12372 << getDeletedOrUnavailableSuffix(Best->Function)
12373 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12375 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12376 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12377 return ExprError();
12380 // We matched a built-in operator; build it.
12381 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12385 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12386 SourceLocation RLoc,
12387 Expr *Base, Expr *Idx) {
12388 Expr *Args[2] = { Base, Idx };
12389 DeclarationName OpName =
12390 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12392 // If either side is type-dependent, create an appropriate dependent
12394 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12396 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12397 // CHECKME: no 'operator' keyword?
12398 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12399 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12400 UnresolvedLookupExpr *Fn
12401 = UnresolvedLookupExpr::Create(Context, NamingClass,
12402 NestedNameSpecifierLoc(), OpNameInfo,
12403 /*ADL*/ true, /*Overloaded*/ false,
12404 UnresolvedSetIterator(),
12405 UnresolvedSetIterator());
12406 // Can't add any actual overloads yet
12408 return new (Context)
12409 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12410 Context.DependentTy, VK_RValue, RLoc, false);
12413 // Handle placeholders on both operands.
12414 if (checkPlaceholderForOverload(*this, Args[0]))
12415 return ExprError();
12416 if (checkPlaceholderForOverload(*this, Args[1]))
12417 return ExprError();
12419 // Build an empty overload set.
12420 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12422 // Subscript can only be overloaded as a member function.
12424 // Add operator candidates that are member functions.
12425 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12427 // Add builtin operator candidates.
12428 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12430 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12432 // Perform overload resolution.
12433 OverloadCandidateSet::iterator Best;
12434 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12436 // We found a built-in operator or an overloaded operator.
12437 FunctionDecl *FnDecl = Best->Function;
12440 // We matched an overloaded operator. Build a call to that
12443 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12445 // Convert the arguments.
12446 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12448 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12449 Best->FoundDecl, Method);
12450 if (Arg0.isInvalid())
12451 return ExprError();
12452 Args[0] = Arg0.get();
12454 // Convert the arguments.
12455 ExprResult InputInit
12456 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12458 FnDecl->getParamDecl(0)),
12461 if (InputInit.isInvalid())
12462 return ExprError();
12464 Args[1] = InputInit.getAs<Expr>();
12466 // Build the actual expression node.
12467 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12468 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12469 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12471 HadMultipleCandidates,
12472 OpLocInfo.getLoc(),
12473 OpLocInfo.getInfo());
12474 if (FnExpr.isInvalid())
12475 return ExprError();
12477 // Determine the result type
12478 QualType ResultTy = FnDecl->getReturnType();
12479 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12480 ResultTy = ResultTy.getNonLValueExprType(Context);
12482 CXXOperatorCallExpr *TheCall =
12483 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12484 FnExpr.get(), Args,
12485 ResultTy, VK, RLoc,
12488 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12489 return ExprError();
12491 if (CheckFunctionCall(Method, TheCall,
12492 Method->getType()->castAs<FunctionProtoType>()))
12493 return ExprError();
12495 return MaybeBindToTemporary(TheCall);
12497 // We matched a built-in operator. Convert the arguments, then
12498 // break out so that we will build the appropriate built-in
12500 ExprResult ArgsRes0 =
12501 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12502 Best->Conversions[0], AA_Passing);
12503 if (ArgsRes0.isInvalid())
12504 return ExprError();
12505 Args[0] = ArgsRes0.get();
12507 ExprResult ArgsRes1 =
12508 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12509 Best->Conversions[1], AA_Passing);
12510 if (ArgsRes1.isInvalid())
12511 return ExprError();
12512 Args[1] = ArgsRes1.get();
12518 case OR_No_Viable_Function: {
12519 if (CandidateSet.empty())
12520 Diag(LLoc, diag::err_ovl_no_oper)
12521 << Args[0]->getType() << /*subscript*/ 0
12522 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12524 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12525 << Args[0]->getType()
12526 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12527 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12529 return ExprError();
12533 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12535 << Args[0]->getType() << Args[1]->getType()
12536 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12537 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12539 return ExprError();
12542 Diag(LLoc, diag::err_ovl_deleted_oper)
12543 << Best->Function->isDeleted() << "[]"
12544 << getDeletedOrUnavailableSuffix(Best->Function)
12545 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12546 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12548 return ExprError();
12551 // We matched a built-in operator; build it.
12552 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12555 /// BuildCallToMemberFunction - Build a call to a member
12556 /// function. MemExpr is the expression that refers to the member
12557 /// function (and includes the object parameter), Args/NumArgs are the
12558 /// arguments to the function call (not including the object
12559 /// parameter). The caller needs to validate that the member
12560 /// expression refers to a non-static member function or an overloaded
12561 /// member function.
12563 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12564 SourceLocation LParenLoc,
12566 SourceLocation RParenLoc) {
12567 assert(MemExprE->getType() == Context.BoundMemberTy ||
12568 MemExprE->getType() == Context.OverloadTy);
12570 // Dig out the member expression. This holds both the object
12571 // argument and the member function we're referring to.
12572 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12574 // Determine whether this is a call to a pointer-to-member function.
12575 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12576 assert(op->getType() == Context.BoundMemberTy);
12577 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12580 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12582 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12583 QualType resultType = proto->getCallResultType(Context);
12584 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12586 // Check that the object type isn't more qualified than the
12587 // member function we're calling.
12588 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12590 QualType objectType = op->getLHS()->getType();
12591 if (op->getOpcode() == BO_PtrMemI)
12592 objectType = objectType->castAs<PointerType>()->getPointeeType();
12593 Qualifiers objectQuals = objectType.getQualifiers();
12595 Qualifiers difference = objectQuals - funcQuals;
12596 difference.removeObjCGCAttr();
12597 difference.removeAddressSpace();
12599 std::string qualsString = difference.getAsString();
12600 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12601 << fnType.getUnqualifiedType()
12603 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12606 CXXMemberCallExpr *call
12607 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12608 resultType, valueKind, RParenLoc);
12610 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12612 return ExprError();
12614 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12615 return ExprError();
12617 if (CheckOtherCall(call, proto))
12618 return ExprError();
12620 return MaybeBindToTemporary(call);
12623 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12624 return new (Context)
12625 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12627 UnbridgedCastsSet UnbridgedCasts;
12628 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12629 return ExprError();
12631 MemberExpr *MemExpr;
12632 CXXMethodDecl *Method = nullptr;
12633 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12634 NestedNameSpecifier *Qualifier = nullptr;
12635 if (isa<MemberExpr>(NakedMemExpr)) {
12636 MemExpr = cast<MemberExpr>(NakedMemExpr);
12637 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12638 FoundDecl = MemExpr->getFoundDecl();
12639 Qualifier = MemExpr->getQualifier();
12640 UnbridgedCasts.restore();
12642 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12643 Qualifier = UnresExpr->getQualifier();
12645 QualType ObjectType = UnresExpr->getBaseType();
12646 Expr::Classification ObjectClassification
12647 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12648 : UnresExpr->getBase()->Classify(Context);
12650 // Add overload candidates
12651 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12652 OverloadCandidateSet::CSK_Normal);
12654 // FIXME: avoid copy.
12655 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12656 if (UnresExpr->hasExplicitTemplateArgs()) {
12657 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12658 TemplateArgs = &TemplateArgsBuffer;
12661 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12662 E = UnresExpr->decls_end(); I != E; ++I) {
12664 NamedDecl *Func = *I;
12665 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12666 if (isa<UsingShadowDecl>(Func))
12667 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12670 // Microsoft supports direct constructor calls.
12671 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12672 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12673 Args, CandidateSet);
12674 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12675 // If explicit template arguments were provided, we can't call a
12676 // non-template member function.
12680 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12681 ObjectClassification, Args, CandidateSet,
12682 /*SuppressUserConversions=*/false);
12684 AddMethodTemplateCandidate(
12685 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12686 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12687 /*SuppressUsedConversions=*/false);
12691 DeclarationName DeclName = UnresExpr->getMemberName();
12693 UnbridgedCasts.restore();
12695 OverloadCandidateSet::iterator Best;
12696 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12699 Method = cast<CXXMethodDecl>(Best->Function);
12700 FoundDecl = Best->FoundDecl;
12701 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12702 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12703 return ExprError();
12704 // If FoundDecl is different from Method (such as if one is a template
12705 // and the other a specialization), make sure DiagnoseUseOfDecl is
12707 // FIXME: This would be more comprehensively addressed by modifying
12708 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12710 if (Method != FoundDecl.getDecl() &&
12711 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12712 return ExprError();
12715 case OR_No_Viable_Function:
12716 Diag(UnresExpr->getMemberLoc(),
12717 diag::err_ovl_no_viable_member_function_in_call)
12718 << DeclName << MemExprE->getSourceRange();
12719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12720 // FIXME: Leaking incoming expressions!
12721 return ExprError();
12724 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12725 << DeclName << MemExprE->getSourceRange();
12726 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12727 // FIXME: Leaking incoming expressions!
12728 return ExprError();
12731 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12732 << Best->Function->isDeleted()
12734 << getDeletedOrUnavailableSuffix(Best->Function)
12735 << MemExprE->getSourceRange();
12736 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12737 // FIXME: Leaking incoming expressions!
12738 return ExprError();
12741 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12743 // If overload resolution picked a static member, build a
12744 // non-member call based on that function.
12745 if (Method->isStatic()) {
12746 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12750 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12753 QualType ResultType = Method->getReturnType();
12754 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12755 ResultType = ResultType.getNonLValueExprType(Context);
12757 assert(Method && "Member call to something that isn't a method?");
12758 CXXMemberCallExpr *TheCall =
12759 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12760 ResultType, VK, RParenLoc);
12762 // Check for a valid return type.
12763 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12765 return ExprError();
12767 // Convert the object argument (for a non-static member function call).
12768 // We only need to do this if there was actually an overload; otherwise
12769 // it was done at lookup.
12770 if (!Method->isStatic()) {
12771 ExprResult ObjectArg =
12772 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12773 FoundDecl, Method);
12774 if (ObjectArg.isInvalid())
12775 return ExprError();
12776 MemExpr->setBase(ObjectArg.get());
12779 // Convert the rest of the arguments
12780 const FunctionProtoType *Proto =
12781 Method->getType()->getAs<FunctionProtoType>();
12782 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12784 return ExprError();
12786 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12788 if (CheckFunctionCall(Method, TheCall, Proto))
12789 return ExprError();
12791 // In the case the method to call was not selected by the overloading
12792 // resolution process, we still need to handle the enable_if attribute. Do
12793 // that here, so it will not hide previous -- and more relevant -- errors.
12794 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12795 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12796 Diag(MemE->getMemberLoc(),
12797 diag::err_ovl_no_viable_member_function_in_call)
12798 << Method << Method->getSourceRange();
12799 Diag(Method->getLocation(),
12800 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12801 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12802 return ExprError();
12806 if ((isa<CXXConstructorDecl>(CurContext) ||
12807 isa<CXXDestructorDecl>(CurContext)) &&
12808 TheCall->getMethodDecl()->isPure()) {
12809 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12811 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12812 MemExpr->performsVirtualDispatch(getLangOpts())) {
12813 Diag(MemExpr->getLocStart(),
12814 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12815 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12816 << MD->getParent()->getDeclName();
12818 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12819 if (getLangOpts().AppleKext)
12820 Diag(MemExpr->getLocStart(),
12821 diag::note_pure_qualified_call_kext)
12822 << MD->getParent()->getDeclName()
12823 << MD->getDeclName();
12827 if (CXXDestructorDecl *DD =
12828 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12829 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12830 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12831 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12832 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12833 MemExpr->getMemberLoc());
12836 return MaybeBindToTemporary(TheCall);
12839 /// BuildCallToObjectOfClassType - Build a call to an object of class
12840 /// type (C++ [over.call.object]), which can end up invoking an
12841 /// overloaded function call operator (@c operator()) or performing a
12842 /// user-defined conversion on the object argument.
12844 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12845 SourceLocation LParenLoc,
12847 SourceLocation RParenLoc) {
12848 if (checkPlaceholderForOverload(*this, Obj))
12849 return ExprError();
12850 ExprResult Object = Obj;
12852 UnbridgedCastsSet UnbridgedCasts;
12853 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12854 return ExprError();
12856 assert(Object.get()->getType()->isRecordType() &&
12857 "Requires object type argument");
12858 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12860 // C++ [over.call.object]p1:
12861 // If the primary-expression E in the function call syntax
12862 // evaluates to a class object of type "cv T", then the set of
12863 // candidate functions includes at least the function call
12864 // operators of T. The function call operators of T are obtained by
12865 // ordinary lookup of the name operator() in the context of
12867 OverloadCandidateSet CandidateSet(LParenLoc,
12868 OverloadCandidateSet::CSK_Operator);
12869 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12871 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12872 diag::err_incomplete_object_call, Object.get()))
12875 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12876 LookupQualifiedName(R, Record->getDecl());
12877 R.suppressDiagnostics();
12879 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12880 Oper != OperEnd; ++Oper) {
12881 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12882 Object.get()->Classify(Context), Args, CandidateSet,
12883 /*SuppressUserConversions=*/false);
12886 // C++ [over.call.object]p2:
12887 // In addition, for each (non-explicit in C++0x) conversion function
12888 // declared in T of the form
12890 // operator conversion-type-id () cv-qualifier;
12892 // where cv-qualifier is the same cv-qualification as, or a
12893 // greater cv-qualification than, cv, and where conversion-type-id
12894 // denotes the type "pointer to function of (P1,...,Pn) returning
12895 // R", or the type "reference to pointer to function of
12896 // (P1,...,Pn) returning R", or the type "reference to function
12897 // of (P1,...,Pn) returning R", a surrogate call function [...]
12898 // is also considered as a candidate function. Similarly,
12899 // surrogate call functions are added to the set of candidate
12900 // functions for each conversion function declared in an
12901 // accessible base class provided the function is not hidden
12902 // within T by another intervening declaration.
12903 const auto &Conversions =
12904 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12905 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12907 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12908 if (isa<UsingShadowDecl>(D))
12909 D = cast<UsingShadowDecl>(D)->getTargetDecl();
12911 // Skip over templated conversion functions; they aren't
12913 if (isa<FunctionTemplateDecl>(D))
12916 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12917 if (!Conv->isExplicit()) {
12918 // Strip the reference type (if any) and then the pointer type (if
12919 // any) to get down to what might be a function type.
12920 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12921 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12922 ConvType = ConvPtrType->getPointeeType();
12924 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12926 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12927 Object.get(), Args, CandidateSet);
12932 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12934 // Perform overload resolution.
12935 OverloadCandidateSet::iterator Best;
12936 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12939 // Overload resolution succeeded; we'll build the appropriate call
12943 case OR_No_Viable_Function:
12944 if (CandidateSet.empty())
12945 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12946 << Object.get()->getType() << /*call*/ 1
12947 << Object.get()->getSourceRange();
12949 Diag(Object.get()->getLocStart(),
12950 diag::err_ovl_no_viable_object_call)
12951 << Object.get()->getType() << Object.get()->getSourceRange();
12952 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12956 Diag(Object.get()->getLocStart(),
12957 diag::err_ovl_ambiguous_object_call)
12958 << Object.get()->getType() << Object.get()->getSourceRange();
12959 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12963 Diag(Object.get()->getLocStart(),
12964 diag::err_ovl_deleted_object_call)
12965 << Best->Function->isDeleted()
12966 << Object.get()->getType()
12967 << getDeletedOrUnavailableSuffix(Best->Function)
12968 << Object.get()->getSourceRange();
12969 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12973 if (Best == CandidateSet.end())
12976 UnbridgedCasts.restore();
12978 if (Best->Function == nullptr) {
12979 // Since there is no function declaration, this is one of the
12980 // surrogate candidates. Dig out the conversion function.
12981 CXXConversionDecl *Conv
12982 = cast<CXXConversionDecl>(
12983 Best->Conversions[0].UserDefined.ConversionFunction);
12985 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12987 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12988 return ExprError();
12989 assert(Conv == Best->FoundDecl.getDecl() &&
12990 "Found Decl & conversion-to-functionptr should be same, right?!");
12991 // We selected one of the surrogate functions that converts the
12992 // object parameter to a function pointer. Perform the conversion
12993 // on the object argument, then let ActOnCallExpr finish the job.
12995 // Create an implicit member expr to refer to the conversion operator.
12996 // and then call it.
12997 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12998 Conv, HadMultipleCandidates);
12999 if (Call.isInvalid())
13000 return ExprError();
13001 // Record usage of conversion in an implicit cast.
13002 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13003 CK_UserDefinedConversion, Call.get(),
13004 nullptr, VK_RValue);
13006 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13009 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13011 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13012 // that calls this method, using Object for the implicit object
13013 // parameter and passing along the remaining arguments.
13014 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13016 // An error diagnostic has already been printed when parsing the declaration.
13017 if (Method->isInvalidDecl())
13018 return ExprError();
13020 const FunctionProtoType *Proto =
13021 Method->getType()->getAs<FunctionProtoType>();
13023 unsigned NumParams = Proto->getNumParams();
13025 DeclarationNameInfo OpLocInfo(
13026 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13027 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13028 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13029 HadMultipleCandidates,
13030 OpLocInfo.getLoc(),
13031 OpLocInfo.getInfo());
13032 if (NewFn.isInvalid())
13035 // Build the full argument list for the method call (the implicit object
13036 // parameter is placed at the beginning of the list).
13037 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13038 MethodArgs[0] = Object.get();
13039 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13041 // Once we've built TheCall, all of the expressions are properly
13043 QualType ResultTy = Method->getReturnType();
13044 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13045 ResultTy = ResultTy.getNonLValueExprType(Context);
13047 CXXOperatorCallExpr *TheCall = new (Context)
13048 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13049 VK, RParenLoc, false);
13051 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13054 // We may have default arguments. If so, we need to allocate more
13055 // slots in the call for them.
13056 if (Args.size() < NumParams)
13057 TheCall->setNumArgs(Context, NumParams + 1);
13059 bool IsError = false;
13061 // Initialize the implicit object parameter.
13062 ExprResult ObjRes =
13063 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13064 Best->FoundDecl, Method);
13065 if (ObjRes.isInvalid())
13069 TheCall->setArg(0, Object.get());
13071 // Check the argument types.
13072 for (unsigned i = 0; i != NumParams; i++) {
13074 if (i < Args.size()) {
13077 // Pass the argument.
13079 ExprResult InputInit
13080 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13082 Method->getParamDecl(i)),
13083 SourceLocation(), Arg);
13085 IsError |= InputInit.isInvalid();
13086 Arg = InputInit.getAs<Expr>();
13089 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13090 if (DefArg.isInvalid()) {
13095 Arg = DefArg.getAs<Expr>();
13098 TheCall->setArg(i + 1, Arg);
13101 // If this is a variadic call, handle args passed through "...".
13102 if (Proto->isVariadic()) {
13103 // Promote the arguments (C99 6.5.2.2p7).
13104 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13105 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13107 IsError |= Arg.isInvalid();
13108 TheCall->setArg(i + 1, Arg.get());
13112 if (IsError) return true;
13114 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13116 if (CheckFunctionCall(Method, TheCall, Proto))
13119 return MaybeBindToTemporary(TheCall);
13122 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13123 /// (if one exists), where @c Base is an expression of class type and
13124 /// @c Member is the name of the member we're trying to find.
13126 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13127 bool *NoArrowOperatorFound) {
13128 assert(Base->getType()->isRecordType() &&
13129 "left-hand side must have class type");
13131 if (checkPlaceholderForOverload(*this, Base))
13132 return ExprError();
13134 SourceLocation Loc = Base->getExprLoc();
13136 // C++ [over.ref]p1:
13138 // [...] An expression x->m is interpreted as (x.operator->())->m
13139 // for a class object x of type T if T::operator->() exists and if
13140 // the operator is selected as the best match function by the
13141 // overload resolution mechanism (13.3).
13142 DeclarationName OpName =
13143 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13144 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13145 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13147 if (RequireCompleteType(Loc, Base->getType(),
13148 diag::err_typecheck_incomplete_tag, Base))
13149 return ExprError();
13151 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13152 LookupQualifiedName(R, BaseRecord->getDecl());
13153 R.suppressDiagnostics();
13155 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13156 Oper != OperEnd; ++Oper) {
13157 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13158 None, CandidateSet, /*SuppressUserConversions=*/false);
13161 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13163 // Perform overload resolution.
13164 OverloadCandidateSet::iterator Best;
13165 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13167 // Overload resolution succeeded; we'll build the call below.
13170 case OR_No_Viable_Function:
13171 if (CandidateSet.empty()) {
13172 QualType BaseType = Base->getType();
13173 if (NoArrowOperatorFound) {
13174 // Report this specific error to the caller instead of emitting a
13175 // diagnostic, as requested.
13176 *NoArrowOperatorFound = true;
13177 return ExprError();
13179 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13180 << BaseType << Base->getSourceRange();
13181 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13182 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13183 << FixItHint::CreateReplacement(OpLoc, ".");
13186 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13187 << "operator->" << Base->getSourceRange();
13188 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13189 return ExprError();
13192 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13193 << "->" << Base->getType() << Base->getSourceRange();
13194 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13195 return ExprError();
13198 Diag(OpLoc, diag::err_ovl_deleted_oper)
13199 << Best->Function->isDeleted()
13201 << getDeletedOrUnavailableSuffix(Best->Function)
13202 << Base->getSourceRange();
13203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13204 return ExprError();
13207 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13209 // Convert the object parameter.
13210 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13211 ExprResult BaseResult =
13212 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13213 Best->FoundDecl, Method);
13214 if (BaseResult.isInvalid())
13215 return ExprError();
13216 Base = BaseResult.get();
13218 // Build the operator call.
13219 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13220 HadMultipleCandidates, OpLoc);
13221 if (FnExpr.isInvalid())
13222 return ExprError();
13224 QualType ResultTy = Method->getReturnType();
13225 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13226 ResultTy = ResultTy.getNonLValueExprType(Context);
13227 CXXOperatorCallExpr *TheCall =
13228 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13229 Base, ResultTy, VK, OpLoc, false);
13231 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13232 return ExprError();
13234 if (CheckFunctionCall(Method, TheCall,
13235 Method->getType()->castAs<FunctionProtoType>()))
13236 return ExprError();
13238 return MaybeBindToTemporary(TheCall);
13241 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13242 /// a literal operator described by the provided lookup results.
13243 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13244 DeclarationNameInfo &SuffixInfo,
13245 ArrayRef<Expr*> Args,
13246 SourceLocation LitEndLoc,
13247 TemplateArgumentListInfo *TemplateArgs) {
13248 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13250 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13251 OverloadCandidateSet::CSK_Normal);
13252 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13253 /*SuppressUserConversions=*/true);
13255 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13257 // Perform overload resolution. This will usually be trivial, but might need
13258 // to perform substitutions for a literal operator template.
13259 OverloadCandidateSet::iterator Best;
13260 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13265 case OR_No_Viable_Function:
13266 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13267 << R.getLookupName();
13268 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13269 return ExprError();
13272 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13273 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13274 return ExprError();
13277 FunctionDecl *FD = Best->Function;
13278 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13279 HadMultipleCandidates,
13280 SuffixInfo.getLoc(),
13281 SuffixInfo.getInfo());
13282 if (Fn.isInvalid())
13285 // Check the argument types. This should almost always be a no-op, except
13286 // that array-to-pointer decay is applied to string literals.
13288 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13289 ExprResult InputInit = PerformCopyInitialization(
13290 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13291 SourceLocation(), Args[ArgIdx]);
13292 if (InputInit.isInvalid())
13294 ConvArgs[ArgIdx] = InputInit.get();
13297 QualType ResultTy = FD->getReturnType();
13298 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13299 ResultTy = ResultTy.getNonLValueExprType(Context);
13301 UserDefinedLiteral *UDL =
13302 new (Context) UserDefinedLiteral(Context, Fn.get(),
13303 llvm::makeArrayRef(ConvArgs, Args.size()),
13304 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13306 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13307 return ExprError();
13309 if (CheckFunctionCall(FD, UDL, nullptr))
13310 return ExprError();
13312 return MaybeBindToTemporary(UDL);
13315 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13316 /// given LookupResult is non-empty, it is assumed to describe a member which
13317 /// will be invoked. Otherwise, the function will be found via argument
13318 /// dependent lookup.
13319 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13320 /// otherwise CallExpr is set to ExprError() and some non-success value
13322 Sema::ForRangeStatus
13323 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13324 SourceLocation RangeLoc,
13325 const DeclarationNameInfo &NameInfo,
13326 LookupResult &MemberLookup,
13327 OverloadCandidateSet *CandidateSet,
13328 Expr *Range, ExprResult *CallExpr) {
13329 Scope *S = nullptr;
13331 CandidateSet->clear();
13332 if (!MemberLookup.empty()) {
13333 ExprResult MemberRef =
13334 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13335 /*IsPtr=*/false, CXXScopeSpec(),
13336 /*TemplateKWLoc=*/SourceLocation(),
13337 /*FirstQualifierInScope=*/nullptr,
13339 /*TemplateArgs=*/nullptr, S);
13340 if (MemberRef.isInvalid()) {
13341 *CallExpr = ExprError();
13342 return FRS_DiagnosticIssued;
13344 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13345 if (CallExpr->isInvalid()) {
13346 *CallExpr = ExprError();
13347 return FRS_DiagnosticIssued;
13350 UnresolvedSet<0> FoundNames;
13351 UnresolvedLookupExpr *Fn =
13352 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13353 NestedNameSpecifierLoc(), NameInfo,
13354 /*NeedsADL=*/true, /*Overloaded=*/false,
13355 FoundNames.begin(), FoundNames.end());
13357 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13358 CandidateSet, CallExpr);
13359 if (CandidateSet->empty() || CandidateSetError) {
13360 *CallExpr = ExprError();
13361 return FRS_NoViableFunction;
13363 OverloadCandidateSet::iterator Best;
13364 OverloadingResult OverloadResult =
13365 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13367 if (OverloadResult == OR_No_Viable_Function) {
13368 *CallExpr = ExprError();
13369 return FRS_NoViableFunction;
13371 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13372 Loc, nullptr, CandidateSet, &Best,
13374 /*AllowTypoCorrection=*/false);
13375 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13376 *CallExpr = ExprError();
13377 return FRS_DiagnosticIssued;
13380 return FRS_Success;
13384 /// FixOverloadedFunctionReference - E is an expression that refers to
13385 /// a C++ overloaded function (possibly with some parentheses and
13386 /// perhaps a '&' around it). We have resolved the overloaded function
13387 /// to the function declaration Fn, so patch up the expression E to
13388 /// refer (possibly indirectly) to Fn. Returns the new expr.
13389 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13390 FunctionDecl *Fn) {
13391 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13392 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13394 if (SubExpr == PE->getSubExpr())
13397 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13400 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13401 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13403 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13404 SubExpr->getType()) &&
13405 "Implicit cast type cannot be determined from overload");
13406 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13407 if (SubExpr == ICE->getSubExpr())
13410 return ImplicitCastExpr::Create(Context, ICE->getType(),
13411 ICE->getCastKind(),
13413 ICE->getValueKind());
13416 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13417 if (!GSE->isResultDependent()) {
13419 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13420 if (SubExpr == GSE->getResultExpr())
13423 // Replace the resulting type information before rebuilding the generic
13424 // selection expression.
13425 ArrayRef<Expr *> A = GSE->getAssocExprs();
13426 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13427 unsigned ResultIdx = GSE->getResultIndex();
13428 AssocExprs[ResultIdx] = SubExpr;
13430 return new (Context) GenericSelectionExpr(
13431 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13432 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13433 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13436 // Rather than fall through to the unreachable, return the original generic
13437 // selection expression.
13441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13442 assert(UnOp->getOpcode() == UO_AddrOf &&
13443 "Can only take the address of an overloaded function");
13444 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13445 if (Method->isStatic()) {
13446 // Do nothing: static member functions aren't any different
13447 // from non-member functions.
13449 // Fix the subexpression, which really has to be an
13450 // UnresolvedLookupExpr holding an overloaded member function
13452 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13454 if (SubExpr == UnOp->getSubExpr())
13457 assert(isa<DeclRefExpr>(SubExpr)
13458 && "fixed to something other than a decl ref");
13459 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13460 && "fixed to a member ref with no nested name qualifier");
13462 // We have taken the address of a pointer to member
13463 // function. Perform the computation here so that we get the
13464 // appropriate pointer to member type.
13466 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13467 QualType MemPtrType
13468 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13469 // Under the MS ABI, lock down the inheritance model now.
13470 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13471 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13473 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13474 VK_RValue, OK_Ordinary,
13475 UnOp->getOperatorLoc());
13478 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13480 if (SubExpr == UnOp->getSubExpr())
13483 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13484 Context.getPointerType(SubExpr->getType()),
13485 VK_RValue, OK_Ordinary,
13486 UnOp->getOperatorLoc());
13489 // C++ [except.spec]p17:
13490 // An exception-specification is considered to be needed when:
13491 // - in an expression the function is the unique lookup result or the
13492 // selected member of a set of overloaded functions
13493 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13494 ResolveExceptionSpec(E->getExprLoc(), FPT);
13496 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13497 // FIXME: avoid copy.
13498 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13499 if (ULE->hasExplicitTemplateArgs()) {
13500 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13501 TemplateArgs = &TemplateArgsBuffer;
13504 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13505 ULE->getQualifierLoc(),
13506 ULE->getTemplateKeywordLoc(),
13508 /*enclosing*/ false, // FIXME?
13514 MarkDeclRefReferenced(DRE);
13515 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13519 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13520 // FIXME: avoid copy.
13521 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13522 if (MemExpr->hasExplicitTemplateArgs()) {
13523 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13524 TemplateArgs = &TemplateArgsBuffer;
13529 // If we're filling in a static method where we used to have an
13530 // implicit member access, rewrite to a simple decl ref.
13531 if (MemExpr->isImplicitAccess()) {
13532 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13533 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13534 MemExpr->getQualifierLoc(),
13535 MemExpr->getTemplateKeywordLoc(),
13537 /*enclosing*/ false,
13538 MemExpr->getMemberLoc(),
13543 MarkDeclRefReferenced(DRE);
13544 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13547 SourceLocation Loc = MemExpr->getMemberLoc();
13548 if (MemExpr->getQualifier())
13549 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13550 CheckCXXThisCapture(Loc);
13551 Base = new (Context) CXXThisExpr(Loc,
13552 MemExpr->getBaseType(),
13553 /*isImplicit=*/true);
13556 Base = MemExpr->getBase();
13558 ExprValueKind valueKind;
13560 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13561 valueKind = VK_LValue;
13562 type = Fn->getType();
13564 valueKind = VK_RValue;
13565 type = Context.BoundMemberTy;
13568 MemberExpr *ME = MemberExpr::Create(
13569 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13570 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13571 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13573 ME->setHadMultipleCandidates(true);
13574 MarkMemberReferenced(ME);
13578 llvm_unreachable("Invalid reference to overloaded function");
13581 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13582 DeclAccessPair Found,
13583 FunctionDecl *Fn) {
13584 return FixOverloadedFunctionReference(E.get(), Found, Fn);