[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaOverload.cpp
blob9aea1569f9b32e9060336283a64acf6742b8a2c7
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/CXXInheritance.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DependenceFlags.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
40 using namespace clang;
41 using namespace sema;
43 using AllowedExplicit = Sema::AllowedExplicit;
45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47 return P->hasAttr<PassObjectSizeAttr>();
48 });
51 /// A convenience routine for creating a decayed reference to a function.
52 static ExprResult CreateFunctionRefExpr(
53 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
54 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
55 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
56 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
57 return ExprError();
58 // If FoundDecl is different from Fn (such as if one is a template
59 // and the other a specialization), make sure DiagnoseUseOfDecl is
60 // called on both.
61 // FIXME: This would be more comprehensively addressed by modifying
62 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
63 // being used.
64 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
65 return ExprError();
66 DeclRefExpr *DRE = new (S.Context)
67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
71 S.MarkDeclRefReferenced(DRE, Base);
72 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
73 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
74 S.ResolveExceptionSpec(Loc, FPT);
75 DRE->setType(Fn->getType());
78 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
79 CK_FunctionToPointerDecay);
82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle,
86 bool AllowObjCWritebackConversion);
88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
89 QualType &ToType,
90 bool InOverloadResolution,
91 StandardConversionSequence &SCS,
92 bool CStyle);
93 static OverloadingResult
94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
95 UserDefinedConversionSequence& User,
96 OverloadCandidateSet& Conversions,
97 AllowedExplicit AllowExplicit,
98 bool AllowObjCConversionOnExplicit);
100 static ImplicitConversionSequence::CompareKind
101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
105 static ImplicitConversionSequence::CompareKind
106 CompareQualificationConversions(Sema &S,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
110 static ImplicitConversionSequence::CompareKind
111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
115 /// GetConversionRank - Retrieve the implicit conversion rank
116 /// corresponding to the given implicit conversion kind.
117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
118 static const ImplicitConversionRank
119 Rank[(int)ICK_Num_Conversion_Kinds] = {
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Promotion,
127 ICR_Promotion,
128 ICR_Promotion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_OCL_Scalar_Widening,
141 ICR_Complex_Real_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Writeback_Conversion,
145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146 // it was omitted by the patch that added
147 // ICK_Zero_Event_Conversion
148 ICR_C_Conversion,
149 ICR_C_Conversion_Extension
151 return Rank[(int)Kind];
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
162 "Function pointer conversion",
163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
166 "Complex promotion",
167 "Integral conversion",
168 "Floating conversion",
169 "Complex conversion",
170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
173 "Boolean conversion",
174 "Compatible-types conversion",
175 "Derived-to-base conversion",
176 "Vector conversion",
177 "SVE Vector conversion",
178 "Vector splat",
179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion",
182 "Writeback conversion",
183 "OpenCL Zero Event Conversion",
184 "C specific type conversion",
185 "Incompatible pointer conversion"
187 return Name[Kind];
190 /// StandardConversionSequence - Set the standard conversion
191 /// sequence to the identity conversion.
192 void StandardConversionSequence::setAsIdentityConversion() {
193 First = ICK_Identity;
194 Second = ICK_Identity;
195 Third = ICK_Identity;
196 DeprecatedStringLiteralToCharPtr = false;
197 QualificationIncludesObjCLifetime = false;
198 ReferenceBinding = false;
199 DirectBinding = false;
200 IsLvalueReference = true;
201 BindsToFunctionLvalue = false;
202 BindsToRvalue = false;
203 BindsImplicitObjectArgumentWithoutRefQualifier = false;
204 ObjCLifetimeConversionBinding = false;
205 CopyConstructor = nullptr;
208 /// getRank - Retrieve the rank of this standard conversion sequence
209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
210 /// implicit conversions.
211 ImplicitConversionRank StandardConversionSequence::getRank() const {
212 ImplicitConversionRank Rank = ICR_Exact_Match;
213 if (GetConversionRank(First) > Rank)
214 Rank = GetConversionRank(First);
215 if (GetConversionRank(Second) > Rank)
216 Rank = GetConversionRank(Second);
217 if (GetConversionRank(Third) > Rank)
218 Rank = GetConversionRank(Third);
219 return Rank;
222 /// isPointerConversionToBool - Determines whether this conversion is
223 /// a conversion of a pointer or pointer-to-member to bool. This is
224 /// used as part of the ranking of standard conversion sequences
225 /// (C++ 13.3.3.2p4).
226 bool StandardConversionSequence::isPointerConversionToBool() const {
227 // Note that FromType has not necessarily been transformed by the
228 // array-to-pointer or function-to-pointer implicit conversions, so
229 // check for their presence as well as checking whether FromType is
230 // a pointer.
231 if (getToType(1)->isBooleanType() &&
232 (getFromType()->isPointerType() ||
233 getFromType()->isMemberPointerType() ||
234 getFromType()->isObjCObjectPointerType() ||
235 getFromType()->isBlockPointerType() ||
236 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
237 return true;
239 return false;
242 /// isPointerConversionToVoidPointer - Determines whether this
243 /// conversion is a conversion of a pointer to a void pointer. This is
244 /// used as part of the ranking of standard conversion sequences (C++
245 /// 13.3.3.2p4).
246 bool
247 StandardConversionSequence::
248 isPointerConversionToVoidPointer(ASTContext& Context) const {
249 QualType FromType = getFromType();
250 QualType ToType = getToType(1);
252 // Note that FromType has not necessarily been transformed by the
253 // array-to-pointer implicit conversion, so check for its presence
254 // and redo the conversion to get a pointer.
255 if (First == ICK_Array_To_Pointer)
256 FromType = Context.getArrayDecayedType(FromType);
258 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
259 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
260 return ToPtrType->getPointeeType()->isVoidType();
262 return false;
265 /// Skip any implicit casts which could be either part of a narrowing conversion
266 /// or after one in an implicit conversion.
267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
268 const Expr *Converted) {
269 // We can have cleanups wrapping the converted expression; these need to be
270 // preserved so that destructors run if necessary.
271 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
272 Expr *Inner =
273 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
274 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275 EWC->getObjects());
278 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
279 switch (ICE->getCastKind()) {
280 case CK_NoOp:
281 case CK_IntegralCast:
282 case CK_IntegralToBoolean:
283 case CK_IntegralToFloating:
284 case CK_BooleanToSignedIntegral:
285 case CK_FloatingToIntegral:
286 case CK_FloatingToBoolean:
287 case CK_FloatingCast:
288 Converted = ICE->getSubExpr();
289 continue;
291 default:
292 return Converted;
296 return Converted;
299 /// Check if this standard conversion sequence represents a narrowing
300 /// conversion, according to C++11 [dcl.init.list]p7.
302 /// \param Ctx The AST context.
303 /// \param Converted The result of applying this standard conversion sequence.
304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305 /// value of the expression prior to the narrowing conversion.
306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307 /// type of the expression prior to the narrowing conversion.
308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
309 /// from floating point types to integral types should be ignored.
310 NarrowingKind StandardConversionSequence::getNarrowingKind(
311 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
312 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315 // C++11 [dcl.init.list]p7:
316 // A narrowing conversion is an implicit conversion ...
317 QualType FromType = getToType(0);
318 QualType ToType = getToType(1);
320 // A conversion to an enumeration type is narrowing if the conversion to
321 // the underlying type is narrowing. This only arises for expressions of
322 // the form 'Enum{init}'.
323 if (auto *ET = ToType->getAs<EnumType>())
324 ToType = ET->getDecl()->getIntegerType();
326 switch (Second) {
327 // 'bool' is an integral type; dispatch to the right place to handle it.
328 case ICK_Boolean_Conversion:
329 if (FromType->isRealFloatingType())
330 goto FloatingIntegralConversion;
331 if (FromType->isIntegralOrUnscopedEnumerationType())
332 goto IntegralConversion;
333 // -- from a pointer type or pointer-to-member type to bool, or
334 return NK_Type_Narrowing;
336 // -- from a floating-point type to an integer type, or
338 // -- from an integer type or unscoped enumeration type to a floating-point
339 // type, except where the source is a constant expression and the actual
340 // value after conversion will fit into the target type and will produce
341 // the original value when converted back to the original type, or
342 case ICK_Floating_Integral:
343 FloatingIntegralConversion:
344 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
345 return NK_Type_Narrowing;
346 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
347 ToType->isRealFloatingType()) {
348 if (IgnoreFloatToIntegralConversion)
349 return NK_Not_Narrowing;
350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351 assert(Initializer && "Unknown conversion expression");
353 // If it's value-dependent, we can't tell whether it's narrowing.
354 if (Initializer->isValueDependent())
355 return NK_Dependent_Narrowing;
357 if (Optional<llvm::APSInt> IntConstantValue =
358 Initializer->getIntegerConstantExpr(Ctx)) {
359 // Convert the integer to the floating type.
360 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
361 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
362 llvm::APFloat::rmNearestTiesToEven);
363 // And back.
364 llvm::APSInt ConvertedValue = *IntConstantValue;
365 bool ignored;
366 Result.convertToInteger(ConvertedValue,
367 llvm::APFloat::rmTowardZero, &ignored);
368 // If the resulting value is different, this was a narrowing conversion.
369 if (*IntConstantValue != ConvertedValue) {
370 ConstantValue = APValue(*IntConstantValue);
371 ConstantType = Initializer->getType();
372 return NK_Constant_Narrowing;
374 } else {
375 // Variables are always narrowings.
376 return NK_Variable_Narrowing;
379 return NK_Not_Narrowing;
381 // -- from long double to double or float, or from double to float, except
382 // where the source is a constant expression and the actual value after
383 // conversion is within the range of values that can be represented (even
384 // if it cannot be represented exactly), or
385 case ICK_Floating_Conversion:
386 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
387 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
388 // FromType is larger than ToType.
389 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391 // If it's value-dependent, we can't tell whether it's narrowing.
392 if (Initializer->isValueDependent())
393 return NK_Dependent_Narrowing;
395 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
396 // Constant!
397 assert(ConstantValue.isFloat());
398 llvm::APFloat FloatVal = ConstantValue.getFloat();
399 // Convert the source value into the target type.
400 bool ignored;
401 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
402 Ctx.getFloatTypeSemantics(ToType),
403 llvm::APFloat::rmNearestTiesToEven, &ignored);
404 // If there was no overflow, the source value is within the range of
405 // values that can be represented.
406 if (ConvertStatus & llvm::APFloat::opOverflow) {
407 ConstantType = Initializer->getType();
408 return NK_Constant_Narrowing;
410 } else {
411 return NK_Variable_Narrowing;
414 return NK_Not_Narrowing;
416 // -- from an integer type or unscoped enumeration type to an integer type
417 // that cannot represent all the values of the original type, except where
418 // the source is a constant expression and the actual value after
419 // conversion will fit into the target type and will produce the original
420 // value when converted back to the original type.
421 case ICK_Integral_Conversion:
422 IntegralConversion: {
423 assert(FromType->isIntegralOrUnscopedEnumerationType());
424 assert(ToType->isIntegralOrUnscopedEnumerationType());
425 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
426 const unsigned FromWidth = Ctx.getIntWidth(FromType);
427 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
428 const unsigned ToWidth = Ctx.getIntWidth(ToType);
430 if (FromWidth > ToWidth ||
431 (FromWidth == ToWidth && FromSigned != ToSigned) ||
432 (FromSigned && !ToSigned)) {
433 // Not all values of FromType can be represented in ToType.
434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436 // If it's value-dependent, we can't tell whether it's narrowing.
437 if (Initializer->isValueDependent())
438 return NK_Dependent_Narrowing;
440 Optional<llvm::APSInt> OptInitializerValue;
441 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
442 // Such conversions on variables are always narrowing.
443 return NK_Variable_Narrowing;
445 llvm::APSInt &InitializerValue = *OptInitializerValue;
446 bool Narrowing = false;
447 if (FromWidth < ToWidth) {
448 // Negative -> unsigned is narrowing. Otherwise, more bits is never
449 // narrowing.
450 if (InitializerValue.isSigned() && InitializerValue.isNegative())
451 Narrowing = true;
452 } else {
453 // Add a bit to the InitializerValue so we don't have to worry about
454 // signed vs. unsigned comparisons.
455 InitializerValue = InitializerValue.extend(
456 InitializerValue.getBitWidth() + 1);
457 // Convert the initializer to and from the target width and signed-ness.
458 llvm::APSInt ConvertedValue = InitializerValue;
459 ConvertedValue = ConvertedValue.trunc(ToWidth);
460 ConvertedValue.setIsSigned(ToSigned);
461 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
462 ConvertedValue.setIsSigned(InitializerValue.isSigned());
463 // If the result is different, this was a narrowing conversion.
464 if (ConvertedValue != InitializerValue)
465 Narrowing = true;
467 if (Narrowing) {
468 ConstantType = Initializer->getType();
469 ConstantValue = APValue(InitializerValue);
470 return NK_Constant_Narrowing;
473 return NK_Not_Narrowing;
476 default:
477 // Other kinds of conversions are not narrowings.
478 return NK_Not_Narrowing;
482 /// dump - Print this standard conversion sequence to standard
483 /// error. Useful for debugging overloading issues.
484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
485 raw_ostream &OS = llvm::errs();
486 bool PrintedSomething = false;
487 if (First != ICK_Identity) {
488 OS << GetImplicitConversionName(First);
489 PrintedSomething = true;
492 if (Second != ICK_Identity) {
493 if (PrintedSomething) {
494 OS << " -> ";
496 OS << GetImplicitConversionName(Second);
498 if (CopyConstructor) {
499 OS << " (by copy constructor)";
500 } else if (DirectBinding) {
501 OS << " (direct reference binding)";
502 } else if (ReferenceBinding) {
503 OS << " (reference binding)";
505 PrintedSomething = true;
508 if (Third != ICK_Identity) {
509 if (PrintedSomething) {
510 OS << " -> ";
512 OS << GetImplicitConversionName(Third);
513 PrintedSomething = true;
516 if (!PrintedSomething) {
517 OS << "No conversions required";
521 /// dump - Print this user-defined conversion sequence to standard
522 /// error. Useful for debugging overloading issues.
523 void UserDefinedConversionSequence::dump() const {
524 raw_ostream &OS = llvm::errs();
525 if (Before.First || Before.Second || Before.Third) {
526 Before.dump();
527 OS << " -> ";
529 if (ConversionFunction)
530 OS << '\'' << *ConversionFunction << '\'';
531 else
532 OS << "aggregate initialization";
533 if (After.First || After.Second || After.Third) {
534 OS << " -> ";
535 After.dump();
539 /// dump - Print this implicit conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
541 void ImplicitConversionSequence::dump() const {
542 raw_ostream &OS = llvm::errs();
543 if (hasInitializerListContainerType())
544 OS << "Worst list element conversion: ";
545 switch (ConversionKind) {
546 case StandardConversion:
547 OS << "Standard conversion: ";
548 Standard.dump();
549 break;
550 case UserDefinedConversion:
551 OS << "User-defined conversion: ";
552 UserDefined.dump();
553 break;
554 case EllipsisConversion:
555 OS << "Ellipsis conversion";
556 break;
557 case AmbiguousConversion:
558 OS << "Ambiguous conversion";
559 break;
560 case BadConversion:
561 OS << "Bad conversion";
562 break;
565 OS << "\n";
568 void AmbiguousConversionSequence::construct() {
569 new (&conversions()) ConversionSet();
572 void AmbiguousConversionSequence::destruct() {
573 conversions().~ConversionSet();
576 void
577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
578 FromTypePtr = O.FromTypePtr;
579 ToTypePtr = O.ToTypePtr;
580 new (&conversions()) ConversionSet(O.conversions());
583 namespace {
584 // Structure used by DeductionFailureInfo to store
585 // template argument information.
586 struct DFIArguments {
587 TemplateArgument FirstArg;
588 TemplateArgument SecondArg;
590 // Structure used by DeductionFailureInfo to store
591 // template parameter and template argument information.
592 struct DFIParamWithArguments : DFIArguments {
593 TemplateParameter Param;
595 // Structure used by DeductionFailureInfo to store template argument
596 // information and the index of the problematic call argument.
597 struct DFIDeducedMismatchArgs : DFIArguments {
598 TemplateArgumentList *TemplateArgs;
599 unsigned CallArgIndex;
601 // Structure used by DeductionFailureInfo to store information about
602 // unsatisfied constraints.
603 struct CNSInfo {
604 TemplateArgumentList *TemplateArgs;
605 ConstraintSatisfaction Satisfaction;
609 /// Convert from Sema's representation of template deduction information
610 /// to the form used in overload-candidate information.
611 DeductionFailureInfo
612 clang::MakeDeductionFailureInfo(ASTContext &Context,
613 Sema::TemplateDeductionResult TDK,
614 TemplateDeductionInfo &Info) {
615 DeductionFailureInfo Result;
616 Result.Result = static_cast<unsigned>(TDK);
617 Result.HasDiagnostic = false;
618 switch (TDK) {
619 case Sema::TDK_Invalid:
620 case Sema::TDK_InstantiationDepth:
621 case Sema::TDK_TooManyArguments:
622 case Sema::TDK_TooFewArguments:
623 case Sema::TDK_MiscellaneousDeductionFailure:
624 case Sema::TDK_CUDATargetMismatch:
625 Result.Data = nullptr;
626 break;
628 case Sema::TDK_Incomplete:
629 case Sema::TDK_InvalidExplicitArguments:
630 Result.Data = Info.Param.getOpaqueValue();
631 break;
633 case Sema::TDK_DeducedMismatch:
634 case Sema::TDK_DeducedMismatchNested: {
635 // FIXME: Should allocate from normal heap so that we can free this later.
636 auto *Saved = new (Context) DFIDeducedMismatchArgs;
637 Saved->FirstArg = Info.FirstArg;
638 Saved->SecondArg = Info.SecondArg;
639 Saved->TemplateArgs = Info.take();
640 Saved->CallArgIndex = Info.CallArgIndex;
641 Result.Data = Saved;
642 break;
645 case Sema::TDK_NonDeducedMismatch: {
646 // FIXME: Should allocate from normal heap so that we can free this later.
647 DFIArguments *Saved = new (Context) DFIArguments;
648 Saved->FirstArg = Info.FirstArg;
649 Saved->SecondArg = Info.SecondArg;
650 Result.Data = Saved;
651 break;
654 case Sema::TDK_IncompletePack:
655 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
656 case Sema::TDK_Inconsistent:
657 case Sema::TDK_Underqualified: {
658 // FIXME: Should allocate from normal heap so that we can free this later.
659 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
660 Saved->Param = Info.Param;
661 Saved->FirstArg = Info.FirstArg;
662 Saved->SecondArg = Info.SecondArg;
663 Result.Data = Saved;
664 break;
667 case Sema::TDK_SubstitutionFailure:
668 Result.Data = Info.take();
669 if (Info.hasSFINAEDiagnostic()) {
670 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
671 SourceLocation(), PartialDiagnostic::NullDiagnostic());
672 Info.takeSFINAEDiagnostic(*Diag);
673 Result.HasDiagnostic = true;
675 break;
677 case Sema::TDK_ConstraintsNotSatisfied: {
678 CNSInfo *Saved = new (Context) CNSInfo;
679 Saved->TemplateArgs = Info.take();
680 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
681 Result.Data = Saved;
682 break;
685 case Sema::TDK_Success:
686 case Sema::TDK_NonDependentConversionFailure:
687 case Sema::TDK_AlreadyDiagnosed:
688 llvm_unreachable("not a deduction failure");
691 return Result;
694 void DeductionFailureInfo::Destroy() {
695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696 case Sema::TDK_Success:
697 case Sema::TDK_Invalid:
698 case Sema::TDK_InstantiationDepth:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
702 case Sema::TDK_InvalidExplicitArguments:
703 case Sema::TDK_CUDATargetMismatch:
704 case Sema::TDK_NonDependentConversionFailure:
705 break;
707 case Sema::TDK_IncompletePack:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_DeducedMismatch:
711 case Sema::TDK_DeducedMismatchNested:
712 case Sema::TDK_NonDeducedMismatch:
713 // FIXME: Destroy the data?
714 Data = nullptr;
715 break;
717 case Sema::TDK_SubstitutionFailure:
718 // FIXME: Destroy the template argument list?
719 Data = nullptr;
720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721 Diag->~PartialDiagnosticAt();
722 HasDiagnostic = false;
724 break;
726 case Sema::TDK_ConstraintsNotSatisfied:
727 // FIXME: Destroy the template argument list?
728 Data = nullptr;
729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730 Diag->~PartialDiagnosticAt();
731 HasDiagnostic = false;
733 break;
735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 case Sema::TDK_AlreadyDiagnosed:
738 break;
742 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
743 if (HasDiagnostic)
744 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
745 return nullptr;
748 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
749 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
750 case Sema::TDK_Success:
751 case Sema::TDK_Invalid:
752 case Sema::TDK_InstantiationDepth:
753 case Sema::TDK_TooManyArguments:
754 case Sema::TDK_TooFewArguments:
755 case Sema::TDK_SubstitutionFailure:
756 case Sema::TDK_DeducedMismatch:
757 case Sema::TDK_DeducedMismatchNested:
758 case Sema::TDK_NonDeducedMismatch:
759 case Sema::TDK_CUDATargetMismatch:
760 case Sema::TDK_NonDependentConversionFailure:
761 case Sema::TDK_ConstraintsNotSatisfied:
762 return TemplateParameter();
764 case Sema::TDK_Incomplete:
765 case Sema::TDK_InvalidExplicitArguments:
766 return TemplateParameter::getFromOpaqueValue(Data);
768 case Sema::TDK_IncompletePack:
769 case Sema::TDK_Inconsistent:
770 case Sema::TDK_Underqualified:
771 return static_cast<DFIParamWithArguments*>(Data)->Param;
773 // Unhandled
774 case Sema::TDK_MiscellaneousDeductionFailure:
775 case Sema::TDK_AlreadyDiagnosed:
776 break;
779 return TemplateParameter();
782 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
783 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
784 case Sema::TDK_Success:
785 case Sema::TDK_Invalid:
786 case Sema::TDK_InstantiationDepth:
787 case Sema::TDK_TooManyArguments:
788 case Sema::TDK_TooFewArguments:
789 case Sema::TDK_Incomplete:
790 case Sema::TDK_IncompletePack:
791 case Sema::TDK_InvalidExplicitArguments:
792 case Sema::TDK_Inconsistent:
793 case Sema::TDK_Underqualified:
794 case Sema::TDK_NonDeducedMismatch:
795 case Sema::TDK_CUDATargetMismatch:
796 case Sema::TDK_NonDependentConversionFailure:
797 return nullptr;
799 case Sema::TDK_DeducedMismatch:
800 case Sema::TDK_DeducedMismatchNested:
801 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
803 case Sema::TDK_SubstitutionFailure:
804 return static_cast<TemplateArgumentList*>(Data);
806 case Sema::TDK_ConstraintsNotSatisfied:
807 return static_cast<CNSInfo*>(Data)->TemplateArgs;
809 // Unhandled
810 case Sema::TDK_MiscellaneousDeductionFailure:
811 case Sema::TDK_AlreadyDiagnosed:
812 break;
815 return nullptr;
818 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
819 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
820 case Sema::TDK_Success:
821 case Sema::TDK_Invalid:
822 case Sema::TDK_InstantiationDepth:
823 case Sema::TDK_Incomplete:
824 case Sema::TDK_TooManyArguments:
825 case Sema::TDK_TooFewArguments:
826 case Sema::TDK_InvalidExplicitArguments:
827 case Sema::TDK_SubstitutionFailure:
828 case Sema::TDK_CUDATargetMismatch:
829 case Sema::TDK_NonDependentConversionFailure:
830 case Sema::TDK_ConstraintsNotSatisfied:
831 return nullptr;
833 case Sema::TDK_IncompletePack:
834 case Sema::TDK_Inconsistent:
835 case Sema::TDK_Underqualified:
836 case Sema::TDK_DeducedMismatch:
837 case Sema::TDK_DeducedMismatchNested:
838 case Sema::TDK_NonDeducedMismatch:
839 return &static_cast<DFIArguments*>(Data)->FirstArg;
841 // Unhandled
842 case Sema::TDK_MiscellaneousDeductionFailure:
843 case Sema::TDK_AlreadyDiagnosed:
844 break;
847 return nullptr;
850 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
851 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
852 case Sema::TDK_Success:
853 case Sema::TDK_Invalid:
854 case Sema::TDK_InstantiationDepth:
855 case Sema::TDK_Incomplete:
856 case Sema::TDK_IncompletePack:
857 case Sema::TDK_TooManyArguments:
858 case Sema::TDK_TooFewArguments:
859 case Sema::TDK_InvalidExplicitArguments:
860 case Sema::TDK_SubstitutionFailure:
861 case Sema::TDK_CUDATargetMismatch:
862 case Sema::TDK_NonDependentConversionFailure:
863 case Sema::TDK_ConstraintsNotSatisfied:
864 return nullptr;
866 case Sema::TDK_Inconsistent:
867 case Sema::TDK_Underqualified:
868 case Sema::TDK_DeducedMismatch:
869 case Sema::TDK_DeducedMismatchNested:
870 case Sema::TDK_NonDeducedMismatch:
871 return &static_cast<DFIArguments*>(Data)->SecondArg;
873 // Unhandled
874 case Sema::TDK_MiscellaneousDeductionFailure:
875 case Sema::TDK_AlreadyDiagnosed:
876 break;
879 return nullptr;
882 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
883 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
884 case Sema::TDK_DeducedMismatch:
885 case Sema::TDK_DeducedMismatchNested:
886 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
888 default:
889 return llvm::None;
893 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
894 OverloadedOperatorKind Op) {
895 if (!AllowRewrittenCandidates)
896 return false;
897 return Op == OO_EqualEqual || Op == OO_Spaceship;
900 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
901 ASTContext &Ctx, const FunctionDecl *FD) {
902 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
903 return false;
904 // Don't bother adding a reversed candidate that can never be a better
905 // match than the non-reversed version.
906 return FD->getNumParams() != 2 ||
907 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
908 FD->getParamDecl(1)->getType()) ||
909 FD->hasAttr<EnableIfAttr>();
912 void OverloadCandidateSet::destroyCandidates() {
913 for (iterator i = begin(), e = end(); i != e; ++i) {
914 for (auto &C : i->Conversions)
915 C.~ImplicitConversionSequence();
916 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
917 i->DeductionFailure.Destroy();
921 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
922 destroyCandidates();
923 SlabAllocator.Reset();
924 NumInlineBytesUsed = 0;
925 Candidates.clear();
926 Functions.clear();
927 Kind = CSK;
930 namespace {
931 class UnbridgedCastsSet {
932 struct Entry {
933 Expr **Addr;
934 Expr *Saved;
936 SmallVector<Entry, 2> Entries;
938 public:
939 void save(Sema &S, Expr *&E) {
940 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
941 Entry entry = { &E, E };
942 Entries.push_back(entry);
943 E = S.stripARCUnbridgedCast(E);
946 void restore() {
947 for (SmallVectorImpl<Entry>::iterator
948 i = Entries.begin(), e = Entries.end(); i != e; ++i)
949 *i->Addr = i->Saved;
954 /// checkPlaceholderForOverload - Do any interesting placeholder-like
955 /// preprocessing on the given expression.
957 /// \param unbridgedCasts a collection to which to add unbridged casts;
958 /// without this, they will be immediately diagnosed as errors
960 /// Return true on unrecoverable error.
961 static bool
962 checkPlaceholderForOverload(Sema &S, Expr *&E,
963 UnbridgedCastsSet *unbridgedCasts = nullptr) {
964 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
965 // We can't handle overloaded expressions here because overload
966 // resolution might reasonably tweak them.
967 if (placeholder->getKind() == BuiltinType::Overload) return false;
969 // If the context potentially accepts unbridged ARC casts, strip
970 // the unbridged cast and add it to the collection for later restoration.
971 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
972 unbridgedCasts) {
973 unbridgedCasts->save(S, E);
974 return false;
977 // Go ahead and check everything else.
978 ExprResult result = S.CheckPlaceholderExpr(E);
979 if (result.isInvalid())
980 return true;
982 E = result.get();
983 return false;
986 // Nothing to do.
987 return false;
990 /// checkArgPlaceholdersForOverload - Check a set of call operands for
991 /// placeholders.
992 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
993 UnbridgedCastsSet &unbridged) {
994 for (unsigned i = 0, e = Args.size(); i != e; ++i)
995 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
996 return true;
998 return false;
1001 /// Determine whether the given New declaration is an overload of the
1002 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1003 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1004 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1005 /// functions (or function templates) at all. When it does return Ovl_Match or
1006 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1007 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1008 /// declaration.
1010 /// Example: Given the following input:
1012 /// void f(int, float); // #1
1013 /// void f(int, int); // #2
1014 /// int f(int, int); // #3
1016 /// When we process #1, there is no previous declaration of "f", so IsOverload
1017 /// will not be used.
1019 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1020 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1021 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1022 /// unchanged.
1024 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1025 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1026 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1027 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1028 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1030 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1031 /// by a using declaration. The rules for whether to hide shadow declarations
1032 /// ignore some properties which otherwise figure into a function template's
1033 /// signature.
1034 Sema::OverloadKind
1035 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1036 NamedDecl *&Match, bool NewIsUsingDecl) {
1037 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1038 I != E; ++I) {
1039 NamedDecl *OldD = *I;
1041 bool OldIsUsingDecl = false;
1042 if (isa<UsingShadowDecl>(OldD)) {
1043 OldIsUsingDecl = true;
1045 // We can always introduce two using declarations into the same
1046 // context, even if they have identical signatures.
1047 if (NewIsUsingDecl) continue;
1049 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1052 // A using-declaration does not conflict with another declaration
1053 // if one of them is hidden.
1054 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1055 continue;
1057 // If either declaration was introduced by a using declaration,
1058 // we'll need to use slightly different rules for matching.
1059 // Essentially, these rules are the normal rules, except that
1060 // function templates hide function templates with different
1061 // return types or template parameter lists.
1062 bool UseMemberUsingDeclRules =
1063 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1064 !New->getFriendObjectKind();
1066 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1067 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1068 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1069 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1070 continue;
1073 if (!isa<FunctionTemplateDecl>(OldD) &&
1074 !shouldLinkPossiblyHiddenDecl(*I, New))
1075 continue;
1077 Match = *I;
1078 return Ovl_Match;
1081 // Builtins that have custom typechecking or have a reference should
1082 // not be overloadable or redeclarable.
1083 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1084 Match = *I;
1085 return Ovl_NonFunction;
1087 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1088 // We can overload with these, which can show up when doing
1089 // redeclaration checks for UsingDecls.
1090 assert(Old.getLookupKind() == LookupUsingDeclName);
1091 } else if (isa<TagDecl>(OldD)) {
1092 // We can always overload with tags by hiding them.
1093 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1094 // Optimistically assume that an unresolved using decl will
1095 // overload; if it doesn't, we'll have to diagnose during
1096 // template instantiation.
1098 // Exception: if the scope is dependent and this is not a class
1099 // member, the using declaration can only introduce an enumerator.
1100 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1101 Match = *I;
1102 return Ovl_NonFunction;
1104 } else {
1105 // (C++ 13p1):
1106 // Only function declarations can be overloaded; object and type
1107 // declarations cannot be overloaded.
1108 Match = *I;
1109 return Ovl_NonFunction;
1113 // C++ [temp.friend]p1:
1114 // For a friend function declaration that is not a template declaration:
1115 // -- if the name of the friend is a qualified or unqualified template-id,
1116 // [...], otherwise
1117 // -- if the name of the friend is a qualified-id and a matching
1118 // non-template function is found in the specified class or namespace,
1119 // the friend declaration refers to that function, otherwise,
1120 // -- if the name of the friend is a qualified-id and a matching function
1121 // template is found in the specified class or namespace, the friend
1122 // declaration refers to the deduced specialization of that function
1123 // template, otherwise
1124 // -- the name shall be an unqualified-id [...]
1125 // If we get here for a qualified friend declaration, we've just reached the
1126 // third bullet. If the type of the friend is dependent, skip this lookup
1127 // until instantiation.
1128 if (New->getFriendObjectKind() && New->getQualifier() &&
1129 !New->getDescribedFunctionTemplate() &&
1130 !New->getDependentSpecializationInfo() &&
1131 !New->getType()->isDependentType()) {
1132 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1133 TemplateSpecResult.addAllDecls(Old);
1134 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1135 /*QualifiedFriend*/true)) {
1136 New->setInvalidDecl();
1137 return Ovl_Overload;
1140 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1141 return Ovl_Match;
1144 return Ovl_Overload;
1147 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1148 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1149 bool ConsiderRequiresClauses) {
1150 // C++ [basic.start.main]p2: This function shall not be overloaded.
1151 if (New->isMain())
1152 return false;
1154 // MSVCRT user defined entry points cannot be overloaded.
1155 if (New->isMSVCRTEntryPoint())
1156 return false;
1158 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1159 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1161 // C++ [temp.fct]p2:
1162 // A function template can be overloaded with other function templates
1163 // and with normal (non-template) functions.
1164 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1165 return true;
1167 // Is the function New an overload of the function Old?
1168 QualType OldQType = Context.getCanonicalType(Old->getType());
1169 QualType NewQType = Context.getCanonicalType(New->getType());
1171 // Compare the signatures (C++ 1.3.10) of the two functions to
1172 // determine whether they are overloads. If we find any mismatch
1173 // in the signature, they are overloads.
1175 // If either of these functions is a K&R-style function (no
1176 // prototype), then we consider them to have matching signatures.
1177 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1178 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1179 return false;
1181 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1182 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1184 // The signature of a function includes the types of its
1185 // parameters (C++ 1.3.10), which includes the presence or absence
1186 // of the ellipsis; see C++ DR 357).
1187 if (OldQType != NewQType &&
1188 (OldType->getNumParams() != NewType->getNumParams() ||
1189 OldType->isVariadic() != NewType->isVariadic() ||
1190 !FunctionParamTypesAreEqual(OldType, NewType)))
1191 return true;
1193 // C++ [temp.over.link]p4:
1194 // The signature of a function template consists of its function
1195 // signature, its return type and its template parameter list. The names
1196 // of the template parameters are significant only for establishing the
1197 // relationship between the template parameters and the rest of the
1198 // signature.
1200 // We check the return type and template parameter lists for function
1201 // templates first; the remaining checks follow.
1203 // However, we don't consider either of these when deciding whether
1204 // a member introduced by a shadow declaration is hidden.
1205 if (!UseMemberUsingDeclRules && NewTemplate &&
1206 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1207 OldTemplate->getTemplateParameters(),
1208 false, TPL_TemplateMatch) ||
1209 !Context.hasSameType(Old->getDeclaredReturnType(),
1210 New->getDeclaredReturnType())))
1211 return true;
1213 // If the function is a class member, its signature includes the
1214 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1216 // As part of this, also check whether one of the member functions
1217 // is static, in which case they are not overloads (C++
1218 // 13.1p2). While not part of the definition of the signature,
1219 // this check is important to determine whether these functions
1220 // can be overloaded.
1221 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1222 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1223 if (OldMethod && NewMethod &&
1224 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1225 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1226 if (!UseMemberUsingDeclRules &&
1227 (OldMethod->getRefQualifier() == RQ_None ||
1228 NewMethod->getRefQualifier() == RQ_None)) {
1229 // C++0x [over.load]p2:
1230 // - Member function declarations with the same name and the same
1231 // parameter-type-list as well as member function template
1232 // declarations with the same name, the same parameter-type-list, and
1233 // the same template parameter lists cannot be overloaded if any of
1234 // them, but not all, have a ref-qualifier (8.3.5).
1235 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1236 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1237 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1239 return true;
1242 // We may not have applied the implicit const for a constexpr member
1243 // function yet (because we haven't yet resolved whether this is a static
1244 // or non-static member function). Add it now, on the assumption that this
1245 // is a redeclaration of OldMethod.
1246 auto OldQuals = OldMethod->getMethodQualifiers();
1247 auto NewQuals = NewMethod->getMethodQualifiers();
1248 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1249 !isa<CXXConstructorDecl>(NewMethod))
1250 NewQuals.addConst();
1251 // We do not allow overloading based off of '__restrict'.
1252 OldQuals.removeRestrict();
1253 NewQuals.removeRestrict();
1254 if (OldQuals != NewQuals)
1255 return true;
1258 // Though pass_object_size is placed on parameters and takes an argument, we
1259 // consider it to be a function-level modifier for the sake of function
1260 // identity. Either the function has one or more parameters with
1261 // pass_object_size or it doesn't.
1262 if (functionHasPassObjectSizeParams(New) !=
1263 functionHasPassObjectSizeParams(Old))
1264 return true;
1266 // enable_if attributes are an order-sensitive part of the signature.
1267 for (specific_attr_iterator<EnableIfAttr>
1268 NewI = New->specific_attr_begin<EnableIfAttr>(),
1269 NewE = New->specific_attr_end<EnableIfAttr>(),
1270 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1271 OldE = Old->specific_attr_end<EnableIfAttr>();
1272 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1273 if (NewI == NewE || OldI == OldE)
1274 return true;
1275 llvm::FoldingSetNodeID NewID, OldID;
1276 NewI->getCond()->Profile(NewID, Context, true);
1277 OldI->getCond()->Profile(OldID, Context, true);
1278 if (NewID != OldID)
1279 return true;
1282 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1283 // Don't allow overloading of destructors. (In theory we could, but it
1284 // would be a giant change to clang.)
1285 if (!isa<CXXDestructorDecl>(New)) {
1286 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1287 OldTarget = IdentifyCUDATarget(Old);
1288 if (NewTarget != CFT_InvalidTarget) {
1289 assert((OldTarget != CFT_InvalidTarget) &&
1290 "Unexpected invalid target.");
1292 // Allow overloading of functions with same signature and different CUDA
1293 // target attributes.
1294 if (NewTarget != OldTarget)
1295 return true;
1300 if (ConsiderRequiresClauses) {
1301 Expr *NewRC = New->getTrailingRequiresClause(),
1302 *OldRC = Old->getTrailingRequiresClause();
1303 if ((NewRC != nullptr) != (OldRC != nullptr))
1304 // RC are most certainly different - these are overloads.
1305 return true;
1307 if (NewRC) {
1308 llvm::FoldingSetNodeID NewID, OldID;
1309 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1310 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1311 if (NewID != OldID)
1312 // RCs are not equivalent - these are overloads.
1313 return true;
1317 // The signatures match; this is not an overload.
1318 return false;
1321 /// Tries a user-defined conversion from From to ToType.
1323 /// Produces an implicit conversion sequence for when a standard conversion
1324 /// is not an option. See TryImplicitConversion for more information.
1325 static ImplicitConversionSequence
1326 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1327 bool SuppressUserConversions,
1328 AllowedExplicit AllowExplicit,
1329 bool InOverloadResolution,
1330 bool CStyle,
1331 bool AllowObjCWritebackConversion,
1332 bool AllowObjCConversionOnExplicit) {
1333 ImplicitConversionSequence ICS;
1335 if (SuppressUserConversions) {
1336 // We're not in the case above, so there is no conversion that
1337 // we can perform.
1338 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1339 return ICS;
1342 // Attempt user-defined conversion.
1343 OverloadCandidateSet Conversions(From->getExprLoc(),
1344 OverloadCandidateSet::CSK_Normal);
1345 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1346 Conversions, AllowExplicit,
1347 AllowObjCConversionOnExplicit)) {
1348 case OR_Success:
1349 case OR_Deleted:
1350 ICS.setUserDefined();
1351 // C++ [over.ics.user]p4:
1352 // A conversion of an expression of class type to the same class
1353 // type is given Exact Match rank, and a conversion of an
1354 // expression of class type to a base class of that type is
1355 // given Conversion rank, in spite of the fact that a copy
1356 // constructor (i.e., a user-defined conversion function) is
1357 // called for those cases.
1358 if (CXXConstructorDecl *Constructor
1359 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1360 QualType FromCanon
1361 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1362 QualType ToCanon
1363 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1364 if (Constructor->isCopyConstructor() &&
1365 (FromCanon == ToCanon ||
1366 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1367 // Turn this into a "standard" conversion sequence, so that it
1368 // gets ranked with standard conversion sequences.
1369 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1370 ICS.setStandard();
1371 ICS.Standard.setAsIdentityConversion();
1372 ICS.Standard.setFromType(From->getType());
1373 ICS.Standard.setAllToTypes(ToType);
1374 ICS.Standard.CopyConstructor = Constructor;
1375 ICS.Standard.FoundCopyConstructor = Found;
1376 if (ToCanon != FromCanon)
1377 ICS.Standard.Second = ICK_Derived_To_Base;
1380 break;
1382 case OR_Ambiguous:
1383 ICS.setAmbiguous();
1384 ICS.Ambiguous.setFromType(From->getType());
1385 ICS.Ambiguous.setToType(ToType);
1386 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1387 Cand != Conversions.end(); ++Cand)
1388 if (Cand->Best)
1389 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1390 break;
1392 // Fall through.
1393 case OR_No_Viable_Function:
1394 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1395 break;
1398 return ICS;
1401 /// TryImplicitConversion - Attempt to perform an implicit conversion
1402 /// from the given expression (Expr) to the given type (ToType). This
1403 /// function returns an implicit conversion sequence that can be used
1404 /// to perform the initialization. Given
1406 /// void f(float f);
1407 /// void g(int i) { f(i); }
1409 /// this routine would produce an implicit conversion sequence to
1410 /// describe the initialization of f from i, which will be a standard
1411 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1412 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1414 /// Note that this routine only determines how the conversion can be
1415 /// performed; it does not actually perform the conversion. As such,
1416 /// it will not produce any diagnostics if no conversion is available,
1417 /// but will instead return an implicit conversion sequence of kind
1418 /// "BadConversion".
1420 /// If @p SuppressUserConversions, then user-defined conversions are
1421 /// not permitted.
1422 /// If @p AllowExplicit, then explicit user-defined conversions are
1423 /// permitted.
1425 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1426 /// writeback conversion, which allows __autoreleasing id* parameters to
1427 /// be initialized with __strong id* or __weak id* arguments.
1428 static ImplicitConversionSequence
1429 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1430 bool SuppressUserConversions,
1431 AllowedExplicit AllowExplicit,
1432 bool InOverloadResolution,
1433 bool CStyle,
1434 bool AllowObjCWritebackConversion,
1435 bool AllowObjCConversionOnExplicit) {
1436 ImplicitConversionSequence ICS;
1437 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1438 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1439 ICS.setStandard();
1440 return ICS;
1443 if (!S.getLangOpts().CPlusPlus) {
1444 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1445 return ICS;
1448 // C++ [over.ics.user]p4:
1449 // A conversion of an expression of class type to the same class
1450 // type is given Exact Match rank, and a conversion of an
1451 // expression of class type to a base class of that type is
1452 // given Conversion rank, in spite of the fact that a copy/move
1453 // constructor (i.e., a user-defined conversion function) is
1454 // called for those cases.
1455 QualType FromType = From->getType();
1456 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1457 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1458 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1459 ICS.setStandard();
1460 ICS.Standard.setAsIdentityConversion();
1461 ICS.Standard.setFromType(FromType);
1462 ICS.Standard.setAllToTypes(ToType);
1464 // We don't actually check at this point whether there is a valid
1465 // copy/move constructor, since overloading just assumes that it
1466 // exists. When we actually perform initialization, we'll find the
1467 // appropriate constructor to copy the returned object, if needed.
1468 ICS.Standard.CopyConstructor = nullptr;
1470 // Determine whether this is considered a derived-to-base conversion.
1471 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1472 ICS.Standard.Second = ICK_Derived_To_Base;
1474 return ICS;
1477 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1478 AllowExplicit, InOverloadResolution, CStyle,
1479 AllowObjCWritebackConversion,
1480 AllowObjCConversionOnExplicit);
1483 ImplicitConversionSequence
1484 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1485 bool SuppressUserConversions,
1486 AllowedExplicit AllowExplicit,
1487 bool InOverloadResolution,
1488 bool CStyle,
1489 bool AllowObjCWritebackConversion) {
1490 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1491 AllowExplicit, InOverloadResolution, CStyle,
1492 AllowObjCWritebackConversion,
1493 /*AllowObjCConversionOnExplicit=*/false);
1496 /// PerformImplicitConversion - Perform an implicit conversion of the
1497 /// expression From to the type ToType. Returns the
1498 /// converted expression. Flavor is the kind of conversion we're
1499 /// performing, used in the error message. If @p AllowExplicit,
1500 /// explicit user-defined conversions are permitted.
1501 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1502 AssignmentAction Action,
1503 bool AllowExplicit) {
1504 if (checkPlaceholderForOverload(*this, From))
1505 return ExprError();
1507 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1508 bool AllowObjCWritebackConversion
1509 = getLangOpts().ObjCAutoRefCount &&
1510 (Action == AA_Passing || Action == AA_Sending);
1511 if (getLangOpts().ObjC)
1512 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1513 From->getType(), From);
1514 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1515 *this, From, ToType,
1516 /*SuppressUserConversions=*/false,
1517 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1518 /*InOverloadResolution=*/false,
1519 /*CStyle=*/false, AllowObjCWritebackConversion,
1520 /*AllowObjCConversionOnExplicit=*/false);
1521 return PerformImplicitConversion(From, ToType, ICS, Action);
1524 /// Determine whether the conversion from FromType to ToType is a valid
1525 /// conversion that strips "noexcept" or "noreturn" off the nested function
1526 /// type.
1527 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1528 QualType &ResultTy) {
1529 if (Context.hasSameUnqualifiedType(FromType, ToType))
1530 return false;
1532 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1533 // or F(t noexcept) -> F(t)
1534 // where F adds one of the following at most once:
1535 // - a pointer
1536 // - a member pointer
1537 // - a block pointer
1538 // Changes here need matching changes in FindCompositePointerType.
1539 CanQualType CanTo = Context.getCanonicalType(ToType);
1540 CanQualType CanFrom = Context.getCanonicalType(FromType);
1541 Type::TypeClass TyClass = CanTo->getTypeClass();
1542 if (TyClass != CanFrom->getTypeClass()) return false;
1543 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1544 if (TyClass == Type::Pointer) {
1545 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1546 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1547 } else if (TyClass == Type::BlockPointer) {
1548 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1549 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1550 } else if (TyClass == Type::MemberPointer) {
1551 auto ToMPT = CanTo.castAs<MemberPointerType>();
1552 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1553 // A function pointer conversion cannot change the class of the function.
1554 if (ToMPT->getClass() != FromMPT->getClass())
1555 return false;
1556 CanTo = ToMPT->getPointeeType();
1557 CanFrom = FromMPT->getPointeeType();
1558 } else {
1559 return false;
1562 TyClass = CanTo->getTypeClass();
1563 if (TyClass != CanFrom->getTypeClass()) return false;
1564 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1565 return false;
1568 const auto *FromFn = cast<FunctionType>(CanFrom);
1569 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571 const auto *ToFn = cast<FunctionType>(CanTo);
1572 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574 bool Changed = false;
1576 // Drop 'noreturn' if not present in target type.
1577 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1578 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1579 Changed = true;
1582 // Drop 'noexcept' if not present in target type.
1583 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1584 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1585 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1586 FromFn = cast<FunctionType>(
1587 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1588 EST_None)
1589 .getTypePtr());
1590 Changed = true;
1593 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1594 // only if the ExtParameterInfo lists of the two function prototypes can be
1595 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1596 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1597 bool CanUseToFPT, CanUseFromFPT;
1598 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1599 CanUseFromFPT, NewParamInfos) &&
1600 CanUseToFPT && !CanUseFromFPT) {
1601 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1602 ExtInfo.ExtParameterInfos =
1603 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1604 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1605 FromFPT->getParamTypes(), ExtInfo);
1606 FromFn = QT->getAs<FunctionType>();
1607 Changed = true;
1611 if (!Changed)
1612 return false;
1614 assert(QualType(FromFn, 0).isCanonical());
1615 if (QualType(FromFn, 0) != CanTo) return false;
1617 ResultTy = ToType;
1618 return true;
1621 /// Determine whether the conversion from FromType to ToType is a valid
1622 /// vector conversion.
1624 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1625 /// conversion.
1626 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1627 ImplicitConversionKind &ICK, Expr *From,
1628 bool InOverloadResolution) {
1629 // We need at least one of these types to be a vector type to have a vector
1630 // conversion.
1631 if (!ToType->isVectorType() && !FromType->isVectorType())
1632 return false;
1634 // Identical types require no conversions.
1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636 return false;
1638 // There are no conversions between extended vector types, only identity.
1639 if (ToType->isExtVectorType()) {
1640 // There are no conversions between extended vector types other than the
1641 // identity conversion.
1642 if (FromType->isExtVectorType())
1643 return false;
1645 // Vector splat from any arithmetic type to a vector.
1646 if (FromType->isArithmeticType()) {
1647 ICK = ICK_Vector_Splat;
1648 return true;
1652 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1653 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1654 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1655 ICK = ICK_SVE_Vector_Conversion;
1656 return true;
1659 // We can perform the conversion between vector types in the following cases:
1660 // 1)vector types are equivalent AltiVec and GCC vector types
1661 // 2)lax vector conversions are permitted and the vector types are of the
1662 // same size
1663 // 3)the destination type does not have the ARM MVE strict-polymorphism
1664 // attribute, which inhibits lax vector conversion for overload resolution
1665 // only
1666 if (ToType->isVectorType() && FromType->isVectorType()) {
1667 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1668 (S.isLaxVectorConversion(FromType, ToType) &&
1669 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1670 if (S.isLaxVectorConversion(FromType, ToType) &&
1671 S.anyAltivecTypes(FromType, ToType) &&
1672 !S.areSameVectorElemTypes(FromType, ToType) &&
1673 !InOverloadResolution) {
1674 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1675 << FromType << ToType;
1677 ICK = ICK_Vector_Conversion;
1678 return true;
1682 return false;
1685 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1686 bool InOverloadResolution,
1687 StandardConversionSequence &SCS,
1688 bool CStyle);
1690 /// IsStandardConversion - Determines whether there is a standard
1691 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1692 /// expression From to the type ToType. Standard conversion sequences
1693 /// only consider non-class types; for conversions that involve class
1694 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1695 /// contain the standard conversion sequence required to perform this
1696 /// conversion and this routine will return true. Otherwise, this
1697 /// routine will return false and the value of SCS is unspecified.
1698 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1699 bool InOverloadResolution,
1700 StandardConversionSequence &SCS,
1701 bool CStyle,
1702 bool AllowObjCWritebackConversion) {
1703 QualType FromType = From->getType();
1705 // Standard conversions (C++ [conv])
1706 SCS.setAsIdentityConversion();
1707 SCS.IncompatibleObjC = false;
1708 SCS.setFromType(FromType);
1709 SCS.CopyConstructor = nullptr;
1711 // There are no standard conversions for class types in C++, so
1712 // abort early. When overloading in C, however, we do permit them.
1713 if (S.getLangOpts().CPlusPlus &&
1714 (FromType->isRecordType() || ToType->isRecordType()))
1715 return false;
1717 // The first conversion can be an lvalue-to-rvalue conversion,
1718 // array-to-pointer conversion, or function-to-pointer conversion
1719 // (C++ 4p1).
1721 if (FromType == S.Context.OverloadTy) {
1722 DeclAccessPair AccessPair;
1723 if (FunctionDecl *Fn
1724 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1725 AccessPair)) {
1726 // We were able to resolve the address of the overloaded function,
1727 // so we can convert to the type of that function.
1728 FromType = Fn->getType();
1729 SCS.setFromType(FromType);
1731 // we can sometimes resolve &foo<int> regardless of ToType, so check
1732 // if the type matches (identity) or we are converting to bool
1733 if (!S.Context.hasSameUnqualifiedType(
1734 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1735 QualType resultTy;
1736 // if the function type matches except for [[noreturn]], it's ok
1737 if (!S.IsFunctionConversion(FromType,
1738 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1739 // otherwise, only a boolean conversion is standard
1740 if (!ToType->isBooleanType())
1741 return false;
1744 // Check if the "from" expression is taking the address of an overloaded
1745 // function and recompute the FromType accordingly. Take advantage of the
1746 // fact that non-static member functions *must* have such an address-of
1747 // expression.
1748 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1749 if (Method && !Method->isStatic()) {
1750 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1751 "Non-unary operator on non-static member address");
1752 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1753 == UO_AddrOf &&
1754 "Non-address-of operator on non-static member address");
1755 const Type *ClassType
1756 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1757 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1758 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1759 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1760 UO_AddrOf &&
1761 "Non-address-of operator for overloaded function expression");
1762 FromType = S.Context.getPointerType(FromType);
1764 } else {
1765 return false;
1768 // Lvalue-to-rvalue conversion (C++11 4.1):
1769 // A glvalue (3.10) of a non-function, non-array type T can
1770 // be converted to a prvalue.
1771 bool argIsLValue = From->isGLValue();
1772 if (argIsLValue &&
1773 !FromType->isFunctionType() && !FromType->isArrayType() &&
1774 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1775 SCS.First = ICK_Lvalue_To_Rvalue;
1777 // C11 6.3.2.1p2:
1778 // ... if the lvalue has atomic type, the value has the non-atomic version
1779 // of the type of the lvalue ...
1780 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1781 FromType = Atomic->getValueType();
1783 // If T is a non-class type, the type of the rvalue is the
1784 // cv-unqualified version of T. Otherwise, the type of the rvalue
1785 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1786 // just strip the qualifiers because they don't matter.
1787 FromType = FromType.getUnqualifiedType();
1788 } else if (FromType->isArrayType()) {
1789 // Array-to-pointer conversion (C++ 4.2)
1790 SCS.First = ICK_Array_To_Pointer;
1792 // An lvalue or rvalue of type "array of N T" or "array of unknown
1793 // bound of T" can be converted to an rvalue of type "pointer to
1794 // T" (C++ 4.2p1).
1795 FromType = S.Context.getArrayDecayedType(FromType);
1797 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1798 // This conversion is deprecated in C++03 (D.4)
1799 SCS.DeprecatedStringLiteralToCharPtr = true;
1801 // For the purpose of ranking in overload resolution
1802 // (13.3.3.1.1), this conversion is considered an
1803 // array-to-pointer conversion followed by a qualification
1804 // conversion (4.4). (C++ 4.2p2)
1805 SCS.Second = ICK_Identity;
1806 SCS.Third = ICK_Qualification;
1807 SCS.QualificationIncludesObjCLifetime = false;
1808 SCS.setAllToTypes(FromType);
1809 return true;
1811 } else if (FromType->isFunctionType() && argIsLValue) {
1812 // Function-to-pointer conversion (C++ 4.3).
1813 SCS.First = ICK_Function_To_Pointer;
1815 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1816 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1817 if (!S.checkAddressOfFunctionIsAvailable(FD))
1818 return false;
1820 // An lvalue of function type T can be converted to an rvalue of
1821 // type "pointer to T." The result is a pointer to the
1822 // function. (C++ 4.3p1).
1823 FromType = S.Context.getPointerType(FromType);
1824 } else {
1825 // We don't require any conversions for the first step.
1826 SCS.First = ICK_Identity;
1828 SCS.setToType(0, FromType);
1830 // The second conversion can be an integral promotion, floating
1831 // point promotion, integral conversion, floating point conversion,
1832 // floating-integral conversion, pointer conversion,
1833 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1834 // For overloading in C, this can also be a "compatible-type"
1835 // conversion.
1836 bool IncompatibleObjC = false;
1837 ImplicitConversionKind SecondICK = ICK_Identity;
1838 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1839 // The unqualified versions of the types are the same: there's no
1840 // conversion to do.
1841 SCS.Second = ICK_Identity;
1842 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1843 // Integral promotion (C++ 4.5).
1844 SCS.Second = ICK_Integral_Promotion;
1845 FromType = ToType.getUnqualifiedType();
1846 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1847 // Floating point promotion (C++ 4.6).
1848 SCS.Second = ICK_Floating_Promotion;
1849 FromType = ToType.getUnqualifiedType();
1850 } else if (S.IsComplexPromotion(FromType, ToType)) {
1851 // Complex promotion (Clang extension)
1852 SCS.Second = ICK_Complex_Promotion;
1853 FromType = ToType.getUnqualifiedType();
1854 } else if (ToType->isBooleanType() &&
1855 (FromType->isArithmeticType() ||
1856 FromType->isAnyPointerType() ||
1857 FromType->isBlockPointerType() ||
1858 FromType->isMemberPointerType())) {
1859 // Boolean conversions (C++ 4.12).
1860 SCS.Second = ICK_Boolean_Conversion;
1861 FromType = S.Context.BoolTy;
1862 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1863 ToType->isIntegralType(S.Context)) {
1864 // Integral conversions (C++ 4.7).
1865 SCS.Second = ICK_Integral_Conversion;
1866 FromType = ToType.getUnqualifiedType();
1867 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1868 // Complex conversions (C99 6.3.1.6)
1869 SCS.Second = ICK_Complex_Conversion;
1870 FromType = ToType.getUnqualifiedType();
1871 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1872 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1873 // Complex-real conversions (C99 6.3.1.7)
1874 SCS.Second = ICK_Complex_Real;
1875 FromType = ToType.getUnqualifiedType();
1876 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1877 // FIXME: disable conversions between long double, __ibm128 and __float128
1878 // if their representation is different until there is back end support
1879 // We of course allow this conversion if long double is really double.
1881 // Conversions between bfloat and other floats are not permitted.
1882 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1883 return false;
1885 // Conversions between IEEE-quad and IBM-extended semantics are not
1886 // permitted.
1887 const llvm::fltSemantics &FromSem =
1888 S.Context.getFloatTypeSemantics(FromType);
1889 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1890 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1891 &ToSem == &llvm::APFloat::IEEEquad()) ||
1892 (&FromSem == &llvm::APFloat::IEEEquad() &&
1893 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1894 return false;
1896 // Floating point conversions (C++ 4.8).
1897 SCS.Second = ICK_Floating_Conversion;
1898 FromType = ToType.getUnqualifiedType();
1899 } else if ((FromType->isRealFloatingType() &&
1900 ToType->isIntegralType(S.Context)) ||
1901 (FromType->isIntegralOrUnscopedEnumerationType() &&
1902 ToType->isRealFloatingType())) {
1903 // Conversions between bfloat and int are not permitted.
1904 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1905 return false;
1907 // Floating-integral conversions (C++ 4.9).
1908 SCS.Second = ICK_Floating_Integral;
1909 FromType = ToType.getUnqualifiedType();
1910 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1911 SCS.Second = ICK_Block_Pointer_Conversion;
1912 } else if (AllowObjCWritebackConversion &&
1913 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1914 SCS.Second = ICK_Writeback_Conversion;
1915 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1916 FromType, IncompatibleObjC)) {
1917 // Pointer conversions (C++ 4.10).
1918 SCS.Second = ICK_Pointer_Conversion;
1919 SCS.IncompatibleObjC = IncompatibleObjC;
1920 FromType = FromType.getUnqualifiedType();
1921 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1922 InOverloadResolution, FromType)) {
1923 // Pointer to member conversions (4.11).
1924 SCS.Second = ICK_Pointer_Member;
1925 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
1926 InOverloadResolution)) {
1927 SCS.Second = SecondICK;
1928 FromType = ToType.getUnqualifiedType();
1929 } else if (!S.getLangOpts().CPlusPlus &&
1930 S.Context.typesAreCompatible(ToType, FromType)) {
1931 // Compatible conversions (Clang extension for C function overloading)
1932 SCS.Second = ICK_Compatible_Conversion;
1933 FromType = ToType.getUnqualifiedType();
1934 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1935 InOverloadResolution,
1936 SCS, CStyle)) {
1937 SCS.Second = ICK_TransparentUnionConversion;
1938 FromType = ToType;
1939 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1940 CStyle)) {
1941 // tryAtomicConversion has updated the standard conversion sequence
1942 // appropriately.
1943 return true;
1944 } else if (ToType->isEventT() &&
1945 From->isIntegerConstantExpr(S.getASTContext()) &&
1946 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1947 SCS.Second = ICK_Zero_Event_Conversion;
1948 FromType = ToType;
1949 } else if (ToType->isQueueT() &&
1950 From->isIntegerConstantExpr(S.getASTContext()) &&
1951 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1952 SCS.Second = ICK_Zero_Queue_Conversion;
1953 FromType = ToType;
1954 } else if (ToType->isSamplerT() &&
1955 From->isIntegerConstantExpr(S.getASTContext())) {
1956 SCS.Second = ICK_Compatible_Conversion;
1957 FromType = ToType;
1958 } else {
1959 // No second conversion required.
1960 SCS.Second = ICK_Identity;
1962 SCS.setToType(1, FromType);
1964 // The third conversion can be a function pointer conversion or a
1965 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1966 bool ObjCLifetimeConversion;
1967 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1968 // Function pointer conversions (removing 'noexcept') including removal of
1969 // 'noreturn' (Clang extension).
1970 SCS.Third = ICK_Function_Conversion;
1971 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1972 ObjCLifetimeConversion)) {
1973 SCS.Third = ICK_Qualification;
1974 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1975 FromType = ToType;
1976 } else {
1977 // No conversion required
1978 SCS.Third = ICK_Identity;
1981 // C++ [over.best.ics]p6:
1982 // [...] Any difference in top-level cv-qualification is
1983 // subsumed by the initialization itself and does not constitute
1984 // a conversion. [...]
1985 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1986 QualType CanonTo = S.Context.getCanonicalType(ToType);
1987 if (CanonFrom.getLocalUnqualifiedType()
1988 == CanonTo.getLocalUnqualifiedType() &&
1989 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1990 FromType = ToType;
1991 CanonFrom = CanonTo;
1994 SCS.setToType(2, FromType);
1996 if (CanonFrom == CanonTo)
1997 return true;
1999 // If we have not converted the argument type to the parameter type,
2000 // this is a bad conversion sequence, unless we're resolving an overload in C.
2001 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2002 return false;
2004 ExprResult ER = ExprResult{From};
2005 Sema::AssignConvertType Conv =
2006 S.CheckSingleAssignmentConstraints(ToType, ER,
2007 /*Diagnose=*/false,
2008 /*DiagnoseCFAudited=*/false,
2009 /*ConvertRHS=*/false);
2010 ImplicitConversionKind SecondConv;
2011 switch (Conv) {
2012 case Sema::Compatible:
2013 SecondConv = ICK_C_Only_Conversion;
2014 break;
2015 // For our purposes, discarding qualifiers is just as bad as using an
2016 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2017 // qualifiers, as well.
2018 case Sema::CompatiblePointerDiscardsQualifiers:
2019 case Sema::IncompatiblePointer:
2020 case Sema::IncompatiblePointerSign:
2021 SecondConv = ICK_Incompatible_Pointer_Conversion;
2022 break;
2023 default:
2024 return false;
2027 // First can only be an lvalue conversion, so we pretend that this was the
2028 // second conversion. First should already be valid from earlier in the
2029 // function.
2030 SCS.Second = SecondConv;
2031 SCS.setToType(1, ToType);
2033 // Third is Identity, because Second should rank us worse than any other
2034 // conversion. This could also be ICK_Qualification, but it's simpler to just
2035 // lump everything in with the second conversion, and we don't gain anything
2036 // from making this ICK_Qualification.
2037 SCS.Third = ICK_Identity;
2038 SCS.setToType(2, ToType);
2039 return true;
2042 static bool
2043 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2044 QualType &ToType,
2045 bool InOverloadResolution,
2046 StandardConversionSequence &SCS,
2047 bool CStyle) {
2049 const RecordType *UT = ToType->getAsUnionType();
2050 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2051 return false;
2052 // The field to initialize within the transparent union.
2053 RecordDecl *UD = UT->getDecl();
2054 // It's compatible if the expression matches any of the fields.
2055 for (const auto *it : UD->fields()) {
2056 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2057 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2058 ToType = it->getType();
2059 return true;
2062 return false;
2065 /// IsIntegralPromotion - Determines whether the conversion from the
2066 /// expression From (whose potentially-adjusted type is FromType) to
2067 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2068 /// sets PromotedType to the promoted type.
2069 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2070 const BuiltinType *To = ToType->getAs<BuiltinType>();
2071 // All integers are built-in.
2072 if (!To) {
2073 return false;
2076 // An rvalue of type char, signed char, unsigned char, short int, or
2077 // unsigned short int can be converted to an rvalue of type int if
2078 // int can represent all the values of the source type; otherwise,
2079 // the source rvalue can be converted to an rvalue of type unsigned
2080 // int (C++ 4.5p1).
2081 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2082 !FromType->isEnumeralType()) {
2083 if (// We can promote any signed, promotable integer type to an int
2084 (FromType->isSignedIntegerType() ||
2085 // We can promote any unsigned integer type whose size is
2086 // less than int to an int.
2087 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2088 return To->getKind() == BuiltinType::Int;
2091 return To->getKind() == BuiltinType::UInt;
2094 // C++11 [conv.prom]p3:
2095 // A prvalue of an unscoped enumeration type whose underlying type is not
2096 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2097 // following types that can represent all the values of the enumeration
2098 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2099 // unsigned int, long int, unsigned long int, long long int, or unsigned
2100 // long long int. If none of the types in that list can represent all the
2101 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2102 // type can be converted to an rvalue a prvalue of the extended integer type
2103 // with lowest integer conversion rank (4.13) greater than the rank of long
2104 // long in which all the values of the enumeration can be represented. If
2105 // there are two such extended types, the signed one is chosen.
2106 // C++11 [conv.prom]p4:
2107 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2108 // can be converted to a prvalue of its underlying type. Moreover, if
2109 // integral promotion can be applied to its underlying type, a prvalue of an
2110 // unscoped enumeration type whose underlying type is fixed can also be
2111 // converted to a prvalue of the promoted underlying type.
2112 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2113 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2114 // provided for a scoped enumeration.
2115 if (FromEnumType->getDecl()->isScoped())
2116 return false;
2118 // We can perform an integral promotion to the underlying type of the enum,
2119 // even if that's not the promoted type. Note that the check for promoting
2120 // the underlying type is based on the type alone, and does not consider
2121 // the bitfield-ness of the actual source expression.
2122 if (FromEnumType->getDecl()->isFixed()) {
2123 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2124 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2125 IsIntegralPromotion(nullptr, Underlying, ToType);
2128 // We have already pre-calculated the promotion type, so this is trivial.
2129 if (ToType->isIntegerType() &&
2130 isCompleteType(From->getBeginLoc(), FromType))
2131 return Context.hasSameUnqualifiedType(
2132 ToType, FromEnumType->getDecl()->getPromotionType());
2134 // C++ [conv.prom]p5:
2135 // If the bit-field has an enumerated type, it is treated as any other
2136 // value of that type for promotion purposes.
2138 // ... so do not fall through into the bit-field checks below in C++.
2139 if (getLangOpts().CPlusPlus)
2140 return false;
2143 // C++0x [conv.prom]p2:
2144 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2145 // to an rvalue a prvalue of the first of the following types that can
2146 // represent all the values of its underlying type: int, unsigned int,
2147 // long int, unsigned long int, long long int, or unsigned long long int.
2148 // If none of the types in that list can represent all the values of its
2149 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2150 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2151 // type.
2152 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2153 ToType->isIntegerType()) {
2154 // Determine whether the type we're converting from is signed or
2155 // unsigned.
2156 bool FromIsSigned = FromType->isSignedIntegerType();
2157 uint64_t FromSize = Context.getTypeSize(FromType);
2159 // The types we'll try to promote to, in the appropriate
2160 // order. Try each of these types.
2161 QualType PromoteTypes[6] = {
2162 Context.IntTy, Context.UnsignedIntTy,
2163 Context.LongTy, Context.UnsignedLongTy ,
2164 Context.LongLongTy, Context.UnsignedLongLongTy
2166 for (int Idx = 0; Idx < 6; ++Idx) {
2167 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2168 if (FromSize < ToSize ||
2169 (FromSize == ToSize &&
2170 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2171 // We found the type that we can promote to. If this is the
2172 // type we wanted, we have a promotion. Otherwise, no
2173 // promotion.
2174 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2179 // An rvalue for an integral bit-field (9.6) can be converted to an
2180 // rvalue of type int if int can represent all the values of the
2181 // bit-field; otherwise, it can be converted to unsigned int if
2182 // unsigned int can represent all the values of the bit-field. If
2183 // the bit-field is larger yet, no integral promotion applies to
2184 // it. If the bit-field has an enumerated type, it is treated as any
2185 // other value of that type for promotion purposes (C++ 4.5p3).
2186 // FIXME: We should delay checking of bit-fields until we actually perform the
2187 // conversion.
2189 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2190 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2191 // bit-fields and those whose underlying type is larger than int) for GCC
2192 // compatibility.
2193 if (From) {
2194 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2195 Optional<llvm::APSInt> BitWidth;
2196 if (FromType->isIntegralType(Context) &&
2197 (BitWidth =
2198 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2199 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2200 ToSize = Context.getTypeSize(ToType);
2202 // Are we promoting to an int from a bitfield that fits in an int?
2203 if (*BitWidth < ToSize ||
2204 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2205 return To->getKind() == BuiltinType::Int;
2208 // Are we promoting to an unsigned int from an unsigned bitfield
2209 // that fits into an unsigned int?
2210 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2211 return To->getKind() == BuiltinType::UInt;
2214 return false;
2219 // An rvalue of type bool can be converted to an rvalue of type int,
2220 // with false becoming zero and true becoming one (C++ 4.5p4).
2221 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2222 return true;
2225 return false;
2228 /// IsFloatingPointPromotion - Determines whether the conversion from
2229 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2230 /// returns true and sets PromotedType to the promoted type.
2231 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2232 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2233 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2234 /// An rvalue of type float can be converted to an rvalue of type
2235 /// double. (C++ 4.6p1).
2236 if (FromBuiltin->getKind() == BuiltinType::Float &&
2237 ToBuiltin->getKind() == BuiltinType::Double)
2238 return true;
2240 // C99 6.3.1.5p1:
2241 // When a float is promoted to double or long double, or a
2242 // double is promoted to long double [...].
2243 if (!getLangOpts().CPlusPlus &&
2244 (FromBuiltin->getKind() == BuiltinType::Float ||
2245 FromBuiltin->getKind() == BuiltinType::Double) &&
2246 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2247 ToBuiltin->getKind() == BuiltinType::Float128 ||
2248 ToBuiltin->getKind() == BuiltinType::Ibm128))
2249 return true;
2251 // Half can be promoted to float.
2252 if (!getLangOpts().NativeHalfType &&
2253 FromBuiltin->getKind() == BuiltinType::Half &&
2254 ToBuiltin->getKind() == BuiltinType::Float)
2255 return true;
2258 return false;
2261 /// Determine if a conversion is a complex promotion.
2263 /// A complex promotion is defined as a complex -> complex conversion
2264 /// where the conversion between the underlying real types is a
2265 /// floating-point or integral promotion.
2266 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2267 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2268 if (!FromComplex)
2269 return false;
2271 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2272 if (!ToComplex)
2273 return false;
2275 return IsFloatingPointPromotion(FromComplex->getElementType(),
2276 ToComplex->getElementType()) ||
2277 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2278 ToComplex->getElementType());
2281 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2282 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2283 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2284 /// if non-empty, will be a pointer to ToType that may or may not have
2285 /// the right set of qualifiers on its pointee.
2287 static QualType
2288 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2289 QualType ToPointee, QualType ToType,
2290 ASTContext &Context,
2291 bool StripObjCLifetime = false) {
2292 assert((FromPtr->getTypeClass() == Type::Pointer ||
2293 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2294 "Invalid similarly-qualified pointer type");
2296 /// Conversions to 'id' subsume cv-qualifier conversions.
2297 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2298 return ToType.getUnqualifiedType();
2300 QualType CanonFromPointee
2301 = Context.getCanonicalType(FromPtr->getPointeeType());
2302 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2303 Qualifiers Quals = CanonFromPointee.getQualifiers();
2305 if (StripObjCLifetime)
2306 Quals.removeObjCLifetime();
2308 // Exact qualifier match -> return the pointer type we're converting to.
2309 if (CanonToPointee.getLocalQualifiers() == Quals) {
2310 // ToType is exactly what we need. Return it.
2311 if (!ToType.isNull())
2312 return ToType.getUnqualifiedType();
2314 // Build a pointer to ToPointee. It has the right qualifiers
2315 // already.
2316 if (isa<ObjCObjectPointerType>(ToType))
2317 return Context.getObjCObjectPointerType(ToPointee);
2318 return Context.getPointerType(ToPointee);
2321 // Just build a canonical type that has the right qualifiers.
2322 QualType QualifiedCanonToPointee
2323 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2325 if (isa<ObjCObjectPointerType>(ToType))
2326 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2327 return Context.getPointerType(QualifiedCanonToPointee);
2330 static bool isNullPointerConstantForConversion(Expr *Expr,
2331 bool InOverloadResolution,
2332 ASTContext &Context) {
2333 // Handle value-dependent integral null pointer constants correctly.
2334 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2335 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2336 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2337 return !InOverloadResolution;
2339 return Expr->isNullPointerConstant(Context,
2340 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2341 : Expr::NPC_ValueDependentIsNull);
2344 /// IsPointerConversion - Determines whether the conversion of the
2345 /// expression From, which has the (possibly adjusted) type FromType,
2346 /// can be converted to the type ToType via a pointer conversion (C++
2347 /// 4.10). If so, returns true and places the converted type (that
2348 /// might differ from ToType in its cv-qualifiers at some level) into
2349 /// ConvertedType.
2351 /// This routine also supports conversions to and from block pointers
2352 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2353 /// pointers to interfaces. FIXME: Once we've determined the
2354 /// appropriate overloading rules for Objective-C, we may want to
2355 /// split the Objective-C checks into a different routine; however,
2356 /// GCC seems to consider all of these conversions to be pointer
2357 /// conversions, so for now they live here. IncompatibleObjC will be
2358 /// set if the conversion is an allowed Objective-C conversion that
2359 /// should result in a warning.
2360 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2361 bool InOverloadResolution,
2362 QualType& ConvertedType,
2363 bool &IncompatibleObjC) {
2364 IncompatibleObjC = false;
2365 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2366 IncompatibleObjC))
2367 return true;
2369 // Conversion from a null pointer constant to any Objective-C pointer type.
2370 if (ToType->isObjCObjectPointerType() &&
2371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372 ConvertedType = ToType;
2373 return true;
2376 // Blocks: Block pointers can be converted to void*.
2377 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2378 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2379 ConvertedType = ToType;
2380 return true;
2382 // Blocks: A null pointer constant can be converted to a block
2383 // pointer type.
2384 if (ToType->isBlockPointerType() &&
2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386 ConvertedType = ToType;
2387 return true;
2390 // If the left-hand-side is nullptr_t, the right side can be a null
2391 // pointer constant.
2392 if (ToType->isNullPtrType() &&
2393 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2394 ConvertedType = ToType;
2395 return true;
2398 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2399 if (!ToTypePtr)
2400 return false;
2402 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2403 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2404 ConvertedType = ToType;
2405 return true;
2408 // Beyond this point, both types need to be pointers
2409 // , including objective-c pointers.
2410 QualType ToPointeeType = ToTypePtr->getPointeeType();
2411 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2412 !getLangOpts().ObjCAutoRefCount) {
2413 ConvertedType = BuildSimilarlyQualifiedPointerType(
2414 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2415 Context);
2416 return true;
2418 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2419 if (!FromTypePtr)
2420 return false;
2422 QualType FromPointeeType = FromTypePtr->getPointeeType();
2424 // If the unqualified pointee types are the same, this can't be a
2425 // pointer conversion, so don't do all of the work below.
2426 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2427 return false;
2429 // An rvalue of type "pointer to cv T," where T is an object type,
2430 // can be converted to an rvalue of type "pointer to cv void" (C++
2431 // 4.10p2).
2432 if (FromPointeeType->isIncompleteOrObjectType() &&
2433 ToPointeeType->isVoidType()) {
2434 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2435 ToPointeeType,
2436 ToType, Context,
2437 /*StripObjCLifetime=*/true);
2438 return true;
2441 // MSVC allows implicit function to void* type conversion.
2442 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2443 ToPointeeType->isVoidType()) {
2444 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2445 ToPointeeType,
2446 ToType, Context);
2447 return true;
2450 // When we're overloading in C, we allow a special kind of pointer
2451 // conversion for compatible-but-not-identical pointee types.
2452 if (!getLangOpts().CPlusPlus &&
2453 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2454 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2455 ToPointeeType,
2456 ToType, Context);
2457 return true;
2460 // C++ [conv.ptr]p3:
2462 // An rvalue of type "pointer to cv D," where D is a class type,
2463 // can be converted to an rvalue of type "pointer to cv B," where
2464 // B is a base class (clause 10) of D. If B is an inaccessible
2465 // (clause 11) or ambiguous (10.2) base class of D, a program that
2466 // necessitates this conversion is ill-formed. The result of the
2467 // conversion is a pointer to the base class sub-object of the
2468 // derived class object. The null pointer value is converted to
2469 // the null pointer value of the destination type.
2471 // Note that we do not check for ambiguity or inaccessibility
2472 // here. That is handled by CheckPointerConversion.
2473 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2474 ToPointeeType->isRecordType() &&
2475 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2476 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2477 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478 ToPointeeType,
2479 ToType, Context);
2480 return true;
2483 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2484 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2485 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2486 ToPointeeType,
2487 ToType, Context);
2488 return true;
2491 return false;
2494 /// Adopt the given qualifiers for the given type.
2495 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2496 Qualifiers TQs = T.getQualifiers();
2498 // Check whether qualifiers already match.
2499 if (TQs == Qs)
2500 return T;
2502 if (Qs.compatiblyIncludes(TQs))
2503 return Context.getQualifiedType(T, Qs);
2505 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2508 /// isObjCPointerConversion - Determines whether this is an
2509 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2510 /// with the same arguments and return values.
2511 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2512 QualType& ConvertedType,
2513 bool &IncompatibleObjC) {
2514 if (!getLangOpts().ObjC)
2515 return false;
2517 // The set of qualifiers on the type we're converting from.
2518 Qualifiers FromQualifiers = FromType.getQualifiers();
2520 // First, we handle all conversions on ObjC object pointer types.
2521 const ObjCObjectPointerType* ToObjCPtr =
2522 ToType->getAs<ObjCObjectPointerType>();
2523 const ObjCObjectPointerType *FromObjCPtr =
2524 FromType->getAs<ObjCObjectPointerType>();
2526 if (ToObjCPtr && FromObjCPtr) {
2527 // If the pointee types are the same (ignoring qualifications),
2528 // then this is not a pointer conversion.
2529 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2530 FromObjCPtr->getPointeeType()))
2531 return false;
2533 // Conversion between Objective-C pointers.
2534 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2535 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2536 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2537 if (getLangOpts().CPlusPlus && LHS && RHS &&
2538 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2539 FromObjCPtr->getPointeeType()))
2540 return false;
2541 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2542 ToObjCPtr->getPointeeType(),
2543 ToType, Context);
2544 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2545 return true;
2548 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2549 // Okay: this is some kind of implicit downcast of Objective-C
2550 // interfaces, which is permitted. However, we're going to
2551 // complain about it.
2552 IncompatibleObjC = true;
2553 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2554 ToObjCPtr->getPointeeType(),
2555 ToType, Context);
2556 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2557 return true;
2560 // Beyond this point, both types need to be C pointers or block pointers.
2561 QualType ToPointeeType;
2562 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2563 ToPointeeType = ToCPtr->getPointeeType();
2564 else if (const BlockPointerType *ToBlockPtr =
2565 ToType->getAs<BlockPointerType>()) {
2566 // Objective C++: We're able to convert from a pointer to any object
2567 // to a block pointer type.
2568 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2569 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2570 return true;
2572 ToPointeeType = ToBlockPtr->getPointeeType();
2574 else if (FromType->getAs<BlockPointerType>() &&
2575 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2576 // Objective C++: We're able to convert from a block pointer type to a
2577 // pointer to any object.
2578 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2579 return true;
2581 else
2582 return false;
2584 QualType FromPointeeType;
2585 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2586 FromPointeeType = FromCPtr->getPointeeType();
2587 else if (const BlockPointerType *FromBlockPtr =
2588 FromType->getAs<BlockPointerType>())
2589 FromPointeeType = FromBlockPtr->getPointeeType();
2590 else
2591 return false;
2593 // If we have pointers to pointers, recursively check whether this
2594 // is an Objective-C conversion.
2595 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2596 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2597 IncompatibleObjC)) {
2598 // We always complain about this conversion.
2599 IncompatibleObjC = true;
2600 ConvertedType = Context.getPointerType(ConvertedType);
2601 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2602 return true;
2604 // Allow conversion of pointee being objective-c pointer to another one;
2605 // as in I* to id.
2606 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2607 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2608 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2609 IncompatibleObjC)) {
2611 ConvertedType = Context.getPointerType(ConvertedType);
2612 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2613 return true;
2616 // If we have pointers to functions or blocks, check whether the only
2617 // differences in the argument and result types are in Objective-C
2618 // pointer conversions. If so, we permit the conversion (but
2619 // complain about it).
2620 const FunctionProtoType *FromFunctionType
2621 = FromPointeeType->getAs<FunctionProtoType>();
2622 const FunctionProtoType *ToFunctionType
2623 = ToPointeeType->getAs<FunctionProtoType>();
2624 if (FromFunctionType && ToFunctionType) {
2625 // If the function types are exactly the same, this isn't an
2626 // Objective-C pointer conversion.
2627 if (Context.getCanonicalType(FromPointeeType)
2628 == Context.getCanonicalType(ToPointeeType))
2629 return false;
2631 // Perform the quick checks that will tell us whether these
2632 // function types are obviously different.
2633 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2634 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2635 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2636 return false;
2638 bool HasObjCConversion = false;
2639 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2640 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2641 // Okay, the types match exactly. Nothing to do.
2642 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2643 ToFunctionType->getReturnType(),
2644 ConvertedType, IncompatibleObjC)) {
2645 // Okay, we have an Objective-C pointer conversion.
2646 HasObjCConversion = true;
2647 } else {
2648 // Function types are too different. Abort.
2649 return false;
2652 // Check argument types.
2653 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2654 ArgIdx != NumArgs; ++ArgIdx) {
2655 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2656 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2657 if (Context.getCanonicalType(FromArgType)
2658 == Context.getCanonicalType(ToArgType)) {
2659 // Okay, the types match exactly. Nothing to do.
2660 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2661 ConvertedType, IncompatibleObjC)) {
2662 // Okay, we have an Objective-C pointer conversion.
2663 HasObjCConversion = true;
2664 } else {
2665 // Argument types are too different. Abort.
2666 return false;
2670 if (HasObjCConversion) {
2671 // We had an Objective-C conversion. Allow this pointer
2672 // conversion, but complain about it.
2673 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2674 IncompatibleObjC = true;
2675 return true;
2679 return false;
2682 /// Determine whether this is an Objective-C writeback conversion,
2683 /// used for parameter passing when performing automatic reference counting.
2685 /// \param FromType The type we're converting form.
2687 /// \param ToType The type we're converting to.
2689 /// \param ConvertedType The type that will be produced after applying
2690 /// this conversion.
2691 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2692 QualType &ConvertedType) {
2693 if (!getLangOpts().ObjCAutoRefCount ||
2694 Context.hasSameUnqualifiedType(FromType, ToType))
2695 return false;
2697 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2698 QualType ToPointee;
2699 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2700 ToPointee = ToPointer->getPointeeType();
2701 else
2702 return false;
2704 Qualifiers ToQuals = ToPointee.getQualifiers();
2705 if (!ToPointee->isObjCLifetimeType() ||
2706 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2707 !ToQuals.withoutObjCLifetime().empty())
2708 return false;
2710 // Argument must be a pointer to __strong to __weak.
2711 QualType FromPointee;
2712 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2713 FromPointee = FromPointer->getPointeeType();
2714 else
2715 return false;
2717 Qualifiers FromQuals = FromPointee.getQualifiers();
2718 if (!FromPointee->isObjCLifetimeType() ||
2719 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2720 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2721 return false;
2723 // Make sure that we have compatible qualifiers.
2724 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2725 if (!ToQuals.compatiblyIncludes(FromQuals))
2726 return false;
2728 // Remove qualifiers from the pointee type we're converting from; they
2729 // aren't used in the compatibility check belong, and we'll be adding back
2730 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2731 FromPointee = FromPointee.getUnqualifiedType();
2733 // The unqualified form of the pointee types must be compatible.
2734 ToPointee = ToPointee.getUnqualifiedType();
2735 bool IncompatibleObjC;
2736 if (Context.typesAreCompatible(FromPointee, ToPointee))
2737 FromPointee = ToPointee;
2738 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2739 IncompatibleObjC))
2740 return false;
2742 /// Construct the type we're converting to, which is a pointer to
2743 /// __autoreleasing pointee.
2744 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2745 ConvertedType = Context.getPointerType(FromPointee);
2746 return true;
2749 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2750 QualType& ConvertedType) {
2751 QualType ToPointeeType;
2752 if (const BlockPointerType *ToBlockPtr =
2753 ToType->getAs<BlockPointerType>())
2754 ToPointeeType = ToBlockPtr->getPointeeType();
2755 else
2756 return false;
2758 QualType FromPointeeType;
2759 if (const BlockPointerType *FromBlockPtr =
2760 FromType->getAs<BlockPointerType>())
2761 FromPointeeType = FromBlockPtr->getPointeeType();
2762 else
2763 return false;
2764 // We have pointer to blocks, check whether the only
2765 // differences in the argument and result types are in Objective-C
2766 // pointer conversions. If so, we permit the conversion.
2768 const FunctionProtoType *FromFunctionType
2769 = FromPointeeType->getAs<FunctionProtoType>();
2770 const FunctionProtoType *ToFunctionType
2771 = ToPointeeType->getAs<FunctionProtoType>();
2773 if (!FromFunctionType || !ToFunctionType)
2774 return false;
2776 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2777 return true;
2779 // Perform the quick checks that will tell us whether these
2780 // function types are obviously different.
2781 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2782 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2783 return false;
2785 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2786 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2787 if (FromEInfo != ToEInfo)
2788 return false;
2790 bool IncompatibleObjC = false;
2791 if (Context.hasSameType(FromFunctionType->getReturnType(),
2792 ToFunctionType->getReturnType())) {
2793 // Okay, the types match exactly. Nothing to do.
2794 } else {
2795 QualType RHS = FromFunctionType->getReturnType();
2796 QualType LHS = ToFunctionType->getReturnType();
2797 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2798 !RHS.hasQualifiers() && LHS.hasQualifiers())
2799 LHS = LHS.getUnqualifiedType();
2801 if (Context.hasSameType(RHS,LHS)) {
2802 // OK exact match.
2803 } else if (isObjCPointerConversion(RHS, LHS,
2804 ConvertedType, IncompatibleObjC)) {
2805 if (IncompatibleObjC)
2806 return false;
2807 // Okay, we have an Objective-C pointer conversion.
2809 else
2810 return false;
2813 // Check argument types.
2814 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2815 ArgIdx != NumArgs; ++ArgIdx) {
2816 IncompatibleObjC = false;
2817 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2818 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2819 if (Context.hasSameType(FromArgType, ToArgType)) {
2820 // Okay, the types match exactly. Nothing to do.
2821 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2822 ConvertedType, IncompatibleObjC)) {
2823 if (IncompatibleObjC)
2824 return false;
2825 // Okay, we have an Objective-C pointer conversion.
2826 } else
2827 // Argument types are too different. Abort.
2828 return false;
2831 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2832 bool CanUseToFPT, CanUseFromFPT;
2833 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2834 CanUseToFPT, CanUseFromFPT,
2835 NewParamInfos))
2836 return false;
2838 ConvertedType = ToType;
2839 return true;
2842 enum {
2843 ft_default,
2844 ft_different_class,
2845 ft_parameter_arity,
2846 ft_parameter_mismatch,
2847 ft_return_type,
2848 ft_qualifer_mismatch,
2849 ft_noexcept
2852 /// Attempts to get the FunctionProtoType from a Type. Handles
2853 /// MemberFunctionPointers properly.
2854 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2855 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2856 return FPT;
2858 if (auto *MPT = FromType->getAs<MemberPointerType>())
2859 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2861 return nullptr;
2864 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2865 /// function types. Catches different number of parameter, mismatch in
2866 /// parameter types, and different return types.
2867 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2868 QualType FromType, QualType ToType) {
2869 // If either type is not valid, include no extra info.
2870 if (FromType.isNull() || ToType.isNull()) {
2871 PDiag << ft_default;
2872 return;
2875 // Get the function type from the pointers.
2876 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2877 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2878 *ToMember = ToType->castAs<MemberPointerType>();
2879 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2880 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2881 << QualType(FromMember->getClass(), 0);
2882 return;
2884 FromType = FromMember->getPointeeType();
2885 ToType = ToMember->getPointeeType();
2888 if (FromType->isPointerType())
2889 FromType = FromType->getPointeeType();
2890 if (ToType->isPointerType())
2891 ToType = ToType->getPointeeType();
2893 // Remove references.
2894 FromType = FromType.getNonReferenceType();
2895 ToType = ToType.getNonReferenceType();
2897 // Don't print extra info for non-specialized template functions.
2898 if (FromType->isInstantiationDependentType() &&
2899 !FromType->getAs<TemplateSpecializationType>()) {
2900 PDiag << ft_default;
2901 return;
2904 // No extra info for same types.
2905 if (Context.hasSameType(FromType, ToType)) {
2906 PDiag << ft_default;
2907 return;
2910 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2911 *ToFunction = tryGetFunctionProtoType(ToType);
2913 // Both types need to be function types.
2914 if (!FromFunction || !ToFunction) {
2915 PDiag << ft_default;
2916 return;
2919 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2920 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2921 << FromFunction->getNumParams();
2922 return;
2925 // Handle different parameter types.
2926 unsigned ArgPos;
2927 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2928 PDiag << ft_parameter_mismatch << ArgPos + 1
2929 << ToFunction->getParamType(ArgPos)
2930 << FromFunction->getParamType(ArgPos);
2931 return;
2934 // Handle different return type.
2935 if (!Context.hasSameType(FromFunction->getReturnType(),
2936 ToFunction->getReturnType())) {
2937 PDiag << ft_return_type << ToFunction->getReturnType()
2938 << FromFunction->getReturnType();
2939 return;
2942 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2943 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2944 << FromFunction->getMethodQuals();
2945 return;
2948 // Handle exception specification differences on canonical type (in C++17
2949 // onwards).
2950 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2951 ->isNothrow() !=
2952 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2953 ->isNothrow()) {
2954 PDiag << ft_noexcept;
2955 return;
2958 // Unable to find a difference, so add no extra info.
2959 PDiag << ft_default;
2962 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2963 /// for equality of their parameter types. Caller has already checked that
2964 /// they have same number of parameters. If the parameters are different,
2965 /// ArgPos will have the parameter index of the first different parameter.
2966 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2967 /// reverse order. That's useful if one of the functions is being used as a C++20
2968 /// synthesized operator overload with a reversed parameter order.
2969 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2970 const FunctionProtoType *NewType,
2971 unsigned *ArgPos, bool Reversed) {
2972 assert(OldType->getNumParams() == NewType->getNumParams() &&
2973 "Can't compare parameters of functions with different number of "
2974 "parameters!");
2975 for (size_t I = 0; I < OldType->getNumParams(); I++) {
2976 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2977 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2979 // Ignore address spaces in pointee type. This is to disallow overloading
2980 // on __ptr32/__ptr64 address spaces.
2981 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2982 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2984 if (!Context.hasSameType(Old, New)) {
2985 if (ArgPos)
2986 *ArgPos = I;
2987 return false;
2990 return true;
2993 /// CheckPointerConversion - Check the pointer conversion from the
2994 /// expression From to the type ToType. This routine checks for
2995 /// ambiguous or inaccessible derived-to-base pointer
2996 /// conversions for which IsPointerConversion has already returned
2997 /// true. It returns true and produces a diagnostic if there was an
2998 /// error, or returns false otherwise.
2999 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3000 CastKind &Kind,
3001 CXXCastPath& BasePath,
3002 bool IgnoreBaseAccess,
3003 bool Diagnose) {
3004 QualType FromType = From->getType();
3005 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3007 Kind = CK_BitCast;
3009 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3010 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3011 Expr::NPCK_ZeroExpression) {
3012 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3013 DiagRuntimeBehavior(From->getExprLoc(), From,
3014 PDiag(diag::warn_impcast_bool_to_null_pointer)
3015 << ToType << From->getSourceRange());
3016 else if (!isUnevaluatedContext())
3017 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3018 << ToType << From->getSourceRange();
3020 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3021 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3022 QualType FromPointeeType = FromPtrType->getPointeeType(),
3023 ToPointeeType = ToPtrType->getPointeeType();
3025 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3026 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3027 // We must have a derived-to-base conversion. Check an
3028 // ambiguous or inaccessible conversion.
3029 unsigned InaccessibleID = 0;
3030 unsigned AmbiguousID = 0;
3031 if (Diagnose) {
3032 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3033 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3035 if (CheckDerivedToBaseConversion(
3036 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3037 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3038 &BasePath, IgnoreBaseAccess))
3039 return true;
3041 // The conversion was successful.
3042 Kind = CK_DerivedToBase;
3045 if (Diagnose && !IsCStyleOrFunctionalCast &&
3046 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3047 assert(getLangOpts().MSVCCompat &&
3048 "this should only be possible with MSVCCompat!");
3049 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3050 << From->getSourceRange();
3053 } else if (const ObjCObjectPointerType *ToPtrType =
3054 ToType->getAs<ObjCObjectPointerType>()) {
3055 if (const ObjCObjectPointerType *FromPtrType =
3056 FromType->getAs<ObjCObjectPointerType>()) {
3057 // Objective-C++ conversions are always okay.
3058 // FIXME: We should have a different class of conversions for the
3059 // Objective-C++ implicit conversions.
3060 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3061 return false;
3062 } else if (FromType->isBlockPointerType()) {
3063 Kind = CK_BlockPointerToObjCPointerCast;
3064 } else {
3065 Kind = CK_CPointerToObjCPointerCast;
3067 } else if (ToType->isBlockPointerType()) {
3068 if (!FromType->isBlockPointerType())
3069 Kind = CK_AnyPointerToBlockPointerCast;
3072 // We shouldn't fall into this case unless it's valid for other
3073 // reasons.
3074 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3075 Kind = CK_NullToPointer;
3077 return false;
3080 /// IsMemberPointerConversion - Determines whether the conversion of the
3081 /// expression From, which has the (possibly adjusted) type FromType, can be
3082 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3083 /// If so, returns true and places the converted type (that might differ from
3084 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3085 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3086 QualType ToType,
3087 bool InOverloadResolution,
3088 QualType &ConvertedType) {
3089 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3090 if (!ToTypePtr)
3091 return false;
3093 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3094 if (From->isNullPointerConstant(Context,
3095 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3096 : Expr::NPC_ValueDependentIsNull)) {
3097 ConvertedType = ToType;
3098 return true;
3101 // Otherwise, both types have to be member pointers.
3102 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3103 if (!FromTypePtr)
3104 return false;
3106 // A pointer to member of B can be converted to a pointer to member of D,
3107 // where D is derived from B (C++ 4.11p2).
3108 QualType FromClass(FromTypePtr->getClass(), 0);
3109 QualType ToClass(ToTypePtr->getClass(), 0);
3111 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3112 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3113 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3114 ToClass.getTypePtr());
3115 return true;
3118 return false;
3121 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3122 /// expression From to the type ToType. This routine checks for ambiguous or
3123 /// virtual or inaccessible base-to-derived member pointer conversions
3124 /// for which IsMemberPointerConversion has already returned true. It returns
3125 /// true and produces a diagnostic if there was an error, or returns false
3126 /// otherwise.
3127 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3128 CastKind &Kind,
3129 CXXCastPath &BasePath,
3130 bool IgnoreBaseAccess) {
3131 QualType FromType = From->getType();
3132 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3133 if (!FromPtrType) {
3134 // This must be a null pointer to member pointer conversion
3135 assert(From->isNullPointerConstant(Context,
3136 Expr::NPC_ValueDependentIsNull) &&
3137 "Expr must be null pointer constant!");
3138 Kind = CK_NullToMemberPointer;
3139 return false;
3142 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3143 assert(ToPtrType && "No member pointer cast has a target type "
3144 "that is not a member pointer.");
3146 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3147 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3149 // FIXME: What about dependent types?
3150 assert(FromClass->isRecordType() && "Pointer into non-class.");
3151 assert(ToClass->isRecordType() && "Pointer into non-class.");
3153 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3154 /*DetectVirtual=*/true);
3155 bool DerivationOkay =
3156 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3157 assert(DerivationOkay &&
3158 "Should not have been called if derivation isn't OK.");
3159 (void)DerivationOkay;
3161 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3162 getUnqualifiedType())) {
3163 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3164 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3165 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3166 return true;
3169 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3170 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3171 << FromClass << ToClass << QualType(VBase, 0)
3172 << From->getSourceRange();
3173 return true;
3176 if (!IgnoreBaseAccess)
3177 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3178 Paths.front(),
3179 diag::err_downcast_from_inaccessible_base);
3181 // Must be a base to derived member conversion.
3182 BuildBasePathArray(Paths, BasePath);
3183 Kind = CK_BaseToDerivedMemberPointer;
3184 return false;
3187 /// Determine whether the lifetime conversion between the two given
3188 /// qualifiers sets is nontrivial.
3189 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3190 Qualifiers ToQuals) {
3191 // Converting anything to const __unsafe_unretained is trivial.
3192 if (ToQuals.hasConst() &&
3193 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3194 return false;
3196 return true;
3199 /// Perform a single iteration of the loop for checking if a qualification
3200 /// conversion is valid.
3202 /// Specifically, check whether any change between the qualifiers of \p
3203 /// FromType and \p ToType is permissible, given knowledge about whether every
3204 /// outer layer is const-qualified.
3205 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3206 bool CStyle, bool IsTopLevel,
3207 bool &PreviousToQualsIncludeConst,
3208 bool &ObjCLifetimeConversion) {
3209 Qualifiers FromQuals = FromType.getQualifiers();
3210 Qualifiers ToQuals = ToType.getQualifiers();
3212 // Ignore __unaligned qualifier.
3213 FromQuals.removeUnaligned();
3215 // Objective-C ARC:
3216 // Check Objective-C lifetime conversions.
3217 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3218 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3219 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3220 ObjCLifetimeConversion = true;
3221 FromQuals.removeObjCLifetime();
3222 ToQuals.removeObjCLifetime();
3223 } else {
3224 // Qualification conversions cannot cast between different
3225 // Objective-C lifetime qualifiers.
3226 return false;
3230 // Allow addition/removal of GC attributes but not changing GC attributes.
3231 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3232 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3233 FromQuals.removeObjCGCAttr();
3234 ToQuals.removeObjCGCAttr();
3237 // -- for every j > 0, if const is in cv 1,j then const is in cv
3238 // 2,j, and similarly for volatile.
3239 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3240 return false;
3242 // If address spaces mismatch:
3243 // - in top level it is only valid to convert to addr space that is a
3244 // superset in all cases apart from C-style casts where we allow
3245 // conversions between overlapping address spaces.
3246 // - in non-top levels it is not a valid conversion.
3247 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3248 (!IsTopLevel ||
3249 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3250 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3251 return false;
3253 // -- if the cv 1,j and cv 2,j are different, then const is in
3254 // every cv for 0 < k < j.
3255 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3256 !PreviousToQualsIncludeConst)
3257 return false;
3259 // The following wording is from C++20, where the result of the conversion
3260 // is T3, not T2.
3261 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3262 // "array of unknown bound of"
3263 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3264 return false;
3266 // -- if the resulting P3,i is different from P1,i [...], then const is
3267 // added to every cv 3_k for 0 < k < i.
3268 if (!CStyle && FromType->isConstantArrayType() &&
3269 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3270 return false;
3272 // Keep track of whether all prior cv-qualifiers in the "to" type
3273 // include const.
3274 PreviousToQualsIncludeConst =
3275 PreviousToQualsIncludeConst && ToQuals.hasConst();
3276 return true;
3279 /// IsQualificationConversion - Determines whether the conversion from
3280 /// an rvalue of type FromType to ToType is a qualification conversion
3281 /// (C++ 4.4).
3283 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3284 /// when the qualification conversion involves a change in the Objective-C
3285 /// object lifetime.
3286 bool
3287 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3288 bool CStyle, bool &ObjCLifetimeConversion) {
3289 FromType = Context.getCanonicalType(FromType);
3290 ToType = Context.getCanonicalType(ToType);
3291 ObjCLifetimeConversion = false;
3293 // If FromType and ToType are the same type, this is not a
3294 // qualification conversion.
3295 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3296 return false;
3298 // (C++ 4.4p4):
3299 // A conversion can add cv-qualifiers at levels other than the first
3300 // in multi-level pointers, subject to the following rules: [...]
3301 bool PreviousToQualsIncludeConst = true;
3302 bool UnwrappedAnyPointer = false;
3303 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3304 if (!isQualificationConversionStep(
3305 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3306 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3307 return false;
3308 UnwrappedAnyPointer = true;
3311 // We are left with FromType and ToType being the pointee types
3312 // after unwrapping the original FromType and ToType the same number
3313 // of times. If we unwrapped any pointers, and if FromType and
3314 // ToType have the same unqualified type (since we checked
3315 // qualifiers above), then this is a qualification conversion.
3316 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3319 /// - Determine whether this is a conversion from a scalar type to an
3320 /// atomic type.
3322 /// If successful, updates \c SCS's second and third steps in the conversion
3323 /// sequence to finish the conversion.
3324 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3325 bool InOverloadResolution,
3326 StandardConversionSequence &SCS,
3327 bool CStyle) {
3328 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3329 if (!ToAtomic)
3330 return false;
3332 StandardConversionSequence InnerSCS;
3333 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3334 InOverloadResolution, InnerSCS,
3335 CStyle, /*AllowObjCWritebackConversion=*/false))
3336 return false;
3338 SCS.Second = InnerSCS.Second;
3339 SCS.setToType(1, InnerSCS.getToType(1));
3340 SCS.Third = InnerSCS.Third;
3341 SCS.QualificationIncludesObjCLifetime
3342 = InnerSCS.QualificationIncludesObjCLifetime;
3343 SCS.setToType(2, InnerSCS.getToType(2));
3344 return true;
3347 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3348 CXXConstructorDecl *Constructor,
3349 QualType Type) {
3350 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3351 if (CtorType->getNumParams() > 0) {
3352 QualType FirstArg = CtorType->getParamType(0);
3353 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3354 return true;
3356 return false;
3359 static OverloadingResult
3360 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3361 CXXRecordDecl *To,
3362 UserDefinedConversionSequence &User,
3363 OverloadCandidateSet &CandidateSet,
3364 bool AllowExplicit) {
3365 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3366 for (auto *D : S.LookupConstructors(To)) {
3367 auto Info = getConstructorInfo(D);
3368 if (!Info)
3369 continue;
3371 bool Usable = !Info.Constructor->isInvalidDecl() &&
3372 S.isInitListConstructor(Info.Constructor);
3373 if (Usable) {
3374 bool SuppressUserConversions = false;
3375 if (Info.ConstructorTmpl)
3376 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3377 /*ExplicitArgs*/ nullptr, From,
3378 CandidateSet, SuppressUserConversions,
3379 /*PartialOverloading*/ false,
3380 AllowExplicit);
3381 else
3382 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3383 CandidateSet, SuppressUserConversions,
3384 /*PartialOverloading*/ false, AllowExplicit);
3388 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3390 OverloadCandidateSet::iterator Best;
3391 switch (auto Result =
3392 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3393 case OR_Deleted:
3394 case OR_Success: {
3395 // Record the standard conversion we used and the conversion function.
3396 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3397 QualType ThisType = Constructor->getThisType();
3398 // Initializer lists don't have conversions as such.
3399 User.Before.setAsIdentityConversion();
3400 User.HadMultipleCandidates = HadMultipleCandidates;
3401 User.ConversionFunction = Constructor;
3402 User.FoundConversionFunction = Best->FoundDecl;
3403 User.After.setAsIdentityConversion();
3404 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3405 User.After.setAllToTypes(ToType);
3406 return Result;
3409 case OR_No_Viable_Function:
3410 return OR_No_Viable_Function;
3411 case OR_Ambiguous:
3412 return OR_Ambiguous;
3415 llvm_unreachable("Invalid OverloadResult!");
3418 /// Determines whether there is a user-defined conversion sequence
3419 /// (C++ [over.ics.user]) that converts expression From to the type
3420 /// ToType. If such a conversion exists, User will contain the
3421 /// user-defined conversion sequence that performs such a conversion
3422 /// and this routine will return true. Otherwise, this routine returns
3423 /// false and User is unspecified.
3425 /// \param AllowExplicit true if the conversion should consider C++0x
3426 /// "explicit" conversion functions as well as non-explicit conversion
3427 /// functions (C++0x [class.conv.fct]p2).
3429 /// \param AllowObjCConversionOnExplicit true if the conversion should
3430 /// allow an extra Objective-C pointer conversion on uses of explicit
3431 /// constructors. Requires \c AllowExplicit to also be set.
3432 static OverloadingResult
3433 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3434 UserDefinedConversionSequence &User,
3435 OverloadCandidateSet &CandidateSet,
3436 AllowedExplicit AllowExplicit,
3437 bool AllowObjCConversionOnExplicit) {
3438 assert(AllowExplicit != AllowedExplicit::None ||
3439 !AllowObjCConversionOnExplicit);
3440 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3442 // Whether we will only visit constructors.
3443 bool ConstructorsOnly = false;
3445 // If the type we are conversion to is a class type, enumerate its
3446 // constructors.
3447 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3448 // C++ [over.match.ctor]p1:
3449 // When objects of class type are direct-initialized (8.5), or
3450 // copy-initialized from an expression of the same or a
3451 // derived class type (8.5), overload resolution selects the
3452 // constructor. [...] For copy-initialization, the candidate
3453 // functions are all the converting constructors (12.3.1) of
3454 // that class. The argument list is the expression-list within
3455 // the parentheses of the initializer.
3456 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3457 (From->getType()->getAs<RecordType>() &&
3458 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3459 ConstructorsOnly = true;
3461 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3462 // We're not going to find any constructors.
3463 } else if (CXXRecordDecl *ToRecordDecl
3464 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3466 Expr **Args = &From;
3467 unsigned NumArgs = 1;
3468 bool ListInitializing = false;
3469 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3470 // But first, see if there is an init-list-constructor that will work.
3471 OverloadingResult Result = IsInitializerListConstructorConversion(
3472 S, From, ToType, ToRecordDecl, User, CandidateSet,
3473 AllowExplicit == AllowedExplicit::All);
3474 if (Result != OR_No_Viable_Function)
3475 return Result;
3476 // Never mind.
3477 CandidateSet.clear(
3478 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3480 // If we're list-initializing, we pass the individual elements as
3481 // arguments, not the entire list.
3482 Args = InitList->getInits();
3483 NumArgs = InitList->getNumInits();
3484 ListInitializing = true;
3487 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3488 auto Info = getConstructorInfo(D);
3489 if (!Info)
3490 continue;
3492 bool Usable = !Info.Constructor->isInvalidDecl();
3493 if (!ListInitializing)
3494 Usable = Usable && Info.Constructor->isConvertingConstructor(
3495 /*AllowExplicit*/ true);
3496 if (Usable) {
3497 bool SuppressUserConversions = !ConstructorsOnly;
3498 // C++20 [over.best.ics.general]/4.5:
3499 // if the target is the first parameter of a constructor [of class
3500 // X] and the constructor [...] is a candidate by [...] the second
3501 // phase of [over.match.list] when the initializer list has exactly
3502 // one element that is itself an initializer list, [...] and the
3503 // conversion is to X or reference to cv X, user-defined conversion
3504 // sequences are not cnosidered.
3505 if (SuppressUserConversions && ListInitializing) {
3506 SuppressUserConversions =
3507 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3508 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3509 ToType);
3511 if (Info.ConstructorTmpl)
3512 S.AddTemplateOverloadCandidate(
3513 Info.ConstructorTmpl, Info.FoundDecl,
3514 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3515 CandidateSet, SuppressUserConversions,
3516 /*PartialOverloading*/ false,
3517 AllowExplicit == AllowedExplicit::All);
3518 else
3519 // Allow one user-defined conversion when user specifies a
3520 // From->ToType conversion via an static cast (c-style, etc).
3521 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3522 llvm::makeArrayRef(Args, NumArgs),
3523 CandidateSet, SuppressUserConversions,
3524 /*PartialOverloading*/ false,
3525 AllowExplicit == AllowedExplicit::All);
3531 // Enumerate conversion functions, if we're allowed to.
3532 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3533 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3534 // No conversion functions from incomplete types.
3535 } else if (const RecordType *FromRecordType =
3536 From->getType()->getAs<RecordType>()) {
3537 if (CXXRecordDecl *FromRecordDecl
3538 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3539 // Add all of the conversion functions as candidates.
3540 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3541 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3542 DeclAccessPair FoundDecl = I.getPair();
3543 NamedDecl *D = FoundDecl.getDecl();
3544 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3545 if (isa<UsingShadowDecl>(D))
3546 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3548 CXXConversionDecl *Conv;
3549 FunctionTemplateDecl *ConvTemplate;
3550 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3551 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3552 else
3553 Conv = cast<CXXConversionDecl>(D);
3555 if (ConvTemplate)
3556 S.AddTemplateConversionCandidate(
3557 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3558 CandidateSet, AllowObjCConversionOnExplicit,
3559 AllowExplicit != AllowedExplicit::None);
3560 else
3561 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3562 CandidateSet, AllowObjCConversionOnExplicit,
3563 AllowExplicit != AllowedExplicit::None);
3568 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3570 OverloadCandidateSet::iterator Best;
3571 switch (auto Result =
3572 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3573 case OR_Success:
3574 case OR_Deleted:
3575 // Record the standard conversion we used and the conversion function.
3576 if (CXXConstructorDecl *Constructor
3577 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3578 // C++ [over.ics.user]p1:
3579 // If the user-defined conversion is specified by a
3580 // constructor (12.3.1), the initial standard conversion
3581 // sequence converts the source type to the type required by
3582 // the argument of the constructor.
3584 QualType ThisType = Constructor->getThisType();
3585 if (isa<InitListExpr>(From)) {
3586 // Initializer lists don't have conversions as such.
3587 User.Before.setAsIdentityConversion();
3588 } else {
3589 if (Best->Conversions[0].isEllipsis())
3590 User.EllipsisConversion = true;
3591 else {
3592 User.Before = Best->Conversions[0].Standard;
3593 User.EllipsisConversion = false;
3596 User.HadMultipleCandidates = HadMultipleCandidates;
3597 User.ConversionFunction = Constructor;
3598 User.FoundConversionFunction = Best->FoundDecl;
3599 User.After.setAsIdentityConversion();
3600 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3601 User.After.setAllToTypes(ToType);
3602 return Result;
3604 if (CXXConversionDecl *Conversion
3605 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3606 // C++ [over.ics.user]p1:
3608 // [...] If the user-defined conversion is specified by a
3609 // conversion function (12.3.2), the initial standard
3610 // conversion sequence converts the source type to the
3611 // implicit object parameter of the conversion function.
3612 User.Before = Best->Conversions[0].Standard;
3613 User.HadMultipleCandidates = HadMultipleCandidates;
3614 User.ConversionFunction = Conversion;
3615 User.FoundConversionFunction = Best->FoundDecl;
3616 User.EllipsisConversion = false;
3618 // C++ [over.ics.user]p2:
3619 // The second standard conversion sequence converts the
3620 // result of the user-defined conversion to the target type
3621 // for the sequence. Since an implicit conversion sequence
3622 // is an initialization, the special rules for
3623 // initialization by user-defined conversion apply when
3624 // selecting the best user-defined conversion for a
3625 // user-defined conversion sequence (see 13.3.3 and
3626 // 13.3.3.1).
3627 User.After = Best->FinalConversion;
3628 return Result;
3630 llvm_unreachable("Not a constructor or conversion function?");
3632 case OR_No_Viable_Function:
3633 return OR_No_Viable_Function;
3635 case OR_Ambiguous:
3636 return OR_Ambiguous;
3639 llvm_unreachable("Invalid OverloadResult!");
3642 bool
3643 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3644 ImplicitConversionSequence ICS;
3645 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3646 OverloadCandidateSet::CSK_Normal);
3647 OverloadingResult OvResult =
3648 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3649 CandidateSet, AllowedExplicit::None, false);
3651 if (!(OvResult == OR_Ambiguous ||
3652 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3653 return false;
3655 auto Cands = CandidateSet.CompleteCandidates(
3656 *this,
3657 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3658 From);
3659 if (OvResult == OR_Ambiguous)
3660 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3661 << From->getType() << ToType << From->getSourceRange();
3662 else { // OR_No_Viable_Function && !CandidateSet.empty()
3663 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3664 diag::err_typecheck_nonviable_condition_incomplete,
3665 From->getType(), From->getSourceRange()))
3666 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3667 << false << From->getType() << From->getSourceRange() << ToType;
3670 CandidateSet.NoteCandidates(
3671 *this, From, Cands);
3672 return true;
3675 // Helper for compareConversionFunctions that gets the FunctionType that the
3676 // conversion-operator return value 'points' to, or nullptr.
3677 static const FunctionType *
3678 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3679 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3680 const PointerType *RetPtrTy =
3681 ConvFuncTy->getReturnType()->getAs<PointerType>();
3683 if (!RetPtrTy)
3684 return nullptr;
3686 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3689 /// Compare the user-defined conversion functions or constructors
3690 /// of two user-defined conversion sequences to determine whether any ordering
3691 /// is possible.
3692 static ImplicitConversionSequence::CompareKind
3693 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3694 FunctionDecl *Function2) {
3695 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3696 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3697 if (!Conv1 || !Conv2)
3698 return ImplicitConversionSequence::Indistinguishable;
3700 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3701 return ImplicitConversionSequence::Indistinguishable;
3703 // Objective-C++:
3704 // If both conversion functions are implicitly-declared conversions from
3705 // a lambda closure type to a function pointer and a block pointer,
3706 // respectively, always prefer the conversion to a function pointer,
3707 // because the function pointer is more lightweight and is more likely
3708 // to keep code working.
3709 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3710 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3711 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3712 if (Block1 != Block2)
3713 return Block1 ? ImplicitConversionSequence::Worse
3714 : ImplicitConversionSequence::Better;
3717 // In order to support multiple calling conventions for the lambda conversion
3718 // operator (such as when the free and member function calling convention is
3719 // different), prefer the 'free' mechanism, followed by the calling-convention
3720 // of operator(). The latter is in place to support the MSVC-like solution of
3721 // defining ALL of the possible conversions in regards to calling-convention.
3722 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3723 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3725 if (Conv1FuncRet && Conv2FuncRet &&
3726 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3727 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3728 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3730 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3731 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3733 CallingConv CallOpCC =
3734 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3735 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3736 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3737 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3738 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3740 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3741 for (CallingConv CC : PrefOrder) {
3742 if (Conv1CC == CC)
3743 return ImplicitConversionSequence::Better;
3744 if (Conv2CC == CC)
3745 return ImplicitConversionSequence::Worse;
3749 return ImplicitConversionSequence::Indistinguishable;
3752 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3753 const ImplicitConversionSequence &ICS) {
3754 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3755 (ICS.isUserDefined() &&
3756 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3759 /// CompareImplicitConversionSequences - Compare two implicit
3760 /// conversion sequences to determine whether one is better than the
3761 /// other or if they are indistinguishable (C++ 13.3.3.2).
3762 static ImplicitConversionSequence::CompareKind
3763 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3764 const ImplicitConversionSequence& ICS1,
3765 const ImplicitConversionSequence& ICS2)
3767 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3768 // conversion sequences (as defined in 13.3.3.1)
3769 // -- a standard conversion sequence (13.3.3.1.1) is a better
3770 // conversion sequence than a user-defined conversion sequence or
3771 // an ellipsis conversion sequence, and
3772 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3773 // conversion sequence than an ellipsis conversion sequence
3774 // (13.3.3.1.3).
3776 // C++0x [over.best.ics]p10:
3777 // For the purpose of ranking implicit conversion sequences as
3778 // described in 13.3.3.2, the ambiguous conversion sequence is
3779 // treated as a user-defined sequence that is indistinguishable
3780 // from any other user-defined conversion sequence.
3782 // String literal to 'char *' conversion has been deprecated in C++03. It has
3783 // been removed from C++11. We still accept this conversion, if it happens at
3784 // the best viable function. Otherwise, this conversion is considered worse
3785 // than ellipsis conversion. Consider this as an extension; this is not in the
3786 // standard. For example:
3788 // int &f(...); // #1
3789 // void f(char*); // #2
3790 // void g() { int &r = f("foo"); }
3792 // In C++03, we pick #2 as the best viable function.
3793 // In C++11, we pick #1 as the best viable function, because ellipsis
3794 // conversion is better than string-literal to char* conversion (since there
3795 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3796 // convert arguments, #2 would be the best viable function in C++11.
3797 // If the best viable function has this conversion, a warning will be issued
3798 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3800 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3801 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3802 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3803 // Ill-formedness must not differ
3804 ICS1.isBad() == ICS2.isBad())
3805 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3806 ? ImplicitConversionSequence::Worse
3807 : ImplicitConversionSequence::Better;
3809 if (ICS1.getKindRank() < ICS2.getKindRank())
3810 return ImplicitConversionSequence::Better;
3811 if (ICS2.getKindRank() < ICS1.getKindRank())
3812 return ImplicitConversionSequence::Worse;
3814 // The following checks require both conversion sequences to be of
3815 // the same kind.
3816 if (ICS1.getKind() != ICS2.getKind())
3817 return ImplicitConversionSequence::Indistinguishable;
3819 ImplicitConversionSequence::CompareKind Result =
3820 ImplicitConversionSequence::Indistinguishable;
3822 // Two implicit conversion sequences of the same form are
3823 // indistinguishable conversion sequences unless one of the
3824 // following rules apply: (C++ 13.3.3.2p3):
3826 // List-initialization sequence L1 is a better conversion sequence than
3827 // list-initialization sequence L2 if:
3828 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3829 // if not that,
3830 // — L1 and L2 convert to arrays of the same element type, and either the
3831 // number of elements n_1 initialized by L1 is less than the number of
3832 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3833 // an array of unknown bound and L1 does not,
3834 // even if one of the other rules in this paragraph would otherwise apply.
3835 if (!ICS1.isBad()) {
3836 bool StdInit1 = false, StdInit2 = false;
3837 if (ICS1.hasInitializerListContainerType())
3838 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3839 nullptr);
3840 if (ICS2.hasInitializerListContainerType())
3841 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3842 nullptr);
3843 if (StdInit1 != StdInit2)
3844 return StdInit1 ? ImplicitConversionSequence::Better
3845 : ImplicitConversionSequence::Worse;
3847 if (ICS1.hasInitializerListContainerType() &&
3848 ICS2.hasInitializerListContainerType())
3849 if (auto *CAT1 = S.Context.getAsConstantArrayType(
3850 ICS1.getInitializerListContainerType()))
3851 if (auto *CAT2 = S.Context.getAsConstantArrayType(
3852 ICS2.getInitializerListContainerType())) {
3853 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3854 CAT2->getElementType())) {
3855 // Both to arrays of the same element type
3856 if (CAT1->getSize() != CAT2->getSize())
3857 // Different sized, the smaller wins
3858 return CAT1->getSize().ult(CAT2->getSize())
3859 ? ImplicitConversionSequence::Better
3860 : ImplicitConversionSequence::Worse;
3861 if (ICS1.isInitializerListOfIncompleteArray() !=
3862 ICS2.isInitializerListOfIncompleteArray())
3863 // One is incomplete, it loses
3864 return ICS2.isInitializerListOfIncompleteArray()
3865 ? ImplicitConversionSequence::Better
3866 : ImplicitConversionSequence::Worse;
3871 if (ICS1.isStandard())
3872 // Standard conversion sequence S1 is a better conversion sequence than
3873 // standard conversion sequence S2 if [...]
3874 Result = CompareStandardConversionSequences(S, Loc,
3875 ICS1.Standard, ICS2.Standard);
3876 else if (ICS1.isUserDefined()) {
3877 // User-defined conversion sequence U1 is a better conversion
3878 // sequence than another user-defined conversion sequence U2 if
3879 // they contain the same user-defined conversion function or
3880 // constructor and if the second standard conversion sequence of
3881 // U1 is better than the second standard conversion sequence of
3882 // U2 (C++ 13.3.3.2p3).
3883 if (ICS1.UserDefined.ConversionFunction ==
3884 ICS2.UserDefined.ConversionFunction)
3885 Result = CompareStandardConversionSequences(S, Loc,
3886 ICS1.UserDefined.After,
3887 ICS2.UserDefined.After);
3888 else
3889 Result = compareConversionFunctions(S,
3890 ICS1.UserDefined.ConversionFunction,
3891 ICS2.UserDefined.ConversionFunction);
3894 return Result;
3897 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3898 // determine if one is a proper subset of the other.
3899 static ImplicitConversionSequence::CompareKind
3900 compareStandardConversionSubsets(ASTContext &Context,
3901 const StandardConversionSequence& SCS1,
3902 const StandardConversionSequence& SCS2) {
3903 ImplicitConversionSequence::CompareKind Result
3904 = ImplicitConversionSequence::Indistinguishable;
3906 // the identity conversion sequence is considered to be a subsequence of
3907 // any non-identity conversion sequence
3908 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3909 return ImplicitConversionSequence::Better;
3910 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3911 return ImplicitConversionSequence::Worse;
3913 if (SCS1.Second != SCS2.Second) {
3914 if (SCS1.Second == ICK_Identity)
3915 Result = ImplicitConversionSequence::Better;
3916 else if (SCS2.Second == ICK_Identity)
3917 Result = ImplicitConversionSequence::Worse;
3918 else
3919 return ImplicitConversionSequence::Indistinguishable;
3920 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3921 return ImplicitConversionSequence::Indistinguishable;
3923 if (SCS1.Third == SCS2.Third) {
3924 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3925 : ImplicitConversionSequence::Indistinguishable;
3928 if (SCS1.Third == ICK_Identity)
3929 return Result == ImplicitConversionSequence::Worse
3930 ? ImplicitConversionSequence::Indistinguishable
3931 : ImplicitConversionSequence::Better;
3933 if (SCS2.Third == ICK_Identity)
3934 return Result == ImplicitConversionSequence::Better
3935 ? ImplicitConversionSequence::Indistinguishable
3936 : ImplicitConversionSequence::Worse;
3938 return ImplicitConversionSequence::Indistinguishable;
3941 /// Determine whether one of the given reference bindings is better
3942 /// than the other based on what kind of bindings they are.
3943 static bool
3944 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3945 const StandardConversionSequence &SCS2) {
3946 // C++0x [over.ics.rank]p3b4:
3947 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3948 // implicit object parameter of a non-static member function declared
3949 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3950 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3951 // lvalue reference to a function lvalue and S2 binds an rvalue
3952 // reference*.
3954 // FIXME: Rvalue references. We're going rogue with the above edits,
3955 // because the semantics in the current C++0x working paper (N3225 at the
3956 // time of this writing) break the standard definition of std::forward
3957 // and std::reference_wrapper when dealing with references to functions.
3958 // Proposed wording changes submitted to CWG for consideration.
3959 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3960 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3961 return false;
3963 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3964 SCS2.IsLvalueReference) ||
3965 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3966 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3969 enum class FixedEnumPromotion {
3970 None,
3971 ToUnderlyingType,
3972 ToPromotedUnderlyingType
3975 /// Returns kind of fixed enum promotion the \a SCS uses.
3976 static FixedEnumPromotion
3977 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3979 if (SCS.Second != ICK_Integral_Promotion)
3980 return FixedEnumPromotion::None;
3982 QualType FromType = SCS.getFromType();
3983 if (!FromType->isEnumeralType())
3984 return FixedEnumPromotion::None;
3986 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3987 if (!Enum->isFixed())
3988 return FixedEnumPromotion::None;
3990 QualType UnderlyingType = Enum->getIntegerType();
3991 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3992 return FixedEnumPromotion::ToUnderlyingType;
3994 return FixedEnumPromotion::ToPromotedUnderlyingType;
3997 /// CompareStandardConversionSequences - Compare two standard
3998 /// conversion sequences to determine whether one is better than the
3999 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4000 static ImplicitConversionSequence::CompareKind
4001 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4002 const StandardConversionSequence& SCS1,
4003 const StandardConversionSequence& SCS2)
4005 // Standard conversion sequence S1 is a better conversion sequence
4006 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4008 // -- S1 is a proper subsequence of S2 (comparing the conversion
4009 // sequences in the canonical form defined by 13.3.3.1.1,
4010 // excluding any Lvalue Transformation; the identity conversion
4011 // sequence is considered to be a subsequence of any
4012 // non-identity conversion sequence) or, if not that,
4013 if (ImplicitConversionSequence::CompareKind CK
4014 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4015 return CK;
4017 // -- the rank of S1 is better than the rank of S2 (by the rules
4018 // defined below), or, if not that,
4019 ImplicitConversionRank Rank1 = SCS1.getRank();
4020 ImplicitConversionRank Rank2 = SCS2.getRank();
4021 if (Rank1 < Rank2)
4022 return ImplicitConversionSequence::Better;
4023 else if (Rank2 < Rank1)
4024 return ImplicitConversionSequence::Worse;
4026 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4027 // are indistinguishable unless one of the following rules
4028 // applies:
4030 // A conversion that is not a conversion of a pointer, or
4031 // pointer to member, to bool is better than another conversion
4032 // that is such a conversion.
4033 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4034 return SCS2.isPointerConversionToBool()
4035 ? ImplicitConversionSequence::Better
4036 : ImplicitConversionSequence::Worse;
4038 // C++14 [over.ics.rank]p4b2:
4039 // This is retroactively applied to C++11 by CWG 1601.
4041 // A conversion that promotes an enumeration whose underlying type is fixed
4042 // to its underlying type is better than one that promotes to the promoted
4043 // underlying type, if the two are different.
4044 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4045 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4046 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4047 FEP1 != FEP2)
4048 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4049 ? ImplicitConversionSequence::Better
4050 : ImplicitConversionSequence::Worse;
4052 // C++ [over.ics.rank]p4b2:
4054 // If class B is derived directly or indirectly from class A,
4055 // conversion of B* to A* is better than conversion of B* to
4056 // void*, and conversion of A* to void* is better than conversion
4057 // of B* to void*.
4058 bool SCS1ConvertsToVoid
4059 = SCS1.isPointerConversionToVoidPointer(S.Context);
4060 bool SCS2ConvertsToVoid
4061 = SCS2.isPointerConversionToVoidPointer(S.Context);
4062 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4063 // Exactly one of the conversion sequences is a conversion to
4064 // a void pointer; it's the worse conversion.
4065 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4066 : ImplicitConversionSequence::Worse;
4067 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4068 // Neither conversion sequence converts to a void pointer; compare
4069 // their derived-to-base conversions.
4070 if (ImplicitConversionSequence::CompareKind DerivedCK
4071 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4072 return DerivedCK;
4073 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4074 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4075 // Both conversion sequences are conversions to void
4076 // pointers. Compare the source types to determine if there's an
4077 // inheritance relationship in their sources.
4078 QualType FromType1 = SCS1.getFromType();
4079 QualType FromType2 = SCS2.getFromType();
4081 // Adjust the types we're converting from via the array-to-pointer
4082 // conversion, if we need to.
4083 if (SCS1.First == ICK_Array_To_Pointer)
4084 FromType1 = S.Context.getArrayDecayedType(FromType1);
4085 if (SCS2.First == ICK_Array_To_Pointer)
4086 FromType2 = S.Context.getArrayDecayedType(FromType2);
4088 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4089 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4091 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4092 return ImplicitConversionSequence::Better;
4093 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4094 return ImplicitConversionSequence::Worse;
4096 // Objective-C++: If one interface is more specific than the
4097 // other, it is the better one.
4098 const ObjCObjectPointerType* FromObjCPtr1
4099 = FromType1->getAs<ObjCObjectPointerType>();
4100 const ObjCObjectPointerType* FromObjCPtr2
4101 = FromType2->getAs<ObjCObjectPointerType>();
4102 if (FromObjCPtr1 && FromObjCPtr2) {
4103 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4104 FromObjCPtr2);
4105 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4106 FromObjCPtr1);
4107 if (AssignLeft != AssignRight) {
4108 return AssignLeft? ImplicitConversionSequence::Better
4109 : ImplicitConversionSequence::Worse;
4114 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4115 // Check for a better reference binding based on the kind of bindings.
4116 if (isBetterReferenceBindingKind(SCS1, SCS2))
4117 return ImplicitConversionSequence::Better;
4118 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4119 return ImplicitConversionSequence::Worse;
4122 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4123 // bullet 3).
4124 if (ImplicitConversionSequence::CompareKind QualCK
4125 = CompareQualificationConversions(S, SCS1, SCS2))
4126 return QualCK;
4128 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4129 // C++ [over.ics.rank]p3b4:
4130 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4131 // which the references refer are the same type except for
4132 // top-level cv-qualifiers, and the type to which the reference
4133 // initialized by S2 refers is more cv-qualified than the type
4134 // to which the reference initialized by S1 refers.
4135 QualType T1 = SCS1.getToType(2);
4136 QualType T2 = SCS2.getToType(2);
4137 T1 = S.Context.getCanonicalType(T1);
4138 T2 = S.Context.getCanonicalType(T2);
4139 Qualifiers T1Quals, T2Quals;
4140 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4141 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4142 if (UnqualT1 == UnqualT2) {
4143 // Objective-C++ ARC: If the references refer to objects with different
4144 // lifetimes, prefer bindings that don't change lifetime.
4145 if (SCS1.ObjCLifetimeConversionBinding !=
4146 SCS2.ObjCLifetimeConversionBinding) {
4147 return SCS1.ObjCLifetimeConversionBinding
4148 ? ImplicitConversionSequence::Worse
4149 : ImplicitConversionSequence::Better;
4152 // If the type is an array type, promote the element qualifiers to the
4153 // type for comparison.
4154 if (isa<ArrayType>(T1) && T1Quals)
4155 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4156 if (isa<ArrayType>(T2) && T2Quals)
4157 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4158 if (T2.isMoreQualifiedThan(T1))
4159 return ImplicitConversionSequence::Better;
4160 if (T1.isMoreQualifiedThan(T2))
4161 return ImplicitConversionSequence::Worse;
4165 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4166 // floating-to-integral conversion if the integral conversion
4167 // is between types of the same size.
4168 // For example:
4169 // void f(float);
4170 // void f(int);
4171 // int main {
4172 // long a;
4173 // f(a);
4174 // }
4175 // Here, MSVC will call f(int) instead of generating a compile error
4176 // as clang will do in standard mode.
4177 if (S.getLangOpts().MSVCCompat &&
4178 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4179 SCS1.Second == ICK_Integral_Conversion &&
4180 SCS2.Second == ICK_Floating_Integral &&
4181 S.Context.getTypeSize(SCS1.getFromType()) ==
4182 S.Context.getTypeSize(SCS1.getToType(2)))
4183 return ImplicitConversionSequence::Better;
4185 // Prefer a compatible vector conversion over a lax vector conversion
4186 // For example:
4188 // typedef float __v4sf __attribute__((__vector_size__(16)));
4189 // void f(vector float);
4190 // void f(vector signed int);
4191 // int main() {
4192 // __v4sf a;
4193 // f(a);
4194 // }
4195 // Here, we'd like to choose f(vector float) and not
4196 // report an ambiguous call error
4197 if (SCS1.Second == ICK_Vector_Conversion &&
4198 SCS2.Second == ICK_Vector_Conversion) {
4199 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4200 SCS1.getFromType(), SCS1.getToType(2));
4201 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4202 SCS2.getFromType(), SCS2.getToType(2));
4204 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4205 return SCS1IsCompatibleVectorConversion
4206 ? ImplicitConversionSequence::Better
4207 : ImplicitConversionSequence::Worse;
4210 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4211 SCS2.Second == ICK_SVE_Vector_Conversion) {
4212 bool SCS1IsCompatibleSVEVectorConversion =
4213 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4214 bool SCS2IsCompatibleSVEVectorConversion =
4215 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4217 if (SCS1IsCompatibleSVEVectorConversion !=
4218 SCS2IsCompatibleSVEVectorConversion)
4219 return SCS1IsCompatibleSVEVectorConversion
4220 ? ImplicitConversionSequence::Better
4221 : ImplicitConversionSequence::Worse;
4224 return ImplicitConversionSequence::Indistinguishable;
4227 /// CompareQualificationConversions - Compares two standard conversion
4228 /// sequences to determine whether they can be ranked based on their
4229 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4230 static ImplicitConversionSequence::CompareKind
4231 CompareQualificationConversions(Sema &S,
4232 const StandardConversionSequence& SCS1,
4233 const StandardConversionSequence& SCS2) {
4234 // C++ [over.ics.rank]p3:
4235 // -- S1 and S2 differ only in their qualification conversion and
4236 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4237 // [C++98]
4238 // [...] and the cv-qualification signature of type T1 is a proper subset
4239 // of the cv-qualification signature of type T2, and S1 is not the
4240 // deprecated string literal array-to-pointer conversion (4.2).
4241 // [C++2a]
4242 // [...] where T1 can be converted to T2 by a qualification conversion.
4243 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4244 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4245 return ImplicitConversionSequence::Indistinguishable;
4247 // FIXME: the example in the standard doesn't use a qualification
4248 // conversion (!)
4249 QualType T1 = SCS1.getToType(2);
4250 QualType T2 = SCS2.getToType(2);
4251 T1 = S.Context.getCanonicalType(T1);
4252 T2 = S.Context.getCanonicalType(T2);
4253 assert(!T1->isReferenceType() && !T2->isReferenceType());
4254 Qualifiers T1Quals, T2Quals;
4255 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4256 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4258 // If the types are the same, we won't learn anything by unwrapping
4259 // them.
4260 if (UnqualT1 == UnqualT2)
4261 return ImplicitConversionSequence::Indistinguishable;
4263 // Don't ever prefer a standard conversion sequence that uses the deprecated
4264 // string literal array to pointer conversion.
4265 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4266 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4268 // Objective-C++ ARC:
4269 // Prefer qualification conversions not involving a change in lifetime
4270 // to qualification conversions that do change lifetime.
4271 if (SCS1.QualificationIncludesObjCLifetime &&
4272 !SCS2.QualificationIncludesObjCLifetime)
4273 CanPick1 = false;
4274 if (SCS2.QualificationIncludesObjCLifetime &&
4275 !SCS1.QualificationIncludesObjCLifetime)
4276 CanPick2 = false;
4278 bool ObjCLifetimeConversion;
4279 if (CanPick1 &&
4280 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4281 CanPick1 = false;
4282 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4283 // directions, so we can't short-cut this second check in general.
4284 if (CanPick2 &&
4285 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4286 CanPick2 = false;
4288 if (CanPick1 != CanPick2)
4289 return CanPick1 ? ImplicitConversionSequence::Better
4290 : ImplicitConversionSequence::Worse;
4291 return ImplicitConversionSequence::Indistinguishable;
4294 /// CompareDerivedToBaseConversions - Compares two standard conversion
4295 /// sequences to determine whether they can be ranked based on their
4296 /// various kinds of derived-to-base conversions (C++
4297 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4298 /// conversions between Objective-C interface types.
4299 static ImplicitConversionSequence::CompareKind
4300 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4301 const StandardConversionSequence& SCS1,
4302 const StandardConversionSequence& SCS2) {
4303 QualType FromType1 = SCS1.getFromType();
4304 QualType ToType1 = SCS1.getToType(1);
4305 QualType FromType2 = SCS2.getFromType();
4306 QualType ToType2 = SCS2.getToType(1);
4308 // Adjust the types we're converting from via the array-to-pointer
4309 // conversion, if we need to.
4310 if (SCS1.First == ICK_Array_To_Pointer)
4311 FromType1 = S.Context.getArrayDecayedType(FromType1);
4312 if (SCS2.First == ICK_Array_To_Pointer)
4313 FromType2 = S.Context.getArrayDecayedType(FromType2);
4315 // Canonicalize all of the types.
4316 FromType1 = S.Context.getCanonicalType(FromType1);
4317 ToType1 = S.Context.getCanonicalType(ToType1);
4318 FromType2 = S.Context.getCanonicalType(FromType2);
4319 ToType2 = S.Context.getCanonicalType(ToType2);
4321 // C++ [over.ics.rank]p4b3:
4323 // If class B is derived directly or indirectly from class A and
4324 // class C is derived directly or indirectly from B,
4326 // Compare based on pointer conversions.
4327 if (SCS1.Second == ICK_Pointer_Conversion &&
4328 SCS2.Second == ICK_Pointer_Conversion &&
4329 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4330 FromType1->isPointerType() && FromType2->isPointerType() &&
4331 ToType1->isPointerType() && ToType2->isPointerType()) {
4332 QualType FromPointee1 =
4333 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4334 QualType ToPointee1 =
4335 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4336 QualType FromPointee2 =
4337 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4338 QualType ToPointee2 =
4339 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4341 // -- conversion of C* to B* is better than conversion of C* to A*,
4342 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4343 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4344 return ImplicitConversionSequence::Better;
4345 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4346 return ImplicitConversionSequence::Worse;
4349 // -- conversion of B* to A* is better than conversion of C* to A*,
4350 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4351 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4352 return ImplicitConversionSequence::Better;
4353 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4354 return ImplicitConversionSequence::Worse;
4356 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4357 SCS2.Second == ICK_Pointer_Conversion) {
4358 const ObjCObjectPointerType *FromPtr1
4359 = FromType1->getAs<ObjCObjectPointerType>();
4360 const ObjCObjectPointerType *FromPtr2
4361 = FromType2->getAs<ObjCObjectPointerType>();
4362 const ObjCObjectPointerType *ToPtr1
4363 = ToType1->getAs<ObjCObjectPointerType>();
4364 const ObjCObjectPointerType *ToPtr2
4365 = ToType2->getAs<ObjCObjectPointerType>();
4367 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4368 // Apply the same conversion ranking rules for Objective-C pointer types
4369 // that we do for C++ pointers to class types. However, we employ the
4370 // Objective-C pseudo-subtyping relationship used for assignment of
4371 // Objective-C pointer types.
4372 bool FromAssignLeft
4373 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4374 bool FromAssignRight
4375 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4376 bool ToAssignLeft
4377 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4378 bool ToAssignRight
4379 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4381 // A conversion to an a non-id object pointer type or qualified 'id'
4382 // type is better than a conversion to 'id'.
4383 if (ToPtr1->isObjCIdType() &&
4384 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4385 return ImplicitConversionSequence::Worse;
4386 if (ToPtr2->isObjCIdType() &&
4387 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4388 return ImplicitConversionSequence::Better;
4390 // A conversion to a non-id object pointer type is better than a
4391 // conversion to a qualified 'id' type
4392 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4393 return ImplicitConversionSequence::Worse;
4394 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4395 return ImplicitConversionSequence::Better;
4397 // A conversion to an a non-Class object pointer type or qualified 'Class'
4398 // type is better than a conversion to 'Class'.
4399 if (ToPtr1->isObjCClassType() &&
4400 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4401 return ImplicitConversionSequence::Worse;
4402 if (ToPtr2->isObjCClassType() &&
4403 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4404 return ImplicitConversionSequence::Better;
4406 // A conversion to a non-Class object pointer type is better than a
4407 // conversion to a qualified 'Class' type.
4408 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4409 return ImplicitConversionSequence::Worse;
4410 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4411 return ImplicitConversionSequence::Better;
4413 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4414 if (S.Context.hasSameType(FromType1, FromType2) &&
4415 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4416 (ToAssignLeft != ToAssignRight)) {
4417 if (FromPtr1->isSpecialized()) {
4418 // "conversion of B<A> * to B * is better than conversion of B * to
4419 // C *.
4420 bool IsFirstSame =
4421 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4422 bool IsSecondSame =
4423 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4424 if (IsFirstSame) {
4425 if (!IsSecondSame)
4426 return ImplicitConversionSequence::Better;
4427 } else if (IsSecondSame)
4428 return ImplicitConversionSequence::Worse;
4430 return ToAssignLeft? ImplicitConversionSequence::Worse
4431 : ImplicitConversionSequence::Better;
4434 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4435 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4436 (FromAssignLeft != FromAssignRight))
4437 return FromAssignLeft? ImplicitConversionSequence::Better
4438 : ImplicitConversionSequence::Worse;
4442 // Ranking of member-pointer types.
4443 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4444 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4445 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4446 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4447 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4448 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4449 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4450 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4451 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4452 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4453 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4454 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4455 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4456 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4457 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4458 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4459 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4460 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4461 return ImplicitConversionSequence::Worse;
4462 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4463 return ImplicitConversionSequence::Better;
4465 // conversion of B::* to C::* is better than conversion of A::* to C::*
4466 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4467 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4468 return ImplicitConversionSequence::Better;
4469 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4470 return ImplicitConversionSequence::Worse;
4474 if (SCS1.Second == ICK_Derived_To_Base) {
4475 // -- conversion of C to B is better than conversion of C to A,
4476 // -- binding of an expression of type C to a reference of type
4477 // B& is better than binding an expression of type C to a
4478 // reference of type A&,
4479 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4480 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4481 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4482 return ImplicitConversionSequence::Better;
4483 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4484 return ImplicitConversionSequence::Worse;
4487 // -- conversion of B to A is better than conversion of C to A.
4488 // -- binding of an expression of type B to a reference of type
4489 // A& is better than binding an expression of type C to a
4490 // reference of type A&,
4491 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4492 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4493 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4494 return ImplicitConversionSequence::Better;
4495 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4496 return ImplicitConversionSequence::Worse;
4500 return ImplicitConversionSequence::Indistinguishable;
4503 /// Determine whether the given type is valid, e.g., it is not an invalid
4504 /// C++ class.
4505 static bool isTypeValid(QualType T) {
4506 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4507 return !Record->isInvalidDecl();
4509 return true;
4512 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4513 if (!T.getQualifiers().hasUnaligned())
4514 return T;
4516 Qualifiers Q;
4517 T = Ctx.getUnqualifiedArrayType(T, Q);
4518 Q.removeUnaligned();
4519 return Ctx.getQualifiedType(T, Q);
4522 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4523 /// determine whether they are reference-compatible,
4524 /// reference-related, or incompatible, for use in C++ initialization by
4525 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4526 /// type, and the first type (T1) is the pointee type of the reference
4527 /// type being initialized.
4528 Sema::ReferenceCompareResult
4529 Sema::CompareReferenceRelationship(SourceLocation Loc,
4530 QualType OrigT1, QualType OrigT2,
4531 ReferenceConversions *ConvOut) {
4532 assert(!OrigT1->isReferenceType() &&
4533 "T1 must be the pointee type of the reference type");
4534 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4536 QualType T1 = Context.getCanonicalType(OrigT1);
4537 QualType T2 = Context.getCanonicalType(OrigT2);
4538 Qualifiers T1Quals, T2Quals;
4539 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4540 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4542 ReferenceConversions ConvTmp;
4543 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4544 Conv = ReferenceConversions();
4546 // C++2a [dcl.init.ref]p4:
4547 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4548 // reference-related to "cv2 T2" if T1 is similar to T2, or
4549 // T1 is a base class of T2.
4550 // "cv1 T1" is reference-compatible with "cv2 T2" if
4551 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4552 // "pointer to cv1 T1" via a standard conversion sequence.
4554 // Check for standard conversions we can apply to pointers: derived-to-base
4555 // conversions, ObjC pointer conversions, and function pointer conversions.
4556 // (Qualification conversions are checked last.)
4557 QualType ConvertedT2;
4558 if (UnqualT1 == UnqualT2) {
4559 // Nothing to do.
4560 } else if (isCompleteType(Loc, OrigT2) &&
4561 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4562 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4563 Conv |= ReferenceConversions::DerivedToBase;
4564 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4565 UnqualT2->isObjCObjectOrInterfaceType() &&
4566 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4567 Conv |= ReferenceConversions::ObjC;
4568 else if (UnqualT2->isFunctionType() &&
4569 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4570 Conv |= ReferenceConversions::Function;
4571 // No need to check qualifiers; function types don't have them.
4572 return Ref_Compatible;
4574 bool ConvertedReferent = Conv != 0;
4576 // We can have a qualification conversion. Compute whether the types are
4577 // similar at the same time.
4578 bool PreviousToQualsIncludeConst = true;
4579 bool TopLevel = true;
4580 do {
4581 if (T1 == T2)
4582 break;
4584 // We will need a qualification conversion.
4585 Conv |= ReferenceConversions::Qualification;
4587 // Track whether we performed a qualification conversion anywhere other
4588 // than the top level. This matters for ranking reference bindings in
4589 // overload resolution.
4590 if (!TopLevel)
4591 Conv |= ReferenceConversions::NestedQualification;
4593 // MS compiler ignores __unaligned qualifier for references; do the same.
4594 T1 = withoutUnaligned(Context, T1);
4595 T2 = withoutUnaligned(Context, T2);
4597 // If we find a qualifier mismatch, the types are not reference-compatible,
4598 // but are still be reference-related if they're similar.
4599 bool ObjCLifetimeConversion = false;
4600 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4601 PreviousToQualsIncludeConst,
4602 ObjCLifetimeConversion))
4603 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4604 ? Ref_Related
4605 : Ref_Incompatible;
4607 // FIXME: Should we track this for any level other than the first?
4608 if (ObjCLifetimeConversion)
4609 Conv |= ReferenceConversions::ObjCLifetime;
4611 TopLevel = false;
4612 } while (Context.UnwrapSimilarTypes(T1, T2));
4614 // At this point, if the types are reference-related, we must either have the
4615 // same inner type (ignoring qualifiers), or must have already worked out how
4616 // to convert the referent.
4617 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4618 ? Ref_Compatible
4619 : Ref_Incompatible;
4622 /// Look for a user-defined conversion to a value reference-compatible
4623 /// with DeclType. Return true if something definite is found.
4624 static bool
4625 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4626 QualType DeclType, SourceLocation DeclLoc,
4627 Expr *Init, QualType T2, bool AllowRvalues,
4628 bool AllowExplicit) {
4629 assert(T2->isRecordType() && "Can only find conversions of record types.");
4630 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4632 OverloadCandidateSet CandidateSet(
4633 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4634 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4635 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4636 NamedDecl *D = *I;
4637 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4638 if (isa<UsingShadowDecl>(D))
4639 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4641 FunctionTemplateDecl *ConvTemplate
4642 = dyn_cast<FunctionTemplateDecl>(D);
4643 CXXConversionDecl *Conv;
4644 if (ConvTemplate)
4645 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4646 else
4647 Conv = cast<CXXConversionDecl>(D);
4649 if (AllowRvalues) {
4650 // If we are initializing an rvalue reference, don't permit conversion
4651 // functions that return lvalues.
4652 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4653 const ReferenceType *RefType
4654 = Conv->getConversionType()->getAs<LValueReferenceType>();
4655 if (RefType && !RefType->getPointeeType()->isFunctionType())
4656 continue;
4659 if (!ConvTemplate &&
4660 S.CompareReferenceRelationship(
4661 DeclLoc,
4662 Conv->getConversionType()
4663 .getNonReferenceType()
4664 .getUnqualifiedType(),
4665 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4666 Sema::Ref_Incompatible)
4667 continue;
4668 } else {
4669 // If the conversion function doesn't return a reference type,
4670 // it can't be considered for this conversion. An rvalue reference
4671 // is only acceptable if its referencee is a function type.
4673 const ReferenceType *RefType =
4674 Conv->getConversionType()->getAs<ReferenceType>();
4675 if (!RefType ||
4676 (!RefType->isLValueReferenceType() &&
4677 !RefType->getPointeeType()->isFunctionType()))
4678 continue;
4681 if (ConvTemplate)
4682 S.AddTemplateConversionCandidate(
4683 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4684 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4685 else
4686 S.AddConversionCandidate(
4687 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4688 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4691 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4693 OverloadCandidateSet::iterator Best;
4694 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4695 case OR_Success:
4696 // C++ [over.ics.ref]p1:
4698 // [...] If the parameter binds directly to the result of
4699 // applying a conversion function to the argument
4700 // expression, the implicit conversion sequence is a
4701 // user-defined conversion sequence (13.3.3.1.2), with the
4702 // second standard conversion sequence either an identity
4703 // conversion or, if the conversion function returns an
4704 // entity of a type that is a derived class of the parameter
4705 // type, a derived-to-base Conversion.
4706 if (!Best->FinalConversion.DirectBinding)
4707 return false;
4709 ICS.setUserDefined();
4710 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4711 ICS.UserDefined.After = Best->FinalConversion;
4712 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4713 ICS.UserDefined.ConversionFunction = Best->Function;
4714 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4715 ICS.UserDefined.EllipsisConversion = false;
4716 assert(ICS.UserDefined.After.ReferenceBinding &&
4717 ICS.UserDefined.After.DirectBinding &&
4718 "Expected a direct reference binding!");
4719 return true;
4721 case OR_Ambiguous:
4722 ICS.setAmbiguous();
4723 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4724 Cand != CandidateSet.end(); ++Cand)
4725 if (Cand->Best)
4726 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4727 return true;
4729 case OR_No_Viable_Function:
4730 case OR_Deleted:
4731 // There was no suitable conversion, or we found a deleted
4732 // conversion; continue with other checks.
4733 return false;
4736 llvm_unreachable("Invalid OverloadResult!");
4739 /// Compute an implicit conversion sequence for reference
4740 /// initialization.
4741 static ImplicitConversionSequence
4742 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4743 SourceLocation DeclLoc,
4744 bool SuppressUserConversions,
4745 bool AllowExplicit) {
4746 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4748 // Most paths end in a failed conversion.
4749 ImplicitConversionSequence ICS;
4750 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4752 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4753 QualType T2 = Init->getType();
4755 // If the initializer is the address of an overloaded function, try
4756 // to resolve the overloaded function. If all goes well, T2 is the
4757 // type of the resulting function.
4758 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4759 DeclAccessPair Found;
4760 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4761 false, Found))
4762 T2 = Fn->getType();
4765 // Compute some basic properties of the types and the initializer.
4766 bool isRValRef = DeclType->isRValueReferenceType();
4767 Expr::Classification InitCategory = Init->Classify(S.Context);
4769 Sema::ReferenceConversions RefConv;
4770 Sema::ReferenceCompareResult RefRelationship =
4771 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4773 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4774 ICS.setStandard();
4775 ICS.Standard.First = ICK_Identity;
4776 // FIXME: A reference binding can be a function conversion too. We should
4777 // consider that when ordering reference-to-function bindings.
4778 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4779 ? ICK_Derived_To_Base
4780 : (RefConv & Sema::ReferenceConversions::ObjC)
4781 ? ICK_Compatible_Conversion
4782 : ICK_Identity;
4783 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4784 // a reference binding that performs a non-top-level qualification
4785 // conversion as a qualification conversion, not as an identity conversion.
4786 ICS.Standard.Third = (RefConv &
4787 Sema::ReferenceConversions::NestedQualification)
4788 ? ICK_Qualification
4789 : ICK_Identity;
4790 ICS.Standard.setFromType(T2);
4791 ICS.Standard.setToType(0, T2);
4792 ICS.Standard.setToType(1, T1);
4793 ICS.Standard.setToType(2, T1);
4794 ICS.Standard.ReferenceBinding = true;
4795 ICS.Standard.DirectBinding = BindsDirectly;
4796 ICS.Standard.IsLvalueReference = !isRValRef;
4797 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4798 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4799 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4800 ICS.Standard.ObjCLifetimeConversionBinding =
4801 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4802 ICS.Standard.CopyConstructor = nullptr;
4803 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4806 // C++0x [dcl.init.ref]p5:
4807 // A reference to type "cv1 T1" is initialized by an expression
4808 // of type "cv2 T2" as follows:
4810 // -- If reference is an lvalue reference and the initializer expression
4811 if (!isRValRef) {
4812 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4813 // reference-compatible with "cv2 T2," or
4815 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4816 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4817 // C++ [over.ics.ref]p1:
4818 // When a parameter of reference type binds directly (8.5.3)
4819 // to an argument expression, the implicit conversion sequence
4820 // is the identity conversion, unless the argument expression
4821 // has a type that is a derived class of the parameter type,
4822 // in which case the implicit conversion sequence is a
4823 // derived-to-base Conversion (13.3.3.1).
4824 SetAsReferenceBinding(/*BindsDirectly=*/true);
4826 // Nothing more to do: the inaccessibility/ambiguity check for
4827 // derived-to-base conversions is suppressed when we're
4828 // computing the implicit conversion sequence (C++
4829 // [over.best.ics]p2).
4830 return ICS;
4833 // -- has a class type (i.e., T2 is a class type), where T1 is
4834 // not reference-related to T2, and can be implicitly
4835 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4836 // is reference-compatible with "cv3 T3" 92) (this
4837 // conversion is selected by enumerating the applicable
4838 // conversion functions (13.3.1.6) and choosing the best
4839 // one through overload resolution (13.3)),
4840 if (!SuppressUserConversions && T2->isRecordType() &&
4841 S.isCompleteType(DeclLoc, T2) &&
4842 RefRelationship == Sema::Ref_Incompatible) {
4843 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4844 Init, T2, /*AllowRvalues=*/false,
4845 AllowExplicit))
4846 return ICS;
4850 // -- Otherwise, the reference shall be an lvalue reference to a
4851 // non-volatile const type (i.e., cv1 shall be const), or the reference
4852 // shall be an rvalue reference.
4853 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4854 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4855 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4856 return ICS;
4859 // -- If the initializer expression
4861 // -- is an xvalue, class prvalue, array prvalue or function
4862 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4863 if (RefRelationship == Sema::Ref_Compatible &&
4864 (InitCategory.isXValue() ||
4865 (InitCategory.isPRValue() &&
4866 (T2->isRecordType() || T2->isArrayType())) ||
4867 (InitCategory.isLValue() && T2->isFunctionType()))) {
4868 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4869 // binding unless we're binding to a class prvalue.
4870 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4871 // allow the use of rvalue references in C++98/03 for the benefit of
4872 // standard library implementors; therefore, we need the xvalue check here.
4873 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4874 !(InitCategory.isPRValue() || T2->isRecordType()));
4875 return ICS;
4878 // -- has a class type (i.e., T2 is a class type), where T1 is not
4879 // reference-related to T2, and can be implicitly converted to
4880 // an xvalue, class prvalue, or function lvalue of type
4881 // "cv3 T3", where "cv1 T1" is reference-compatible with
4882 // "cv3 T3",
4884 // then the reference is bound to the value of the initializer
4885 // expression in the first case and to the result of the conversion
4886 // in the second case (or, in either case, to an appropriate base
4887 // class subobject).
4888 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4889 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4890 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4891 Init, T2, /*AllowRvalues=*/true,
4892 AllowExplicit)) {
4893 // In the second case, if the reference is an rvalue reference
4894 // and the second standard conversion sequence of the
4895 // user-defined conversion sequence includes an lvalue-to-rvalue
4896 // conversion, the program is ill-formed.
4897 if (ICS.isUserDefined() && isRValRef &&
4898 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4899 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4901 return ICS;
4904 // A temporary of function type cannot be created; don't even try.
4905 if (T1->isFunctionType())
4906 return ICS;
4908 // -- Otherwise, a temporary of type "cv1 T1" is created and
4909 // initialized from the initializer expression using the
4910 // rules for a non-reference copy initialization (8.5). The
4911 // reference is then bound to the temporary. If T1 is
4912 // reference-related to T2, cv1 must be the same
4913 // cv-qualification as, or greater cv-qualification than,
4914 // cv2; otherwise, the program is ill-formed.
4915 if (RefRelationship == Sema::Ref_Related) {
4916 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4917 // we would be reference-compatible or reference-compatible with
4918 // added qualification. But that wasn't the case, so the reference
4919 // initialization fails.
4921 // Note that we only want to check address spaces and cvr-qualifiers here.
4922 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4923 Qualifiers T1Quals = T1.getQualifiers();
4924 Qualifiers T2Quals = T2.getQualifiers();
4925 T1Quals.removeObjCGCAttr();
4926 T1Quals.removeObjCLifetime();
4927 T2Quals.removeObjCGCAttr();
4928 T2Quals.removeObjCLifetime();
4929 // MS compiler ignores __unaligned qualifier for references; do the same.
4930 T1Quals.removeUnaligned();
4931 T2Quals.removeUnaligned();
4932 if (!T1Quals.compatiblyIncludes(T2Quals))
4933 return ICS;
4936 // If at least one of the types is a class type, the types are not
4937 // related, and we aren't allowed any user conversions, the
4938 // reference binding fails. This case is important for breaking
4939 // recursion, since TryImplicitConversion below will attempt to
4940 // create a temporary through the use of a copy constructor.
4941 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4942 (T1->isRecordType() || T2->isRecordType()))
4943 return ICS;
4945 // If T1 is reference-related to T2 and the reference is an rvalue
4946 // reference, the initializer expression shall not be an lvalue.
4947 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4948 Init->Classify(S.Context).isLValue()) {
4949 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4950 return ICS;
4953 // C++ [over.ics.ref]p2:
4954 // When a parameter of reference type is not bound directly to
4955 // an argument expression, the conversion sequence is the one
4956 // required to convert the argument expression to the
4957 // underlying type of the reference according to
4958 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4959 // to copy-initializing a temporary of the underlying type with
4960 // the argument expression. Any difference in top-level
4961 // cv-qualification is subsumed by the initialization itself
4962 // and does not constitute a conversion.
4963 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4964 AllowedExplicit::None,
4965 /*InOverloadResolution=*/false,
4966 /*CStyle=*/false,
4967 /*AllowObjCWritebackConversion=*/false,
4968 /*AllowObjCConversionOnExplicit=*/false);
4970 // Of course, that's still a reference binding.
4971 if (ICS.isStandard()) {
4972 ICS.Standard.ReferenceBinding = true;
4973 ICS.Standard.IsLvalueReference = !isRValRef;
4974 ICS.Standard.BindsToFunctionLvalue = false;
4975 ICS.Standard.BindsToRvalue = true;
4976 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4977 ICS.Standard.ObjCLifetimeConversionBinding = false;
4978 } else if (ICS.isUserDefined()) {
4979 const ReferenceType *LValRefType =
4980 ICS.UserDefined.ConversionFunction->getReturnType()
4981 ->getAs<LValueReferenceType>();
4983 // C++ [over.ics.ref]p3:
4984 // Except for an implicit object parameter, for which see 13.3.1, a
4985 // standard conversion sequence cannot be formed if it requires [...]
4986 // binding an rvalue reference to an lvalue other than a function
4987 // lvalue.
4988 // Note that the function case is not possible here.
4989 if (isRValRef && LValRefType) {
4990 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4991 return ICS;
4994 ICS.UserDefined.After.ReferenceBinding = true;
4995 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4996 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4997 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4998 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4999 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5002 return ICS;
5005 static ImplicitConversionSequence
5006 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5007 bool SuppressUserConversions,
5008 bool InOverloadResolution,
5009 bool AllowObjCWritebackConversion,
5010 bool AllowExplicit = false);
5012 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5013 /// initializer list From.
5014 static ImplicitConversionSequence
5015 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5016 bool SuppressUserConversions,
5017 bool InOverloadResolution,
5018 bool AllowObjCWritebackConversion) {
5019 // C++11 [over.ics.list]p1:
5020 // When an argument is an initializer list, it is not an expression and
5021 // special rules apply for converting it to a parameter type.
5023 ImplicitConversionSequence Result;
5024 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5026 // We need a complete type for what follows. With one C++20 exception,
5027 // incomplete types can never be initialized from init lists.
5028 QualType InitTy = ToType;
5029 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5030 if (AT && S.getLangOpts().CPlusPlus20)
5031 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5032 // C++20 allows list initialization of an incomplete array type.
5033 InitTy = IAT->getElementType();
5034 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5035 return Result;
5037 // Per DR1467:
5038 // If the parameter type is a class X and the initializer list has a single
5039 // element of type cv U, where U is X or a class derived from X, the
5040 // implicit conversion sequence is the one required to convert the element
5041 // to the parameter type.
5043 // Otherwise, if the parameter type is a character array [... ]
5044 // and the initializer list has a single element that is an
5045 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5046 // implicit conversion sequence is the identity conversion.
5047 if (From->getNumInits() == 1) {
5048 if (ToType->isRecordType()) {
5049 QualType InitType = From->getInit(0)->getType();
5050 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5051 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5052 return TryCopyInitialization(S, From->getInit(0), ToType,
5053 SuppressUserConversions,
5054 InOverloadResolution,
5055 AllowObjCWritebackConversion);
5058 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5059 InitializedEntity Entity =
5060 InitializedEntity::InitializeParameter(S.Context, ToType,
5061 /*Consumed=*/false);
5062 if (S.CanPerformCopyInitialization(Entity, From)) {
5063 Result.setStandard();
5064 Result.Standard.setAsIdentityConversion();
5065 Result.Standard.setFromType(ToType);
5066 Result.Standard.setAllToTypes(ToType);
5067 return Result;
5072 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5073 // C++11 [over.ics.list]p2:
5074 // If the parameter type is std::initializer_list<X> or "array of X" and
5075 // all the elements can be implicitly converted to X, the implicit
5076 // conversion sequence is the worst conversion necessary to convert an
5077 // element of the list to X.
5079 // C++14 [over.ics.list]p3:
5080 // Otherwise, if the parameter type is "array of N X", if the initializer
5081 // list has exactly N elements or if it has fewer than N elements and X is
5082 // default-constructible, and if all the elements of the initializer list
5083 // can be implicitly converted to X, the implicit conversion sequence is
5084 // the worst conversion necessary to convert an element of the list to X.
5085 if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5086 unsigned e = From->getNumInits();
5087 ImplicitConversionSequence DfltElt;
5088 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5089 QualType());
5090 QualType ContTy = ToType;
5091 bool IsUnbounded = false;
5092 if (AT) {
5093 InitTy = AT->getElementType();
5094 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5095 if (CT->getSize().ult(e)) {
5096 // Too many inits, fatally bad
5097 Result.setBad(BadConversionSequence::too_many_initializers, From,
5098 ToType);
5099 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5100 return Result;
5102 if (CT->getSize().ugt(e)) {
5103 // Need an init from empty {}, is there one?
5104 InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5105 From->getEndLoc());
5106 EmptyList.setType(S.Context.VoidTy);
5107 DfltElt = TryListConversion(
5108 S, &EmptyList, InitTy, SuppressUserConversions,
5109 InOverloadResolution, AllowObjCWritebackConversion);
5110 if (DfltElt.isBad()) {
5111 // No {} init, fatally bad
5112 Result.setBad(BadConversionSequence::too_few_initializers, From,
5113 ToType);
5114 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5115 return Result;
5118 } else {
5119 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5120 IsUnbounded = true;
5121 if (!e) {
5122 // Cannot convert to zero-sized.
5123 Result.setBad(BadConversionSequence::too_few_initializers, From,
5124 ToType);
5125 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5126 return Result;
5128 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5129 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5130 ArrayType::Normal, 0);
5134 Result.setStandard();
5135 Result.Standard.setAsIdentityConversion();
5136 Result.Standard.setFromType(InitTy);
5137 Result.Standard.setAllToTypes(InitTy);
5138 for (unsigned i = 0; i < e; ++i) {
5139 Expr *Init = From->getInit(i);
5140 ImplicitConversionSequence ICS = TryCopyInitialization(
5141 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5142 AllowObjCWritebackConversion);
5144 // Keep the worse conversion seen so far.
5145 // FIXME: Sequences are not totally ordered, so 'worse' can be
5146 // ambiguous. CWG has been informed.
5147 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5148 Result) ==
5149 ImplicitConversionSequence::Worse) {
5150 Result = ICS;
5151 // Bail as soon as we find something unconvertible.
5152 if (Result.isBad()) {
5153 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5154 return Result;
5159 // If we needed any implicit {} initialization, compare that now.
5160 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5161 // has been informed that this might not be the best thing.
5162 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5163 S, From->getEndLoc(), DfltElt, Result) ==
5164 ImplicitConversionSequence::Worse)
5165 Result = DfltElt;
5166 // Record the type being initialized so that we may compare sequences
5167 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5168 return Result;
5171 // C++14 [over.ics.list]p4:
5172 // C++11 [over.ics.list]p3:
5173 // Otherwise, if the parameter is a non-aggregate class X and overload
5174 // resolution chooses a single best constructor [...] the implicit
5175 // conversion sequence is a user-defined conversion sequence. If multiple
5176 // constructors are viable but none is better than the others, the
5177 // implicit conversion sequence is a user-defined conversion sequence.
5178 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5179 // This function can deal with initializer lists.
5180 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5181 AllowedExplicit::None,
5182 InOverloadResolution, /*CStyle=*/false,
5183 AllowObjCWritebackConversion,
5184 /*AllowObjCConversionOnExplicit=*/false);
5187 // C++14 [over.ics.list]p5:
5188 // C++11 [over.ics.list]p4:
5189 // Otherwise, if the parameter has an aggregate type which can be
5190 // initialized from the initializer list [...] the implicit conversion
5191 // sequence is a user-defined conversion sequence.
5192 if (ToType->isAggregateType()) {
5193 // Type is an aggregate, argument is an init list. At this point it comes
5194 // down to checking whether the initialization works.
5195 // FIXME: Find out whether this parameter is consumed or not.
5196 InitializedEntity Entity =
5197 InitializedEntity::InitializeParameter(S.Context, ToType,
5198 /*Consumed=*/false);
5199 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5200 From)) {
5201 Result.setUserDefined();
5202 Result.UserDefined.Before.setAsIdentityConversion();
5203 // Initializer lists don't have a type.
5204 Result.UserDefined.Before.setFromType(QualType());
5205 Result.UserDefined.Before.setAllToTypes(QualType());
5207 Result.UserDefined.After.setAsIdentityConversion();
5208 Result.UserDefined.After.setFromType(ToType);
5209 Result.UserDefined.After.setAllToTypes(ToType);
5210 Result.UserDefined.ConversionFunction = nullptr;
5212 return Result;
5215 // C++14 [over.ics.list]p6:
5216 // C++11 [over.ics.list]p5:
5217 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5218 if (ToType->isReferenceType()) {
5219 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5220 // mention initializer lists in any way. So we go by what list-
5221 // initialization would do and try to extrapolate from that.
5223 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5225 // If the initializer list has a single element that is reference-related
5226 // to the parameter type, we initialize the reference from that.
5227 if (From->getNumInits() == 1) {
5228 Expr *Init = From->getInit(0);
5230 QualType T2 = Init->getType();
5232 // If the initializer is the address of an overloaded function, try
5233 // to resolve the overloaded function. If all goes well, T2 is the
5234 // type of the resulting function.
5235 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5236 DeclAccessPair Found;
5237 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5238 Init, ToType, false, Found))
5239 T2 = Fn->getType();
5242 // Compute some basic properties of the types and the initializer.
5243 Sema::ReferenceCompareResult RefRelationship =
5244 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5246 if (RefRelationship >= Sema::Ref_Related) {
5247 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5248 SuppressUserConversions,
5249 /*AllowExplicit=*/false);
5253 // Otherwise, we bind the reference to a temporary created from the
5254 // initializer list.
5255 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5256 InOverloadResolution,
5257 AllowObjCWritebackConversion);
5258 if (Result.isFailure())
5259 return Result;
5260 assert(!Result.isEllipsis() &&
5261 "Sub-initialization cannot result in ellipsis conversion.");
5263 // Can we even bind to a temporary?
5264 if (ToType->isRValueReferenceType() ||
5265 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5266 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5267 Result.UserDefined.After;
5268 SCS.ReferenceBinding = true;
5269 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5270 SCS.BindsToRvalue = true;
5271 SCS.BindsToFunctionLvalue = false;
5272 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5273 SCS.ObjCLifetimeConversionBinding = false;
5274 } else
5275 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5276 From, ToType);
5277 return Result;
5280 // C++14 [over.ics.list]p7:
5281 // C++11 [over.ics.list]p6:
5282 // Otherwise, if the parameter type is not a class:
5283 if (!ToType->isRecordType()) {
5284 // - if the initializer list has one element that is not itself an
5285 // initializer list, the implicit conversion sequence is the one
5286 // required to convert the element to the parameter type.
5287 unsigned NumInits = From->getNumInits();
5288 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5289 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5290 SuppressUserConversions,
5291 InOverloadResolution,
5292 AllowObjCWritebackConversion);
5293 // - if the initializer list has no elements, the implicit conversion
5294 // sequence is the identity conversion.
5295 else if (NumInits == 0) {
5296 Result.setStandard();
5297 Result.Standard.setAsIdentityConversion();
5298 Result.Standard.setFromType(ToType);
5299 Result.Standard.setAllToTypes(ToType);
5301 return Result;
5304 // C++14 [over.ics.list]p8:
5305 // C++11 [over.ics.list]p7:
5306 // In all cases other than those enumerated above, no conversion is possible
5307 return Result;
5310 /// TryCopyInitialization - Try to copy-initialize a value of type
5311 /// ToType from the expression From. Return the implicit conversion
5312 /// sequence required to pass this argument, which may be a bad
5313 /// conversion sequence (meaning that the argument cannot be passed to
5314 /// a parameter of this type). If @p SuppressUserConversions, then we
5315 /// do not permit any user-defined conversion sequences.
5316 static ImplicitConversionSequence
5317 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5318 bool SuppressUserConversions,
5319 bool InOverloadResolution,
5320 bool AllowObjCWritebackConversion,
5321 bool AllowExplicit) {
5322 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5323 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5324 InOverloadResolution,AllowObjCWritebackConversion);
5326 if (ToType->isReferenceType())
5327 return TryReferenceInit(S, From, ToType,
5328 /*FIXME:*/ From->getBeginLoc(),
5329 SuppressUserConversions, AllowExplicit);
5331 return TryImplicitConversion(S, From, ToType,
5332 SuppressUserConversions,
5333 AllowedExplicit::None,
5334 InOverloadResolution,
5335 /*CStyle=*/false,
5336 AllowObjCWritebackConversion,
5337 /*AllowObjCConversionOnExplicit=*/false);
5340 static bool TryCopyInitialization(const CanQualType FromQTy,
5341 const CanQualType ToQTy,
5342 Sema &S,
5343 SourceLocation Loc,
5344 ExprValueKind FromVK) {
5345 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5346 ImplicitConversionSequence ICS =
5347 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5349 return !ICS.isBad();
5352 /// TryObjectArgumentInitialization - Try to initialize the object
5353 /// parameter of the given member function (@c Method) from the
5354 /// expression @p From.
5355 static ImplicitConversionSequence
5356 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5357 Expr::Classification FromClassification,
5358 CXXMethodDecl *Method,
5359 CXXRecordDecl *ActingContext) {
5360 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5361 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5362 // const volatile object.
5363 Qualifiers Quals = Method->getMethodQualifiers();
5364 if (isa<CXXDestructorDecl>(Method)) {
5365 Quals.addConst();
5366 Quals.addVolatile();
5369 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5371 // Set up the conversion sequence as a "bad" conversion, to allow us
5372 // to exit early.
5373 ImplicitConversionSequence ICS;
5375 // We need to have an object of class type.
5376 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5377 FromType = PT->getPointeeType();
5379 // When we had a pointer, it's implicitly dereferenced, so we
5380 // better have an lvalue.
5381 assert(FromClassification.isLValue());
5384 assert(FromType->isRecordType());
5386 // C++0x [over.match.funcs]p4:
5387 // For non-static member functions, the type of the implicit object
5388 // parameter is
5390 // - "lvalue reference to cv X" for functions declared without a
5391 // ref-qualifier or with the & ref-qualifier
5392 // - "rvalue reference to cv X" for functions declared with the &&
5393 // ref-qualifier
5395 // where X is the class of which the function is a member and cv is the
5396 // cv-qualification on the member function declaration.
5398 // However, when finding an implicit conversion sequence for the argument, we
5399 // are not allowed to perform user-defined conversions
5400 // (C++ [over.match.funcs]p5). We perform a simplified version of
5401 // reference binding here, that allows class rvalues to bind to
5402 // non-constant references.
5404 // First check the qualifiers.
5405 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5406 if (ImplicitParamType.getCVRQualifiers()
5407 != FromTypeCanon.getLocalCVRQualifiers() &&
5408 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5409 ICS.setBad(BadConversionSequence::bad_qualifiers,
5410 FromType, ImplicitParamType);
5411 return ICS;
5414 if (FromTypeCanon.hasAddressSpace()) {
5415 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5416 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5417 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5418 ICS.setBad(BadConversionSequence::bad_qualifiers,
5419 FromType, ImplicitParamType);
5420 return ICS;
5424 // Check that we have either the same type or a derived type. It
5425 // affects the conversion rank.
5426 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5427 ImplicitConversionKind SecondKind;
5428 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5429 SecondKind = ICK_Identity;
5430 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5431 SecondKind = ICK_Derived_To_Base;
5432 else {
5433 ICS.setBad(BadConversionSequence::unrelated_class,
5434 FromType, ImplicitParamType);
5435 return ICS;
5438 // Check the ref-qualifier.
5439 switch (Method->getRefQualifier()) {
5440 case RQ_None:
5441 // Do nothing; we don't care about lvalueness or rvalueness.
5442 break;
5444 case RQ_LValue:
5445 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5446 // non-const lvalue reference cannot bind to an rvalue
5447 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5448 ImplicitParamType);
5449 return ICS;
5451 break;
5453 case RQ_RValue:
5454 if (!FromClassification.isRValue()) {
5455 // rvalue reference cannot bind to an lvalue
5456 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5457 ImplicitParamType);
5458 return ICS;
5460 break;
5463 // Success. Mark this as a reference binding.
5464 ICS.setStandard();
5465 ICS.Standard.setAsIdentityConversion();
5466 ICS.Standard.Second = SecondKind;
5467 ICS.Standard.setFromType(FromType);
5468 ICS.Standard.setAllToTypes(ImplicitParamType);
5469 ICS.Standard.ReferenceBinding = true;
5470 ICS.Standard.DirectBinding = true;
5471 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5472 ICS.Standard.BindsToFunctionLvalue = false;
5473 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5474 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5475 = (Method->getRefQualifier() == RQ_None);
5476 return ICS;
5479 /// PerformObjectArgumentInitialization - Perform initialization of
5480 /// the implicit object parameter for the given Method with the given
5481 /// expression.
5482 ExprResult
5483 Sema::PerformObjectArgumentInitialization(Expr *From,
5484 NestedNameSpecifier *Qualifier,
5485 NamedDecl *FoundDecl,
5486 CXXMethodDecl *Method) {
5487 QualType FromRecordType, DestType;
5488 QualType ImplicitParamRecordType =
5489 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5491 Expr::Classification FromClassification;
5492 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5493 FromRecordType = PT->getPointeeType();
5494 DestType = Method->getThisType();
5495 FromClassification = Expr::Classification::makeSimpleLValue();
5496 } else {
5497 FromRecordType = From->getType();
5498 DestType = ImplicitParamRecordType;
5499 FromClassification = From->Classify(Context);
5501 // When performing member access on a prvalue, materialize a temporary.
5502 if (From->isPRValue()) {
5503 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5504 Method->getRefQualifier() !=
5505 RefQualifierKind::RQ_RValue);
5509 // Note that we always use the true parent context when performing
5510 // the actual argument initialization.
5511 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5512 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5513 Method->getParent());
5514 if (ICS.isBad()) {
5515 switch (ICS.Bad.Kind) {
5516 case BadConversionSequence::bad_qualifiers: {
5517 Qualifiers FromQs = FromRecordType.getQualifiers();
5518 Qualifiers ToQs = DestType.getQualifiers();
5519 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5520 if (CVR) {
5521 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5522 << Method->getDeclName() << FromRecordType << (CVR - 1)
5523 << From->getSourceRange();
5524 Diag(Method->getLocation(), diag::note_previous_decl)
5525 << Method->getDeclName();
5526 return ExprError();
5528 break;
5531 case BadConversionSequence::lvalue_ref_to_rvalue:
5532 case BadConversionSequence::rvalue_ref_to_lvalue: {
5533 bool IsRValueQualified =
5534 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5535 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5536 << Method->getDeclName() << FromClassification.isRValue()
5537 << IsRValueQualified;
5538 Diag(Method->getLocation(), diag::note_previous_decl)
5539 << Method->getDeclName();
5540 return ExprError();
5543 case BadConversionSequence::no_conversion:
5544 case BadConversionSequence::unrelated_class:
5545 break;
5547 case BadConversionSequence::too_few_initializers:
5548 case BadConversionSequence::too_many_initializers:
5549 llvm_unreachable("Lists are not objects");
5552 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5553 << ImplicitParamRecordType << FromRecordType
5554 << From->getSourceRange();
5557 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5558 ExprResult FromRes =
5559 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5560 if (FromRes.isInvalid())
5561 return ExprError();
5562 From = FromRes.get();
5565 if (!Context.hasSameType(From->getType(), DestType)) {
5566 CastKind CK;
5567 QualType PteeTy = DestType->getPointeeType();
5568 LangAS DestAS =
5569 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5570 if (FromRecordType.getAddressSpace() != DestAS)
5571 CK = CK_AddressSpaceConversion;
5572 else
5573 CK = CK_NoOp;
5574 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5576 return From;
5579 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5580 /// expression From to bool (C++0x [conv]p3).
5581 static ImplicitConversionSequence
5582 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5583 // C++ [dcl.init]/17.8:
5584 // - Otherwise, if the initialization is direct-initialization, the source
5585 // type is std::nullptr_t, and the destination type is bool, the initial
5586 // value of the object being initialized is false.
5587 if (From->getType()->isNullPtrType())
5588 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5589 S.Context.BoolTy,
5590 From->isGLValue());
5592 // All other direct-initialization of bool is equivalent to an implicit
5593 // conversion to bool in which explicit conversions are permitted.
5594 return TryImplicitConversion(S, From, S.Context.BoolTy,
5595 /*SuppressUserConversions=*/false,
5596 AllowedExplicit::Conversions,
5597 /*InOverloadResolution=*/false,
5598 /*CStyle=*/false,
5599 /*AllowObjCWritebackConversion=*/false,
5600 /*AllowObjCConversionOnExplicit=*/false);
5603 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5604 /// of the expression From to bool (C++0x [conv]p3).
5605 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5606 if (checkPlaceholderForOverload(*this, From))
5607 return ExprError();
5609 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5610 if (!ICS.isBad())
5611 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5613 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5614 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5615 << From->getType() << From->getSourceRange();
5616 return ExprError();
5619 /// Check that the specified conversion is permitted in a converted constant
5620 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5621 /// is acceptable.
5622 static bool CheckConvertedConstantConversions(Sema &S,
5623 StandardConversionSequence &SCS) {
5624 // Since we know that the target type is an integral or unscoped enumeration
5625 // type, most conversion kinds are impossible. All possible First and Third
5626 // conversions are fine.
5627 switch (SCS.Second) {
5628 case ICK_Identity:
5629 case ICK_Integral_Promotion:
5630 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5631 case ICK_Zero_Queue_Conversion:
5632 return true;
5634 case ICK_Boolean_Conversion:
5635 // Conversion from an integral or unscoped enumeration type to bool is
5636 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5637 // conversion, so we allow it in a converted constant expression.
5639 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5640 // a lot of popular code. We should at least add a warning for this
5641 // (non-conforming) extension.
5642 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5643 SCS.getToType(2)->isBooleanType();
5645 case ICK_Pointer_Conversion:
5646 case ICK_Pointer_Member:
5647 // C++1z: null pointer conversions and null member pointer conversions are
5648 // only permitted if the source type is std::nullptr_t.
5649 return SCS.getFromType()->isNullPtrType();
5651 case ICK_Floating_Promotion:
5652 case ICK_Complex_Promotion:
5653 case ICK_Floating_Conversion:
5654 case ICK_Complex_Conversion:
5655 case ICK_Floating_Integral:
5656 case ICK_Compatible_Conversion:
5657 case ICK_Derived_To_Base:
5658 case ICK_Vector_Conversion:
5659 case ICK_SVE_Vector_Conversion:
5660 case ICK_Vector_Splat:
5661 case ICK_Complex_Real:
5662 case ICK_Block_Pointer_Conversion:
5663 case ICK_TransparentUnionConversion:
5664 case ICK_Writeback_Conversion:
5665 case ICK_Zero_Event_Conversion:
5666 case ICK_C_Only_Conversion:
5667 case ICK_Incompatible_Pointer_Conversion:
5668 return false;
5670 case ICK_Lvalue_To_Rvalue:
5671 case ICK_Array_To_Pointer:
5672 case ICK_Function_To_Pointer:
5673 llvm_unreachable("found a first conversion kind in Second");
5675 case ICK_Function_Conversion:
5676 case ICK_Qualification:
5677 llvm_unreachable("found a third conversion kind in Second");
5679 case ICK_Num_Conversion_Kinds:
5680 break;
5683 llvm_unreachable("unknown conversion kind");
5686 /// CheckConvertedConstantExpression - Check that the expression From is a
5687 /// converted constant expression of type T, perform the conversion and produce
5688 /// the converted expression, per C++11 [expr.const]p3.
5689 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5690 QualType T, APValue &Value,
5691 Sema::CCEKind CCE,
5692 bool RequireInt,
5693 NamedDecl *Dest) {
5694 assert(S.getLangOpts().CPlusPlus11 &&
5695 "converted constant expression outside C++11");
5697 if (checkPlaceholderForOverload(S, From))
5698 return ExprError();
5700 // C++1z [expr.const]p3:
5701 // A converted constant expression of type T is an expression,
5702 // implicitly converted to type T, where the converted
5703 // expression is a constant expression and the implicit conversion
5704 // sequence contains only [... list of conversions ...].
5705 ImplicitConversionSequence ICS =
5706 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5707 ? TryContextuallyConvertToBool(S, From)
5708 : TryCopyInitialization(S, From, T,
5709 /*SuppressUserConversions=*/false,
5710 /*InOverloadResolution=*/false,
5711 /*AllowObjCWritebackConversion=*/false,
5712 /*AllowExplicit=*/false);
5713 StandardConversionSequence *SCS = nullptr;
5714 switch (ICS.getKind()) {
5715 case ImplicitConversionSequence::StandardConversion:
5716 SCS = &ICS.Standard;
5717 break;
5718 case ImplicitConversionSequence::UserDefinedConversion:
5719 if (T->isRecordType())
5720 SCS = &ICS.UserDefined.Before;
5721 else
5722 SCS = &ICS.UserDefined.After;
5723 break;
5724 case ImplicitConversionSequence::AmbiguousConversion:
5725 case ImplicitConversionSequence::BadConversion:
5726 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5727 return S.Diag(From->getBeginLoc(),
5728 diag::err_typecheck_converted_constant_expression)
5729 << From->getType() << From->getSourceRange() << T;
5730 return ExprError();
5732 case ImplicitConversionSequence::EllipsisConversion:
5733 llvm_unreachable("ellipsis conversion in converted constant expression");
5736 // Check that we would only use permitted conversions.
5737 if (!CheckConvertedConstantConversions(S, *SCS)) {
5738 return S.Diag(From->getBeginLoc(),
5739 diag::err_typecheck_converted_constant_expression_disallowed)
5740 << From->getType() << From->getSourceRange() << T;
5742 // [...] and where the reference binding (if any) binds directly.
5743 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5744 return S.Diag(From->getBeginLoc(),
5745 diag::err_typecheck_converted_constant_expression_indirect)
5746 << From->getType() << From->getSourceRange() << T;
5749 // Usually we can simply apply the ImplicitConversionSequence we formed
5750 // earlier, but that's not guaranteed to work when initializing an object of
5751 // class type.
5752 ExprResult Result;
5753 if (T->isRecordType()) {
5754 assert(CCE == Sema::CCEK_TemplateArg &&
5755 "unexpected class type converted constant expr");
5756 Result = S.PerformCopyInitialization(
5757 InitializedEntity::InitializeTemplateParameter(
5758 T, cast<NonTypeTemplateParmDecl>(Dest)),
5759 SourceLocation(), From);
5760 } else {
5761 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5763 if (Result.isInvalid())
5764 return Result;
5766 // C++2a [intro.execution]p5:
5767 // A full-expression is [...] a constant-expression [...]
5768 Result =
5769 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5770 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5771 if (Result.isInvalid())
5772 return Result;
5774 // Check for a narrowing implicit conversion.
5775 bool ReturnPreNarrowingValue = false;
5776 APValue PreNarrowingValue;
5777 QualType PreNarrowingType;
5778 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5779 PreNarrowingType)) {
5780 case NK_Dependent_Narrowing:
5781 // Implicit conversion to a narrower type, but the expression is
5782 // value-dependent so we can't tell whether it's actually narrowing.
5783 case NK_Variable_Narrowing:
5784 // Implicit conversion to a narrower type, and the value is not a constant
5785 // expression. We'll diagnose this in a moment.
5786 case NK_Not_Narrowing:
5787 break;
5789 case NK_Constant_Narrowing:
5790 if (CCE == Sema::CCEK_ArrayBound &&
5791 PreNarrowingType->isIntegralOrEnumerationType() &&
5792 PreNarrowingValue.isInt()) {
5793 // Don't diagnose array bound narrowing here; we produce more precise
5794 // errors by allowing the un-narrowed value through.
5795 ReturnPreNarrowingValue = true;
5796 break;
5798 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5799 << CCE << /*Constant*/ 1
5800 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5801 break;
5803 case NK_Type_Narrowing:
5804 // FIXME: It would be better to diagnose that the expression is not a
5805 // constant expression.
5806 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5807 << CCE << /*Constant*/ 0 << From->getType() << T;
5808 break;
5811 if (Result.get()->isValueDependent()) {
5812 Value = APValue();
5813 return Result;
5816 // Check the expression is a constant expression.
5817 SmallVector<PartialDiagnosticAt, 8> Notes;
5818 Expr::EvalResult Eval;
5819 Eval.Diag = &Notes;
5821 ConstantExprKind Kind;
5822 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5823 Kind = ConstantExprKind::ClassTemplateArgument;
5824 else if (CCE == Sema::CCEK_TemplateArg)
5825 Kind = ConstantExprKind::NonClassTemplateArgument;
5826 else
5827 Kind = ConstantExprKind::Normal;
5829 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5830 (RequireInt && !Eval.Val.isInt())) {
5831 // The expression can't be folded, so we can't keep it at this position in
5832 // the AST.
5833 Result = ExprError();
5834 } else {
5835 Value = Eval.Val;
5837 if (Notes.empty()) {
5838 // It's a constant expression.
5839 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5840 if (ReturnPreNarrowingValue)
5841 Value = std::move(PreNarrowingValue);
5842 return E;
5846 // It's not a constant expression. Produce an appropriate diagnostic.
5847 if (Notes.size() == 1 &&
5848 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5849 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5850 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5851 diag::note_constexpr_invalid_template_arg) {
5852 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5853 for (unsigned I = 0; I < Notes.size(); ++I)
5854 S.Diag(Notes[I].first, Notes[I].second);
5855 } else {
5856 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5857 << CCE << From->getSourceRange();
5858 for (unsigned I = 0; I < Notes.size(); ++I)
5859 S.Diag(Notes[I].first, Notes[I].second);
5861 return ExprError();
5864 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5865 APValue &Value, CCEKind CCE,
5866 NamedDecl *Dest) {
5867 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5868 Dest);
5871 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5872 llvm::APSInt &Value,
5873 CCEKind CCE) {
5874 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5876 APValue V;
5877 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5878 /*Dest=*/nullptr);
5879 if (!R.isInvalid() && !R.get()->isValueDependent())
5880 Value = V.getInt();
5881 return R;
5885 /// dropPointerConversions - If the given standard conversion sequence
5886 /// involves any pointer conversions, remove them. This may change
5887 /// the result type of the conversion sequence.
5888 static void dropPointerConversion(StandardConversionSequence &SCS) {
5889 if (SCS.Second == ICK_Pointer_Conversion) {
5890 SCS.Second = ICK_Identity;
5891 SCS.Third = ICK_Identity;
5892 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5896 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5897 /// convert the expression From to an Objective-C pointer type.
5898 static ImplicitConversionSequence
5899 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5900 // Do an implicit conversion to 'id'.
5901 QualType Ty = S.Context.getObjCIdType();
5902 ImplicitConversionSequence ICS
5903 = TryImplicitConversion(S, From, Ty,
5904 // FIXME: Are these flags correct?
5905 /*SuppressUserConversions=*/false,
5906 AllowedExplicit::Conversions,
5907 /*InOverloadResolution=*/false,
5908 /*CStyle=*/false,
5909 /*AllowObjCWritebackConversion=*/false,
5910 /*AllowObjCConversionOnExplicit=*/true);
5912 // Strip off any final conversions to 'id'.
5913 switch (ICS.getKind()) {
5914 case ImplicitConversionSequence::BadConversion:
5915 case ImplicitConversionSequence::AmbiguousConversion:
5916 case ImplicitConversionSequence::EllipsisConversion:
5917 break;
5919 case ImplicitConversionSequence::UserDefinedConversion:
5920 dropPointerConversion(ICS.UserDefined.After);
5921 break;
5923 case ImplicitConversionSequence::StandardConversion:
5924 dropPointerConversion(ICS.Standard);
5925 break;
5928 return ICS;
5931 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5932 /// conversion of the expression From to an Objective-C pointer type.
5933 /// Returns a valid but null ExprResult if no conversion sequence exists.
5934 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5935 if (checkPlaceholderForOverload(*this, From))
5936 return ExprError();
5938 QualType Ty = Context.getObjCIdType();
5939 ImplicitConversionSequence ICS =
5940 TryContextuallyConvertToObjCPointer(*this, From);
5941 if (!ICS.isBad())
5942 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5943 return ExprResult();
5946 /// Determine whether the provided type is an integral type, or an enumeration
5947 /// type of a permitted flavor.
5948 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5949 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5950 : T->isIntegralOrUnscopedEnumerationType();
5953 static ExprResult
5954 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5955 Sema::ContextualImplicitConverter &Converter,
5956 QualType T, UnresolvedSetImpl &ViableConversions) {
5958 if (Converter.Suppress)
5959 return ExprError();
5961 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5962 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5963 CXXConversionDecl *Conv =
5964 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5965 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5966 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5968 return From;
5971 static bool
5972 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5973 Sema::ContextualImplicitConverter &Converter,
5974 QualType T, bool HadMultipleCandidates,
5975 UnresolvedSetImpl &ExplicitConversions) {
5976 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5977 DeclAccessPair Found = ExplicitConversions[0];
5978 CXXConversionDecl *Conversion =
5979 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5981 // The user probably meant to invoke the given explicit
5982 // conversion; use it.
5983 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5984 std::string TypeStr;
5985 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5987 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5988 << FixItHint::CreateInsertion(From->getBeginLoc(),
5989 "static_cast<" + TypeStr + ">(")
5990 << FixItHint::CreateInsertion(
5991 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5992 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5994 // If we aren't in a SFINAE context, build a call to the
5995 // explicit conversion function.
5996 if (SemaRef.isSFINAEContext())
5997 return true;
5999 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6000 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6001 HadMultipleCandidates);
6002 if (Result.isInvalid())
6003 return true;
6004 // Record usage of conversion in an implicit cast.
6005 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6006 CK_UserDefinedConversion, Result.get(),
6007 nullptr, Result.get()->getValueKind(),
6008 SemaRef.CurFPFeatureOverrides());
6010 return false;
6013 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6014 Sema::ContextualImplicitConverter &Converter,
6015 QualType T, bool HadMultipleCandidates,
6016 DeclAccessPair &Found) {
6017 CXXConversionDecl *Conversion =
6018 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6019 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6021 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6022 if (!Converter.SuppressConversion) {
6023 if (SemaRef.isSFINAEContext())
6024 return true;
6026 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6027 << From->getSourceRange();
6030 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6031 HadMultipleCandidates);
6032 if (Result.isInvalid())
6033 return true;
6034 // Record usage of conversion in an implicit cast.
6035 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6036 CK_UserDefinedConversion, Result.get(),
6037 nullptr, Result.get()->getValueKind(),
6038 SemaRef.CurFPFeatureOverrides());
6039 return false;
6042 static ExprResult finishContextualImplicitConversion(
6043 Sema &SemaRef, SourceLocation Loc, Expr *From,
6044 Sema::ContextualImplicitConverter &Converter) {
6045 if (!Converter.match(From->getType()) && !Converter.Suppress)
6046 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6047 << From->getSourceRange();
6049 return SemaRef.DefaultLvalueConversion(From);
6052 static void
6053 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6054 UnresolvedSetImpl &ViableConversions,
6055 OverloadCandidateSet &CandidateSet) {
6056 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6057 DeclAccessPair FoundDecl = ViableConversions[I];
6058 NamedDecl *D = FoundDecl.getDecl();
6059 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6060 if (isa<UsingShadowDecl>(D))
6061 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6063 CXXConversionDecl *Conv;
6064 FunctionTemplateDecl *ConvTemplate;
6065 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6066 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6067 else
6068 Conv = cast<CXXConversionDecl>(D);
6070 if (ConvTemplate)
6071 SemaRef.AddTemplateConversionCandidate(
6072 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6073 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6074 else
6075 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6076 ToType, CandidateSet,
6077 /*AllowObjCConversionOnExplicit=*/false,
6078 /*AllowExplicit*/ true);
6082 /// Attempt to convert the given expression to a type which is accepted
6083 /// by the given converter.
6085 /// This routine will attempt to convert an expression of class type to a
6086 /// type accepted by the specified converter. In C++11 and before, the class
6087 /// must have a single non-explicit conversion function converting to a matching
6088 /// type. In C++1y, there can be multiple such conversion functions, but only
6089 /// one target type.
6091 /// \param Loc The source location of the construct that requires the
6092 /// conversion.
6094 /// \param From The expression we're converting from.
6096 /// \param Converter Used to control and diagnose the conversion process.
6098 /// \returns The expression, converted to an integral or enumeration type if
6099 /// successful.
6100 ExprResult Sema::PerformContextualImplicitConversion(
6101 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6102 // We can't perform any more checking for type-dependent expressions.
6103 if (From->isTypeDependent())
6104 return From;
6106 // Process placeholders immediately.
6107 if (From->hasPlaceholderType()) {
6108 ExprResult result = CheckPlaceholderExpr(From);
6109 if (result.isInvalid())
6110 return result;
6111 From = result.get();
6114 // If the expression already has a matching type, we're golden.
6115 QualType T = From->getType();
6116 if (Converter.match(T))
6117 return DefaultLvalueConversion(From);
6119 // FIXME: Check for missing '()' if T is a function type?
6121 // We can only perform contextual implicit conversions on objects of class
6122 // type.
6123 const RecordType *RecordTy = T->getAs<RecordType>();
6124 if (!RecordTy || !getLangOpts().CPlusPlus) {
6125 if (!Converter.Suppress)
6126 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6127 return From;
6130 // We must have a complete class type.
6131 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6132 ContextualImplicitConverter &Converter;
6133 Expr *From;
6135 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6136 : Converter(Converter), From(From) {}
6138 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6139 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6141 } IncompleteDiagnoser(Converter, From);
6143 if (Converter.Suppress ? !isCompleteType(Loc, T)
6144 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6145 return From;
6147 // Look for a conversion to an integral or enumeration type.
6148 UnresolvedSet<4>
6149 ViableConversions; // These are *potentially* viable in C++1y.
6150 UnresolvedSet<4> ExplicitConversions;
6151 const auto &Conversions =
6152 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6154 bool HadMultipleCandidates =
6155 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6157 // To check that there is only one target type, in C++1y:
6158 QualType ToType;
6159 bool HasUniqueTargetType = true;
6161 // Collect explicit or viable (potentially in C++1y) conversions.
6162 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6163 NamedDecl *D = (*I)->getUnderlyingDecl();
6164 CXXConversionDecl *Conversion;
6165 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6166 if (ConvTemplate) {
6167 if (getLangOpts().CPlusPlus14)
6168 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6169 else
6170 continue; // C++11 does not consider conversion operator templates(?).
6171 } else
6172 Conversion = cast<CXXConversionDecl>(D);
6174 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6175 "Conversion operator templates are considered potentially "
6176 "viable in C++1y");
6178 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6179 if (Converter.match(CurToType) || ConvTemplate) {
6181 if (Conversion->isExplicit()) {
6182 // FIXME: For C++1y, do we need this restriction?
6183 // cf. diagnoseNoViableConversion()
6184 if (!ConvTemplate)
6185 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6186 } else {
6187 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6188 if (ToType.isNull())
6189 ToType = CurToType.getUnqualifiedType();
6190 else if (HasUniqueTargetType &&
6191 (CurToType.getUnqualifiedType() != ToType))
6192 HasUniqueTargetType = false;
6194 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6199 if (getLangOpts().CPlusPlus14) {
6200 // C++1y [conv]p6:
6201 // ... An expression e of class type E appearing in such a context
6202 // is said to be contextually implicitly converted to a specified
6203 // type T and is well-formed if and only if e can be implicitly
6204 // converted to a type T that is determined as follows: E is searched
6205 // for conversion functions whose return type is cv T or reference to
6206 // cv T such that T is allowed by the context. There shall be
6207 // exactly one such T.
6209 // If no unique T is found:
6210 if (ToType.isNull()) {
6211 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6212 HadMultipleCandidates,
6213 ExplicitConversions))
6214 return ExprError();
6215 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6218 // If more than one unique Ts are found:
6219 if (!HasUniqueTargetType)
6220 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6221 ViableConversions);
6223 // If one unique T is found:
6224 // First, build a candidate set from the previously recorded
6225 // potentially viable conversions.
6226 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6227 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6228 CandidateSet);
6230 // Then, perform overload resolution over the candidate set.
6231 OverloadCandidateSet::iterator Best;
6232 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6233 case OR_Success: {
6234 // Apply this conversion.
6235 DeclAccessPair Found =
6236 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6237 if (recordConversion(*this, Loc, From, Converter, T,
6238 HadMultipleCandidates, Found))
6239 return ExprError();
6240 break;
6242 case OR_Ambiguous:
6243 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6244 ViableConversions);
6245 case OR_No_Viable_Function:
6246 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6247 HadMultipleCandidates,
6248 ExplicitConversions))
6249 return ExprError();
6250 [[fallthrough]];
6251 case OR_Deleted:
6252 // We'll complain below about a non-integral condition type.
6253 break;
6255 } else {
6256 switch (ViableConversions.size()) {
6257 case 0: {
6258 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6259 HadMultipleCandidates,
6260 ExplicitConversions))
6261 return ExprError();
6263 // We'll complain below about a non-integral condition type.
6264 break;
6266 case 1: {
6267 // Apply this conversion.
6268 DeclAccessPair Found = ViableConversions[0];
6269 if (recordConversion(*this, Loc, From, Converter, T,
6270 HadMultipleCandidates, Found))
6271 return ExprError();
6272 break;
6274 default:
6275 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6276 ViableConversions);
6280 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6283 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6284 /// an acceptable non-member overloaded operator for a call whose
6285 /// arguments have types T1 (and, if non-empty, T2). This routine
6286 /// implements the check in C++ [over.match.oper]p3b2 concerning
6287 /// enumeration types.
6288 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6289 FunctionDecl *Fn,
6290 ArrayRef<Expr *> Args) {
6291 QualType T1 = Args[0]->getType();
6292 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6294 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6295 return true;
6297 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6298 return true;
6300 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6301 if (Proto->getNumParams() < 1)
6302 return false;
6304 if (T1->isEnumeralType()) {
6305 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6306 if (Context.hasSameUnqualifiedType(T1, ArgType))
6307 return true;
6310 if (Proto->getNumParams() < 2)
6311 return false;
6313 if (!T2.isNull() && T2->isEnumeralType()) {
6314 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6315 if (Context.hasSameUnqualifiedType(T2, ArgType))
6316 return true;
6319 return false;
6322 /// AddOverloadCandidate - Adds the given function to the set of
6323 /// candidate functions, using the given function call arguments. If
6324 /// @p SuppressUserConversions, then don't allow user-defined
6325 /// conversions via constructors or conversion operators.
6327 /// \param PartialOverloading true if we are performing "partial" overloading
6328 /// based on an incomplete set of function arguments. This feature is used by
6329 /// code completion.
6330 void Sema::AddOverloadCandidate(
6331 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6332 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6333 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6334 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6335 OverloadCandidateParamOrder PO) {
6336 const FunctionProtoType *Proto
6337 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6338 assert(Proto && "Functions without a prototype cannot be overloaded");
6339 assert(!Function->getDescribedFunctionTemplate() &&
6340 "Use AddTemplateOverloadCandidate for function templates");
6342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6343 if (!isa<CXXConstructorDecl>(Method)) {
6344 // If we get here, it's because we're calling a member function
6345 // that is named without a member access expression (e.g.,
6346 // "this->f") that was either written explicitly or created
6347 // implicitly. This can happen with a qualified call to a member
6348 // function, e.g., X::f(). We use an empty type for the implied
6349 // object argument (C++ [over.call.func]p3), and the acting context
6350 // is irrelevant.
6351 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6352 Expr::Classification::makeSimpleLValue(), Args,
6353 CandidateSet, SuppressUserConversions,
6354 PartialOverloading, EarlyConversions, PO);
6355 return;
6357 // We treat a constructor like a non-member function, since its object
6358 // argument doesn't participate in overload resolution.
6361 if (!CandidateSet.isNewCandidate(Function, PO))
6362 return;
6364 // C++11 [class.copy]p11: [DR1402]
6365 // A defaulted move constructor that is defined as deleted is ignored by
6366 // overload resolution.
6367 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6368 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6369 Constructor->isMoveConstructor())
6370 return;
6372 // Overload resolution is always an unevaluated context.
6373 EnterExpressionEvaluationContext Unevaluated(
6374 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6376 // C++ [over.match.oper]p3:
6377 // if no operand has a class type, only those non-member functions in the
6378 // lookup set that have a first parameter of type T1 or "reference to
6379 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6380 // is a right operand) a second parameter of type T2 or "reference to
6381 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6382 // candidate functions.
6383 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6384 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6385 return;
6387 // Add this candidate
6388 OverloadCandidate &Candidate =
6389 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6390 Candidate.FoundDecl = FoundDecl;
6391 Candidate.Function = Function;
6392 Candidate.Viable = true;
6393 Candidate.RewriteKind =
6394 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6395 Candidate.IsSurrogate = false;
6396 Candidate.IsADLCandidate = IsADLCandidate;
6397 Candidate.IgnoreObjectArgument = false;
6398 Candidate.ExplicitCallArguments = Args.size();
6400 // Explicit functions are not actually candidates at all if we're not
6401 // allowing them in this context, but keep them around so we can point
6402 // to them in diagnostics.
6403 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6404 Candidate.Viable = false;
6405 Candidate.FailureKind = ovl_fail_explicit;
6406 return;
6409 // Functions with internal linkage are only viable in the same module unit.
6410 if (auto *MF = Function->getOwningModule()) {
6411 if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
6412 !isModuleUnitOfCurrentTU(MF)) {
6413 /// FIXME: Currently, the semantics of linkage in clang is slightly
6414 /// different from the semantics in C++ spec. In C++ spec, only names
6415 /// have linkage. So that all entities of the same should share one
6416 /// linkage. But in clang, different entities of the same could have
6417 /// different linkage.
6418 NamedDecl *ND = Function;
6419 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6420 ND = SpecInfo->getTemplate();
6422 if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6423 Candidate.Viable = false;
6424 Candidate.FailureKind = ovl_fail_module_mismatched;
6425 return;
6430 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6431 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6432 Candidate.Viable = false;
6433 Candidate.FailureKind = ovl_non_default_multiversion_function;
6434 return;
6437 if (Constructor) {
6438 // C++ [class.copy]p3:
6439 // A member function template is never instantiated to perform the copy
6440 // of a class object to an object of its class type.
6441 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6442 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6443 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6444 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6445 ClassType))) {
6446 Candidate.Viable = false;
6447 Candidate.FailureKind = ovl_fail_illegal_constructor;
6448 return;
6451 // C++ [over.match.funcs]p8: (proposed DR resolution)
6452 // A constructor inherited from class type C that has a first parameter
6453 // of type "reference to P" (including such a constructor instantiated
6454 // from a template) is excluded from the set of candidate functions when
6455 // constructing an object of type cv D if the argument list has exactly
6456 // one argument and D is reference-related to P and P is reference-related
6457 // to C.
6458 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6459 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6460 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6461 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6462 QualType C = Context.getRecordType(Constructor->getParent());
6463 QualType D = Context.getRecordType(Shadow->getParent());
6464 SourceLocation Loc = Args.front()->getExprLoc();
6465 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6466 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6467 Candidate.Viable = false;
6468 Candidate.FailureKind = ovl_fail_inhctor_slice;
6469 return;
6473 // Check that the constructor is capable of constructing an object in the
6474 // destination address space.
6475 if (!Qualifiers::isAddressSpaceSupersetOf(
6476 Constructor->getMethodQualifiers().getAddressSpace(),
6477 CandidateSet.getDestAS())) {
6478 Candidate.Viable = false;
6479 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6483 unsigned NumParams = Proto->getNumParams();
6485 // (C++ 13.3.2p2): A candidate function having fewer than m
6486 // parameters is viable only if it has an ellipsis in its parameter
6487 // list (8.3.5).
6488 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6489 !Proto->isVariadic() &&
6490 shouldEnforceArgLimit(PartialOverloading, Function)) {
6491 Candidate.Viable = false;
6492 Candidate.FailureKind = ovl_fail_too_many_arguments;
6493 return;
6496 // (C++ 13.3.2p2): A candidate function having more than m parameters
6497 // is viable only if the (m+1)st parameter has a default argument
6498 // (8.3.6). For the purposes of overload resolution, the
6499 // parameter list is truncated on the right, so that there are
6500 // exactly m parameters.
6501 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6502 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6503 // Not enough arguments.
6504 Candidate.Viable = false;
6505 Candidate.FailureKind = ovl_fail_too_few_arguments;
6506 return;
6509 // (CUDA B.1): Check for invalid calls between targets.
6510 if (getLangOpts().CUDA)
6511 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6512 // Skip the check for callers that are implicit members, because in this
6513 // case we may not yet know what the member's target is; the target is
6514 // inferred for the member automatically, based on the bases and fields of
6515 // the class.
6516 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6517 Candidate.Viable = false;
6518 Candidate.FailureKind = ovl_fail_bad_target;
6519 return;
6522 if (Function->getTrailingRequiresClause()) {
6523 ConstraintSatisfaction Satisfaction;
6524 if (CheckFunctionConstraints(Function, Satisfaction) ||
6525 !Satisfaction.IsSatisfied) {
6526 Candidate.Viable = false;
6527 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6528 return;
6532 // Determine the implicit conversion sequences for each of the
6533 // arguments.
6534 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6535 unsigned ConvIdx =
6536 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6537 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6538 // We already formed a conversion sequence for this parameter during
6539 // template argument deduction.
6540 } else if (ArgIdx < NumParams) {
6541 // (C++ 13.3.2p3): for F to be a viable function, there shall
6542 // exist for each argument an implicit conversion sequence
6543 // (13.3.3.1) that converts that argument to the corresponding
6544 // parameter of F.
6545 QualType ParamType = Proto->getParamType(ArgIdx);
6546 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6547 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6548 /*InOverloadResolution=*/true,
6549 /*AllowObjCWritebackConversion=*/
6550 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6551 if (Candidate.Conversions[ConvIdx].isBad()) {
6552 Candidate.Viable = false;
6553 Candidate.FailureKind = ovl_fail_bad_conversion;
6554 return;
6556 } else {
6557 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6558 // argument for which there is no corresponding parameter is
6559 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6560 Candidate.Conversions[ConvIdx].setEllipsis();
6564 if (EnableIfAttr *FailedAttr =
6565 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6566 Candidate.Viable = false;
6567 Candidate.FailureKind = ovl_fail_enable_if;
6568 Candidate.DeductionFailure.Data = FailedAttr;
6569 return;
6573 ObjCMethodDecl *
6574 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6575 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6576 if (Methods.size() <= 1)
6577 return nullptr;
6579 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6580 bool Match = true;
6581 ObjCMethodDecl *Method = Methods[b];
6582 unsigned NumNamedArgs = Sel.getNumArgs();
6583 // Method might have more arguments than selector indicates. This is due
6584 // to addition of c-style arguments in method.
6585 if (Method->param_size() > NumNamedArgs)
6586 NumNamedArgs = Method->param_size();
6587 if (Args.size() < NumNamedArgs)
6588 continue;
6590 for (unsigned i = 0; i < NumNamedArgs; i++) {
6591 // We can't do any type-checking on a type-dependent argument.
6592 if (Args[i]->isTypeDependent()) {
6593 Match = false;
6594 break;
6597 ParmVarDecl *param = Method->parameters()[i];
6598 Expr *argExpr = Args[i];
6599 assert(argExpr && "SelectBestMethod(): missing expression");
6601 // Strip the unbridged-cast placeholder expression off unless it's
6602 // a consumed argument.
6603 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6604 !param->hasAttr<CFConsumedAttr>())
6605 argExpr = stripARCUnbridgedCast(argExpr);
6607 // If the parameter is __unknown_anytype, move on to the next method.
6608 if (param->getType() == Context.UnknownAnyTy) {
6609 Match = false;
6610 break;
6613 ImplicitConversionSequence ConversionState
6614 = TryCopyInitialization(*this, argExpr, param->getType(),
6615 /*SuppressUserConversions*/false,
6616 /*InOverloadResolution=*/true,
6617 /*AllowObjCWritebackConversion=*/
6618 getLangOpts().ObjCAutoRefCount,
6619 /*AllowExplicit*/false);
6620 // This function looks for a reasonably-exact match, so we consider
6621 // incompatible pointer conversions to be a failure here.
6622 if (ConversionState.isBad() ||
6623 (ConversionState.isStandard() &&
6624 ConversionState.Standard.Second ==
6625 ICK_Incompatible_Pointer_Conversion)) {
6626 Match = false;
6627 break;
6630 // Promote additional arguments to variadic methods.
6631 if (Match && Method->isVariadic()) {
6632 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6633 if (Args[i]->isTypeDependent()) {
6634 Match = false;
6635 break;
6637 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6638 nullptr);
6639 if (Arg.isInvalid()) {
6640 Match = false;
6641 break;
6644 } else {
6645 // Check for extra arguments to non-variadic methods.
6646 if (Args.size() != NumNamedArgs)
6647 Match = false;
6648 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6649 // Special case when selectors have no argument. In this case, select
6650 // one with the most general result type of 'id'.
6651 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6652 QualType ReturnT = Methods[b]->getReturnType();
6653 if (ReturnT->isObjCIdType())
6654 return Methods[b];
6659 if (Match)
6660 return Method;
6662 return nullptr;
6665 static bool convertArgsForAvailabilityChecks(
6666 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6667 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6668 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6669 if (ThisArg) {
6670 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6671 assert(!isa<CXXConstructorDecl>(Method) &&
6672 "Shouldn't have `this` for ctors!");
6673 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6674 ExprResult R = S.PerformObjectArgumentInitialization(
6675 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6676 if (R.isInvalid())
6677 return false;
6678 ConvertedThis = R.get();
6679 } else {
6680 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6681 (void)MD;
6682 assert((MissingImplicitThis || MD->isStatic() ||
6683 isa<CXXConstructorDecl>(MD)) &&
6684 "Expected `this` for non-ctor instance methods");
6686 ConvertedThis = nullptr;
6689 // Ignore any variadic arguments. Converting them is pointless, since the
6690 // user can't refer to them in the function condition.
6691 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6693 // Convert the arguments.
6694 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6695 ExprResult R;
6696 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6697 S.Context, Function->getParamDecl(I)),
6698 SourceLocation(), Args[I]);
6700 if (R.isInvalid())
6701 return false;
6703 ConvertedArgs.push_back(R.get());
6706 if (Trap.hasErrorOccurred())
6707 return false;
6709 // Push default arguments if needed.
6710 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6711 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6712 ParmVarDecl *P = Function->getParamDecl(i);
6713 if (!P->hasDefaultArg())
6714 return false;
6715 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6716 if (R.isInvalid())
6717 return false;
6718 ConvertedArgs.push_back(R.get());
6721 if (Trap.hasErrorOccurred())
6722 return false;
6724 return true;
6727 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6728 SourceLocation CallLoc,
6729 ArrayRef<Expr *> Args,
6730 bool MissingImplicitThis) {
6731 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6732 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6733 return nullptr;
6735 SFINAETrap Trap(*this);
6736 SmallVector<Expr *, 16> ConvertedArgs;
6737 // FIXME: We should look into making enable_if late-parsed.
6738 Expr *DiscardedThis;
6739 if (!convertArgsForAvailabilityChecks(
6740 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6741 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6742 return *EnableIfAttrs.begin();
6744 for (auto *EIA : EnableIfAttrs) {
6745 APValue Result;
6746 // FIXME: This doesn't consider value-dependent cases, because doing so is
6747 // very difficult. Ideally, we should handle them more gracefully.
6748 if (EIA->getCond()->isValueDependent() ||
6749 !EIA->getCond()->EvaluateWithSubstitution(
6750 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6751 return EIA;
6753 if (!Result.isInt() || !Result.getInt().getBoolValue())
6754 return EIA;
6756 return nullptr;
6759 template <typename CheckFn>
6760 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6761 bool ArgDependent, SourceLocation Loc,
6762 CheckFn &&IsSuccessful) {
6763 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6764 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6765 if (ArgDependent == DIA->getArgDependent())
6766 Attrs.push_back(DIA);
6769 // Common case: No diagnose_if attributes, so we can quit early.
6770 if (Attrs.empty())
6771 return false;
6773 auto WarningBegin = std::stable_partition(
6774 Attrs.begin(), Attrs.end(),
6775 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6777 // Note that diagnose_if attributes are late-parsed, so they appear in the
6778 // correct order (unlike enable_if attributes).
6779 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6780 IsSuccessful);
6781 if (ErrAttr != WarningBegin) {
6782 const DiagnoseIfAttr *DIA = *ErrAttr;
6783 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6784 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6785 << DIA->getParent() << DIA->getCond()->getSourceRange();
6786 return true;
6789 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6790 if (IsSuccessful(DIA)) {
6791 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6792 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6793 << DIA->getParent() << DIA->getCond()->getSourceRange();
6796 return false;
6799 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6800 const Expr *ThisArg,
6801 ArrayRef<const Expr *> Args,
6802 SourceLocation Loc) {
6803 return diagnoseDiagnoseIfAttrsWith(
6804 *this, Function, /*ArgDependent=*/true, Loc,
6805 [&](const DiagnoseIfAttr *DIA) {
6806 APValue Result;
6807 // It's sane to use the same Args for any redecl of this function, since
6808 // EvaluateWithSubstitution only cares about the position of each
6809 // argument in the arg list, not the ParmVarDecl* it maps to.
6810 if (!DIA->getCond()->EvaluateWithSubstitution(
6811 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6812 return false;
6813 return Result.isInt() && Result.getInt().getBoolValue();
6817 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6818 SourceLocation Loc) {
6819 return diagnoseDiagnoseIfAttrsWith(
6820 *this, ND, /*ArgDependent=*/false, Loc,
6821 [&](const DiagnoseIfAttr *DIA) {
6822 bool Result;
6823 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6824 Result;
6828 /// Add all of the function declarations in the given function set to
6829 /// the overload candidate set.
6830 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6831 ArrayRef<Expr *> Args,
6832 OverloadCandidateSet &CandidateSet,
6833 TemplateArgumentListInfo *ExplicitTemplateArgs,
6834 bool SuppressUserConversions,
6835 bool PartialOverloading,
6836 bool FirstArgumentIsBase) {
6837 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6838 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6839 ArrayRef<Expr *> FunctionArgs = Args;
6841 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6842 FunctionDecl *FD =
6843 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6845 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6846 QualType ObjectType;
6847 Expr::Classification ObjectClassification;
6848 if (Args.size() > 0) {
6849 if (Expr *E = Args[0]) {
6850 // Use the explicit base to restrict the lookup:
6851 ObjectType = E->getType();
6852 // Pointers in the object arguments are implicitly dereferenced, so we
6853 // always classify them as l-values.
6854 if (!ObjectType.isNull() && ObjectType->isPointerType())
6855 ObjectClassification = Expr::Classification::makeSimpleLValue();
6856 else
6857 ObjectClassification = E->Classify(Context);
6858 } // .. else there is an implicit base.
6859 FunctionArgs = Args.slice(1);
6861 if (FunTmpl) {
6862 AddMethodTemplateCandidate(
6863 FunTmpl, F.getPair(),
6864 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6865 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6866 FunctionArgs, CandidateSet, SuppressUserConversions,
6867 PartialOverloading);
6868 } else {
6869 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6870 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6871 ObjectClassification, FunctionArgs, CandidateSet,
6872 SuppressUserConversions, PartialOverloading);
6874 } else {
6875 // This branch handles both standalone functions and static methods.
6877 // Slice the first argument (which is the base) when we access
6878 // static method as non-static.
6879 if (Args.size() > 0 &&
6880 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6881 !isa<CXXConstructorDecl>(FD)))) {
6882 assert(cast<CXXMethodDecl>(FD)->isStatic());
6883 FunctionArgs = Args.slice(1);
6885 if (FunTmpl) {
6886 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6887 ExplicitTemplateArgs, FunctionArgs,
6888 CandidateSet, SuppressUserConversions,
6889 PartialOverloading);
6890 } else {
6891 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6892 SuppressUserConversions, PartialOverloading);
6898 /// AddMethodCandidate - Adds a named decl (which is some kind of
6899 /// method) as a method candidate to the given overload set.
6900 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6901 Expr::Classification ObjectClassification,
6902 ArrayRef<Expr *> Args,
6903 OverloadCandidateSet &CandidateSet,
6904 bool SuppressUserConversions,
6905 OverloadCandidateParamOrder PO) {
6906 NamedDecl *Decl = FoundDecl.getDecl();
6907 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6909 if (isa<UsingShadowDecl>(Decl))
6910 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6912 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6913 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6914 "Expected a member function template");
6915 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6916 /*ExplicitArgs*/ nullptr, ObjectType,
6917 ObjectClassification, Args, CandidateSet,
6918 SuppressUserConversions, false, PO);
6919 } else {
6920 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6921 ObjectType, ObjectClassification, Args, CandidateSet,
6922 SuppressUserConversions, false, None, PO);
6926 /// AddMethodCandidate - Adds the given C++ member function to the set
6927 /// of candidate functions, using the given function call arguments
6928 /// and the object argument (@c Object). For example, in a call
6929 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6930 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6931 /// allow user-defined conversions via constructors or conversion
6932 /// operators.
6933 void
6934 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6935 CXXRecordDecl *ActingContext, QualType ObjectType,
6936 Expr::Classification ObjectClassification,
6937 ArrayRef<Expr *> Args,
6938 OverloadCandidateSet &CandidateSet,
6939 bool SuppressUserConversions,
6940 bool PartialOverloading,
6941 ConversionSequenceList EarlyConversions,
6942 OverloadCandidateParamOrder PO) {
6943 const FunctionProtoType *Proto
6944 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6945 assert(Proto && "Methods without a prototype cannot be overloaded");
6946 assert(!isa<CXXConstructorDecl>(Method) &&
6947 "Use AddOverloadCandidate for constructors");
6949 if (!CandidateSet.isNewCandidate(Method, PO))
6950 return;
6952 // C++11 [class.copy]p23: [DR1402]
6953 // A defaulted move assignment operator that is defined as deleted is
6954 // ignored by overload resolution.
6955 if (Method->isDefaulted() && Method->isDeleted() &&
6956 Method->isMoveAssignmentOperator())
6957 return;
6959 // Overload resolution is always an unevaluated context.
6960 EnterExpressionEvaluationContext Unevaluated(
6961 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6963 // Add this candidate
6964 OverloadCandidate &Candidate =
6965 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6966 Candidate.FoundDecl = FoundDecl;
6967 Candidate.Function = Method;
6968 Candidate.RewriteKind =
6969 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6970 Candidate.IsSurrogate = false;
6971 Candidate.IgnoreObjectArgument = false;
6972 Candidate.ExplicitCallArguments = Args.size();
6974 unsigned NumParams = Proto->getNumParams();
6976 // (C++ 13.3.2p2): A candidate function having fewer than m
6977 // parameters is viable only if it has an ellipsis in its parameter
6978 // list (8.3.5).
6979 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6980 !Proto->isVariadic() &&
6981 shouldEnforceArgLimit(PartialOverloading, Method)) {
6982 Candidate.Viable = false;
6983 Candidate.FailureKind = ovl_fail_too_many_arguments;
6984 return;
6987 // (C++ 13.3.2p2): A candidate function having more than m parameters
6988 // is viable only if the (m+1)st parameter has a default argument
6989 // (8.3.6). For the purposes of overload resolution, the
6990 // parameter list is truncated on the right, so that there are
6991 // exactly m parameters.
6992 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6993 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6994 // Not enough arguments.
6995 Candidate.Viable = false;
6996 Candidate.FailureKind = ovl_fail_too_few_arguments;
6997 return;
7000 Candidate.Viable = true;
7002 if (Method->isStatic() || ObjectType.isNull())
7003 // The implicit object argument is ignored.
7004 Candidate.IgnoreObjectArgument = true;
7005 else {
7006 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7007 // Determine the implicit conversion sequence for the object
7008 // parameter.
7009 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
7010 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7011 Method, ActingContext);
7012 if (Candidate.Conversions[ConvIdx].isBad()) {
7013 Candidate.Viable = false;
7014 Candidate.FailureKind = ovl_fail_bad_conversion;
7015 return;
7019 // (CUDA B.1): Check for invalid calls between targets.
7020 if (getLangOpts().CUDA)
7021 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7022 if (!IsAllowedCUDACall(Caller, Method)) {
7023 Candidate.Viable = false;
7024 Candidate.FailureKind = ovl_fail_bad_target;
7025 return;
7028 if (Method->getTrailingRequiresClause()) {
7029 ConstraintSatisfaction Satisfaction;
7030 if (CheckFunctionConstraints(Method, Satisfaction) ||
7031 !Satisfaction.IsSatisfied) {
7032 Candidate.Viable = false;
7033 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7034 return;
7038 // Determine the implicit conversion sequences for each of the
7039 // arguments.
7040 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7041 unsigned ConvIdx =
7042 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7043 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7044 // We already formed a conversion sequence for this parameter during
7045 // template argument deduction.
7046 } else if (ArgIdx < NumParams) {
7047 // (C++ 13.3.2p3): for F to be a viable function, there shall
7048 // exist for each argument an implicit conversion sequence
7049 // (13.3.3.1) that converts that argument to the corresponding
7050 // parameter of F.
7051 QualType ParamType = Proto->getParamType(ArgIdx);
7052 Candidate.Conversions[ConvIdx]
7053 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7054 SuppressUserConversions,
7055 /*InOverloadResolution=*/true,
7056 /*AllowObjCWritebackConversion=*/
7057 getLangOpts().ObjCAutoRefCount);
7058 if (Candidate.Conversions[ConvIdx].isBad()) {
7059 Candidate.Viable = false;
7060 Candidate.FailureKind = ovl_fail_bad_conversion;
7061 return;
7063 } else {
7064 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7065 // argument for which there is no corresponding parameter is
7066 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7067 Candidate.Conversions[ConvIdx].setEllipsis();
7071 if (EnableIfAttr *FailedAttr =
7072 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7073 Candidate.Viable = false;
7074 Candidate.FailureKind = ovl_fail_enable_if;
7075 Candidate.DeductionFailure.Data = FailedAttr;
7076 return;
7079 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7080 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7081 Candidate.Viable = false;
7082 Candidate.FailureKind = ovl_non_default_multiversion_function;
7086 /// Add a C++ member function template as a candidate to the candidate
7087 /// set, using template argument deduction to produce an appropriate member
7088 /// function template specialization.
7089 void Sema::AddMethodTemplateCandidate(
7090 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7091 CXXRecordDecl *ActingContext,
7092 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7093 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7094 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7095 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7096 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7097 return;
7099 // C++ [over.match.funcs]p7:
7100 // In each case where a candidate is a function template, candidate
7101 // function template specializations are generated using template argument
7102 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7103 // candidate functions in the usual way.113) A given name can refer to one
7104 // or more function templates and also to a set of overloaded non-template
7105 // functions. In such a case, the candidate functions generated from each
7106 // function template are combined with the set of non-template candidate
7107 // functions.
7108 TemplateDeductionInfo Info(CandidateSet.getLocation());
7109 FunctionDecl *Specialization = nullptr;
7110 ConversionSequenceList Conversions;
7111 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7112 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7113 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7114 return CheckNonDependentConversions(
7115 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7116 SuppressUserConversions, ActingContext, ObjectType,
7117 ObjectClassification, PO);
7118 })) {
7119 OverloadCandidate &Candidate =
7120 CandidateSet.addCandidate(Conversions.size(), Conversions);
7121 Candidate.FoundDecl = FoundDecl;
7122 Candidate.Function = MethodTmpl->getTemplatedDecl();
7123 Candidate.Viable = false;
7124 Candidate.RewriteKind =
7125 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7126 Candidate.IsSurrogate = false;
7127 Candidate.IgnoreObjectArgument =
7128 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7129 ObjectType.isNull();
7130 Candidate.ExplicitCallArguments = Args.size();
7131 if (Result == TDK_NonDependentConversionFailure)
7132 Candidate.FailureKind = ovl_fail_bad_conversion;
7133 else {
7134 Candidate.FailureKind = ovl_fail_bad_deduction;
7135 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7136 Info);
7138 return;
7141 // Add the function template specialization produced by template argument
7142 // deduction as a candidate.
7143 assert(Specialization && "Missing member function template specialization?");
7144 assert(isa<CXXMethodDecl>(Specialization) &&
7145 "Specialization is not a member function?");
7146 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7147 ActingContext, ObjectType, ObjectClassification, Args,
7148 CandidateSet, SuppressUserConversions, PartialOverloading,
7149 Conversions, PO);
7152 /// Determine whether a given function template has a simple explicit specifier
7153 /// or a non-value-dependent explicit-specification that evaluates to true.
7154 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7155 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7158 /// Add a C++ function template specialization as a candidate
7159 /// in the candidate set, using template argument deduction to produce
7160 /// an appropriate function template specialization.
7161 void Sema::AddTemplateOverloadCandidate(
7162 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7163 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7164 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7165 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7166 OverloadCandidateParamOrder PO) {
7167 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7168 return;
7170 // If the function template has a non-dependent explicit specification,
7171 // exclude it now if appropriate; we are not permitted to perform deduction
7172 // and substitution in this case.
7173 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7174 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7175 Candidate.FoundDecl = FoundDecl;
7176 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7177 Candidate.Viable = false;
7178 Candidate.FailureKind = ovl_fail_explicit;
7179 return;
7182 // C++ [over.match.funcs]p7:
7183 // In each case where a candidate is a function template, candidate
7184 // function template specializations are generated using template argument
7185 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7186 // candidate functions in the usual way.113) A given name can refer to one
7187 // or more function templates and also to a set of overloaded non-template
7188 // functions. In such a case, the candidate functions generated from each
7189 // function template are combined with the set of non-template candidate
7190 // functions.
7191 TemplateDeductionInfo Info(CandidateSet.getLocation());
7192 FunctionDecl *Specialization = nullptr;
7193 ConversionSequenceList Conversions;
7194 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7195 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7196 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7197 return CheckNonDependentConversions(
7198 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7199 SuppressUserConversions, nullptr, QualType(), {}, PO);
7200 })) {
7201 OverloadCandidate &Candidate =
7202 CandidateSet.addCandidate(Conversions.size(), Conversions);
7203 Candidate.FoundDecl = FoundDecl;
7204 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7205 Candidate.Viable = false;
7206 Candidate.RewriteKind =
7207 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7208 Candidate.IsSurrogate = false;
7209 Candidate.IsADLCandidate = IsADLCandidate;
7210 // Ignore the object argument if there is one, since we don't have an object
7211 // type.
7212 Candidate.IgnoreObjectArgument =
7213 isa<CXXMethodDecl>(Candidate.Function) &&
7214 !isa<CXXConstructorDecl>(Candidate.Function);
7215 Candidate.ExplicitCallArguments = Args.size();
7216 if (Result == TDK_NonDependentConversionFailure)
7217 Candidate.FailureKind = ovl_fail_bad_conversion;
7218 else {
7219 Candidate.FailureKind = ovl_fail_bad_deduction;
7220 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7221 Info);
7223 return;
7226 // Add the function template specialization produced by template argument
7227 // deduction as a candidate.
7228 assert(Specialization && "Missing function template specialization?");
7229 AddOverloadCandidate(
7230 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7231 PartialOverloading, AllowExplicit,
7232 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7235 /// Check that implicit conversion sequences can be formed for each argument
7236 /// whose corresponding parameter has a non-dependent type, per DR1391's
7237 /// [temp.deduct.call]p10.
7238 bool Sema::CheckNonDependentConversions(
7239 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7240 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7241 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7242 CXXRecordDecl *ActingContext, QualType ObjectType,
7243 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7244 // FIXME: The cases in which we allow explicit conversions for constructor
7245 // arguments never consider calling a constructor template. It's not clear
7246 // that is correct.
7247 const bool AllowExplicit = false;
7249 auto *FD = FunctionTemplate->getTemplatedDecl();
7250 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7251 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7252 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7254 Conversions =
7255 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7257 // Overload resolution is always an unevaluated context.
7258 EnterExpressionEvaluationContext Unevaluated(
7259 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7261 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7262 // require that, but this check should never result in a hard error, and
7263 // overload resolution is permitted to sidestep instantiations.
7264 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7265 !ObjectType.isNull()) {
7266 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7267 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7268 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7269 Method, ActingContext);
7270 if (Conversions[ConvIdx].isBad())
7271 return true;
7274 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7275 ++I) {
7276 QualType ParamType = ParamTypes[I];
7277 if (!ParamType->isDependentType()) {
7278 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7280 : (ThisConversions + I);
7281 Conversions[ConvIdx]
7282 = TryCopyInitialization(*this, Args[I], ParamType,
7283 SuppressUserConversions,
7284 /*InOverloadResolution=*/true,
7285 /*AllowObjCWritebackConversion=*/
7286 getLangOpts().ObjCAutoRefCount,
7287 AllowExplicit);
7288 if (Conversions[ConvIdx].isBad())
7289 return true;
7293 return false;
7296 /// Determine whether this is an allowable conversion from the result
7297 /// of an explicit conversion operator to the expected type, per C++
7298 /// [over.match.conv]p1 and [over.match.ref]p1.
7300 /// \param ConvType The return type of the conversion function.
7302 /// \param ToType The type we are converting to.
7304 /// \param AllowObjCPointerConversion Allow a conversion from one
7305 /// Objective-C pointer to another.
7307 /// \returns true if the conversion is allowable, false otherwise.
7308 static bool isAllowableExplicitConversion(Sema &S,
7309 QualType ConvType, QualType ToType,
7310 bool AllowObjCPointerConversion) {
7311 QualType ToNonRefType = ToType.getNonReferenceType();
7313 // Easy case: the types are the same.
7314 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7315 return true;
7317 // Allow qualification conversions.
7318 bool ObjCLifetimeConversion;
7319 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7320 ObjCLifetimeConversion))
7321 return true;
7323 // If we're not allowed to consider Objective-C pointer conversions,
7324 // we're done.
7325 if (!AllowObjCPointerConversion)
7326 return false;
7328 // Is this an Objective-C pointer conversion?
7329 bool IncompatibleObjC = false;
7330 QualType ConvertedType;
7331 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7332 IncompatibleObjC);
7335 /// AddConversionCandidate - Add a C++ conversion function as a
7336 /// candidate in the candidate set (C++ [over.match.conv],
7337 /// C++ [over.match.copy]). From is the expression we're converting from,
7338 /// and ToType is the type that we're eventually trying to convert to
7339 /// (which may or may not be the same type as the type that the
7340 /// conversion function produces).
7341 void Sema::AddConversionCandidate(
7342 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7343 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7344 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7345 bool AllowExplicit, bool AllowResultConversion) {
7346 assert(!Conversion->getDescribedFunctionTemplate() &&
7347 "Conversion function templates use AddTemplateConversionCandidate");
7348 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7349 if (!CandidateSet.isNewCandidate(Conversion))
7350 return;
7352 // If the conversion function has an undeduced return type, trigger its
7353 // deduction now.
7354 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7355 if (DeduceReturnType(Conversion, From->getExprLoc()))
7356 return;
7357 ConvType = Conversion->getConversionType().getNonReferenceType();
7360 // If we don't allow any conversion of the result type, ignore conversion
7361 // functions that don't convert to exactly (possibly cv-qualified) T.
7362 if (!AllowResultConversion &&
7363 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7364 return;
7366 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7367 // operator is only a candidate if its return type is the target type or
7368 // can be converted to the target type with a qualification conversion.
7370 // FIXME: Include such functions in the candidate list and explain why we
7371 // can't select them.
7372 if (Conversion->isExplicit() &&
7373 !isAllowableExplicitConversion(*this, ConvType, ToType,
7374 AllowObjCConversionOnExplicit))
7375 return;
7377 // Overload resolution is always an unevaluated context.
7378 EnterExpressionEvaluationContext Unevaluated(
7379 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7381 // Add this candidate
7382 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7383 Candidate.FoundDecl = FoundDecl;
7384 Candidate.Function = Conversion;
7385 Candidate.IsSurrogate = false;
7386 Candidate.IgnoreObjectArgument = false;
7387 Candidate.FinalConversion.setAsIdentityConversion();
7388 Candidate.FinalConversion.setFromType(ConvType);
7389 Candidate.FinalConversion.setAllToTypes(ToType);
7390 Candidate.Viable = true;
7391 Candidate.ExplicitCallArguments = 1;
7393 // Explicit functions are not actually candidates at all if we're not
7394 // allowing them in this context, but keep them around so we can point
7395 // to them in diagnostics.
7396 if (!AllowExplicit && Conversion->isExplicit()) {
7397 Candidate.Viable = false;
7398 Candidate.FailureKind = ovl_fail_explicit;
7399 return;
7402 // C++ [over.match.funcs]p4:
7403 // For conversion functions, the function is considered to be a member of
7404 // the class of the implicit implied object argument for the purpose of
7405 // defining the type of the implicit object parameter.
7407 // Determine the implicit conversion sequence for the implicit
7408 // object parameter.
7409 QualType ImplicitParamType = From->getType();
7410 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7411 ImplicitParamType = FromPtrType->getPointeeType();
7412 CXXRecordDecl *ConversionContext
7413 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7415 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7416 *this, CandidateSet.getLocation(), From->getType(),
7417 From->Classify(Context), Conversion, ConversionContext);
7419 if (Candidate.Conversions[0].isBad()) {
7420 Candidate.Viable = false;
7421 Candidate.FailureKind = ovl_fail_bad_conversion;
7422 return;
7425 if (Conversion->getTrailingRequiresClause()) {
7426 ConstraintSatisfaction Satisfaction;
7427 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7428 !Satisfaction.IsSatisfied) {
7429 Candidate.Viable = false;
7430 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7431 return;
7435 // We won't go through a user-defined type conversion function to convert a
7436 // derived to base as such conversions are given Conversion Rank. They only
7437 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7438 QualType FromCanon
7439 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7440 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7441 if (FromCanon == ToCanon ||
7442 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7443 Candidate.Viable = false;
7444 Candidate.FailureKind = ovl_fail_trivial_conversion;
7445 return;
7448 // To determine what the conversion from the result of calling the
7449 // conversion function to the type we're eventually trying to
7450 // convert to (ToType), we need to synthesize a call to the
7451 // conversion function and attempt copy initialization from it. This
7452 // makes sure that we get the right semantics with respect to
7453 // lvalues/rvalues and the type. Fortunately, we can allocate this
7454 // call on the stack and we don't need its arguments to be
7455 // well-formed.
7456 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7457 VK_LValue, From->getBeginLoc());
7458 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7459 Context.getPointerType(Conversion->getType()),
7460 CK_FunctionToPointerDecay, &ConversionRef,
7461 VK_PRValue, FPOptionsOverride());
7463 QualType ConversionType = Conversion->getConversionType();
7464 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7465 Candidate.Viable = false;
7466 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7467 return;
7470 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7472 // Note that it is safe to allocate CallExpr on the stack here because
7473 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7474 // allocator).
7475 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7477 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7478 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7479 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7481 ImplicitConversionSequence ICS =
7482 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7483 /*SuppressUserConversions=*/true,
7484 /*InOverloadResolution=*/false,
7485 /*AllowObjCWritebackConversion=*/false);
7487 switch (ICS.getKind()) {
7488 case ImplicitConversionSequence::StandardConversion:
7489 Candidate.FinalConversion = ICS.Standard;
7491 // C++ [over.ics.user]p3:
7492 // If the user-defined conversion is specified by a specialization of a
7493 // conversion function template, the second standard conversion sequence
7494 // shall have exact match rank.
7495 if (Conversion->getPrimaryTemplate() &&
7496 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7497 Candidate.Viable = false;
7498 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7499 return;
7502 // C++0x [dcl.init.ref]p5:
7503 // In the second case, if the reference is an rvalue reference and
7504 // the second standard conversion sequence of the user-defined
7505 // conversion sequence includes an lvalue-to-rvalue conversion, the
7506 // program is ill-formed.
7507 if (ToType->isRValueReferenceType() &&
7508 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7509 Candidate.Viable = false;
7510 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7511 return;
7513 break;
7515 case ImplicitConversionSequence::BadConversion:
7516 Candidate.Viable = false;
7517 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7518 return;
7520 default:
7521 llvm_unreachable(
7522 "Can only end up with a standard conversion sequence or failure");
7525 if (EnableIfAttr *FailedAttr =
7526 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7527 Candidate.Viable = false;
7528 Candidate.FailureKind = ovl_fail_enable_if;
7529 Candidate.DeductionFailure.Data = FailedAttr;
7530 return;
7533 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7534 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7535 Candidate.Viable = false;
7536 Candidate.FailureKind = ovl_non_default_multiversion_function;
7540 /// Adds a conversion function template specialization
7541 /// candidate to the overload set, using template argument deduction
7542 /// to deduce the template arguments of the conversion function
7543 /// template from the type that we are converting to (C++
7544 /// [temp.deduct.conv]).
7545 void Sema::AddTemplateConversionCandidate(
7546 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7547 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7548 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7549 bool AllowExplicit, bool AllowResultConversion) {
7550 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7551 "Only conversion function templates permitted here");
7553 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7554 return;
7556 // If the function template has a non-dependent explicit specification,
7557 // exclude it now if appropriate; we are not permitted to perform deduction
7558 // and substitution in this case.
7559 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7560 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7561 Candidate.FoundDecl = FoundDecl;
7562 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7563 Candidate.Viable = false;
7564 Candidate.FailureKind = ovl_fail_explicit;
7565 return;
7568 TemplateDeductionInfo Info(CandidateSet.getLocation());
7569 CXXConversionDecl *Specialization = nullptr;
7570 if (TemplateDeductionResult Result
7571 = DeduceTemplateArguments(FunctionTemplate, ToType,
7572 Specialization, Info)) {
7573 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7574 Candidate.FoundDecl = FoundDecl;
7575 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7576 Candidate.Viable = false;
7577 Candidate.FailureKind = ovl_fail_bad_deduction;
7578 Candidate.IsSurrogate = false;
7579 Candidate.IgnoreObjectArgument = false;
7580 Candidate.ExplicitCallArguments = 1;
7581 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7582 Info);
7583 return;
7586 // Add the conversion function template specialization produced by
7587 // template argument deduction as a candidate.
7588 assert(Specialization && "Missing function template specialization?");
7589 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7590 CandidateSet, AllowObjCConversionOnExplicit,
7591 AllowExplicit, AllowResultConversion);
7594 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7595 /// converts the given @c Object to a function pointer via the
7596 /// conversion function @c Conversion, and then attempts to call it
7597 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7598 /// the type of function that we'll eventually be calling.
7599 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7600 DeclAccessPair FoundDecl,
7601 CXXRecordDecl *ActingContext,
7602 const FunctionProtoType *Proto,
7603 Expr *Object,
7604 ArrayRef<Expr *> Args,
7605 OverloadCandidateSet& CandidateSet) {
7606 if (!CandidateSet.isNewCandidate(Conversion))
7607 return;
7609 // Overload resolution is always an unevaluated context.
7610 EnterExpressionEvaluationContext Unevaluated(
7611 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7613 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7614 Candidate.FoundDecl = FoundDecl;
7615 Candidate.Function = nullptr;
7616 Candidate.Surrogate = Conversion;
7617 Candidate.Viable = true;
7618 Candidate.IsSurrogate = true;
7619 Candidate.IgnoreObjectArgument = false;
7620 Candidate.ExplicitCallArguments = Args.size();
7622 // Determine the implicit conversion sequence for the implicit
7623 // object parameter.
7624 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7625 *this, CandidateSet.getLocation(), Object->getType(),
7626 Object->Classify(Context), Conversion, ActingContext);
7627 if (ObjectInit.isBad()) {
7628 Candidate.Viable = false;
7629 Candidate.FailureKind = ovl_fail_bad_conversion;
7630 Candidate.Conversions[0] = ObjectInit;
7631 return;
7634 // The first conversion is actually a user-defined conversion whose
7635 // first conversion is ObjectInit's standard conversion (which is
7636 // effectively a reference binding). Record it as such.
7637 Candidate.Conversions[0].setUserDefined();
7638 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7639 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7640 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7641 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7642 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7643 Candidate.Conversions[0].UserDefined.After
7644 = Candidate.Conversions[0].UserDefined.Before;
7645 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7647 // Find the
7648 unsigned NumParams = Proto->getNumParams();
7650 // (C++ 13.3.2p2): A candidate function having fewer than m
7651 // parameters is viable only if it has an ellipsis in its parameter
7652 // list (8.3.5).
7653 if (Args.size() > NumParams && !Proto->isVariadic()) {
7654 Candidate.Viable = false;
7655 Candidate.FailureKind = ovl_fail_too_many_arguments;
7656 return;
7659 // Function types don't have any default arguments, so just check if
7660 // we have enough arguments.
7661 if (Args.size() < NumParams) {
7662 // Not enough arguments.
7663 Candidate.Viable = false;
7664 Candidate.FailureKind = ovl_fail_too_few_arguments;
7665 return;
7668 // Determine the implicit conversion sequences for each of the
7669 // arguments.
7670 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7671 if (ArgIdx < NumParams) {
7672 // (C++ 13.3.2p3): for F to be a viable function, there shall
7673 // exist for each argument an implicit conversion sequence
7674 // (13.3.3.1) that converts that argument to the corresponding
7675 // parameter of F.
7676 QualType ParamType = Proto->getParamType(ArgIdx);
7677 Candidate.Conversions[ArgIdx + 1]
7678 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7679 /*SuppressUserConversions=*/false,
7680 /*InOverloadResolution=*/false,
7681 /*AllowObjCWritebackConversion=*/
7682 getLangOpts().ObjCAutoRefCount);
7683 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7684 Candidate.Viable = false;
7685 Candidate.FailureKind = ovl_fail_bad_conversion;
7686 return;
7688 } else {
7689 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7690 // argument for which there is no corresponding parameter is
7691 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7692 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7696 if (EnableIfAttr *FailedAttr =
7697 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7698 Candidate.Viable = false;
7699 Candidate.FailureKind = ovl_fail_enable_if;
7700 Candidate.DeductionFailure.Data = FailedAttr;
7701 return;
7705 /// Add all of the non-member operator function declarations in the given
7706 /// function set to the overload candidate set.
7707 void Sema::AddNonMemberOperatorCandidates(
7708 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7709 OverloadCandidateSet &CandidateSet,
7710 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7711 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7712 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7713 ArrayRef<Expr *> FunctionArgs = Args;
7715 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7716 FunctionDecl *FD =
7717 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7719 // Don't consider rewritten functions if we're not rewriting.
7720 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7721 continue;
7723 assert(!isa<CXXMethodDecl>(FD) &&
7724 "unqualified operator lookup found a member function");
7726 if (FunTmpl) {
7727 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7728 FunctionArgs, CandidateSet);
7729 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7730 AddTemplateOverloadCandidate(
7731 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7732 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7733 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7734 } else {
7735 if (ExplicitTemplateArgs)
7736 continue;
7737 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7738 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7739 AddOverloadCandidate(FD, F.getPair(),
7740 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7741 false, false, true, false, ADLCallKind::NotADL,
7742 None, OverloadCandidateParamOrder::Reversed);
7747 /// Add overload candidates for overloaded operators that are
7748 /// member functions.
7750 /// Add the overloaded operator candidates that are member functions
7751 /// for the operator Op that was used in an operator expression such
7752 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7753 /// CandidateSet will store the added overload candidates. (C++
7754 /// [over.match.oper]).
7755 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7756 SourceLocation OpLoc,
7757 ArrayRef<Expr *> Args,
7758 OverloadCandidateSet &CandidateSet,
7759 OverloadCandidateParamOrder PO) {
7760 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7762 // C++ [over.match.oper]p3:
7763 // For a unary operator @ with an operand of a type whose
7764 // cv-unqualified version is T1, and for a binary operator @ with
7765 // a left operand of a type whose cv-unqualified version is T1 and
7766 // a right operand of a type whose cv-unqualified version is T2,
7767 // three sets of candidate functions, designated member
7768 // candidates, non-member candidates and built-in candidates, are
7769 // constructed as follows:
7770 QualType T1 = Args[0]->getType();
7772 // -- If T1 is a complete class type or a class currently being
7773 // defined, the set of member candidates is the result of the
7774 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7775 // the set of member candidates is empty.
7776 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7777 // Complete the type if it can be completed.
7778 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7779 return;
7780 // If the type is neither complete nor being defined, bail out now.
7781 if (!T1Rec->getDecl()->getDefinition())
7782 return;
7784 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7785 LookupQualifiedName(Operators, T1Rec->getDecl());
7786 Operators.suppressDiagnostics();
7788 for (LookupResult::iterator Oper = Operators.begin(),
7789 OperEnd = Operators.end();
7790 Oper != OperEnd;
7791 ++Oper)
7792 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7793 Args[0]->Classify(Context), Args.slice(1),
7794 CandidateSet, /*SuppressUserConversion=*/false, PO);
7798 /// AddBuiltinCandidate - Add a candidate for a built-in
7799 /// operator. ResultTy and ParamTys are the result and parameter types
7800 /// of the built-in candidate, respectively. Args and NumArgs are the
7801 /// arguments being passed to the candidate. IsAssignmentOperator
7802 /// should be true when this built-in candidate is an assignment
7803 /// operator. NumContextualBoolArguments is the number of arguments
7804 /// (at the beginning of the argument list) that will be contextually
7805 /// converted to bool.
7806 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7807 OverloadCandidateSet& CandidateSet,
7808 bool IsAssignmentOperator,
7809 unsigned NumContextualBoolArguments) {
7810 // Overload resolution is always an unevaluated context.
7811 EnterExpressionEvaluationContext Unevaluated(
7812 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7814 // Add this candidate
7815 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7816 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7817 Candidate.Function = nullptr;
7818 Candidate.IsSurrogate = false;
7819 Candidate.IgnoreObjectArgument = false;
7820 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7822 // Determine the implicit conversion sequences for each of the
7823 // arguments.
7824 Candidate.Viable = true;
7825 Candidate.ExplicitCallArguments = Args.size();
7826 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7827 // C++ [over.match.oper]p4:
7828 // For the built-in assignment operators, conversions of the
7829 // left operand are restricted as follows:
7830 // -- no temporaries are introduced to hold the left operand, and
7831 // -- no user-defined conversions are applied to the left
7832 // operand to achieve a type match with the left-most
7833 // parameter of a built-in candidate.
7835 // We block these conversions by turning off user-defined
7836 // conversions, since that is the only way that initialization of
7837 // a reference to a non-class type can occur from something that
7838 // is not of the same type.
7839 if (ArgIdx < NumContextualBoolArguments) {
7840 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7841 "Contextual conversion to bool requires bool type");
7842 Candidate.Conversions[ArgIdx]
7843 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7844 } else {
7845 Candidate.Conversions[ArgIdx]
7846 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7847 ArgIdx == 0 && IsAssignmentOperator,
7848 /*InOverloadResolution=*/false,
7849 /*AllowObjCWritebackConversion=*/
7850 getLangOpts().ObjCAutoRefCount);
7852 if (Candidate.Conversions[ArgIdx].isBad()) {
7853 Candidate.Viable = false;
7854 Candidate.FailureKind = ovl_fail_bad_conversion;
7855 break;
7860 namespace {
7862 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7863 /// candidate operator functions for built-in operators (C++
7864 /// [over.built]). The types are separated into pointer types and
7865 /// enumeration types.
7866 class BuiltinCandidateTypeSet {
7867 /// TypeSet - A set of types.
7868 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7869 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7871 /// PointerTypes - The set of pointer types that will be used in the
7872 /// built-in candidates.
7873 TypeSet PointerTypes;
7875 /// MemberPointerTypes - The set of member pointer types that will be
7876 /// used in the built-in candidates.
7877 TypeSet MemberPointerTypes;
7879 /// EnumerationTypes - The set of enumeration types that will be
7880 /// used in the built-in candidates.
7881 TypeSet EnumerationTypes;
7883 /// The set of vector types that will be used in the built-in
7884 /// candidates.
7885 TypeSet VectorTypes;
7887 /// The set of matrix types that will be used in the built-in
7888 /// candidates.
7889 TypeSet MatrixTypes;
7891 /// A flag indicating non-record types are viable candidates
7892 bool HasNonRecordTypes;
7894 /// A flag indicating whether either arithmetic or enumeration types
7895 /// were present in the candidate set.
7896 bool HasArithmeticOrEnumeralTypes;
7898 /// A flag indicating whether the nullptr type was present in the
7899 /// candidate set.
7900 bool HasNullPtrType;
7902 /// Sema - The semantic analysis instance where we are building the
7903 /// candidate type set.
7904 Sema &SemaRef;
7906 /// Context - The AST context in which we will build the type sets.
7907 ASTContext &Context;
7909 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7910 const Qualifiers &VisibleQuals);
7911 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7913 public:
7914 /// iterator - Iterates through the types that are part of the set.
7915 typedef TypeSet::iterator iterator;
7917 BuiltinCandidateTypeSet(Sema &SemaRef)
7918 : HasNonRecordTypes(false),
7919 HasArithmeticOrEnumeralTypes(false),
7920 HasNullPtrType(false),
7921 SemaRef(SemaRef),
7922 Context(SemaRef.Context) { }
7924 void AddTypesConvertedFrom(QualType Ty,
7925 SourceLocation Loc,
7926 bool AllowUserConversions,
7927 bool AllowExplicitConversions,
7928 const Qualifiers &VisibleTypeConversionsQuals);
7930 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7931 llvm::iterator_range<iterator> member_pointer_types() {
7932 return MemberPointerTypes;
7934 llvm::iterator_range<iterator> enumeration_types() {
7935 return EnumerationTypes;
7937 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7938 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7940 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7941 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7942 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7943 bool hasNullPtrType() const { return HasNullPtrType; }
7946 } // end anonymous namespace
7948 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7949 /// the set of pointer types along with any more-qualified variants of
7950 /// that type. For example, if @p Ty is "int const *", this routine
7951 /// will add "int const *", "int const volatile *", "int const
7952 /// restrict *", and "int const volatile restrict *" to the set of
7953 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7954 /// false otherwise.
7956 /// FIXME: what to do about extended qualifiers?
7957 bool
7958 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7959 const Qualifiers &VisibleQuals) {
7961 // Insert this type.
7962 if (!PointerTypes.insert(Ty))
7963 return false;
7965 QualType PointeeTy;
7966 const PointerType *PointerTy = Ty->getAs<PointerType>();
7967 bool buildObjCPtr = false;
7968 if (!PointerTy) {
7969 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7970 PointeeTy = PTy->getPointeeType();
7971 buildObjCPtr = true;
7972 } else {
7973 PointeeTy = PointerTy->getPointeeType();
7976 // Don't add qualified variants of arrays. For one, they're not allowed
7977 // (the qualifier would sink to the element type), and for another, the
7978 // only overload situation where it matters is subscript or pointer +- int,
7979 // and those shouldn't have qualifier variants anyway.
7980 if (PointeeTy->isArrayType())
7981 return true;
7983 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7984 bool hasVolatile = VisibleQuals.hasVolatile();
7985 bool hasRestrict = VisibleQuals.hasRestrict();
7987 // Iterate through all strict supersets of BaseCVR.
7988 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7989 if ((CVR | BaseCVR) != CVR) continue;
7990 // Skip over volatile if no volatile found anywhere in the types.
7991 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7993 // Skip over restrict if no restrict found anywhere in the types, or if
7994 // the type cannot be restrict-qualified.
7995 if ((CVR & Qualifiers::Restrict) &&
7996 (!hasRestrict ||
7997 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7998 continue;
8000 // Build qualified pointee type.
8001 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8003 // Build qualified pointer type.
8004 QualType QPointerTy;
8005 if (!buildObjCPtr)
8006 QPointerTy = Context.getPointerType(QPointeeTy);
8007 else
8008 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8010 // Insert qualified pointer type.
8011 PointerTypes.insert(QPointerTy);
8014 return true;
8017 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8018 /// to the set of pointer types along with any more-qualified variants of
8019 /// that type. For example, if @p Ty is "int const *", this routine
8020 /// will add "int const *", "int const volatile *", "int const
8021 /// restrict *", and "int const volatile restrict *" to the set of
8022 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8023 /// false otherwise.
8025 /// FIXME: what to do about extended qualifiers?
8026 bool
8027 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8028 QualType Ty) {
8029 // Insert this type.
8030 if (!MemberPointerTypes.insert(Ty))
8031 return false;
8033 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8034 assert(PointerTy && "type was not a member pointer type!");
8036 QualType PointeeTy = PointerTy->getPointeeType();
8037 // Don't add qualified variants of arrays. For one, they're not allowed
8038 // (the qualifier would sink to the element type), and for another, the
8039 // only overload situation where it matters is subscript or pointer +- int,
8040 // and those shouldn't have qualifier variants anyway.
8041 if (PointeeTy->isArrayType())
8042 return true;
8043 const Type *ClassTy = PointerTy->getClass();
8045 // Iterate through all strict supersets of the pointee type's CVR
8046 // qualifiers.
8047 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8048 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8049 if ((CVR | BaseCVR) != CVR) continue;
8051 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8052 MemberPointerTypes.insert(
8053 Context.getMemberPointerType(QPointeeTy, ClassTy));
8056 return true;
8059 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8060 /// Ty can be implicit converted to the given set of @p Types. We're
8061 /// primarily interested in pointer types and enumeration types. We also
8062 /// take member pointer types, for the conditional operator.
8063 /// AllowUserConversions is true if we should look at the conversion
8064 /// functions of a class type, and AllowExplicitConversions if we
8065 /// should also include the explicit conversion functions of a class
8066 /// type.
8067 void
8068 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8069 SourceLocation Loc,
8070 bool AllowUserConversions,
8071 bool AllowExplicitConversions,
8072 const Qualifiers &VisibleQuals) {
8073 // Only deal with canonical types.
8074 Ty = Context.getCanonicalType(Ty);
8076 // Look through reference types; they aren't part of the type of an
8077 // expression for the purposes of conversions.
8078 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8079 Ty = RefTy->getPointeeType();
8081 // If we're dealing with an array type, decay to the pointer.
8082 if (Ty->isArrayType())
8083 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8085 // Otherwise, we don't care about qualifiers on the type.
8086 Ty = Ty.getLocalUnqualifiedType();
8088 // Flag if we ever add a non-record type.
8089 const RecordType *TyRec = Ty->getAs<RecordType>();
8090 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8092 // Flag if we encounter an arithmetic type.
8093 HasArithmeticOrEnumeralTypes =
8094 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8096 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8097 PointerTypes.insert(Ty);
8098 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8099 // Insert our type, and its more-qualified variants, into the set
8100 // of types.
8101 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8102 return;
8103 } else if (Ty->isMemberPointerType()) {
8104 // Member pointers are far easier, since the pointee can't be converted.
8105 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8106 return;
8107 } else if (Ty->isEnumeralType()) {
8108 HasArithmeticOrEnumeralTypes = true;
8109 EnumerationTypes.insert(Ty);
8110 } else if (Ty->isVectorType()) {
8111 // We treat vector types as arithmetic types in many contexts as an
8112 // extension.
8113 HasArithmeticOrEnumeralTypes = true;
8114 VectorTypes.insert(Ty);
8115 } else if (Ty->isMatrixType()) {
8116 // Similar to vector types, we treat vector types as arithmetic types in
8117 // many contexts as an extension.
8118 HasArithmeticOrEnumeralTypes = true;
8119 MatrixTypes.insert(Ty);
8120 } else if (Ty->isNullPtrType()) {
8121 HasNullPtrType = true;
8122 } else if (AllowUserConversions && TyRec) {
8123 // No conversion functions in incomplete types.
8124 if (!SemaRef.isCompleteType(Loc, Ty))
8125 return;
8127 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8128 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8129 if (isa<UsingShadowDecl>(D))
8130 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8132 // Skip conversion function templates; they don't tell us anything
8133 // about which builtin types we can convert to.
8134 if (isa<FunctionTemplateDecl>(D))
8135 continue;
8137 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8138 if (AllowExplicitConversions || !Conv->isExplicit()) {
8139 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8140 VisibleQuals);
8145 /// Helper function for adjusting address spaces for the pointer or reference
8146 /// operands of builtin operators depending on the argument.
8147 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8148 Expr *Arg) {
8149 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8152 /// Helper function for AddBuiltinOperatorCandidates() that adds
8153 /// the volatile- and non-volatile-qualified assignment operators for the
8154 /// given type to the candidate set.
8155 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8156 QualType T,
8157 ArrayRef<Expr *> Args,
8158 OverloadCandidateSet &CandidateSet) {
8159 QualType ParamTypes[2];
8161 // T& operator=(T&, T)
8162 ParamTypes[0] = S.Context.getLValueReferenceType(
8163 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8164 ParamTypes[1] = T;
8165 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8166 /*IsAssignmentOperator=*/true);
8168 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8169 // volatile T& operator=(volatile T&, T)
8170 ParamTypes[0] = S.Context.getLValueReferenceType(
8171 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8172 Args[0]));
8173 ParamTypes[1] = T;
8174 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8175 /*IsAssignmentOperator=*/true);
8179 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8180 /// if any, found in visible type conversion functions found in ArgExpr's type.
8181 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8182 Qualifiers VRQuals;
8183 const RecordType *TyRec;
8184 if (const MemberPointerType *RHSMPType =
8185 ArgExpr->getType()->getAs<MemberPointerType>())
8186 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8187 else
8188 TyRec = ArgExpr->getType()->getAs<RecordType>();
8189 if (!TyRec) {
8190 // Just to be safe, assume the worst case.
8191 VRQuals.addVolatile();
8192 VRQuals.addRestrict();
8193 return VRQuals;
8196 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8197 if (!ClassDecl->hasDefinition())
8198 return VRQuals;
8200 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8201 if (isa<UsingShadowDecl>(D))
8202 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8203 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8204 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8205 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8206 CanTy = ResTypeRef->getPointeeType();
8207 // Need to go down the pointer/mempointer chain and add qualifiers
8208 // as see them.
8209 bool done = false;
8210 while (!done) {
8211 if (CanTy.isRestrictQualified())
8212 VRQuals.addRestrict();
8213 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8214 CanTy = ResTypePtr->getPointeeType();
8215 else if (const MemberPointerType *ResTypeMPtr =
8216 CanTy->getAs<MemberPointerType>())
8217 CanTy = ResTypeMPtr->getPointeeType();
8218 else
8219 done = true;
8220 if (CanTy.isVolatileQualified())
8221 VRQuals.addVolatile();
8222 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8223 return VRQuals;
8227 return VRQuals;
8230 // Note: We're currently only handling qualifiers that are meaningful for the
8231 // LHS of compound assignment overloading.
8232 static void forAllQualifierCombinationsImpl(
8233 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8234 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8235 // _Atomic
8236 if (Available.hasAtomic()) {
8237 Available.removeAtomic();
8238 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8239 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8240 return;
8243 // volatile
8244 if (Available.hasVolatile()) {
8245 Available.removeVolatile();
8246 assert(!Applied.hasVolatile());
8247 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8248 Callback);
8249 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8250 return;
8253 Callback(Applied);
8256 static void forAllQualifierCombinations(
8257 QualifiersAndAtomic Quals,
8258 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8259 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8260 Callback);
8263 static QualType makeQualifiedLValueReferenceType(QualType Base,
8264 QualifiersAndAtomic Quals,
8265 Sema &S) {
8266 if (Quals.hasAtomic())
8267 Base = S.Context.getAtomicType(Base);
8268 if (Quals.hasVolatile())
8269 Base = S.Context.getVolatileType(Base);
8270 return S.Context.getLValueReferenceType(Base);
8273 namespace {
8275 /// Helper class to manage the addition of builtin operator overload
8276 /// candidates. It provides shared state and utility methods used throughout
8277 /// the process, as well as a helper method to add each group of builtin
8278 /// operator overloads from the standard to a candidate set.
8279 class BuiltinOperatorOverloadBuilder {
8280 // Common instance state available to all overload candidate addition methods.
8281 Sema &S;
8282 ArrayRef<Expr *> Args;
8283 QualifiersAndAtomic VisibleTypeConversionsQuals;
8284 bool HasArithmeticOrEnumeralCandidateType;
8285 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8286 OverloadCandidateSet &CandidateSet;
8288 static constexpr int ArithmeticTypesCap = 24;
8289 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8291 // Define some indices used to iterate over the arithmetic types in
8292 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8293 // types are that preserved by promotion (C++ [over.built]p2).
8294 unsigned FirstIntegralType,
8295 LastIntegralType;
8296 unsigned FirstPromotedIntegralType,
8297 LastPromotedIntegralType;
8298 unsigned FirstPromotedArithmeticType,
8299 LastPromotedArithmeticType;
8300 unsigned NumArithmeticTypes;
8302 void InitArithmeticTypes() {
8303 // Start of promoted types.
8304 FirstPromotedArithmeticType = 0;
8305 ArithmeticTypes.push_back(S.Context.FloatTy);
8306 ArithmeticTypes.push_back(S.Context.DoubleTy);
8307 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8308 if (S.Context.getTargetInfo().hasFloat128Type())
8309 ArithmeticTypes.push_back(S.Context.Float128Ty);
8310 if (S.Context.getTargetInfo().hasIbm128Type())
8311 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8313 // Start of integral types.
8314 FirstIntegralType = ArithmeticTypes.size();
8315 FirstPromotedIntegralType = ArithmeticTypes.size();
8316 ArithmeticTypes.push_back(S.Context.IntTy);
8317 ArithmeticTypes.push_back(S.Context.LongTy);
8318 ArithmeticTypes.push_back(S.Context.LongLongTy);
8319 if (S.Context.getTargetInfo().hasInt128Type() ||
8320 (S.Context.getAuxTargetInfo() &&
8321 S.Context.getAuxTargetInfo()->hasInt128Type()))
8322 ArithmeticTypes.push_back(S.Context.Int128Ty);
8323 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8324 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8325 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8326 if (S.Context.getTargetInfo().hasInt128Type() ||
8327 (S.Context.getAuxTargetInfo() &&
8328 S.Context.getAuxTargetInfo()->hasInt128Type()))
8329 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8330 LastPromotedIntegralType = ArithmeticTypes.size();
8331 LastPromotedArithmeticType = ArithmeticTypes.size();
8332 // End of promoted types.
8334 ArithmeticTypes.push_back(S.Context.BoolTy);
8335 ArithmeticTypes.push_back(S.Context.CharTy);
8336 ArithmeticTypes.push_back(S.Context.WCharTy);
8337 if (S.Context.getLangOpts().Char8)
8338 ArithmeticTypes.push_back(S.Context.Char8Ty);
8339 ArithmeticTypes.push_back(S.Context.Char16Ty);
8340 ArithmeticTypes.push_back(S.Context.Char32Ty);
8341 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8342 ArithmeticTypes.push_back(S.Context.ShortTy);
8343 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8344 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8345 LastIntegralType = ArithmeticTypes.size();
8346 NumArithmeticTypes = ArithmeticTypes.size();
8347 // End of integral types.
8348 // FIXME: What about complex? What about half?
8350 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8351 "Enough inline storage for all arithmetic types.");
8354 /// Helper method to factor out the common pattern of adding overloads
8355 /// for '++' and '--' builtin operators.
8356 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8357 bool HasVolatile,
8358 bool HasRestrict) {
8359 QualType ParamTypes[2] = {
8360 S.Context.getLValueReferenceType(CandidateTy),
8361 S.Context.IntTy
8364 // Non-volatile version.
8365 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8367 // Use a heuristic to reduce number of builtin candidates in the set:
8368 // add volatile version only if there are conversions to a volatile type.
8369 if (HasVolatile) {
8370 ParamTypes[0] =
8371 S.Context.getLValueReferenceType(
8372 S.Context.getVolatileType(CandidateTy));
8373 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8376 // Add restrict version only if there are conversions to a restrict type
8377 // and our candidate type is a non-restrict-qualified pointer.
8378 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8379 !CandidateTy.isRestrictQualified()) {
8380 ParamTypes[0]
8381 = S.Context.getLValueReferenceType(
8382 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8383 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8385 if (HasVolatile) {
8386 ParamTypes[0]
8387 = S.Context.getLValueReferenceType(
8388 S.Context.getCVRQualifiedType(CandidateTy,
8389 (Qualifiers::Volatile |
8390 Qualifiers::Restrict)));
8391 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8397 /// Helper to add an overload candidate for a binary builtin with types \p L
8398 /// and \p R.
8399 void AddCandidate(QualType L, QualType R) {
8400 QualType LandR[2] = {L, R};
8401 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8404 public:
8405 BuiltinOperatorOverloadBuilder(
8406 Sema &S, ArrayRef<Expr *> Args,
8407 QualifiersAndAtomic VisibleTypeConversionsQuals,
8408 bool HasArithmeticOrEnumeralCandidateType,
8409 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8410 OverloadCandidateSet &CandidateSet)
8411 : S(S), Args(Args),
8412 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8413 HasArithmeticOrEnumeralCandidateType(
8414 HasArithmeticOrEnumeralCandidateType),
8415 CandidateTypes(CandidateTypes),
8416 CandidateSet(CandidateSet) {
8418 InitArithmeticTypes();
8421 // Increment is deprecated for bool since C++17.
8423 // C++ [over.built]p3:
8425 // For every pair (T, VQ), where T is an arithmetic type other
8426 // than bool, and VQ is either volatile or empty, there exist
8427 // candidate operator functions of the form
8429 // VQ T& operator++(VQ T&);
8430 // T operator++(VQ T&, int);
8432 // C++ [over.built]p4:
8434 // For every pair (T, VQ), where T is an arithmetic type other
8435 // than bool, and VQ is either volatile or empty, there exist
8436 // candidate operator functions of the form
8438 // VQ T& operator--(VQ T&);
8439 // T operator--(VQ T&, int);
8440 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8441 if (!HasArithmeticOrEnumeralCandidateType)
8442 return;
8444 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8445 const auto TypeOfT = ArithmeticTypes[Arith];
8446 if (TypeOfT == S.Context.BoolTy) {
8447 if (Op == OO_MinusMinus)
8448 continue;
8449 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8450 continue;
8452 addPlusPlusMinusMinusStyleOverloads(
8453 TypeOfT,
8454 VisibleTypeConversionsQuals.hasVolatile(),
8455 VisibleTypeConversionsQuals.hasRestrict());
8459 // C++ [over.built]p5:
8461 // For every pair (T, VQ), where T is a cv-qualified or
8462 // cv-unqualified object type, and VQ is either volatile or
8463 // empty, there exist candidate operator functions of the form
8465 // T*VQ& operator++(T*VQ&);
8466 // T*VQ& operator--(T*VQ&);
8467 // T* operator++(T*VQ&, int);
8468 // T* operator--(T*VQ&, int);
8469 void addPlusPlusMinusMinusPointerOverloads() {
8470 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8471 // Skip pointer types that aren't pointers to object types.
8472 if (!PtrTy->getPointeeType()->isObjectType())
8473 continue;
8475 addPlusPlusMinusMinusStyleOverloads(
8476 PtrTy,
8477 (!PtrTy.isVolatileQualified() &&
8478 VisibleTypeConversionsQuals.hasVolatile()),
8479 (!PtrTy.isRestrictQualified() &&
8480 VisibleTypeConversionsQuals.hasRestrict()));
8484 // C++ [over.built]p6:
8485 // For every cv-qualified or cv-unqualified object type T, there
8486 // exist candidate operator functions of the form
8488 // T& operator*(T*);
8490 // C++ [over.built]p7:
8491 // For every function type T that does not have cv-qualifiers or a
8492 // ref-qualifier, there exist candidate operator functions of the form
8493 // T& operator*(T*);
8494 void addUnaryStarPointerOverloads() {
8495 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8496 QualType PointeeTy = ParamTy->getPointeeType();
8497 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8498 continue;
8500 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8501 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8502 continue;
8504 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8508 // C++ [over.built]p9:
8509 // For every promoted arithmetic type T, there exist candidate
8510 // operator functions of the form
8512 // T operator+(T);
8513 // T operator-(T);
8514 void addUnaryPlusOrMinusArithmeticOverloads() {
8515 if (!HasArithmeticOrEnumeralCandidateType)
8516 return;
8518 for (unsigned Arith = FirstPromotedArithmeticType;
8519 Arith < LastPromotedArithmeticType; ++Arith) {
8520 QualType ArithTy = ArithmeticTypes[Arith];
8521 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8524 // Extension: We also add these operators for vector types.
8525 for (QualType VecTy : CandidateTypes[0].vector_types())
8526 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8529 // C++ [over.built]p8:
8530 // For every type T, there exist candidate operator functions of
8531 // the form
8533 // T* operator+(T*);
8534 void addUnaryPlusPointerOverloads() {
8535 for (QualType ParamTy : CandidateTypes[0].pointer_types())
8536 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8539 // C++ [over.built]p10:
8540 // For every promoted integral type T, there exist candidate
8541 // operator functions of the form
8543 // T operator~(T);
8544 void addUnaryTildePromotedIntegralOverloads() {
8545 if (!HasArithmeticOrEnumeralCandidateType)
8546 return;
8548 for (unsigned Int = FirstPromotedIntegralType;
8549 Int < LastPromotedIntegralType; ++Int) {
8550 QualType IntTy = ArithmeticTypes[Int];
8551 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8554 // Extension: We also add this operator for vector types.
8555 for (QualType VecTy : CandidateTypes[0].vector_types())
8556 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8559 // C++ [over.match.oper]p16:
8560 // For every pointer to member type T or type std::nullptr_t, there
8561 // exist candidate operator functions of the form
8563 // bool operator==(T,T);
8564 // bool operator!=(T,T);
8565 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8566 /// Set of (canonical) types that we've already handled.
8567 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8569 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8570 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8571 // Don't add the same builtin candidate twice.
8572 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8573 continue;
8575 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8576 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8579 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8580 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8581 if (AddedTypes.insert(NullPtrTy).second) {
8582 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8583 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8589 // C++ [over.built]p15:
8591 // For every T, where T is an enumeration type or a pointer type,
8592 // there exist candidate operator functions of the form
8594 // bool operator<(T, T);
8595 // bool operator>(T, T);
8596 // bool operator<=(T, T);
8597 // bool operator>=(T, T);
8598 // bool operator==(T, T);
8599 // bool operator!=(T, T);
8600 // R operator<=>(T, T)
8601 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8602 // C++ [over.match.oper]p3:
8603 // [...]the built-in candidates include all of the candidate operator
8604 // functions defined in 13.6 that, compared to the given operator, [...]
8605 // do not have the same parameter-type-list as any non-template non-member
8606 // candidate.
8608 // Note that in practice, this only affects enumeration types because there
8609 // aren't any built-in candidates of record type, and a user-defined operator
8610 // must have an operand of record or enumeration type. Also, the only other
8611 // overloaded operator with enumeration arguments, operator=,
8612 // cannot be overloaded for enumeration types, so this is the only place
8613 // where we must suppress candidates like this.
8614 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8615 UserDefinedBinaryOperators;
8617 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8618 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8619 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8620 CEnd = CandidateSet.end();
8621 C != CEnd; ++C) {
8622 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8623 continue;
8625 if (C->Function->isFunctionTemplateSpecialization())
8626 continue;
8628 // We interpret "same parameter-type-list" as applying to the
8629 // "synthesized candidate, with the order of the two parameters
8630 // reversed", not to the original function.
8631 bool Reversed = C->isReversed();
8632 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8633 ->getType()
8634 .getUnqualifiedType();
8635 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8636 ->getType()
8637 .getUnqualifiedType();
8639 // Skip if either parameter isn't of enumeral type.
8640 if (!FirstParamType->isEnumeralType() ||
8641 !SecondParamType->isEnumeralType())
8642 continue;
8644 // Add this operator to the set of known user-defined operators.
8645 UserDefinedBinaryOperators.insert(
8646 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8647 S.Context.getCanonicalType(SecondParamType)));
8652 /// Set of (canonical) types that we've already handled.
8653 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8655 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8656 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8657 // Don't add the same builtin candidate twice.
8658 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8659 continue;
8660 if (IsSpaceship && PtrTy->isFunctionPointerType())
8661 continue;
8663 QualType ParamTypes[2] = {PtrTy, PtrTy};
8664 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8666 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8667 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8669 // Don't add the same builtin candidate twice, or if a user defined
8670 // candidate exists.
8671 if (!AddedTypes.insert(CanonType).second ||
8672 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8673 CanonType)))
8674 continue;
8675 QualType ParamTypes[2] = {EnumTy, EnumTy};
8676 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8681 // C++ [over.built]p13:
8683 // For every cv-qualified or cv-unqualified object type T
8684 // there exist candidate operator functions of the form
8686 // T* operator+(T*, ptrdiff_t);
8687 // T& operator[](T*, ptrdiff_t); [BELOW]
8688 // T* operator-(T*, ptrdiff_t);
8689 // T* operator+(ptrdiff_t, T*);
8690 // T& operator[](ptrdiff_t, T*); [BELOW]
8692 // C++ [over.built]p14:
8694 // For every T, where T is a pointer to object type, there
8695 // exist candidate operator functions of the form
8697 // ptrdiff_t operator-(T, T);
8698 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8699 /// Set of (canonical) types that we've already handled.
8700 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8702 for (int Arg = 0; Arg < 2; ++Arg) {
8703 QualType AsymmetricParamTypes[2] = {
8704 S.Context.getPointerDiffType(),
8705 S.Context.getPointerDiffType(),
8707 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8708 QualType PointeeTy = PtrTy->getPointeeType();
8709 if (!PointeeTy->isObjectType())
8710 continue;
8712 AsymmetricParamTypes[Arg] = PtrTy;
8713 if (Arg == 0 || Op == OO_Plus) {
8714 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8715 // T* operator+(ptrdiff_t, T*);
8716 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8718 if (Op == OO_Minus) {
8719 // ptrdiff_t operator-(T, T);
8720 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8721 continue;
8723 QualType ParamTypes[2] = {PtrTy, PtrTy};
8724 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8730 // C++ [over.built]p12:
8732 // For every pair of promoted arithmetic types L and R, there
8733 // exist candidate operator functions of the form
8735 // LR operator*(L, R);
8736 // LR operator/(L, R);
8737 // LR operator+(L, R);
8738 // LR operator-(L, R);
8739 // bool operator<(L, R);
8740 // bool operator>(L, R);
8741 // bool operator<=(L, R);
8742 // bool operator>=(L, R);
8743 // bool operator==(L, R);
8744 // bool operator!=(L, R);
8746 // where LR is the result of the usual arithmetic conversions
8747 // between types L and R.
8749 // C++ [over.built]p24:
8751 // For every pair of promoted arithmetic types L and R, there exist
8752 // candidate operator functions of the form
8754 // LR operator?(bool, L, R);
8756 // where LR is the result of the usual arithmetic conversions
8757 // between types L and R.
8758 // Our candidates ignore the first parameter.
8759 void addGenericBinaryArithmeticOverloads() {
8760 if (!HasArithmeticOrEnumeralCandidateType)
8761 return;
8763 for (unsigned Left = FirstPromotedArithmeticType;
8764 Left < LastPromotedArithmeticType; ++Left) {
8765 for (unsigned Right = FirstPromotedArithmeticType;
8766 Right < LastPromotedArithmeticType; ++Right) {
8767 QualType LandR[2] = { ArithmeticTypes[Left],
8768 ArithmeticTypes[Right] };
8769 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8773 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8774 // conditional operator for vector types.
8775 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8776 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8777 QualType LandR[2] = {Vec1Ty, Vec2Ty};
8778 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8782 /// Add binary operator overloads for each candidate matrix type M1, M2:
8783 /// * (M1, M1) -> M1
8784 /// * (M1, M1.getElementType()) -> M1
8785 /// * (M2.getElementType(), M2) -> M2
8786 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8787 void addMatrixBinaryArithmeticOverloads() {
8788 if (!HasArithmeticOrEnumeralCandidateType)
8789 return;
8791 for (QualType M1 : CandidateTypes[0].matrix_types()) {
8792 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8793 AddCandidate(M1, M1);
8796 for (QualType M2 : CandidateTypes[1].matrix_types()) {
8797 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8798 if (!CandidateTypes[0].containsMatrixType(M2))
8799 AddCandidate(M2, M2);
8803 // C++2a [over.built]p14:
8805 // For every integral type T there exists a candidate operator function
8806 // of the form
8808 // std::strong_ordering operator<=>(T, T)
8810 // C++2a [over.built]p15:
8812 // For every pair of floating-point types L and R, there exists a candidate
8813 // operator function of the form
8815 // std::partial_ordering operator<=>(L, R);
8817 // FIXME: The current specification for integral types doesn't play nice with
8818 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8819 // comparisons. Under the current spec this can lead to ambiguity during
8820 // overload resolution. For example:
8822 // enum A : int {a};
8823 // auto x = (a <=> (long)42);
8825 // error: call is ambiguous for arguments 'A' and 'long'.
8826 // note: candidate operator<=>(int, int)
8827 // note: candidate operator<=>(long, long)
8829 // To avoid this error, this function deviates from the specification and adds
8830 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8831 // arithmetic types (the same as the generic relational overloads).
8833 // For now this function acts as a placeholder.
8834 void addThreeWayArithmeticOverloads() {
8835 addGenericBinaryArithmeticOverloads();
8838 // C++ [over.built]p17:
8840 // For every pair of promoted integral types L and R, there
8841 // exist candidate operator functions of the form
8843 // LR operator%(L, R);
8844 // LR operator&(L, R);
8845 // LR operator^(L, R);
8846 // LR operator|(L, R);
8847 // L operator<<(L, R);
8848 // L operator>>(L, R);
8850 // where LR is the result of the usual arithmetic conversions
8851 // between types L and R.
8852 void addBinaryBitwiseArithmeticOverloads() {
8853 if (!HasArithmeticOrEnumeralCandidateType)
8854 return;
8856 for (unsigned Left = FirstPromotedIntegralType;
8857 Left < LastPromotedIntegralType; ++Left) {
8858 for (unsigned Right = FirstPromotedIntegralType;
8859 Right < LastPromotedIntegralType; ++Right) {
8860 QualType LandR[2] = { ArithmeticTypes[Left],
8861 ArithmeticTypes[Right] };
8862 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8867 // C++ [over.built]p20:
8869 // For every pair (T, VQ), where T is an enumeration or
8870 // pointer to member type and VQ is either volatile or
8871 // empty, there exist candidate operator functions of the form
8873 // VQ T& operator=(VQ T&, T);
8874 void addAssignmentMemberPointerOrEnumeralOverloads() {
8875 /// Set of (canonical) types that we've already handled.
8876 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8878 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8879 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8880 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8881 continue;
8883 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8886 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8887 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8888 continue;
8890 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8895 // C++ [over.built]p19:
8897 // For every pair (T, VQ), where T is any type and VQ is either
8898 // volatile or empty, there exist candidate operator functions
8899 // of the form
8901 // T*VQ& operator=(T*VQ&, T*);
8903 // C++ [over.built]p21:
8905 // For every pair (T, VQ), where T is a cv-qualified or
8906 // cv-unqualified object type and VQ is either volatile or
8907 // empty, there exist candidate operator functions of the form
8909 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8910 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8911 void addAssignmentPointerOverloads(bool isEqualOp) {
8912 /// Set of (canonical) types that we've already handled.
8913 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8915 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8916 // If this is operator=, keep track of the builtin candidates we added.
8917 if (isEqualOp)
8918 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8919 else if (!PtrTy->getPointeeType()->isObjectType())
8920 continue;
8922 // non-volatile version
8923 QualType ParamTypes[2] = {
8924 S.Context.getLValueReferenceType(PtrTy),
8925 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8927 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8928 /*IsAssignmentOperator=*/ isEqualOp);
8930 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8931 VisibleTypeConversionsQuals.hasVolatile();
8932 if (NeedVolatile) {
8933 // volatile version
8934 ParamTypes[0] =
8935 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8936 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8937 /*IsAssignmentOperator=*/isEqualOp);
8940 if (!PtrTy.isRestrictQualified() &&
8941 VisibleTypeConversionsQuals.hasRestrict()) {
8942 // restrict version
8943 ParamTypes[0] =
8944 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8945 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8946 /*IsAssignmentOperator=*/isEqualOp);
8948 if (NeedVolatile) {
8949 // volatile restrict version
8950 ParamTypes[0] =
8951 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8952 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8954 /*IsAssignmentOperator=*/isEqualOp);
8959 if (isEqualOp) {
8960 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8961 // Make sure we don't add the same candidate twice.
8962 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8963 continue;
8965 QualType ParamTypes[2] = {
8966 S.Context.getLValueReferenceType(PtrTy),
8967 PtrTy,
8970 // non-volatile version
8971 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8972 /*IsAssignmentOperator=*/true);
8974 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8975 VisibleTypeConversionsQuals.hasVolatile();
8976 if (NeedVolatile) {
8977 // volatile version
8978 ParamTypes[0] = S.Context.getLValueReferenceType(
8979 S.Context.getVolatileType(PtrTy));
8980 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8981 /*IsAssignmentOperator=*/true);
8984 if (!PtrTy.isRestrictQualified() &&
8985 VisibleTypeConversionsQuals.hasRestrict()) {
8986 // restrict version
8987 ParamTypes[0] = S.Context.getLValueReferenceType(
8988 S.Context.getRestrictType(PtrTy));
8989 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8990 /*IsAssignmentOperator=*/true);
8992 if (NeedVolatile) {
8993 // volatile restrict version
8994 ParamTypes[0] =
8995 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8996 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8997 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8998 /*IsAssignmentOperator=*/true);
9005 // C++ [over.built]p18:
9007 // For every triple (L, VQ, R), where L is an arithmetic type,
9008 // VQ is either volatile or empty, and R is a promoted
9009 // arithmetic type, there exist candidate operator functions of
9010 // the form
9012 // VQ L& operator=(VQ L&, R);
9013 // VQ L& operator*=(VQ L&, R);
9014 // VQ L& operator/=(VQ L&, R);
9015 // VQ L& operator+=(VQ L&, R);
9016 // VQ L& operator-=(VQ L&, R);
9017 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9018 if (!HasArithmeticOrEnumeralCandidateType)
9019 return;
9021 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9022 for (unsigned Right = FirstPromotedArithmeticType;
9023 Right < LastPromotedArithmeticType; ++Right) {
9024 QualType ParamTypes[2];
9025 ParamTypes[1] = ArithmeticTypes[Right];
9026 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9027 S, ArithmeticTypes[Left], Args[0]);
9029 forAllQualifierCombinations(
9030 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9031 ParamTypes[0] =
9032 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9033 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9034 /*IsAssignmentOperator=*/isEqualOp);
9039 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9040 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9041 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9042 QualType ParamTypes[2];
9043 ParamTypes[1] = Vec2Ty;
9044 // Add this built-in operator as a candidate (VQ is empty).
9045 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9046 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9047 /*IsAssignmentOperator=*/isEqualOp);
9049 // Add this built-in operator as a candidate (VQ is 'volatile').
9050 if (VisibleTypeConversionsQuals.hasVolatile()) {
9051 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9052 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9053 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9054 /*IsAssignmentOperator=*/isEqualOp);
9059 // C++ [over.built]p22:
9061 // For every triple (L, VQ, R), where L is an integral type, VQ
9062 // is either volatile or empty, and R is a promoted integral
9063 // type, there exist candidate operator functions of the form
9065 // VQ L& operator%=(VQ L&, R);
9066 // VQ L& operator<<=(VQ L&, R);
9067 // VQ L& operator>>=(VQ L&, R);
9068 // VQ L& operator&=(VQ L&, R);
9069 // VQ L& operator^=(VQ L&, R);
9070 // VQ L& operator|=(VQ L&, R);
9071 void addAssignmentIntegralOverloads() {
9072 if (!HasArithmeticOrEnumeralCandidateType)
9073 return;
9075 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9076 for (unsigned Right = FirstPromotedIntegralType;
9077 Right < LastPromotedIntegralType; ++Right) {
9078 QualType ParamTypes[2];
9079 ParamTypes[1] = ArithmeticTypes[Right];
9080 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9081 S, ArithmeticTypes[Left], Args[0]);
9083 forAllQualifierCombinations(
9084 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9085 ParamTypes[0] =
9086 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9087 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9093 // C++ [over.operator]p23:
9095 // There also exist candidate operator functions of the form
9097 // bool operator!(bool);
9098 // bool operator&&(bool, bool);
9099 // bool operator||(bool, bool);
9100 void addExclaimOverload() {
9101 QualType ParamTy = S.Context.BoolTy;
9102 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9103 /*IsAssignmentOperator=*/false,
9104 /*NumContextualBoolArguments=*/1);
9106 void addAmpAmpOrPipePipeOverload() {
9107 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9108 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9109 /*IsAssignmentOperator=*/false,
9110 /*NumContextualBoolArguments=*/2);
9113 // C++ [over.built]p13:
9115 // For every cv-qualified or cv-unqualified object type T there
9116 // exist candidate operator functions of the form
9118 // T* operator+(T*, ptrdiff_t); [ABOVE]
9119 // T& operator[](T*, ptrdiff_t);
9120 // T* operator-(T*, ptrdiff_t); [ABOVE]
9121 // T* operator+(ptrdiff_t, T*); [ABOVE]
9122 // T& operator[](ptrdiff_t, T*);
9123 void addSubscriptOverloads() {
9124 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9125 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9126 QualType PointeeType = PtrTy->getPointeeType();
9127 if (!PointeeType->isObjectType())
9128 continue;
9130 // T& operator[](T*, ptrdiff_t)
9131 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9134 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9135 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9136 QualType PointeeType = PtrTy->getPointeeType();
9137 if (!PointeeType->isObjectType())
9138 continue;
9140 // T& operator[](ptrdiff_t, T*)
9141 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9145 // C++ [over.built]p11:
9146 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9147 // C1 is the same type as C2 or is a derived class of C2, T is an object
9148 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9149 // there exist candidate operator functions of the form
9151 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9153 // where CV12 is the union of CV1 and CV2.
9154 void addArrowStarOverloads() {
9155 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9156 QualType C1Ty = PtrTy;
9157 QualType C1;
9158 QualifierCollector Q1;
9159 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9160 if (!isa<RecordType>(C1))
9161 continue;
9162 // heuristic to reduce number of builtin candidates in the set.
9163 // Add volatile/restrict version only if there are conversions to a
9164 // volatile/restrict type.
9165 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9166 continue;
9167 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9168 continue;
9169 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9170 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9171 QualType C2 = QualType(mptr->getClass(), 0);
9172 C2 = C2.getUnqualifiedType();
9173 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9174 break;
9175 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9176 // build CV12 T&
9177 QualType T = mptr->getPointeeType();
9178 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9179 T.isVolatileQualified())
9180 continue;
9181 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9182 T.isRestrictQualified())
9183 continue;
9184 T = Q1.apply(S.Context, T);
9185 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9190 // Note that we don't consider the first argument, since it has been
9191 // contextually converted to bool long ago. The candidates below are
9192 // therefore added as binary.
9194 // C++ [over.built]p25:
9195 // For every type T, where T is a pointer, pointer-to-member, or scoped
9196 // enumeration type, there exist candidate operator functions of the form
9198 // T operator?(bool, T, T);
9200 void addConditionalOperatorOverloads() {
9201 /// Set of (canonical) types that we've already handled.
9202 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9204 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9205 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9206 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9207 continue;
9209 QualType ParamTypes[2] = {PtrTy, PtrTy};
9210 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9213 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9214 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9215 continue;
9217 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9218 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9221 if (S.getLangOpts().CPlusPlus11) {
9222 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9223 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9224 continue;
9226 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9227 continue;
9229 QualType ParamTypes[2] = {EnumTy, EnumTy};
9230 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9237 } // end anonymous namespace
9239 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9240 /// operator overloads to the candidate set (C++ [over.built]), based
9241 /// on the operator @p Op and the arguments given. For example, if the
9242 /// operator is a binary '+', this routine might add "int
9243 /// operator+(int, int)" to cover integer addition.
9244 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9245 SourceLocation OpLoc,
9246 ArrayRef<Expr *> Args,
9247 OverloadCandidateSet &CandidateSet) {
9248 // Find all of the types that the arguments can convert to, but only
9249 // if the operator we're looking at has built-in operator candidates
9250 // that make use of these types. Also record whether we encounter non-record
9251 // candidate types or either arithmetic or enumeral candidate types.
9252 QualifiersAndAtomic VisibleTypeConversionsQuals;
9253 VisibleTypeConversionsQuals.addConst();
9254 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9255 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9256 if (Args[ArgIdx]->getType()->isAtomicType())
9257 VisibleTypeConversionsQuals.addAtomic();
9260 bool HasNonRecordCandidateType = false;
9261 bool HasArithmeticOrEnumeralCandidateType = false;
9262 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9263 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9264 CandidateTypes.emplace_back(*this);
9265 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9266 OpLoc,
9267 true,
9268 (Op == OO_Exclaim ||
9269 Op == OO_AmpAmp ||
9270 Op == OO_PipePipe),
9271 VisibleTypeConversionsQuals);
9272 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9273 CandidateTypes[ArgIdx].hasNonRecordTypes();
9274 HasArithmeticOrEnumeralCandidateType =
9275 HasArithmeticOrEnumeralCandidateType ||
9276 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9279 // Exit early when no non-record types have been added to the candidate set
9280 // for any of the arguments to the operator.
9282 // We can't exit early for !, ||, or &&, since there we have always have
9283 // 'bool' overloads.
9284 if (!HasNonRecordCandidateType &&
9285 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9286 return;
9288 // Setup an object to manage the common state for building overloads.
9289 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9290 VisibleTypeConversionsQuals,
9291 HasArithmeticOrEnumeralCandidateType,
9292 CandidateTypes, CandidateSet);
9294 // Dispatch over the operation to add in only those overloads which apply.
9295 switch (Op) {
9296 case OO_None:
9297 case NUM_OVERLOADED_OPERATORS:
9298 llvm_unreachable("Expected an overloaded operator");
9300 case OO_New:
9301 case OO_Delete:
9302 case OO_Array_New:
9303 case OO_Array_Delete:
9304 case OO_Call:
9305 llvm_unreachable(
9306 "Special operators don't use AddBuiltinOperatorCandidates");
9308 case OO_Comma:
9309 case OO_Arrow:
9310 case OO_Coawait:
9311 // C++ [over.match.oper]p3:
9312 // -- For the operator ',', the unary operator '&', the
9313 // operator '->', or the operator 'co_await', the
9314 // built-in candidates set is empty.
9315 break;
9317 case OO_Plus: // '+' is either unary or binary
9318 if (Args.size() == 1)
9319 OpBuilder.addUnaryPlusPointerOverloads();
9320 [[fallthrough]];
9322 case OO_Minus: // '-' is either unary or binary
9323 if (Args.size() == 1) {
9324 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9325 } else {
9326 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9327 OpBuilder.addGenericBinaryArithmeticOverloads();
9328 OpBuilder.addMatrixBinaryArithmeticOverloads();
9330 break;
9332 case OO_Star: // '*' is either unary or binary
9333 if (Args.size() == 1)
9334 OpBuilder.addUnaryStarPointerOverloads();
9335 else {
9336 OpBuilder.addGenericBinaryArithmeticOverloads();
9337 OpBuilder.addMatrixBinaryArithmeticOverloads();
9339 break;
9341 case OO_Slash:
9342 OpBuilder.addGenericBinaryArithmeticOverloads();
9343 break;
9345 case OO_PlusPlus:
9346 case OO_MinusMinus:
9347 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9348 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9349 break;
9351 case OO_EqualEqual:
9352 case OO_ExclaimEqual:
9353 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9354 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9355 OpBuilder.addGenericBinaryArithmeticOverloads();
9356 break;
9358 case OO_Less:
9359 case OO_Greater:
9360 case OO_LessEqual:
9361 case OO_GreaterEqual:
9362 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9363 OpBuilder.addGenericBinaryArithmeticOverloads();
9364 break;
9366 case OO_Spaceship:
9367 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9368 OpBuilder.addThreeWayArithmeticOverloads();
9369 break;
9371 case OO_Percent:
9372 case OO_Caret:
9373 case OO_Pipe:
9374 case OO_LessLess:
9375 case OO_GreaterGreater:
9376 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9377 break;
9379 case OO_Amp: // '&' is either unary or binary
9380 if (Args.size() == 1)
9381 // C++ [over.match.oper]p3:
9382 // -- For the operator ',', the unary operator '&', or the
9383 // operator '->', the built-in candidates set is empty.
9384 break;
9386 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9387 break;
9389 case OO_Tilde:
9390 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9391 break;
9393 case OO_Equal:
9394 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9395 [[fallthrough]];
9397 case OO_PlusEqual:
9398 case OO_MinusEqual:
9399 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9400 [[fallthrough]];
9402 case OO_StarEqual:
9403 case OO_SlashEqual:
9404 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9405 break;
9407 case OO_PercentEqual:
9408 case OO_LessLessEqual:
9409 case OO_GreaterGreaterEqual:
9410 case OO_AmpEqual:
9411 case OO_CaretEqual:
9412 case OO_PipeEqual:
9413 OpBuilder.addAssignmentIntegralOverloads();
9414 break;
9416 case OO_Exclaim:
9417 OpBuilder.addExclaimOverload();
9418 break;
9420 case OO_AmpAmp:
9421 case OO_PipePipe:
9422 OpBuilder.addAmpAmpOrPipePipeOverload();
9423 break;
9425 case OO_Subscript:
9426 if (Args.size() == 2)
9427 OpBuilder.addSubscriptOverloads();
9428 break;
9430 case OO_ArrowStar:
9431 OpBuilder.addArrowStarOverloads();
9432 break;
9434 case OO_Conditional:
9435 OpBuilder.addConditionalOperatorOverloads();
9436 OpBuilder.addGenericBinaryArithmeticOverloads();
9437 break;
9441 /// Add function candidates found via argument-dependent lookup
9442 /// to the set of overloading candidates.
9444 /// This routine performs argument-dependent name lookup based on the
9445 /// given function name (which may also be an operator name) and adds
9446 /// all of the overload candidates found by ADL to the overload
9447 /// candidate set (C++ [basic.lookup.argdep]).
9448 void
9449 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9450 SourceLocation Loc,
9451 ArrayRef<Expr *> Args,
9452 TemplateArgumentListInfo *ExplicitTemplateArgs,
9453 OverloadCandidateSet& CandidateSet,
9454 bool PartialOverloading) {
9455 ADLResult Fns;
9457 // FIXME: This approach for uniquing ADL results (and removing
9458 // redundant candidates from the set) relies on pointer-equality,
9459 // which means we need to key off the canonical decl. However,
9460 // always going back to the canonical decl might not get us the
9461 // right set of default arguments. What default arguments are
9462 // we supposed to consider on ADL candidates, anyway?
9464 // FIXME: Pass in the explicit template arguments?
9465 ArgumentDependentLookup(Name, Loc, Args, Fns);
9467 // Erase all of the candidates we already knew about.
9468 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9469 CandEnd = CandidateSet.end();
9470 Cand != CandEnd; ++Cand)
9471 if (Cand->Function) {
9472 Fns.erase(Cand->Function);
9473 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9474 Fns.erase(FunTmpl);
9477 // For each of the ADL candidates we found, add it to the overload
9478 // set.
9479 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9480 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9482 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9483 if (ExplicitTemplateArgs)
9484 continue;
9486 AddOverloadCandidate(
9487 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9488 PartialOverloading, /*AllowExplicit=*/true,
9489 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9490 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9491 AddOverloadCandidate(
9492 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9493 /*SuppressUserConversions=*/false, PartialOverloading,
9494 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9495 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9497 } else {
9498 auto *FTD = cast<FunctionTemplateDecl>(*I);
9499 AddTemplateOverloadCandidate(
9500 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9501 /*SuppressUserConversions=*/false, PartialOverloading,
9502 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9503 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9504 Context, FTD->getTemplatedDecl())) {
9505 AddTemplateOverloadCandidate(
9506 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9507 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9508 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9509 OverloadCandidateParamOrder::Reversed);
9515 namespace {
9516 enum class Comparison { Equal, Better, Worse };
9519 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9520 /// overload resolution.
9522 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9523 /// Cand1's first N enable_if attributes have precisely the same conditions as
9524 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9525 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9527 /// Note that you can have a pair of candidates such that Cand1's enable_if
9528 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9529 /// worse than Cand1's.
9530 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9531 const FunctionDecl *Cand2) {
9532 // Common case: One (or both) decls don't have enable_if attrs.
9533 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9534 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9535 if (!Cand1Attr || !Cand2Attr) {
9536 if (Cand1Attr == Cand2Attr)
9537 return Comparison::Equal;
9538 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9541 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9542 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9544 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9545 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9546 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9547 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9549 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9550 // has fewer enable_if attributes than Cand2, and vice versa.
9551 if (!Cand1A)
9552 return Comparison::Worse;
9553 if (!Cand2A)
9554 return Comparison::Better;
9556 Cand1ID.clear();
9557 Cand2ID.clear();
9559 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9560 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9561 if (Cand1ID != Cand2ID)
9562 return Comparison::Worse;
9565 return Comparison::Equal;
9568 static Comparison
9569 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9570 const OverloadCandidate &Cand2) {
9571 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9572 !Cand2.Function->isMultiVersion())
9573 return Comparison::Equal;
9575 // If both are invalid, they are equal. If one of them is invalid, the other
9576 // is better.
9577 if (Cand1.Function->isInvalidDecl()) {
9578 if (Cand2.Function->isInvalidDecl())
9579 return Comparison::Equal;
9580 return Comparison::Worse;
9582 if (Cand2.Function->isInvalidDecl())
9583 return Comparison::Better;
9585 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9586 // cpu_dispatch, else arbitrarily based on the identifiers.
9587 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9588 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9589 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9590 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9592 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9593 return Comparison::Equal;
9595 if (Cand1CPUDisp && !Cand2CPUDisp)
9596 return Comparison::Better;
9597 if (Cand2CPUDisp && !Cand1CPUDisp)
9598 return Comparison::Worse;
9600 if (Cand1CPUSpec && Cand2CPUSpec) {
9601 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9602 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9603 ? Comparison::Better
9604 : Comparison::Worse;
9606 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9607 FirstDiff = std::mismatch(
9608 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9609 Cand2CPUSpec->cpus_begin(),
9610 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9611 return LHS->getName() == RHS->getName();
9614 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9615 "Two different cpu-specific versions should not have the same "
9616 "identifier list, otherwise they'd be the same decl!");
9617 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9618 ? Comparison::Better
9619 : Comparison::Worse;
9621 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9624 /// Compute the type of the implicit object parameter for the given function,
9625 /// if any. Returns None if there is no implicit object parameter, and a null
9626 /// QualType if there is a 'matches anything' implicit object parameter.
9627 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9628 const FunctionDecl *F) {
9629 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9630 return llvm::None;
9632 auto *M = cast<CXXMethodDecl>(F);
9633 // Static member functions' object parameters match all types.
9634 if (M->isStatic())
9635 return QualType();
9637 QualType T = M->getThisObjectType();
9638 if (M->getRefQualifier() == RQ_RValue)
9639 return Context.getRValueReferenceType(T);
9640 return Context.getLValueReferenceType(T);
9643 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9644 const FunctionDecl *F2, unsigned NumParams) {
9645 if (declaresSameEntity(F1, F2))
9646 return true;
9648 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9649 if (First) {
9650 if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9651 return *T;
9653 assert(I < F->getNumParams());
9654 return F->getParamDecl(I++)->getType();
9657 unsigned I1 = 0, I2 = 0;
9658 for (unsigned I = 0; I != NumParams; ++I) {
9659 QualType T1 = NextParam(F1, I1, I == 0);
9660 QualType T2 = NextParam(F2, I2, I == 0);
9661 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9662 if (!Context.hasSameUnqualifiedType(T1, T2))
9663 return false;
9665 return true;
9668 /// We're allowed to use constraints partial ordering only if the candidates
9669 /// have the same parameter types:
9670 /// [temp.func.order]p6.2.2 [...] or if the function parameters that
9671 /// positionally correspond between the two templates are not of the same type,
9672 /// neither template is more specialized than the other.
9673 /// [over.match.best]p2.6
9674 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9675 /// and F1 is more constrained than F2 [...]
9676 static bool canCompareFunctionConstraints(Sema &S,
9677 const OverloadCandidate &Cand1,
9678 const OverloadCandidate &Cand2) {
9679 // FIXME: Per P2113R0 we also need to compare the template parameter lists
9680 // when comparing template functions.
9681 if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
9682 Cand2.Function->hasPrototype()) {
9683 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9684 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9685 if (PT1->getNumParams() == PT2->getNumParams() &&
9686 PT1->isVariadic() == PT2->isVariadic() &&
9687 S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9688 Cand1.isReversed() ^ Cand2.isReversed()))
9689 return true;
9691 return false;
9694 /// isBetterOverloadCandidate - Determines whether the first overload
9695 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9696 bool clang::isBetterOverloadCandidate(
9697 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9698 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9699 // Define viable functions to be better candidates than non-viable
9700 // functions.
9701 if (!Cand2.Viable)
9702 return Cand1.Viable;
9703 else if (!Cand1.Viable)
9704 return false;
9706 // [CUDA] A function with 'never' preference is marked not viable, therefore
9707 // is never shown up here. The worst preference shown up here is 'wrong side',
9708 // e.g. an H function called by a HD function in device compilation. This is
9709 // valid AST as long as the HD function is not emitted, e.g. it is an inline
9710 // function which is called only by an H function. A deferred diagnostic will
9711 // be triggered if it is emitted. However a wrong-sided function is still
9712 // a viable candidate here.
9714 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9715 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9716 // can be emitted, Cand1 is not better than Cand2. This rule should have
9717 // precedence over other rules.
9719 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9720 // other rules should be used to determine which is better. This is because
9721 // host/device based overloading resolution is mostly for determining
9722 // viability of a function. If two functions are both viable, other factors
9723 // should take precedence in preference, e.g. the standard-defined preferences
9724 // like argument conversion ranks or enable_if partial-ordering. The
9725 // preference for pass-object-size parameters is probably most similar to a
9726 // type-based-overloading decision and so should take priority.
9728 // If other rules cannot determine which is better, CUDA preference will be
9729 // used again to determine which is better.
9731 // TODO: Currently IdentifyCUDAPreference does not return correct values
9732 // for functions called in global variable initializers due to missing
9733 // correct context about device/host. Therefore we can only enforce this
9734 // rule when there is a caller. We should enforce this rule for functions
9735 // in global variable initializers once proper context is added.
9737 // TODO: We can only enable the hostness based overloading resolution when
9738 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9739 // overloading resolution diagnostics.
9740 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9741 S.getLangOpts().GPUExcludeWrongSideOverloads) {
9742 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9743 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9744 bool IsCand1ImplicitHD =
9745 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9746 bool IsCand2ImplicitHD =
9747 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9748 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9749 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9750 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9751 // The implicit HD function may be a function in a system header which
9752 // is forced by pragma. In device compilation, if we prefer HD candidates
9753 // over wrong-sided candidates, overloading resolution may change, which
9754 // may result in non-deferrable diagnostics. As a workaround, we let
9755 // implicit HD candidates take equal preference as wrong-sided candidates.
9756 // This will preserve the overloading resolution.
9757 // TODO: We still need special handling of implicit HD functions since
9758 // they may incur other diagnostics to be deferred. We should make all
9759 // host/device related diagnostics deferrable and remove special handling
9760 // of implicit HD functions.
9761 auto EmitThreshold =
9762 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9763 (IsCand1ImplicitHD || IsCand2ImplicitHD))
9764 ? Sema::CFP_Never
9765 : Sema::CFP_WrongSide;
9766 auto Cand1Emittable = P1 > EmitThreshold;
9767 auto Cand2Emittable = P2 > EmitThreshold;
9768 if (Cand1Emittable && !Cand2Emittable)
9769 return true;
9770 if (!Cand1Emittable && Cand2Emittable)
9771 return false;
9775 // C++ [over.match.best]p1:
9777 // -- if F is a static member function, ICS1(F) is defined such
9778 // that ICS1(F) is neither better nor worse than ICS1(G) for
9779 // any function G, and, symmetrically, ICS1(G) is neither
9780 // better nor worse than ICS1(F).
9781 unsigned StartArg = 0;
9782 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9783 StartArg = 1;
9785 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9786 // We don't allow incompatible pointer conversions in C++.
9787 if (!S.getLangOpts().CPlusPlus)
9788 return ICS.isStandard() &&
9789 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9791 // The only ill-formed conversion we allow in C++ is the string literal to
9792 // char* conversion, which is only considered ill-formed after C++11.
9793 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9794 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9797 // Define functions that don't require ill-formed conversions for a given
9798 // argument to be better candidates than functions that do.
9799 unsigned NumArgs = Cand1.Conversions.size();
9800 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9801 bool HasBetterConversion = false;
9802 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9803 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9804 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9805 if (Cand1Bad != Cand2Bad) {
9806 if (Cand1Bad)
9807 return false;
9808 HasBetterConversion = true;
9812 if (HasBetterConversion)
9813 return true;
9815 // C++ [over.match.best]p1:
9816 // A viable function F1 is defined to be a better function than another
9817 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9818 // conversion sequence than ICSi(F2), and then...
9819 bool HasWorseConversion = false;
9820 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9821 switch (CompareImplicitConversionSequences(S, Loc,
9822 Cand1.Conversions[ArgIdx],
9823 Cand2.Conversions[ArgIdx])) {
9824 case ImplicitConversionSequence::Better:
9825 // Cand1 has a better conversion sequence.
9826 HasBetterConversion = true;
9827 break;
9829 case ImplicitConversionSequence::Worse:
9830 if (Cand1.Function && Cand2.Function &&
9831 Cand1.isReversed() != Cand2.isReversed() &&
9832 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9833 NumArgs)) {
9834 // Work around large-scale breakage caused by considering reversed
9835 // forms of operator== in C++20:
9837 // When comparing a function against a reversed function with the same
9838 // parameter types, if we have a better conversion for one argument and
9839 // a worse conversion for the other, the implicit conversion sequences
9840 // are treated as being equally good.
9842 // This prevents a comparison function from being considered ambiguous
9843 // with a reversed form that is written in the same way.
9845 // We diagnose this as an extension from CreateOverloadedBinOp.
9846 HasWorseConversion = true;
9847 break;
9850 // Cand1 can't be better than Cand2.
9851 return false;
9853 case ImplicitConversionSequence::Indistinguishable:
9854 // Do nothing.
9855 break;
9859 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9860 // ICSj(F2), or, if not that,
9861 if (HasBetterConversion && !HasWorseConversion)
9862 return true;
9864 // -- the context is an initialization by user-defined conversion
9865 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9866 // from the return type of F1 to the destination type (i.e.,
9867 // the type of the entity being initialized) is a better
9868 // conversion sequence than the standard conversion sequence
9869 // from the return type of F2 to the destination type.
9870 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9871 Cand1.Function && Cand2.Function &&
9872 isa<CXXConversionDecl>(Cand1.Function) &&
9873 isa<CXXConversionDecl>(Cand2.Function)) {
9874 // First check whether we prefer one of the conversion functions over the
9875 // other. This only distinguishes the results in non-standard, extension
9876 // cases such as the conversion from a lambda closure type to a function
9877 // pointer or block.
9878 ImplicitConversionSequence::CompareKind Result =
9879 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9880 if (Result == ImplicitConversionSequence::Indistinguishable)
9881 Result = CompareStandardConversionSequences(S, Loc,
9882 Cand1.FinalConversion,
9883 Cand2.FinalConversion);
9885 if (Result != ImplicitConversionSequence::Indistinguishable)
9886 return Result == ImplicitConversionSequence::Better;
9888 // FIXME: Compare kind of reference binding if conversion functions
9889 // convert to a reference type used in direct reference binding, per
9890 // C++14 [over.match.best]p1 section 2 bullet 3.
9893 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9894 // as combined with the resolution to CWG issue 243.
9896 // When the context is initialization by constructor ([over.match.ctor] or
9897 // either phase of [over.match.list]), a constructor is preferred over
9898 // a conversion function.
9899 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9900 Cand1.Function && Cand2.Function &&
9901 isa<CXXConstructorDecl>(Cand1.Function) !=
9902 isa<CXXConstructorDecl>(Cand2.Function))
9903 return isa<CXXConstructorDecl>(Cand1.Function);
9905 // -- F1 is a non-template function and F2 is a function template
9906 // specialization, or, if not that,
9907 bool Cand1IsSpecialization = Cand1.Function &&
9908 Cand1.Function->getPrimaryTemplate();
9909 bool Cand2IsSpecialization = Cand2.Function &&
9910 Cand2.Function->getPrimaryTemplate();
9911 if (Cand1IsSpecialization != Cand2IsSpecialization)
9912 return Cand2IsSpecialization;
9914 // -- F1 and F2 are function template specializations, and the function
9915 // template for F1 is more specialized than the template for F2
9916 // according to the partial ordering rules described in 14.5.5.2, or,
9917 // if not that,
9918 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9919 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9920 Cand1.Function->getPrimaryTemplate(),
9921 Cand2.Function->getPrimaryTemplate(), Loc,
9922 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9923 : TPOC_Call,
9924 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9925 Cand1.isReversed() ^ Cand2.isReversed(),
9926 canCompareFunctionConstraints(S, Cand1, Cand2)))
9927 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9930 // -— F1 and F2 are non-template functions with the same
9931 // parameter-type-lists, and F1 is more constrained than F2 [...],
9932 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
9933 canCompareFunctionConstraints(S, Cand1, Cand2)) {
9934 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9935 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9936 if (RC1 && RC2) {
9937 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9938 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2},
9939 AtLeastAsConstrained1) ||
9940 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1},
9941 AtLeastAsConstrained2))
9942 return false;
9943 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9944 return AtLeastAsConstrained1;
9945 } else if (RC1 || RC2) {
9946 return RC1 != nullptr;
9950 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9951 // class B of D, and for all arguments the corresponding parameters of
9952 // F1 and F2 have the same type.
9953 // FIXME: Implement the "all parameters have the same type" check.
9954 bool Cand1IsInherited =
9955 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9956 bool Cand2IsInherited =
9957 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9958 if (Cand1IsInherited != Cand2IsInherited)
9959 return Cand2IsInherited;
9960 else if (Cand1IsInherited) {
9961 assert(Cand2IsInherited);
9962 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9963 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9964 if (Cand1Class->isDerivedFrom(Cand2Class))
9965 return true;
9966 if (Cand2Class->isDerivedFrom(Cand1Class))
9967 return false;
9968 // Inherited from sibling base classes: still ambiguous.
9971 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9972 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9973 // with reversed order of parameters and F1 is not
9975 // We rank reversed + different operator as worse than just reversed, but
9976 // that comparison can never happen, because we only consider reversing for
9977 // the maximally-rewritten operator (== or <=>).
9978 if (Cand1.RewriteKind != Cand2.RewriteKind)
9979 return Cand1.RewriteKind < Cand2.RewriteKind;
9981 // Check C++17 tie-breakers for deduction guides.
9983 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9984 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9985 if (Guide1 && Guide2) {
9986 // -- F1 is generated from a deduction-guide and F2 is not
9987 if (Guide1->isImplicit() != Guide2->isImplicit())
9988 return Guide2->isImplicit();
9990 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9991 if (Guide1->isCopyDeductionCandidate())
9992 return true;
9996 // Check for enable_if value-based overload resolution.
9997 if (Cand1.Function && Cand2.Function) {
9998 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9999 if (Cmp != Comparison::Equal)
10000 return Cmp == Comparison::Better;
10003 bool HasPS1 = Cand1.Function != nullptr &&
10004 functionHasPassObjectSizeParams(Cand1.Function);
10005 bool HasPS2 = Cand2.Function != nullptr &&
10006 functionHasPassObjectSizeParams(Cand2.Function);
10007 if (HasPS1 != HasPS2 && HasPS1)
10008 return true;
10010 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10011 if (MV == Comparison::Better)
10012 return true;
10013 if (MV == Comparison::Worse)
10014 return false;
10016 // If other rules cannot determine which is better, CUDA preference is used
10017 // to determine which is better.
10018 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10019 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10020 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10021 S.IdentifyCUDAPreference(Caller, Cand2.Function);
10024 // General member function overloading is handled above, so this only handles
10025 // constructors with address spaces.
10026 // This only handles address spaces since C++ has no other
10027 // qualifier that can be used with constructors.
10028 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10029 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10030 if (CD1 && CD2) {
10031 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10032 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10033 if (AS1 != AS2) {
10034 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10035 return true;
10036 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10037 return false;
10041 return false;
10044 /// Determine whether two declarations are "equivalent" for the purposes of
10045 /// name lookup and overload resolution. This applies when the same internal/no
10046 /// linkage entity is defined by two modules (probably by textually including
10047 /// the same header). In such a case, we don't consider the declarations to
10048 /// declare the same entity, but we also don't want lookups with both
10049 /// declarations visible to be ambiguous in some cases (this happens when using
10050 /// a modularized libstdc++).
10051 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10052 const NamedDecl *B) {
10053 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10054 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10055 if (!VA || !VB)
10056 return false;
10058 // The declarations must be declaring the same name as an internal linkage
10059 // entity in different modules.
10060 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10061 VB->getDeclContext()->getRedeclContext()) ||
10062 getOwningModule(VA) == getOwningModule(VB) ||
10063 VA->isExternallyVisible() || VB->isExternallyVisible())
10064 return false;
10066 // Check that the declarations appear to be equivalent.
10068 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10069 // For constants and functions, we should check the initializer or body is
10070 // the same. For non-constant variables, we shouldn't allow it at all.
10071 if (Context.hasSameType(VA->getType(), VB->getType()))
10072 return true;
10074 // Enum constants within unnamed enumerations will have different types, but
10075 // may still be similar enough to be interchangeable for our purposes.
10076 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10077 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10078 // Only handle anonymous enums. If the enumerations were named and
10079 // equivalent, they would have been merged to the same type.
10080 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10081 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10082 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10083 !Context.hasSameType(EnumA->getIntegerType(),
10084 EnumB->getIntegerType()))
10085 return false;
10086 // Allow this only if the value is the same for both enumerators.
10087 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10091 // Nothing else is sufficiently similar.
10092 return false;
10095 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10096 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10097 assert(D && "Unknown declaration");
10098 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10100 Module *M = getOwningModule(D);
10101 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10102 << !M << (M ? M->getFullModuleName() : "");
10104 for (auto *E : Equiv) {
10105 Module *M = getOwningModule(E);
10106 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10107 << !M << (M ? M->getFullModuleName() : "");
10111 /// Computes the best viable function (C++ 13.3.3)
10112 /// within an overload candidate set.
10114 /// \param Loc The location of the function name (or operator symbol) for
10115 /// which overload resolution occurs.
10117 /// \param Best If overload resolution was successful or found a deleted
10118 /// function, \p Best points to the candidate function found.
10120 /// \returns The result of overload resolution.
10121 OverloadingResult
10122 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10123 iterator &Best) {
10124 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10125 std::transform(begin(), end(), std::back_inserter(Candidates),
10126 [](OverloadCandidate &Cand) { return &Cand; });
10128 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10129 // are accepted by both clang and NVCC. However, during a particular
10130 // compilation mode only one call variant is viable. We need to
10131 // exclude non-viable overload candidates from consideration based
10132 // only on their host/device attributes. Specifically, if one
10133 // candidate call is WrongSide and the other is SameSide, we ignore
10134 // the WrongSide candidate.
10135 // We only need to remove wrong-sided candidates here if
10136 // -fgpu-exclude-wrong-side-overloads is off. When
10137 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10138 // uniformly in isBetterOverloadCandidate.
10139 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10140 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10141 bool ContainsSameSideCandidate =
10142 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10143 // Check viable function only.
10144 return Cand->Viable && Cand->Function &&
10145 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10146 Sema::CFP_SameSide;
10148 if (ContainsSameSideCandidate) {
10149 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10150 // Check viable function only to avoid unnecessary data copying/moving.
10151 return Cand->Viable && Cand->Function &&
10152 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10153 Sema::CFP_WrongSide;
10155 llvm::erase_if(Candidates, IsWrongSideCandidate);
10159 // Find the best viable function.
10160 Best = end();
10161 for (auto *Cand : Candidates) {
10162 Cand->Best = false;
10163 if (Cand->Viable)
10164 if (Best == end() ||
10165 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10166 Best = Cand;
10169 // If we didn't find any viable functions, abort.
10170 if (Best == end())
10171 return OR_No_Viable_Function;
10173 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10175 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10176 PendingBest.push_back(&*Best);
10177 Best->Best = true;
10179 // Make sure that this function is better than every other viable
10180 // function. If not, we have an ambiguity.
10181 while (!PendingBest.empty()) {
10182 auto *Curr = PendingBest.pop_back_val();
10183 for (auto *Cand : Candidates) {
10184 if (Cand->Viable && !Cand->Best &&
10185 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10186 PendingBest.push_back(Cand);
10187 Cand->Best = true;
10189 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10190 Curr->Function))
10191 EquivalentCands.push_back(Cand->Function);
10192 else
10193 Best = end();
10198 // If we found more than one best candidate, this is ambiguous.
10199 if (Best == end())
10200 return OR_Ambiguous;
10202 // Best is the best viable function.
10203 if (Best->Function && Best->Function->isDeleted())
10204 return OR_Deleted;
10206 if (!EquivalentCands.empty())
10207 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10208 EquivalentCands);
10210 return OR_Success;
10213 namespace {
10215 enum OverloadCandidateKind {
10216 oc_function,
10217 oc_method,
10218 oc_reversed_binary_operator,
10219 oc_constructor,
10220 oc_implicit_default_constructor,
10221 oc_implicit_copy_constructor,
10222 oc_implicit_move_constructor,
10223 oc_implicit_copy_assignment,
10224 oc_implicit_move_assignment,
10225 oc_implicit_equality_comparison,
10226 oc_inherited_constructor
10229 enum OverloadCandidateSelect {
10230 ocs_non_template,
10231 ocs_template,
10232 ocs_described_template,
10235 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10236 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10237 OverloadCandidateRewriteKind CRK,
10238 std::string &Description) {
10240 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10241 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10242 isTemplate = true;
10243 Description = S.getTemplateArgumentBindingsText(
10244 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10247 OverloadCandidateSelect Select = [&]() {
10248 if (!Description.empty())
10249 return ocs_described_template;
10250 return isTemplate ? ocs_template : ocs_non_template;
10251 }();
10253 OverloadCandidateKind Kind = [&]() {
10254 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10255 return oc_implicit_equality_comparison;
10257 if (CRK & CRK_Reversed)
10258 return oc_reversed_binary_operator;
10260 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10261 if (!Ctor->isImplicit()) {
10262 if (isa<ConstructorUsingShadowDecl>(Found))
10263 return oc_inherited_constructor;
10264 else
10265 return oc_constructor;
10268 if (Ctor->isDefaultConstructor())
10269 return oc_implicit_default_constructor;
10271 if (Ctor->isMoveConstructor())
10272 return oc_implicit_move_constructor;
10274 assert(Ctor->isCopyConstructor() &&
10275 "unexpected sort of implicit constructor");
10276 return oc_implicit_copy_constructor;
10279 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10280 // This actually gets spelled 'candidate function' for now, but
10281 // it doesn't hurt to split it out.
10282 if (!Meth->isImplicit())
10283 return oc_method;
10285 if (Meth->isMoveAssignmentOperator())
10286 return oc_implicit_move_assignment;
10288 if (Meth->isCopyAssignmentOperator())
10289 return oc_implicit_copy_assignment;
10291 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10292 return oc_method;
10295 return oc_function;
10296 }();
10298 return std::make_pair(Kind, Select);
10301 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10302 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10303 // set.
10304 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10305 S.Diag(FoundDecl->getLocation(),
10306 diag::note_ovl_candidate_inherited_constructor)
10307 << Shadow->getNominatedBaseClass();
10310 } // end anonymous namespace
10312 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10313 const FunctionDecl *FD) {
10314 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10315 bool AlwaysTrue;
10316 if (EnableIf->getCond()->isValueDependent() ||
10317 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10318 return false;
10319 if (!AlwaysTrue)
10320 return false;
10322 return true;
10325 /// Returns true if we can take the address of the function.
10327 /// \param Complain - If true, we'll emit a diagnostic
10328 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10329 /// we in overload resolution?
10330 /// \param Loc - The location of the statement we're complaining about. Ignored
10331 /// if we're not complaining, or if we're in overload resolution.
10332 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10333 bool Complain,
10334 bool InOverloadResolution,
10335 SourceLocation Loc) {
10336 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10337 if (Complain) {
10338 if (InOverloadResolution)
10339 S.Diag(FD->getBeginLoc(),
10340 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10341 else
10342 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10344 return false;
10347 if (FD->getTrailingRequiresClause()) {
10348 ConstraintSatisfaction Satisfaction;
10349 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10350 return false;
10351 if (!Satisfaction.IsSatisfied) {
10352 if (Complain) {
10353 if (InOverloadResolution) {
10354 SmallString<128> TemplateArgString;
10355 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10356 TemplateArgString += " ";
10357 TemplateArgString += S.getTemplateArgumentBindingsText(
10358 FunTmpl->getTemplateParameters(),
10359 *FD->getTemplateSpecializationArgs());
10362 S.Diag(FD->getBeginLoc(),
10363 diag::note_ovl_candidate_unsatisfied_constraints)
10364 << TemplateArgString;
10365 } else
10366 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10367 << FD;
10368 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10370 return false;
10374 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10375 return P->hasAttr<PassObjectSizeAttr>();
10377 if (I == FD->param_end())
10378 return true;
10380 if (Complain) {
10381 // Add one to ParamNo because it's user-facing
10382 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10383 if (InOverloadResolution)
10384 S.Diag(FD->getLocation(),
10385 diag::note_ovl_candidate_has_pass_object_size_params)
10386 << ParamNo;
10387 else
10388 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10389 << FD << ParamNo;
10391 return false;
10394 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10395 const FunctionDecl *FD) {
10396 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10397 /*InOverloadResolution=*/true,
10398 /*Loc=*/SourceLocation());
10401 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10402 bool Complain,
10403 SourceLocation Loc) {
10404 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10405 /*InOverloadResolution=*/false,
10406 Loc);
10409 // Don't print candidates other than the one that matches the calling
10410 // convention of the call operator, since that is guaranteed to exist.
10411 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10412 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10414 if (!ConvD)
10415 return false;
10416 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10417 if (!RD->isLambda())
10418 return false;
10420 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10421 CallingConv CallOpCC =
10422 CallOp->getType()->castAs<FunctionType>()->getCallConv();
10423 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10424 CallingConv ConvToCC =
10425 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10427 return ConvToCC != CallOpCC;
10430 // Notes the location of an overload candidate.
10431 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10432 OverloadCandidateRewriteKind RewriteKind,
10433 QualType DestType, bool TakingAddress) {
10434 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10435 return;
10436 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10437 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10438 return;
10439 if (shouldSkipNotingLambdaConversionDecl(Fn))
10440 return;
10442 std::string FnDesc;
10443 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10444 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10445 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10446 << (unsigned)KSPair.first << (unsigned)KSPair.second
10447 << Fn << FnDesc;
10449 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10450 Diag(Fn->getLocation(), PD);
10451 MaybeEmitInheritedConstructorNote(*this, Found);
10454 static void
10455 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10456 // Perhaps the ambiguity was caused by two atomic constraints that are
10457 // 'identical' but not equivalent:
10459 // void foo() requires (sizeof(T) > 4) { } // #1
10460 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10462 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10463 // #2 to subsume #1, but these constraint are not considered equivalent
10464 // according to the subsumption rules because they are not the same
10465 // source-level construct. This behavior is quite confusing and we should try
10466 // to help the user figure out what happened.
10468 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10469 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10470 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10471 if (!I->Function)
10472 continue;
10473 SmallVector<const Expr *, 3> AC;
10474 if (auto *Template = I->Function->getPrimaryTemplate())
10475 Template->getAssociatedConstraints(AC);
10476 else
10477 I->Function->getAssociatedConstraints(AC);
10478 if (AC.empty())
10479 continue;
10480 if (FirstCand == nullptr) {
10481 FirstCand = I->Function;
10482 FirstAC = AC;
10483 } else if (SecondCand == nullptr) {
10484 SecondCand = I->Function;
10485 SecondAC = AC;
10486 } else {
10487 // We have more than one pair of constrained functions - this check is
10488 // expensive and we'd rather not try to diagnose it.
10489 return;
10492 if (!SecondCand)
10493 return;
10494 // The diagnostic can only happen if there are associated constraints on
10495 // both sides (there needs to be some identical atomic constraint).
10496 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10497 SecondCand, SecondAC))
10498 // Just show the user one diagnostic, they'll probably figure it out
10499 // from here.
10500 return;
10503 // Notes the location of all overload candidates designated through
10504 // OverloadedExpr
10505 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10506 bool TakingAddress) {
10507 assert(OverloadedExpr->getType() == Context.OverloadTy);
10509 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10510 OverloadExpr *OvlExpr = Ovl.Expression;
10512 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10513 IEnd = OvlExpr->decls_end();
10514 I != IEnd; ++I) {
10515 if (FunctionTemplateDecl *FunTmpl =
10516 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10517 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10518 TakingAddress);
10519 } else if (FunctionDecl *Fun
10520 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10521 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10526 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
10527 /// "lead" diagnostic; it will be given two arguments, the source and
10528 /// target types of the conversion.
10529 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10530 Sema &S,
10531 SourceLocation CaretLoc,
10532 const PartialDiagnostic &PDiag) const {
10533 S.Diag(CaretLoc, PDiag)
10534 << Ambiguous.getFromType() << Ambiguous.getToType();
10535 unsigned CandsShown = 0;
10536 AmbiguousConversionSequence::const_iterator I, E;
10537 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10538 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10539 break;
10540 ++CandsShown;
10541 S.NoteOverloadCandidate(I->first, I->second);
10543 S.Diags.overloadCandidatesShown(CandsShown);
10544 if (I != E)
10545 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10548 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10549 unsigned I, bool TakingCandidateAddress) {
10550 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10551 assert(Conv.isBad());
10552 assert(Cand->Function && "for now, candidate must be a function");
10553 FunctionDecl *Fn = Cand->Function;
10555 // There's a conversion slot for the object argument if this is a
10556 // non-constructor method. Note that 'I' corresponds the
10557 // conversion-slot index.
10558 bool isObjectArgument = false;
10559 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10560 if (I == 0)
10561 isObjectArgument = true;
10562 else
10563 I--;
10566 std::string FnDesc;
10567 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10568 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10569 FnDesc);
10571 Expr *FromExpr = Conv.Bad.FromExpr;
10572 QualType FromTy = Conv.Bad.getFromType();
10573 QualType ToTy = Conv.Bad.getToType();
10575 if (FromTy == S.Context.OverloadTy) {
10576 assert(FromExpr && "overload set argument came from implicit argument?");
10577 Expr *E = FromExpr->IgnoreParens();
10578 if (isa<UnaryOperator>(E))
10579 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10580 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10582 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10583 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10584 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10585 << Name << I + 1;
10586 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10587 return;
10590 // Do some hand-waving analysis to see if the non-viability is due
10591 // to a qualifier mismatch.
10592 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10593 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10594 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10595 CToTy = RT->getPointeeType();
10596 else {
10597 // TODO: detect and diagnose the full richness of const mismatches.
10598 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10599 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10600 CFromTy = FromPT->getPointeeType();
10601 CToTy = ToPT->getPointeeType();
10605 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10606 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10607 Qualifiers FromQs = CFromTy.getQualifiers();
10608 Qualifiers ToQs = CToTy.getQualifiers();
10610 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10611 if (isObjectArgument)
10612 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10613 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10614 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10615 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10616 else
10617 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10618 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10619 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10620 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10621 << ToTy->isReferenceType() << I + 1;
10622 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10623 return;
10626 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10628 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10629 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10630 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10631 << (unsigned)isObjectArgument << I + 1;
10632 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10633 return;
10636 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10638 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10640 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10641 << (unsigned)isObjectArgument << I + 1;
10642 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10643 return;
10646 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10647 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10648 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10649 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10650 << FromQs.hasUnaligned() << I + 1;
10651 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10652 return;
10655 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10656 assert(CVR && "expected qualifiers mismatch");
10658 if (isObjectArgument) {
10659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10660 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10661 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10662 << (CVR - 1);
10663 } else {
10664 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10665 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10666 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10667 << (CVR - 1) << I + 1;
10669 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10670 return;
10673 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10674 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10675 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10676 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10677 << (unsigned)isObjectArgument << I + 1
10678 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10679 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10681 return;
10684 // Special diagnostic for failure to convert an initializer list, since
10685 // telling the user that it has type void is not useful.
10686 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10687 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10688 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10689 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10690 << ToTy << (unsigned)isObjectArgument << I + 1
10691 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10692 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10694 : 0);
10695 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10696 return;
10699 // Diagnose references or pointers to incomplete types differently,
10700 // since it's far from impossible that the incompleteness triggered
10701 // the failure.
10702 QualType TempFromTy = FromTy.getNonReferenceType();
10703 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10704 TempFromTy = PTy->getPointeeType();
10705 if (TempFromTy->isIncompleteType()) {
10706 // Emit the generic diagnostic and, optionally, add the hints to it.
10707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10708 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10709 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10710 << ToTy << (unsigned)isObjectArgument << I + 1
10711 << (unsigned)(Cand->Fix.Kind);
10713 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10714 return;
10717 // Diagnose base -> derived pointer conversions.
10718 unsigned BaseToDerivedConversion = 0;
10719 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10720 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10721 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10722 FromPtrTy->getPointeeType()) &&
10723 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10724 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10725 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10726 FromPtrTy->getPointeeType()))
10727 BaseToDerivedConversion = 1;
10729 } else if (const ObjCObjectPointerType *FromPtrTy
10730 = FromTy->getAs<ObjCObjectPointerType>()) {
10731 if (const ObjCObjectPointerType *ToPtrTy
10732 = ToTy->getAs<ObjCObjectPointerType>())
10733 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10734 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10735 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10736 FromPtrTy->getPointeeType()) &&
10737 FromIface->isSuperClassOf(ToIface))
10738 BaseToDerivedConversion = 2;
10739 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10740 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10741 !FromTy->isIncompleteType() &&
10742 !ToRefTy->getPointeeType()->isIncompleteType() &&
10743 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10744 BaseToDerivedConversion = 3;
10748 if (BaseToDerivedConversion) {
10749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10750 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10752 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10753 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10754 return;
10757 if (isa<ObjCObjectPointerType>(CFromTy) &&
10758 isa<PointerType>(CToTy)) {
10759 Qualifiers FromQs = CFromTy.getQualifiers();
10760 Qualifiers ToQs = CToTy.getQualifiers();
10761 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10763 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10764 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10765 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10766 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10767 return;
10771 if (TakingCandidateAddress &&
10772 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10773 return;
10775 // Emit the generic diagnostic and, optionally, add the hints to it.
10776 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10777 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10778 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10779 << ToTy << (unsigned)isObjectArgument << I + 1
10780 << (unsigned)(Cand->Fix.Kind);
10782 // If we can fix the conversion, suggest the FixIts.
10783 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10784 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10785 FDiag << *HI;
10786 S.Diag(Fn->getLocation(), FDiag);
10788 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10791 /// Additional arity mismatch diagnosis specific to a function overload
10792 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10793 /// over a candidate in any candidate set.
10794 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10795 unsigned NumArgs) {
10796 FunctionDecl *Fn = Cand->Function;
10797 unsigned MinParams = Fn->getMinRequiredArguments();
10799 // With invalid overloaded operators, it's possible that we think we
10800 // have an arity mismatch when in fact it looks like we have the
10801 // right number of arguments, because only overloaded operators have
10802 // the weird behavior of overloading member and non-member functions.
10803 // Just don't report anything.
10804 if (Fn->isInvalidDecl() &&
10805 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10806 return true;
10808 if (NumArgs < MinParams) {
10809 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10810 (Cand->FailureKind == ovl_fail_bad_deduction &&
10811 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10812 } else {
10813 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10814 (Cand->FailureKind == ovl_fail_bad_deduction &&
10815 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10818 return false;
10821 /// General arity mismatch diagnosis over a candidate in a candidate set.
10822 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10823 unsigned NumFormalArgs) {
10824 assert(isa<FunctionDecl>(D) &&
10825 "The templated declaration should at least be a function"
10826 " when diagnosing bad template argument deduction due to too many"
10827 " or too few arguments");
10829 FunctionDecl *Fn = cast<FunctionDecl>(D);
10831 // TODO: treat calls to a missing default constructor as a special case
10832 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10833 unsigned MinParams = Fn->getMinRequiredArguments();
10835 // at least / at most / exactly
10836 unsigned mode, modeCount;
10837 if (NumFormalArgs < MinParams) {
10838 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10839 FnTy->isTemplateVariadic())
10840 mode = 0; // "at least"
10841 else
10842 mode = 2; // "exactly"
10843 modeCount = MinParams;
10844 } else {
10845 if (MinParams != FnTy->getNumParams())
10846 mode = 1; // "at most"
10847 else
10848 mode = 2; // "exactly"
10849 modeCount = FnTy->getNumParams();
10852 std::string Description;
10853 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10854 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10856 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10857 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10858 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10859 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10860 else
10861 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10862 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10863 << Description << mode << modeCount << NumFormalArgs;
10865 MaybeEmitInheritedConstructorNote(S, Found);
10868 /// Arity mismatch diagnosis specific to a function overload candidate.
10869 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10870 unsigned NumFormalArgs) {
10871 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10872 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10875 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10876 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10877 return TD;
10878 llvm_unreachable("Unsupported: Getting the described template declaration"
10879 " for bad deduction diagnosis");
10882 /// Diagnose a failed template-argument deduction.
10883 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10884 DeductionFailureInfo &DeductionFailure,
10885 unsigned NumArgs,
10886 bool TakingCandidateAddress) {
10887 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10888 NamedDecl *ParamD;
10889 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10890 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10891 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10892 switch (DeductionFailure.Result) {
10893 case Sema::TDK_Success:
10894 llvm_unreachable("TDK_success while diagnosing bad deduction");
10896 case Sema::TDK_Incomplete: {
10897 assert(ParamD && "no parameter found for incomplete deduction result");
10898 S.Diag(Templated->getLocation(),
10899 diag::note_ovl_candidate_incomplete_deduction)
10900 << ParamD->getDeclName();
10901 MaybeEmitInheritedConstructorNote(S, Found);
10902 return;
10905 case Sema::TDK_IncompletePack: {
10906 assert(ParamD && "no parameter found for incomplete deduction result");
10907 S.Diag(Templated->getLocation(),
10908 diag::note_ovl_candidate_incomplete_deduction_pack)
10909 << ParamD->getDeclName()
10910 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10911 << *DeductionFailure.getFirstArg();
10912 MaybeEmitInheritedConstructorNote(S, Found);
10913 return;
10916 case Sema::TDK_Underqualified: {
10917 assert(ParamD && "no parameter found for bad qualifiers deduction result");
10918 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10920 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10922 // Param will have been canonicalized, but it should just be a
10923 // qualified version of ParamD, so move the qualifiers to that.
10924 QualifierCollector Qs;
10925 Qs.strip(Param);
10926 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10927 assert(S.Context.hasSameType(Param, NonCanonParam));
10929 // Arg has also been canonicalized, but there's nothing we can do
10930 // about that. It also doesn't matter as much, because it won't
10931 // have any template parameters in it (because deduction isn't
10932 // done on dependent types).
10933 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10935 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10936 << ParamD->getDeclName() << Arg << NonCanonParam;
10937 MaybeEmitInheritedConstructorNote(S, Found);
10938 return;
10941 case Sema::TDK_Inconsistent: {
10942 assert(ParamD && "no parameter found for inconsistent deduction result");
10943 int which = 0;
10944 if (isa<TemplateTypeParmDecl>(ParamD))
10945 which = 0;
10946 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10947 // Deduction might have failed because we deduced arguments of two
10948 // different types for a non-type template parameter.
10949 // FIXME: Use a different TDK value for this.
10950 QualType T1 =
10951 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10952 QualType T2 =
10953 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10954 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10955 S.Diag(Templated->getLocation(),
10956 diag::note_ovl_candidate_inconsistent_deduction_types)
10957 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10958 << *DeductionFailure.getSecondArg() << T2;
10959 MaybeEmitInheritedConstructorNote(S, Found);
10960 return;
10963 which = 1;
10964 } else {
10965 which = 2;
10968 // Tweak the diagnostic if the problem is that we deduced packs of
10969 // different arities. We'll print the actual packs anyway in case that
10970 // includes additional useful information.
10971 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10972 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10973 DeductionFailure.getFirstArg()->pack_size() !=
10974 DeductionFailure.getSecondArg()->pack_size()) {
10975 which = 3;
10978 S.Diag(Templated->getLocation(),
10979 diag::note_ovl_candidate_inconsistent_deduction)
10980 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10981 << *DeductionFailure.getSecondArg();
10982 MaybeEmitInheritedConstructorNote(S, Found);
10983 return;
10986 case Sema::TDK_InvalidExplicitArguments:
10987 assert(ParamD && "no parameter found for invalid explicit arguments");
10988 if (ParamD->getDeclName())
10989 S.Diag(Templated->getLocation(),
10990 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10991 << ParamD->getDeclName();
10992 else {
10993 int index = 0;
10994 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10995 index = TTP->getIndex();
10996 else if (NonTypeTemplateParmDecl *NTTP
10997 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10998 index = NTTP->getIndex();
10999 else
11000 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11001 S.Diag(Templated->getLocation(),
11002 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11003 << (index + 1);
11005 MaybeEmitInheritedConstructorNote(S, Found);
11006 return;
11008 case Sema::TDK_ConstraintsNotSatisfied: {
11009 // Format the template argument list into the argument string.
11010 SmallString<128> TemplateArgString;
11011 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11012 TemplateArgString = " ";
11013 TemplateArgString += S.getTemplateArgumentBindingsText(
11014 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11015 if (TemplateArgString.size() == 1)
11016 TemplateArgString.clear();
11017 S.Diag(Templated->getLocation(),
11018 diag::note_ovl_candidate_unsatisfied_constraints)
11019 << TemplateArgString;
11021 S.DiagnoseUnsatisfiedConstraint(
11022 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11023 return;
11025 case Sema::TDK_TooManyArguments:
11026 case Sema::TDK_TooFewArguments:
11027 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11028 return;
11030 case Sema::TDK_InstantiationDepth:
11031 S.Diag(Templated->getLocation(),
11032 diag::note_ovl_candidate_instantiation_depth);
11033 MaybeEmitInheritedConstructorNote(S, Found);
11034 return;
11036 case Sema::TDK_SubstitutionFailure: {
11037 // Format the template argument list into the argument string.
11038 SmallString<128> TemplateArgString;
11039 if (TemplateArgumentList *Args =
11040 DeductionFailure.getTemplateArgumentList()) {
11041 TemplateArgString = " ";
11042 TemplateArgString += S.getTemplateArgumentBindingsText(
11043 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11044 if (TemplateArgString.size() == 1)
11045 TemplateArgString.clear();
11048 // If this candidate was disabled by enable_if, say so.
11049 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11050 if (PDiag && PDiag->second.getDiagID() ==
11051 diag::err_typename_nested_not_found_enable_if) {
11052 // FIXME: Use the source range of the condition, and the fully-qualified
11053 // name of the enable_if template. These are both present in PDiag.
11054 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11055 << "'enable_if'" << TemplateArgString;
11056 return;
11059 // We found a specific requirement that disabled the enable_if.
11060 if (PDiag && PDiag->second.getDiagID() ==
11061 diag::err_typename_nested_not_found_requirement) {
11062 S.Diag(Templated->getLocation(),
11063 diag::note_ovl_candidate_disabled_by_requirement)
11064 << PDiag->second.getStringArg(0) << TemplateArgString;
11065 return;
11068 // Format the SFINAE diagnostic into the argument string.
11069 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11070 // formatted message in another diagnostic.
11071 SmallString<128> SFINAEArgString;
11072 SourceRange R;
11073 if (PDiag) {
11074 SFINAEArgString = ": ";
11075 R = SourceRange(PDiag->first, PDiag->first);
11076 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11079 S.Diag(Templated->getLocation(),
11080 diag::note_ovl_candidate_substitution_failure)
11081 << TemplateArgString << SFINAEArgString << R;
11082 MaybeEmitInheritedConstructorNote(S, Found);
11083 return;
11086 case Sema::TDK_DeducedMismatch:
11087 case Sema::TDK_DeducedMismatchNested: {
11088 // Format the template argument list into the argument string.
11089 SmallString<128> TemplateArgString;
11090 if (TemplateArgumentList *Args =
11091 DeductionFailure.getTemplateArgumentList()) {
11092 TemplateArgString = " ";
11093 TemplateArgString += S.getTemplateArgumentBindingsText(
11094 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11095 if (TemplateArgString.size() == 1)
11096 TemplateArgString.clear();
11099 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11100 << (*DeductionFailure.getCallArgIndex() + 1)
11101 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11102 << TemplateArgString
11103 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11104 break;
11107 case Sema::TDK_NonDeducedMismatch: {
11108 // FIXME: Provide a source location to indicate what we couldn't match.
11109 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11110 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11111 if (FirstTA.getKind() == TemplateArgument::Template &&
11112 SecondTA.getKind() == TemplateArgument::Template) {
11113 TemplateName FirstTN = FirstTA.getAsTemplate();
11114 TemplateName SecondTN = SecondTA.getAsTemplate();
11115 if (FirstTN.getKind() == TemplateName::Template &&
11116 SecondTN.getKind() == TemplateName::Template) {
11117 if (FirstTN.getAsTemplateDecl()->getName() ==
11118 SecondTN.getAsTemplateDecl()->getName()) {
11119 // FIXME: This fixes a bad diagnostic where both templates are named
11120 // the same. This particular case is a bit difficult since:
11121 // 1) It is passed as a string to the diagnostic printer.
11122 // 2) The diagnostic printer only attempts to find a better
11123 // name for types, not decls.
11124 // Ideally, this should folded into the diagnostic printer.
11125 S.Diag(Templated->getLocation(),
11126 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11127 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11128 return;
11133 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11134 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11135 return;
11137 // FIXME: For generic lambda parameters, check if the function is a lambda
11138 // call operator, and if so, emit a prettier and more informative
11139 // diagnostic that mentions 'auto' and lambda in addition to
11140 // (or instead of?) the canonical template type parameters.
11141 S.Diag(Templated->getLocation(),
11142 diag::note_ovl_candidate_non_deduced_mismatch)
11143 << FirstTA << SecondTA;
11144 return;
11146 // TODO: diagnose these individually, then kill off
11147 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11148 case Sema::TDK_MiscellaneousDeductionFailure:
11149 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11150 MaybeEmitInheritedConstructorNote(S, Found);
11151 return;
11152 case Sema::TDK_CUDATargetMismatch:
11153 S.Diag(Templated->getLocation(),
11154 diag::note_cuda_ovl_candidate_target_mismatch);
11155 return;
11159 /// Diagnose a failed template-argument deduction, for function calls.
11160 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11161 unsigned NumArgs,
11162 bool TakingCandidateAddress) {
11163 unsigned TDK = Cand->DeductionFailure.Result;
11164 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11165 if (CheckArityMismatch(S, Cand, NumArgs))
11166 return;
11168 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11169 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11172 /// CUDA: diagnose an invalid call across targets.
11173 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11174 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11175 FunctionDecl *Callee = Cand->Function;
11177 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11178 CalleeTarget = S.IdentifyCUDATarget(Callee);
11180 std::string FnDesc;
11181 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11182 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11183 Cand->getRewriteKind(), FnDesc);
11185 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11186 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11187 << FnDesc /* Ignored */
11188 << CalleeTarget << CallerTarget;
11190 // This could be an implicit constructor for which we could not infer the
11191 // target due to a collsion. Diagnose that case.
11192 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11193 if (Meth != nullptr && Meth->isImplicit()) {
11194 CXXRecordDecl *ParentClass = Meth->getParent();
11195 Sema::CXXSpecialMember CSM;
11197 switch (FnKindPair.first) {
11198 default:
11199 return;
11200 case oc_implicit_default_constructor:
11201 CSM = Sema::CXXDefaultConstructor;
11202 break;
11203 case oc_implicit_copy_constructor:
11204 CSM = Sema::CXXCopyConstructor;
11205 break;
11206 case oc_implicit_move_constructor:
11207 CSM = Sema::CXXMoveConstructor;
11208 break;
11209 case oc_implicit_copy_assignment:
11210 CSM = Sema::CXXCopyAssignment;
11211 break;
11212 case oc_implicit_move_assignment:
11213 CSM = Sema::CXXMoveAssignment;
11214 break;
11217 bool ConstRHS = false;
11218 if (Meth->getNumParams()) {
11219 if (const ReferenceType *RT =
11220 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11221 ConstRHS = RT->getPointeeType().isConstQualified();
11225 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11226 /* ConstRHS */ ConstRHS,
11227 /* Diagnose */ true);
11231 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11232 FunctionDecl *Callee = Cand->Function;
11233 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11235 S.Diag(Callee->getLocation(),
11236 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11237 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11240 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11241 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11242 assert(ES.isExplicit() && "not an explicit candidate");
11244 unsigned Kind;
11245 switch (Cand->Function->getDeclKind()) {
11246 case Decl::Kind::CXXConstructor:
11247 Kind = 0;
11248 break;
11249 case Decl::Kind::CXXConversion:
11250 Kind = 1;
11251 break;
11252 case Decl::Kind::CXXDeductionGuide:
11253 Kind = Cand->Function->isImplicit() ? 0 : 2;
11254 break;
11255 default:
11256 llvm_unreachable("invalid Decl");
11259 // Note the location of the first (in-class) declaration; a redeclaration
11260 // (particularly an out-of-class definition) will typically lack the
11261 // 'explicit' specifier.
11262 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11263 FunctionDecl *First = Cand->Function->getFirstDecl();
11264 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11265 First = Pattern->getFirstDecl();
11267 S.Diag(First->getLocation(),
11268 diag::note_ovl_candidate_explicit)
11269 << Kind << (ES.getExpr() ? 1 : 0)
11270 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11273 /// Generates a 'note' diagnostic for an overload candidate. We've
11274 /// already generated a primary error at the call site.
11276 /// It really does need to be a single diagnostic with its caret
11277 /// pointed at the candidate declaration. Yes, this creates some
11278 /// major challenges of technical writing. Yes, this makes pointing
11279 /// out problems with specific arguments quite awkward. It's still
11280 /// better than generating twenty screens of text for every failed
11281 /// overload.
11283 /// It would be great to be able to express per-candidate problems
11284 /// more richly for those diagnostic clients that cared, but we'd
11285 /// still have to be just as careful with the default diagnostics.
11286 /// \param CtorDestAS Addr space of object being constructed (for ctor
11287 /// candidates only).
11288 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11289 unsigned NumArgs,
11290 bool TakingCandidateAddress,
11291 LangAS CtorDestAS = LangAS::Default) {
11292 FunctionDecl *Fn = Cand->Function;
11293 if (shouldSkipNotingLambdaConversionDecl(Fn))
11294 return;
11296 // There is no physical candidate declaration to point to for OpenCL builtins.
11297 // Except for failed conversions, the notes are identical for each candidate,
11298 // so do not generate such notes.
11299 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11300 Cand->FailureKind != ovl_fail_bad_conversion)
11301 return;
11303 // Note deleted candidates, but only if they're viable.
11304 if (Cand->Viable) {
11305 if (Fn->isDeleted()) {
11306 std::string FnDesc;
11307 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11308 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11309 Cand->getRewriteKind(), FnDesc);
11311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11312 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11313 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11314 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11315 return;
11318 // We don't really have anything else to say about viable candidates.
11319 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11320 return;
11323 switch (Cand->FailureKind) {
11324 case ovl_fail_too_many_arguments:
11325 case ovl_fail_too_few_arguments:
11326 return DiagnoseArityMismatch(S, Cand, NumArgs);
11328 case ovl_fail_bad_deduction:
11329 return DiagnoseBadDeduction(S, Cand, NumArgs,
11330 TakingCandidateAddress);
11332 case ovl_fail_illegal_constructor: {
11333 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11334 << (Fn->getPrimaryTemplate() ? 1 : 0);
11335 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11336 return;
11339 case ovl_fail_object_addrspace_mismatch: {
11340 Qualifiers QualsForPrinting;
11341 QualsForPrinting.setAddressSpace(CtorDestAS);
11342 S.Diag(Fn->getLocation(),
11343 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11344 << QualsForPrinting;
11345 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11346 return;
11349 case ovl_fail_trivial_conversion:
11350 case ovl_fail_bad_final_conversion:
11351 case ovl_fail_final_conversion_not_exact:
11352 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11354 case ovl_fail_bad_conversion: {
11355 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11356 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11357 if (Cand->Conversions[I].isBad())
11358 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11360 // FIXME: this currently happens when we're called from SemaInit
11361 // when user-conversion overload fails. Figure out how to handle
11362 // those conditions and diagnose them well.
11363 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11366 case ovl_fail_bad_target:
11367 return DiagnoseBadTarget(S, Cand);
11369 case ovl_fail_enable_if:
11370 return DiagnoseFailedEnableIfAttr(S, Cand);
11372 case ovl_fail_explicit:
11373 return DiagnoseFailedExplicitSpec(S, Cand);
11375 case ovl_fail_inhctor_slice:
11376 // It's generally not interesting to note copy/move constructors here.
11377 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11378 return;
11379 S.Diag(Fn->getLocation(),
11380 diag::note_ovl_candidate_inherited_constructor_slice)
11381 << (Fn->getPrimaryTemplate() ? 1 : 0)
11382 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11383 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11384 return;
11386 case ovl_fail_addr_not_available: {
11387 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11388 (void)Available;
11389 assert(!Available);
11390 break;
11392 case ovl_non_default_multiversion_function:
11393 // Do nothing, these should simply be ignored.
11394 break;
11396 case ovl_fail_constraints_not_satisfied: {
11397 std::string FnDesc;
11398 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11399 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11400 Cand->getRewriteKind(), FnDesc);
11402 S.Diag(Fn->getLocation(),
11403 diag::note_ovl_candidate_constraints_not_satisfied)
11404 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11405 << FnDesc /* Ignored */;
11406 ConstraintSatisfaction Satisfaction;
11407 if (S.CheckFunctionConstraints(Fn, Satisfaction))
11408 break;
11409 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11414 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11415 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11416 return;
11418 // Desugar the type of the surrogate down to a function type,
11419 // retaining as many typedefs as possible while still showing
11420 // the function type (and, therefore, its parameter types).
11421 QualType FnType = Cand->Surrogate->getConversionType();
11422 bool isLValueReference = false;
11423 bool isRValueReference = false;
11424 bool isPointer = false;
11425 if (const LValueReferenceType *FnTypeRef =
11426 FnType->getAs<LValueReferenceType>()) {
11427 FnType = FnTypeRef->getPointeeType();
11428 isLValueReference = true;
11429 } else if (const RValueReferenceType *FnTypeRef =
11430 FnType->getAs<RValueReferenceType>()) {
11431 FnType = FnTypeRef->getPointeeType();
11432 isRValueReference = true;
11434 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11435 FnType = FnTypePtr->getPointeeType();
11436 isPointer = true;
11438 // Desugar down to a function type.
11439 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11440 // Reconstruct the pointer/reference as appropriate.
11441 if (isPointer) FnType = S.Context.getPointerType(FnType);
11442 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11443 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11445 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11446 << FnType;
11449 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11450 SourceLocation OpLoc,
11451 OverloadCandidate *Cand) {
11452 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11453 std::string TypeStr("operator");
11454 TypeStr += Opc;
11455 TypeStr += "(";
11456 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11457 if (Cand->Conversions.size() == 1) {
11458 TypeStr += ")";
11459 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11460 } else {
11461 TypeStr += ", ";
11462 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11463 TypeStr += ")";
11464 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11468 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11469 OverloadCandidate *Cand) {
11470 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11471 if (ICS.isBad()) break; // all meaningless after first invalid
11472 if (!ICS.isAmbiguous()) continue;
11474 ICS.DiagnoseAmbiguousConversion(
11475 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11479 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11480 if (Cand->Function)
11481 return Cand->Function->getLocation();
11482 if (Cand->IsSurrogate)
11483 return Cand->Surrogate->getLocation();
11484 return SourceLocation();
11487 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11488 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11489 case Sema::TDK_Success:
11490 case Sema::TDK_NonDependentConversionFailure:
11491 case Sema::TDK_AlreadyDiagnosed:
11492 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11494 case Sema::TDK_Invalid:
11495 case Sema::TDK_Incomplete:
11496 case Sema::TDK_IncompletePack:
11497 return 1;
11499 case Sema::TDK_Underqualified:
11500 case Sema::TDK_Inconsistent:
11501 return 2;
11503 case Sema::TDK_SubstitutionFailure:
11504 case Sema::TDK_DeducedMismatch:
11505 case Sema::TDK_ConstraintsNotSatisfied:
11506 case Sema::TDK_DeducedMismatchNested:
11507 case Sema::TDK_NonDeducedMismatch:
11508 case Sema::TDK_MiscellaneousDeductionFailure:
11509 case Sema::TDK_CUDATargetMismatch:
11510 return 3;
11512 case Sema::TDK_InstantiationDepth:
11513 return 4;
11515 case Sema::TDK_InvalidExplicitArguments:
11516 return 5;
11518 case Sema::TDK_TooManyArguments:
11519 case Sema::TDK_TooFewArguments:
11520 return 6;
11522 llvm_unreachable("Unhandled deduction result");
11525 namespace {
11526 struct CompareOverloadCandidatesForDisplay {
11527 Sema &S;
11528 SourceLocation Loc;
11529 size_t NumArgs;
11530 OverloadCandidateSet::CandidateSetKind CSK;
11532 CompareOverloadCandidatesForDisplay(
11533 Sema &S, SourceLocation Loc, size_t NArgs,
11534 OverloadCandidateSet::CandidateSetKind CSK)
11535 : S(S), NumArgs(NArgs), CSK(CSK) {}
11537 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11538 // If there are too many or too few arguments, that's the high-order bit we
11539 // want to sort by, even if the immediate failure kind was something else.
11540 if (C->FailureKind == ovl_fail_too_many_arguments ||
11541 C->FailureKind == ovl_fail_too_few_arguments)
11542 return static_cast<OverloadFailureKind>(C->FailureKind);
11544 if (C->Function) {
11545 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11546 return ovl_fail_too_many_arguments;
11547 if (NumArgs < C->Function->getMinRequiredArguments())
11548 return ovl_fail_too_few_arguments;
11551 return static_cast<OverloadFailureKind>(C->FailureKind);
11554 bool operator()(const OverloadCandidate *L,
11555 const OverloadCandidate *R) {
11556 // Fast-path this check.
11557 if (L == R) return false;
11559 // Order first by viability.
11560 if (L->Viable) {
11561 if (!R->Viable) return true;
11563 // TODO: introduce a tri-valued comparison for overload
11564 // candidates. Would be more worthwhile if we had a sort
11565 // that could exploit it.
11566 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11567 return true;
11568 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11569 return false;
11570 } else if (R->Viable)
11571 return false;
11573 assert(L->Viable == R->Viable);
11575 // Criteria by which we can sort non-viable candidates:
11576 if (!L->Viable) {
11577 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11578 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11580 // 1. Arity mismatches come after other candidates.
11581 if (LFailureKind == ovl_fail_too_many_arguments ||
11582 LFailureKind == ovl_fail_too_few_arguments) {
11583 if (RFailureKind == ovl_fail_too_many_arguments ||
11584 RFailureKind == ovl_fail_too_few_arguments) {
11585 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11586 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11587 if (LDist == RDist) {
11588 if (LFailureKind == RFailureKind)
11589 // Sort non-surrogates before surrogates.
11590 return !L->IsSurrogate && R->IsSurrogate;
11591 // Sort candidates requiring fewer parameters than there were
11592 // arguments given after candidates requiring more parameters
11593 // than there were arguments given.
11594 return LFailureKind == ovl_fail_too_many_arguments;
11596 return LDist < RDist;
11598 return false;
11600 if (RFailureKind == ovl_fail_too_many_arguments ||
11601 RFailureKind == ovl_fail_too_few_arguments)
11602 return true;
11604 // 2. Bad conversions come first and are ordered by the number
11605 // of bad conversions and quality of good conversions.
11606 if (LFailureKind == ovl_fail_bad_conversion) {
11607 if (RFailureKind != ovl_fail_bad_conversion)
11608 return true;
11610 // The conversion that can be fixed with a smaller number of changes,
11611 // comes first.
11612 unsigned numLFixes = L->Fix.NumConversionsFixed;
11613 unsigned numRFixes = R->Fix.NumConversionsFixed;
11614 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11615 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11616 if (numLFixes != numRFixes) {
11617 return numLFixes < numRFixes;
11620 // If there's any ordering between the defined conversions...
11621 // FIXME: this might not be transitive.
11622 assert(L->Conversions.size() == R->Conversions.size());
11624 int leftBetter = 0;
11625 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11626 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11627 switch (CompareImplicitConversionSequences(S, Loc,
11628 L->Conversions[I],
11629 R->Conversions[I])) {
11630 case ImplicitConversionSequence::Better:
11631 leftBetter++;
11632 break;
11634 case ImplicitConversionSequence::Worse:
11635 leftBetter--;
11636 break;
11638 case ImplicitConversionSequence::Indistinguishable:
11639 break;
11642 if (leftBetter > 0) return true;
11643 if (leftBetter < 0) return false;
11645 } else if (RFailureKind == ovl_fail_bad_conversion)
11646 return false;
11648 if (LFailureKind == ovl_fail_bad_deduction) {
11649 if (RFailureKind != ovl_fail_bad_deduction)
11650 return true;
11652 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11653 return RankDeductionFailure(L->DeductionFailure)
11654 < RankDeductionFailure(R->DeductionFailure);
11655 } else if (RFailureKind == ovl_fail_bad_deduction)
11656 return false;
11658 // TODO: others?
11661 // Sort everything else by location.
11662 SourceLocation LLoc = GetLocationForCandidate(L);
11663 SourceLocation RLoc = GetLocationForCandidate(R);
11665 // Put candidates without locations (e.g. builtins) at the end.
11666 if (LLoc.isInvalid()) return false;
11667 if (RLoc.isInvalid()) return true;
11669 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11674 /// CompleteNonViableCandidate - Normally, overload resolution only
11675 /// computes up to the first bad conversion. Produces the FixIt set if
11676 /// possible.
11677 static void
11678 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11679 ArrayRef<Expr *> Args,
11680 OverloadCandidateSet::CandidateSetKind CSK) {
11681 assert(!Cand->Viable);
11683 // Don't do anything on failures other than bad conversion.
11684 if (Cand->FailureKind != ovl_fail_bad_conversion)
11685 return;
11687 // We only want the FixIts if all the arguments can be corrected.
11688 bool Unfixable = false;
11689 // Use a implicit copy initialization to check conversion fixes.
11690 Cand->Fix.setConversionChecker(TryCopyInitialization);
11692 // Attempt to fix the bad conversion.
11693 unsigned ConvCount = Cand->Conversions.size();
11694 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11695 ++ConvIdx) {
11696 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11697 if (Cand->Conversions[ConvIdx].isInitialized() &&
11698 Cand->Conversions[ConvIdx].isBad()) {
11699 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11700 break;
11704 // FIXME: this should probably be preserved from the overload
11705 // operation somehow.
11706 bool SuppressUserConversions = false;
11708 unsigned ConvIdx = 0;
11709 unsigned ArgIdx = 0;
11710 ArrayRef<QualType> ParamTypes;
11711 bool Reversed = Cand->isReversed();
11713 if (Cand->IsSurrogate) {
11714 QualType ConvType
11715 = Cand->Surrogate->getConversionType().getNonReferenceType();
11716 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11717 ConvType = ConvPtrType->getPointeeType();
11718 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11719 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11720 ConvIdx = 1;
11721 } else if (Cand->Function) {
11722 ParamTypes =
11723 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11724 if (isa<CXXMethodDecl>(Cand->Function) &&
11725 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11726 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11727 ConvIdx = 1;
11728 if (CSK == OverloadCandidateSet::CSK_Operator &&
11729 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11730 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11731 OO_Subscript)
11732 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11733 ArgIdx = 1;
11735 } else {
11736 // Builtin operator.
11737 assert(ConvCount <= 3);
11738 ParamTypes = Cand->BuiltinParamTypes;
11741 // Fill in the rest of the conversions.
11742 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11743 ConvIdx != ConvCount;
11744 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11745 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11746 if (Cand->Conversions[ConvIdx].isInitialized()) {
11747 // We've already checked this conversion.
11748 } else if (ParamIdx < ParamTypes.size()) {
11749 if (ParamTypes[ParamIdx]->isDependentType())
11750 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11751 Args[ArgIdx]->getType());
11752 else {
11753 Cand->Conversions[ConvIdx] =
11754 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11755 SuppressUserConversions,
11756 /*InOverloadResolution=*/true,
11757 /*AllowObjCWritebackConversion=*/
11758 S.getLangOpts().ObjCAutoRefCount);
11759 // Store the FixIt in the candidate if it exists.
11760 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11761 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11763 } else
11764 Cand->Conversions[ConvIdx].setEllipsis();
11768 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11769 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11770 SourceLocation OpLoc,
11771 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11772 // Sort the candidates by viability and position. Sorting directly would
11773 // be prohibitive, so we make a set of pointers and sort those.
11774 SmallVector<OverloadCandidate*, 32> Cands;
11775 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11776 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11777 if (!Filter(*Cand))
11778 continue;
11779 switch (OCD) {
11780 case OCD_AllCandidates:
11781 if (!Cand->Viable) {
11782 if (!Cand->Function && !Cand->IsSurrogate) {
11783 // This a non-viable builtin candidate. We do not, in general,
11784 // want to list every possible builtin candidate.
11785 continue;
11787 CompleteNonViableCandidate(S, Cand, Args, Kind);
11789 break;
11791 case OCD_ViableCandidates:
11792 if (!Cand->Viable)
11793 continue;
11794 break;
11796 case OCD_AmbiguousCandidates:
11797 if (!Cand->Best)
11798 continue;
11799 break;
11802 Cands.push_back(Cand);
11805 llvm::stable_sort(
11806 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11808 return Cands;
11811 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11812 SourceLocation OpLoc) {
11813 bool DeferHint = false;
11814 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11815 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11816 // host device candidates.
11817 auto WrongSidedCands =
11818 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11819 return (Cand.Viable == false &&
11820 Cand.FailureKind == ovl_fail_bad_target) ||
11821 (Cand.Function &&
11822 Cand.Function->template hasAttr<CUDAHostAttr>() &&
11823 Cand.Function->template hasAttr<CUDADeviceAttr>());
11825 DeferHint = !WrongSidedCands.empty();
11827 return DeferHint;
11830 /// When overload resolution fails, prints diagnostic messages containing the
11831 /// candidates in the candidate set.
11832 void OverloadCandidateSet::NoteCandidates(
11833 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11834 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11835 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11837 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11839 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11841 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11843 if (OCD == OCD_AmbiguousCandidates)
11844 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11847 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11848 ArrayRef<OverloadCandidate *> Cands,
11849 StringRef Opc, SourceLocation OpLoc) {
11850 bool ReportedAmbiguousConversions = false;
11852 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11853 unsigned CandsShown = 0;
11854 auto I = Cands.begin(), E = Cands.end();
11855 for (; I != E; ++I) {
11856 OverloadCandidate *Cand = *I;
11858 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11859 ShowOverloads == Ovl_Best) {
11860 break;
11862 ++CandsShown;
11864 if (Cand->Function)
11865 NoteFunctionCandidate(S, Cand, Args.size(),
11866 /*TakingCandidateAddress=*/false, DestAS);
11867 else if (Cand->IsSurrogate)
11868 NoteSurrogateCandidate(S, Cand);
11869 else {
11870 assert(Cand->Viable &&
11871 "Non-viable built-in candidates are not added to Cands.");
11872 // Generally we only see ambiguities including viable builtin
11873 // operators if overload resolution got screwed up by an
11874 // ambiguous user-defined conversion.
11876 // FIXME: It's quite possible for different conversions to see
11877 // different ambiguities, though.
11878 if (!ReportedAmbiguousConversions) {
11879 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11880 ReportedAmbiguousConversions = true;
11883 // If this is a viable builtin, print it.
11884 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11888 // Inform S.Diags that we've shown an overload set with N elements. This may
11889 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11890 S.Diags.overloadCandidatesShown(CandsShown);
11892 if (I != E)
11893 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11894 shouldDeferDiags(S, Args, OpLoc))
11895 << int(E - I);
11898 static SourceLocation
11899 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11900 return Cand->Specialization ? Cand->Specialization->getLocation()
11901 : SourceLocation();
11904 namespace {
11905 struct CompareTemplateSpecCandidatesForDisplay {
11906 Sema &S;
11907 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11909 bool operator()(const TemplateSpecCandidate *L,
11910 const TemplateSpecCandidate *R) {
11911 // Fast-path this check.
11912 if (L == R)
11913 return false;
11915 // Assuming that both candidates are not matches...
11917 // Sort by the ranking of deduction failures.
11918 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11919 return RankDeductionFailure(L->DeductionFailure) <
11920 RankDeductionFailure(R->DeductionFailure);
11922 // Sort everything else by location.
11923 SourceLocation LLoc = GetLocationForCandidate(L);
11924 SourceLocation RLoc = GetLocationForCandidate(R);
11926 // Put candidates without locations (e.g. builtins) at the end.
11927 if (LLoc.isInvalid())
11928 return false;
11929 if (RLoc.isInvalid())
11930 return true;
11932 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11937 /// Diagnose a template argument deduction failure.
11938 /// We are treating these failures as overload failures due to bad
11939 /// deductions.
11940 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11941 bool ForTakingAddress) {
11942 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11943 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11946 void TemplateSpecCandidateSet::destroyCandidates() {
11947 for (iterator i = begin(), e = end(); i != e; ++i) {
11948 i->DeductionFailure.Destroy();
11952 void TemplateSpecCandidateSet::clear() {
11953 destroyCandidates();
11954 Candidates.clear();
11957 /// NoteCandidates - When no template specialization match is found, prints
11958 /// diagnostic messages containing the non-matching specializations that form
11959 /// the candidate set.
11960 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11961 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11962 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11963 // Sort the candidates by position (assuming no candidate is a match).
11964 // Sorting directly would be prohibitive, so we make a set of pointers
11965 // and sort those.
11966 SmallVector<TemplateSpecCandidate *, 32> Cands;
11967 Cands.reserve(size());
11968 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11969 if (Cand->Specialization)
11970 Cands.push_back(Cand);
11971 // Otherwise, this is a non-matching builtin candidate. We do not,
11972 // in general, want to list every possible builtin candidate.
11975 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11977 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11978 // for generalization purposes (?).
11979 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11981 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11982 unsigned CandsShown = 0;
11983 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11984 TemplateSpecCandidate *Cand = *I;
11986 // Set an arbitrary limit on the number of candidates we'll spam
11987 // the user with. FIXME: This limit should depend on details of the
11988 // candidate list.
11989 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11990 break;
11991 ++CandsShown;
11993 assert(Cand->Specialization &&
11994 "Non-matching built-in candidates are not added to Cands.");
11995 Cand->NoteDeductionFailure(S, ForTakingAddress);
11998 if (I != E)
11999 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12002 // [PossiblyAFunctionType] --> [Return]
12003 // NonFunctionType --> NonFunctionType
12004 // R (A) --> R(A)
12005 // R (*)(A) --> R (A)
12006 // R (&)(A) --> R (A)
12007 // R (S::*)(A) --> R (A)
12008 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12009 QualType Ret = PossiblyAFunctionType;
12010 if (const PointerType *ToTypePtr =
12011 PossiblyAFunctionType->getAs<PointerType>())
12012 Ret = ToTypePtr->getPointeeType();
12013 else if (const ReferenceType *ToTypeRef =
12014 PossiblyAFunctionType->getAs<ReferenceType>())
12015 Ret = ToTypeRef->getPointeeType();
12016 else if (const MemberPointerType *MemTypePtr =
12017 PossiblyAFunctionType->getAs<MemberPointerType>())
12018 Ret = MemTypePtr->getPointeeType();
12019 Ret =
12020 Context.getCanonicalType(Ret).getUnqualifiedType();
12021 return Ret;
12024 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12025 bool Complain = true) {
12026 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12027 S.DeduceReturnType(FD, Loc, Complain))
12028 return true;
12030 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12031 if (S.getLangOpts().CPlusPlus17 &&
12032 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12033 !S.ResolveExceptionSpec(Loc, FPT))
12034 return true;
12036 return false;
12039 namespace {
12040 // A helper class to help with address of function resolution
12041 // - allows us to avoid passing around all those ugly parameters
12042 class AddressOfFunctionResolver {
12043 Sema& S;
12044 Expr* SourceExpr;
12045 const QualType& TargetType;
12046 QualType TargetFunctionType; // Extracted function type from target type
12048 bool Complain;
12049 //DeclAccessPair& ResultFunctionAccessPair;
12050 ASTContext& Context;
12052 bool TargetTypeIsNonStaticMemberFunction;
12053 bool FoundNonTemplateFunction;
12054 bool StaticMemberFunctionFromBoundPointer;
12055 bool HasComplained;
12057 OverloadExpr::FindResult OvlExprInfo;
12058 OverloadExpr *OvlExpr;
12059 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12060 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12061 TemplateSpecCandidateSet FailedCandidates;
12063 public:
12064 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12065 const QualType &TargetType, bool Complain)
12066 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12067 Complain(Complain), Context(S.getASTContext()),
12068 TargetTypeIsNonStaticMemberFunction(
12069 !!TargetType->getAs<MemberPointerType>()),
12070 FoundNonTemplateFunction(false),
12071 StaticMemberFunctionFromBoundPointer(false),
12072 HasComplained(false),
12073 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12074 OvlExpr(OvlExprInfo.Expression),
12075 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12076 ExtractUnqualifiedFunctionTypeFromTargetType();
12078 if (TargetFunctionType->isFunctionType()) {
12079 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12080 if (!UME->isImplicitAccess() &&
12081 !S.ResolveSingleFunctionTemplateSpecialization(UME))
12082 StaticMemberFunctionFromBoundPointer = true;
12083 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12084 DeclAccessPair dap;
12085 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12086 OvlExpr, false, &dap)) {
12087 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12088 if (!Method->isStatic()) {
12089 // If the target type is a non-function type and the function found
12090 // is a non-static member function, pretend as if that was the
12091 // target, it's the only possible type to end up with.
12092 TargetTypeIsNonStaticMemberFunction = true;
12094 // And skip adding the function if its not in the proper form.
12095 // We'll diagnose this due to an empty set of functions.
12096 if (!OvlExprInfo.HasFormOfMemberPointer)
12097 return;
12100 Matches.push_back(std::make_pair(dap, Fn));
12102 return;
12105 if (OvlExpr->hasExplicitTemplateArgs())
12106 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12108 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12109 // C++ [over.over]p4:
12110 // If more than one function is selected, [...]
12111 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12112 if (FoundNonTemplateFunction)
12113 EliminateAllTemplateMatches();
12114 else
12115 EliminateAllExceptMostSpecializedTemplate();
12119 if (S.getLangOpts().CUDA && Matches.size() > 1)
12120 EliminateSuboptimalCudaMatches();
12123 bool hasComplained() const { return HasComplained; }
12125 private:
12126 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12127 QualType Discard;
12128 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12129 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12132 /// \return true if A is considered a better overload candidate for the
12133 /// desired type than B.
12134 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12135 // If A doesn't have exactly the correct type, we don't want to classify it
12136 // as "better" than anything else. This way, the user is required to
12137 // disambiguate for us if there are multiple candidates and no exact match.
12138 return candidateHasExactlyCorrectType(A) &&
12139 (!candidateHasExactlyCorrectType(B) ||
12140 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12143 /// \return true if we were able to eliminate all but one overload candidate,
12144 /// false otherwise.
12145 bool eliminiateSuboptimalOverloadCandidates() {
12146 // Same algorithm as overload resolution -- one pass to pick the "best",
12147 // another pass to be sure that nothing is better than the best.
12148 auto Best = Matches.begin();
12149 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12150 if (isBetterCandidate(I->second, Best->second))
12151 Best = I;
12153 const FunctionDecl *BestFn = Best->second;
12154 auto IsBestOrInferiorToBest = [this, BestFn](
12155 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12156 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12159 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12160 // option, so we can potentially give the user a better error
12161 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12162 return false;
12163 Matches[0] = *Best;
12164 Matches.resize(1);
12165 return true;
12168 bool isTargetTypeAFunction() const {
12169 return TargetFunctionType->isFunctionType();
12172 // [ToType] [Return]
12174 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12175 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12176 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12177 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12178 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12181 // return true if any matching specializations were found
12182 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12183 const DeclAccessPair& CurAccessFunPair) {
12184 if (CXXMethodDecl *Method
12185 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12186 // Skip non-static function templates when converting to pointer, and
12187 // static when converting to member pointer.
12188 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12189 return false;
12191 else if (TargetTypeIsNonStaticMemberFunction)
12192 return false;
12194 // C++ [over.over]p2:
12195 // If the name is a function template, template argument deduction is
12196 // done (14.8.2.2), and if the argument deduction succeeds, the
12197 // resulting template argument list is used to generate a single
12198 // function template specialization, which is added to the set of
12199 // overloaded functions considered.
12200 FunctionDecl *Specialization = nullptr;
12201 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12202 if (Sema::TemplateDeductionResult Result
12203 = S.DeduceTemplateArguments(FunctionTemplate,
12204 &OvlExplicitTemplateArgs,
12205 TargetFunctionType, Specialization,
12206 Info, /*IsAddressOfFunction*/true)) {
12207 // Make a note of the failed deduction for diagnostics.
12208 FailedCandidates.addCandidate()
12209 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12210 MakeDeductionFailureInfo(Context, Result, Info));
12211 return false;
12214 // Template argument deduction ensures that we have an exact match or
12215 // compatible pointer-to-function arguments that would be adjusted by ICS.
12216 // This function template specicalization works.
12217 assert(S.isSameOrCompatibleFunctionType(
12218 Context.getCanonicalType(Specialization->getType()),
12219 Context.getCanonicalType(TargetFunctionType)));
12221 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12222 return false;
12224 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12225 return true;
12228 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12229 const DeclAccessPair& CurAccessFunPair) {
12230 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12231 // Skip non-static functions when converting to pointer, and static
12232 // when converting to member pointer.
12233 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12234 return false;
12236 else if (TargetTypeIsNonStaticMemberFunction)
12237 return false;
12239 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12240 if (S.getLangOpts().CUDA)
12241 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12242 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12243 return false;
12244 if (FunDecl->isMultiVersion()) {
12245 const auto *TA = FunDecl->getAttr<TargetAttr>();
12246 if (TA && !TA->isDefaultVersion())
12247 return false;
12250 // If any candidate has a placeholder return type, trigger its deduction
12251 // now.
12252 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12253 Complain)) {
12254 HasComplained |= Complain;
12255 return false;
12258 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12259 return false;
12261 // If we're in C, we need to support types that aren't exactly identical.
12262 if (!S.getLangOpts().CPlusPlus ||
12263 candidateHasExactlyCorrectType(FunDecl)) {
12264 Matches.push_back(std::make_pair(
12265 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12266 FoundNonTemplateFunction = true;
12267 return true;
12271 return false;
12274 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12275 bool Ret = false;
12277 // If the overload expression doesn't have the form of a pointer to
12278 // member, don't try to convert it to a pointer-to-member type.
12279 if (IsInvalidFormOfPointerToMemberFunction())
12280 return false;
12282 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12283 E = OvlExpr->decls_end();
12284 I != E; ++I) {
12285 // Look through any using declarations to find the underlying function.
12286 NamedDecl *Fn = (*I)->getUnderlyingDecl();
12288 // C++ [over.over]p3:
12289 // Non-member functions and static member functions match
12290 // targets of type "pointer-to-function" or "reference-to-function."
12291 // Nonstatic member functions match targets of
12292 // type "pointer-to-member-function."
12293 // Note that according to DR 247, the containing class does not matter.
12294 if (FunctionTemplateDecl *FunctionTemplate
12295 = dyn_cast<FunctionTemplateDecl>(Fn)) {
12296 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12297 Ret = true;
12299 // If we have explicit template arguments supplied, skip non-templates.
12300 else if (!OvlExpr->hasExplicitTemplateArgs() &&
12301 AddMatchingNonTemplateFunction(Fn, I.getPair()))
12302 Ret = true;
12304 assert(Ret || Matches.empty());
12305 return Ret;
12308 void EliminateAllExceptMostSpecializedTemplate() {
12309 // [...] and any given function template specialization F1 is
12310 // eliminated if the set contains a second function template
12311 // specialization whose function template is more specialized
12312 // than the function template of F1 according to the partial
12313 // ordering rules of 14.5.5.2.
12315 // The algorithm specified above is quadratic. We instead use a
12316 // two-pass algorithm (similar to the one used to identify the
12317 // best viable function in an overload set) that identifies the
12318 // best function template (if it exists).
12320 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12321 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12322 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12324 // TODO: It looks like FailedCandidates does not serve much purpose
12325 // here, since the no_viable diagnostic has index 0.
12326 UnresolvedSetIterator Result = S.getMostSpecialized(
12327 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12328 SourceExpr->getBeginLoc(), S.PDiag(),
12329 S.PDiag(diag::err_addr_ovl_ambiguous)
12330 << Matches[0].second->getDeclName(),
12331 S.PDiag(diag::note_ovl_candidate)
12332 << (unsigned)oc_function << (unsigned)ocs_described_template,
12333 Complain, TargetFunctionType);
12335 if (Result != MatchesCopy.end()) {
12336 // Make it the first and only element
12337 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12338 Matches[0].second = cast<FunctionDecl>(*Result);
12339 Matches.resize(1);
12340 } else
12341 HasComplained |= Complain;
12344 void EliminateAllTemplateMatches() {
12345 // [...] any function template specializations in the set are
12346 // eliminated if the set also contains a non-template function, [...]
12347 for (unsigned I = 0, N = Matches.size(); I != N; ) {
12348 if (Matches[I].second->getPrimaryTemplate() == nullptr)
12349 ++I;
12350 else {
12351 Matches[I] = Matches[--N];
12352 Matches.resize(N);
12357 void EliminateSuboptimalCudaMatches() {
12358 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12359 Matches);
12362 public:
12363 void ComplainNoMatchesFound() const {
12364 assert(Matches.empty());
12365 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12366 << OvlExpr->getName() << TargetFunctionType
12367 << OvlExpr->getSourceRange();
12368 if (FailedCandidates.empty())
12369 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12370 /*TakingAddress=*/true);
12371 else {
12372 // We have some deduction failure messages. Use them to diagnose
12373 // the function templates, and diagnose the non-template candidates
12374 // normally.
12375 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12376 IEnd = OvlExpr->decls_end();
12377 I != IEnd; ++I)
12378 if (FunctionDecl *Fun =
12379 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12380 if (!functionHasPassObjectSizeParams(Fun))
12381 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12382 /*TakingAddress=*/true);
12383 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12387 bool IsInvalidFormOfPointerToMemberFunction() const {
12388 return TargetTypeIsNonStaticMemberFunction &&
12389 !OvlExprInfo.HasFormOfMemberPointer;
12392 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12393 // TODO: Should we condition this on whether any functions might
12394 // have matched, or is it more appropriate to do that in callers?
12395 // TODO: a fixit wouldn't hurt.
12396 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12397 << TargetType << OvlExpr->getSourceRange();
12400 bool IsStaticMemberFunctionFromBoundPointer() const {
12401 return StaticMemberFunctionFromBoundPointer;
12404 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12405 S.Diag(OvlExpr->getBeginLoc(),
12406 diag::err_invalid_form_pointer_member_function)
12407 << OvlExpr->getSourceRange();
12410 void ComplainOfInvalidConversion() const {
12411 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12412 << OvlExpr->getName() << TargetType;
12415 void ComplainMultipleMatchesFound() const {
12416 assert(Matches.size() > 1);
12417 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12418 << OvlExpr->getName() << OvlExpr->getSourceRange();
12419 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12420 /*TakingAddress=*/true);
12423 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12425 int getNumMatches() const { return Matches.size(); }
12427 FunctionDecl* getMatchingFunctionDecl() const {
12428 if (Matches.size() != 1) return nullptr;
12429 return Matches[0].second;
12432 const DeclAccessPair* getMatchingFunctionAccessPair() const {
12433 if (Matches.size() != 1) return nullptr;
12434 return &Matches[0].first;
12439 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12440 /// an overloaded function (C++ [over.over]), where @p From is an
12441 /// expression with overloaded function type and @p ToType is the type
12442 /// we're trying to resolve to. For example:
12444 /// @code
12445 /// int f(double);
12446 /// int f(int);
12448 /// int (*pfd)(double) = f; // selects f(double)
12449 /// @endcode
12451 /// This routine returns the resulting FunctionDecl if it could be
12452 /// resolved, and NULL otherwise. When @p Complain is true, this
12453 /// routine will emit diagnostics if there is an error.
12454 FunctionDecl *
12455 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12456 QualType TargetType,
12457 bool Complain,
12458 DeclAccessPair &FoundResult,
12459 bool *pHadMultipleCandidates) {
12460 assert(AddressOfExpr->getType() == Context.OverloadTy);
12462 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12463 Complain);
12464 int NumMatches = Resolver.getNumMatches();
12465 FunctionDecl *Fn = nullptr;
12466 bool ShouldComplain = Complain && !Resolver.hasComplained();
12467 if (NumMatches == 0 && ShouldComplain) {
12468 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12469 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12470 else
12471 Resolver.ComplainNoMatchesFound();
12473 else if (NumMatches > 1 && ShouldComplain)
12474 Resolver.ComplainMultipleMatchesFound();
12475 else if (NumMatches == 1) {
12476 Fn = Resolver.getMatchingFunctionDecl();
12477 assert(Fn);
12478 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12479 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12480 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12481 if (Complain) {
12482 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12483 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12484 else
12485 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12489 if (pHadMultipleCandidates)
12490 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12491 return Fn;
12494 /// Given an expression that refers to an overloaded function, try to
12495 /// resolve that function to a single function that can have its address taken.
12496 /// This will modify `Pair` iff it returns non-null.
12498 /// This routine can only succeed if from all of the candidates in the overload
12499 /// set for SrcExpr that can have their addresses taken, there is one candidate
12500 /// that is more constrained than the rest.
12501 FunctionDecl *
12502 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12503 OverloadExpr::FindResult R = OverloadExpr::find(E);
12504 OverloadExpr *Ovl = R.Expression;
12505 bool IsResultAmbiguous = false;
12506 FunctionDecl *Result = nullptr;
12507 DeclAccessPair DAP;
12508 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12510 auto CheckMoreConstrained =
12511 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12512 SmallVector<const Expr *, 1> AC1, AC2;
12513 FD1->getAssociatedConstraints(AC1);
12514 FD2->getAssociatedConstraints(AC2);
12515 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12516 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12517 return None;
12518 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12519 return None;
12520 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12521 return None;
12522 return AtLeastAsConstrained1;
12525 // Don't use the AddressOfResolver because we're specifically looking for
12526 // cases where we have one overload candidate that lacks
12527 // enable_if/pass_object_size/...
12528 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12529 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12530 if (!FD)
12531 return nullptr;
12533 if (!checkAddressOfFunctionIsAvailable(FD))
12534 continue;
12536 // We have more than one result - see if it is more constrained than the
12537 // previous one.
12538 if (Result) {
12539 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12540 Result);
12541 if (!MoreConstrainedThanPrevious) {
12542 IsResultAmbiguous = true;
12543 AmbiguousDecls.push_back(FD);
12544 continue;
12546 if (!*MoreConstrainedThanPrevious)
12547 continue;
12548 // FD is more constrained - replace Result with it.
12550 IsResultAmbiguous = false;
12551 DAP = I.getPair();
12552 Result = FD;
12555 if (IsResultAmbiguous)
12556 return nullptr;
12558 if (Result) {
12559 SmallVector<const Expr *, 1> ResultAC;
12560 // We skipped over some ambiguous declarations which might be ambiguous with
12561 // the selected result.
12562 for (FunctionDecl *Skipped : AmbiguousDecls)
12563 if (!CheckMoreConstrained(Skipped, Result))
12564 return nullptr;
12565 Pair = DAP;
12567 return Result;
12570 /// Given an overloaded function, tries to turn it into a non-overloaded
12571 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12572 /// will perform access checks, diagnose the use of the resultant decl, and, if
12573 /// requested, potentially perform a function-to-pointer decay.
12575 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12576 /// Otherwise, returns true. This may emit diagnostics and return true.
12577 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12578 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
12579 Expr *E = SrcExpr.get();
12580 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12582 DeclAccessPair DAP;
12583 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12584 if (!Found || Found->isCPUDispatchMultiVersion() ||
12585 Found->isCPUSpecificMultiVersion())
12586 return false;
12588 // Emitting multiple diagnostics for a function that is both inaccessible and
12589 // unavailable is consistent with our behavior elsewhere. So, always check
12590 // for both.
12591 DiagnoseUseOfDecl(Found, E->getExprLoc());
12592 CheckAddressOfMemberAccess(E, DAP);
12593 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12594 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
12595 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12596 else
12597 SrcExpr = Fixed;
12598 return true;
12601 /// Given an expression that refers to an overloaded function, try to
12602 /// resolve that overloaded function expression down to a single function.
12604 /// This routine can only resolve template-ids that refer to a single function
12605 /// template, where that template-id refers to a single template whose template
12606 /// arguments are either provided by the template-id or have defaults,
12607 /// as described in C++0x [temp.arg.explicit]p3.
12609 /// If no template-ids are found, no diagnostics are emitted and NULL is
12610 /// returned.
12611 FunctionDecl *
12612 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12613 bool Complain,
12614 DeclAccessPair *FoundResult) {
12615 // C++ [over.over]p1:
12616 // [...] [Note: any redundant set of parentheses surrounding the
12617 // overloaded function name is ignored (5.1). ]
12618 // C++ [over.over]p1:
12619 // [...] The overloaded function name can be preceded by the &
12620 // operator.
12622 // If we didn't actually find any template-ids, we're done.
12623 if (!ovl->hasExplicitTemplateArgs())
12624 return nullptr;
12626 TemplateArgumentListInfo ExplicitTemplateArgs;
12627 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12628 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12630 // Look through all of the overloaded functions, searching for one
12631 // whose type matches exactly.
12632 FunctionDecl *Matched = nullptr;
12633 for (UnresolvedSetIterator I = ovl->decls_begin(),
12634 E = ovl->decls_end(); I != E; ++I) {
12635 // C++0x [temp.arg.explicit]p3:
12636 // [...] In contexts where deduction is done and fails, or in contexts
12637 // where deduction is not done, if a template argument list is
12638 // specified and it, along with any default template arguments,
12639 // identifies a single function template specialization, then the
12640 // template-id is an lvalue for the function template specialization.
12641 FunctionTemplateDecl *FunctionTemplate
12642 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12644 // C++ [over.over]p2:
12645 // If the name is a function template, template argument deduction is
12646 // done (14.8.2.2), and if the argument deduction succeeds, the
12647 // resulting template argument list is used to generate a single
12648 // function template specialization, which is added to the set of
12649 // overloaded functions considered.
12650 FunctionDecl *Specialization = nullptr;
12651 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12652 if (TemplateDeductionResult Result
12653 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12654 Specialization, Info,
12655 /*IsAddressOfFunction*/true)) {
12656 // Make a note of the failed deduction for diagnostics.
12657 // TODO: Actually use the failed-deduction info?
12658 FailedCandidates.addCandidate()
12659 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12660 MakeDeductionFailureInfo(Context, Result, Info));
12661 continue;
12664 assert(Specialization && "no specialization and no error?");
12666 // Multiple matches; we can't resolve to a single declaration.
12667 if (Matched) {
12668 if (Complain) {
12669 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12670 << ovl->getName();
12671 NoteAllOverloadCandidates(ovl);
12673 return nullptr;
12676 Matched = Specialization;
12677 if (FoundResult) *FoundResult = I.getPair();
12680 if (Matched &&
12681 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12682 return nullptr;
12684 return Matched;
12687 // Resolve and fix an overloaded expression that can be resolved
12688 // because it identifies a single function template specialization.
12690 // Last three arguments should only be supplied if Complain = true
12692 // Return true if it was logically possible to so resolve the
12693 // expression, regardless of whether or not it succeeded. Always
12694 // returns true if 'complain' is set.
12695 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12696 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
12697 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
12698 unsigned DiagIDForComplaining) {
12699 assert(SrcExpr.get()->getType() == Context.OverloadTy);
12701 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12703 DeclAccessPair found;
12704 ExprResult SingleFunctionExpression;
12705 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12706 ovl.Expression, /*complain*/ false, &found)) {
12707 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12708 SrcExpr = ExprError();
12709 return true;
12712 // It is only correct to resolve to an instance method if we're
12713 // resolving a form that's permitted to be a pointer to member.
12714 // Otherwise we'll end up making a bound member expression, which
12715 // is illegal in all the contexts we resolve like this.
12716 if (!ovl.HasFormOfMemberPointer &&
12717 isa<CXXMethodDecl>(fn) &&
12718 cast<CXXMethodDecl>(fn)->isInstance()) {
12719 if (!complain) return false;
12721 Diag(ovl.Expression->getExprLoc(),
12722 diag::err_bound_member_function)
12723 << 0 << ovl.Expression->getSourceRange();
12725 // TODO: I believe we only end up here if there's a mix of
12726 // static and non-static candidates (otherwise the expression
12727 // would have 'bound member' type, not 'overload' type).
12728 // Ideally we would note which candidate was chosen and why
12729 // the static candidates were rejected.
12730 SrcExpr = ExprError();
12731 return true;
12734 // Fix the expression to refer to 'fn'.
12735 SingleFunctionExpression =
12736 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12738 // If desired, do function-to-pointer decay.
12739 if (doFunctionPointerConversion) {
12740 SingleFunctionExpression =
12741 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12742 if (SingleFunctionExpression.isInvalid()) {
12743 SrcExpr = ExprError();
12744 return true;
12749 if (!SingleFunctionExpression.isUsable()) {
12750 if (complain) {
12751 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12752 << ovl.Expression->getName()
12753 << DestTypeForComplaining
12754 << OpRangeForComplaining
12755 << ovl.Expression->getQualifierLoc().getSourceRange();
12756 NoteAllOverloadCandidates(SrcExpr.get());
12758 SrcExpr = ExprError();
12759 return true;
12762 return false;
12765 SrcExpr = SingleFunctionExpression;
12766 return true;
12769 /// Add a single candidate to the overload set.
12770 static void AddOverloadedCallCandidate(Sema &S,
12771 DeclAccessPair FoundDecl,
12772 TemplateArgumentListInfo *ExplicitTemplateArgs,
12773 ArrayRef<Expr *> Args,
12774 OverloadCandidateSet &CandidateSet,
12775 bool PartialOverloading,
12776 bool KnownValid) {
12777 NamedDecl *Callee = FoundDecl.getDecl();
12778 if (isa<UsingShadowDecl>(Callee))
12779 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12781 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12782 if (ExplicitTemplateArgs) {
12783 assert(!KnownValid && "Explicit template arguments?");
12784 return;
12786 // Prevent ill-formed function decls to be added as overload candidates.
12787 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12788 return;
12790 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12791 /*SuppressUserConversions=*/false,
12792 PartialOverloading);
12793 return;
12796 if (FunctionTemplateDecl *FuncTemplate
12797 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12798 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12799 ExplicitTemplateArgs, Args, CandidateSet,
12800 /*SuppressUserConversions=*/false,
12801 PartialOverloading);
12802 return;
12805 assert(!KnownValid && "unhandled case in overloaded call candidate");
12808 /// Add the overload candidates named by callee and/or found by argument
12809 /// dependent lookup to the given overload set.
12810 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12811 ArrayRef<Expr *> Args,
12812 OverloadCandidateSet &CandidateSet,
12813 bool PartialOverloading) {
12815 #ifndef NDEBUG
12816 // Verify that ArgumentDependentLookup is consistent with the rules
12817 // in C++0x [basic.lookup.argdep]p3:
12819 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12820 // and let Y be the lookup set produced by argument dependent
12821 // lookup (defined as follows). If X contains
12823 // -- a declaration of a class member, or
12825 // -- a block-scope function declaration that is not a
12826 // using-declaration, or
12828 // -- a declaration that is neither a function or a function
12829 // template
12831 // then Y is empty.
12833 if (ULE->requiresADL()) {
12834 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12835 E = ULE->decls_end(); I != E; ++I) {
12836 assert(!(*I)->getDeclContext()->isRecord());
12837 assert(isa<UsingShadowDecl>(*I) ||
12838 !(*I)->getDeclContext()->isFunctionOrMethod());
12839 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12842 #endif
12844 // It would be nice to avoid this copy.
12845 TemplateArgumentListInfo TABuffer;
12846 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12847 if (ULE->hasExplicitTemplateArgs()) {
12848 ULE->copyTemplateArgumentsInto(TABuffer);
12849 ExplicitTemplateArgs = &TABuffer;
12852 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12853 E = ULE->decls_end(); I != E; ++I)
12854 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12855 CandidateSet, PartialOverloading,
12856 /*KnownValid*/ true);
12858 if (ULE->requiresADL())
12859 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12860 Args, ExplicitTemplateArgs,
12861 CandidateSet, PartialOverloading);
12864 /// Add the call candidates from the given set of lookup results to the given
12865 /// overload set. Non-function lookup results are ignored.
12866 void Sema::AddOverloadedCallCandidates(
12867 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12868 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12869 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12870 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12871 CandidateSet, false, /*KnownValid*/ false);
12874 /// Determine whether a declaration with the specified name could be moved into
12875 /// a different namespace.
12876 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12877 switch (Name.getCXXOverloadedOperator()) {
12878 case OO_New: case OO_Array_New:
12879 case OO_Delete: case OO_Array_Delete:
12880 return false;
12882 default:
12883 return true;
12887 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12888 /// template, where the non-dependent name was declared after the template
12889 /// was defined. This is common in code written for a compilers which do not
12890 /// correctly implement two-stage name lookup.
12892 /// Returns true if a viable candidate was found and a diagnostic was issued.
12893 static bool DiagnoseTwoPhaseLookup(
12894 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12895 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12896 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12897 CXXRecordDecl **FoundInClass = nullptr) {
12898 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12899 return false;
12901 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12902 if (DC->isTransparentContext())
12903 continue;
12905 SemaRef.LookupQualifiedName(R, DC);
12907 if (!R.empty()) {
12908 R.suppressDiagnostics();
12910 OverloadCandidateSet Candidates(FnLoc, CSK);
12911 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12912 Candidates);
12914 OverloadCandidateSet::iterator Best;
12915 OverloadingResult OR =
12916 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12918 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12919 // We either found non-function declarations or a best viable function
12920 // at class scope. A class-scope lookup result disables ADL. Don't
12921 // look past this, but let the caller know that we found something that
12922 // either is, or might be, usable in this class.
12923 if (FoundInClass) {
12924 *FoundInClass = RD;
12925 if (OR == OR_Success) {
12926 R.clear();
12927 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12928 R.resolveKind();
12931 return false;
12934 if (OR != OR_Success) {
12935 // There wasn't a unique best function or function template.
12936 return false;
12939 // Find the namespaces where ADL would have looked, and suggest
12940 // declaring the function there instead.
12941 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12942 Sema::AssociatedClassSet AssociatedClasses;
12943 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12944 AssociatedNamespaces,
12945 AssociatedClasses);
12946 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12947 if (canBeDeclaredInNamespace(R.getLookupName())) {
12948 DeclContext *Std = SemaRef.getStdNamespace();
12949 for (Sema::AssociatedNamespaceSet::iterator
12950 it = AssociatedNamespaces.begin(),
12951 end = AssociatedNamespaces.end(); it != end; ++it) {
12952 // Never suggest declaring a function within namespace 'std'.
12953 if (Std && Std->Encloses(*it))
12954 continue;
12956 // Never suggest declaring a function within a namespace with a
12957 // reserved name, like __gnu_cxx.
12958 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12959 if (NS &&
12960 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12961 continue;
12963 SuggestedNamespaces.insert(*it);
12967 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12968 << R.getLookupName();
12969 if (SuggestedNamespaces.empty()) {
12970 SemaRef.Diag(Best->Function->getLocation(),
12971 diag::note_not_found_by_two_phase_lookup)
12972 << R.getLookupName() << 0;
12973 } else if (SuggestedNamespaces.size() == 1) {
12974 SemaRef.Diag(Best->Function->getLocation(),
12975 diag::note_not_found_by_two_phase_lookup)
12976 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12977 } else {
12978 // FIXME: It would be useful to list the associated namespaces here,
12979 // but the diagnostics infrastructure doesn't provide a way to produce
12980 // a localized representation of a list of items.
12981 SemaRef.Diag(Best->Function->getLocation(),
12982 diag::note_not_found_by_two_phase_lookup)
12983 << R.getLookupName() << 2;
12986 // Try to recover by calling this function.
12987 return true;
12990 R.clear();
12993 return false;
12996 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12997 /// template, where the non-dependent operator was declared after the template
12998 /// was defined.
13000 /// Returns true if a viable candidate was found and a diagnostic was issued.
13001 static bool
13002 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13003 SourceLocation OpLoc,
13004 ArrayRef<Expr *> Args) {
13005 DeclarationName OpName =
13006 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13007 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13008 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13009 OverloadCandidateSet::CSK_Operator,
13010 /*ExplicitTemplateArgs=*/nullptr, Args);
13013 namespace {
13014 class BuildRecoveryCallExprRAII {
13015 Sema &SemaRef;
13016 public:
13017 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
13018 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13019 SemaRef.IsBuildingRecoveryCallExpr = true;
13022 ~BuildRecoveryCallExprRAII() {
13023 SemaRef.IsBuildingRecoveryCallExpr = false;
13029 /// Attempts to recover from a call where no functions were found.
13031 /// This function will do one of three things:
13032 /// * Diagnose, recover, and return a recovery expression.
13033 /// * Diagnose, fail to recover, and return ExprError().
13034 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13035 /// expected to diagnose as appropriate.
13036 static ExprResult
13037 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13038 UnresolvedLookupExpr *ULE,
13039 SourceLocation LParenLoc,
13040 MutableArrayRef<Expr *> Args,
13041 SourceLocation RParenLoc,
13042 bool EmptyLookup, bool AllowTypoCorrection) {
13043 // Do not try to recover if it is already building a recovery call.
13044 // This stops infinite loops for template instantiations like
13046 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13047 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13048 if (SemaRef.IsBuildingRecoveryCallExpr)
13049 return ExprResult();
13050 BuildRecoveryCallExprRAII RCE(SemaRef);
13052 CXXScopeSpec SS;
13053 SS.Adopt(ULE->getQualifierLoc());
13054 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13056 TemplateArgumentListInfo TABuffer;
13057 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13058 if (ULE->hasExplicitTemplateArgs()) {
13059 ULE->copyTemplateArgumentsInto(TABuffer);
13060 ExplicitTemplateArgs = &TABuffer;
13063 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13064 Sema::LookupOrdinaryName);
13065 CXXRecordDecl *FoundInClass = nullptr;
13066 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13067 OverloadCandidateSet::CSK_Normal,
13068 ExplicitTemplateArgs, Args, &FoundInClass)) {
13069 // OK, diagnosed a two-phase lookup issue.
13070 } else if (EmptyLookup) {
13071 // Try to recover from an empty lookup with typo correction.
13072 R.clear();
13073 NoTypoCorrectionCCC NoTypoValidator{};
13074 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13075 ExplicitTemplateArgs != nullptr,
13076 dyn_cast<MemberExpr>(Fn));
13077 CorrectionCandidateCallback &Validator =
13078 AllowTypoCorrection
13079 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13080 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13081 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13082 Args))
13083 return ExprError();
13084 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13085 // We found a usable declaration of the name in a dependent base of some
13086 // enclosing class.
13087 // FIXME: We should also explain why the candidates found by name lookup
13088 // were not viable.
13089 if (SemaRef.DiagnoseDependentMemberLookup(R))
13090 return ExprError();
13091 } else {
13092 // We had viable candidates and couldn't recover; let the caller diagnose
13093 // this.
13094 return ExprResult();
13097 // If we get here, we should have issued a diagnostic and formed a recovery
13098 // lookup result.
13099 assert(!R.empty() && "lookup results empty despite recovery");
13101 // If recovery created an ambiguity, just bail out.
13102 if (R.isAmbiguous()) {
13103 R.suppressDiagnostics();
13104 return ExprError();
13107 // Build an implicit member call if appropriate. Just drop the
13108 // casts and such from the call, we don't really care.
13109 ExprResult NewFn = ExprError();
13110 if ((*R.begin())->isCXXClassMember())
13111 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13112 ExplicitTemplateArgs, S);
13113 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13114 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13115 ExplicitTemplateArgs);
13116 else
13117 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13119 if (NewFn.isInvalid())
13120 return ExprError();
13122 // This shouldn't cause an infinite loop because we're giving it
13123 // an expression with viable lookup results, which should never
13124 // end up here.
13125 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13126 MultiExprArg(Args.data(), Args.size()),
13127 RParenLoc);
13130 /// Constructs and populates an OverloadedCandidateSet from
13131 /// the given function.
13132 /// \returns true when an the ExprResult output parameter has been set.
13133 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13134 UnresolvedLookupExpr *ULE,
13135 MultiExprArg Args,
13136 SourceLocation RParenLoc,
13137 OverloadCandidateSet *CandidateSet,
13138 ExprResult *Result) {
13139 #ifndef NDEBUG
13140 if (ULE->requiresADL()) {
13141 // To do ADL, we must have found an unqualified name.
13142 assert(!ULE->getQualifier() && "qualified name with ADL");
13144 // We don't perform ADL for implicit declarations of builtins.
13145 // Verify that this was correctly set up.
13146 FunctionDecl *F;
13147 if (ULE->decls_begin() != ULE->decls_end() &&
13148 ULE->decls_begin() + 1 == ULE->decls_end() &&
13149 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13150 F->getBuiltinID() && F->isImplicit())
13151 llvm_unreachable("performing ADL for builtin");
13153 // We don't perform ADL in C.
13154 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13156 #endif
13158 UnbridgedCastsSet UnbridgedCasts;
13159 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13160 *Result = ExprError();
13161 return true;
13164 // Add the functions denoted by the callee to the set of candidate
13165 // functions, including those from argument-dependent lookup.
13166 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13168 if (getLangOpts().MSVCCompat &&
13169 CurContext->isDependentContext() && !isSFINAEContext() &&
13170 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13172 OverloadCandidateSet::iterator Best;
13173 if (CandidateSet->empty() ||
13174 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13175 OR_No_Viable_Function) {
13176 // In Microsoft mode, if we are inside a template class member function
13177 // then create a type dependent CallExpr. The goal is to postpone name
13178 // lookup to instantiation time to be able to search into type dependent
13179 // base classes.
13180 CallExpr *CE =
13181 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13182 RParenLoc, CurFPFeatureOverrides());
13183 CE->markDependentForPostponedNameLookup();
13184 *Result = CE;
13185 return true;
13189 if (CandidateSet->empty())
13190 return false;
13192 UnbridgedCasts.restore();
13193 return false;
13196 // Guess at what the return type for an unresolvable overload should be.
13197 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13198 OverloadCandidateSet::iterator *Best) {
13199 llvm::Optional<QualType> Result;
13200 // Adjust Type after seeing a candidate.
13201 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13202 if (!Candidate.Function)
13203 return;
13204 if (Candidate.Function->isInvalidDecl())
13205 return;
13206 QualType T = Candidate.Function->getReturnType();
13207 if (T.isNull())
13208 return;
13209 if (!Result)
13210 Result = T;
13211 else if (Result != T)
13212 Result = QualType();
13215 // Look for an unambiguous type from a progressively larger subset.
13216 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13218 // First, consider only the best candidate.
13219 if (Best && *Best != CS.end())
13220 ConsiderCandidate(**Best);
13221 // Next, consider only viable candidates.
13222 if (!Result)
13223 for (const auto &C : CS)
13224 if (C.Viable)
13225 ConsiderCandidate(C);
13226 // Finally, consider all candidates.
13227 if (!Result)
13228 for (const auto &C : CS)
13229 ConsiderCandidate(C);
13231 if (!Result)
13232 return QualType();
13233 auto Value = *Result;
13234 if (Value.isNull() || Value->isUndeducedType())
13235 return QualType();
13236 return Value;
13239 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13240 /// the completed call expression. If overload resolution fails, emits
13241 /// diagnostics and returns ExprError()
13242 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13243 UnresolvedLookupExpr *ULE,
13244 SourceLocation LParenLoc,
13245 MultiExprArg Args,
13246 SourceLocation RParenLoc,
13247 Expr *ExecConfig,
13248 OverloadCandidateSet *CandidateSet,
13249 OverloadCandidateSet::iterator *Best,
13250 OverloadingResult OverloadResult,
13251 bool AllowTypoCorrection) {
13252 switch (OverloadResult) {
13253 case OR_Success: {
13254 FunctionDecl *FDecl = (*Best)->Function;
13255 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13256 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13257 return ExprError();
13258 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13259 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13260 ExecConfig, /*IsExecConfig=*/false,
13261 (*Best)->IsADLCandidate);
13264 case OR_No_Viable_Function: {
13265 // Try to recover by looking for viable functions which the user might
13266 // have meant to call.
13267 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13268 Args, RParenLoc,
13269 CandidateSet->empty(),
13270 AllowTypoCorrection);
13271 if (Recovery.isInvalid() || Recovery.isUsable())
13272 return Recovery;
13274 // If the user passes in a function that we can't take the address of, we
13275 // generally end up emitting really bad error messages. Here, we attempt to
13276 // emit better ones.
13277 for (const Expr *Arg : Args) {
13278 if (!Arg->getType()->isFunctionType())
13279 continue;
13280 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13281 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13282 if (FD &&
13283 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13284 Arg->getExprLoc()))
13285 return ExprError();
13289 CandidateSet->NoteCandidates(
13290 PartialDiagnosticAt(
13291 Fn->getBeginLoc(),
13292 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13293 << ULE->getName() << Fn->getSourceRange()),
13294 SemaRef, OCD_AllCandidates, Args);
13295 break;
13298 case OR_Ambiguous:
13299 CandidateSet->NoteCandidates(
13300 PartialDiagnosticAt(Fn->getBeginLoc(),
13301 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13302 << ULE->getName() << Fn->getSourceRange()),
13303 SemaRef, OCD_AmbiguousCandidates, Args);
13304 break;
13306 case OR_Deleted: {
13307 CandidateSet->NoteCandidates(
13308 PartialDiagnosticAt(Fn->getBeginLoc(),
13309 SemaRef.PDiag(diag::err_ovl_deleted_call)
13310 << ULE->getName() << Fn->getSourceRange()),
13311 SemaRef, OCD_AllCandidates, Args);
13313 // We emitted an error for the unavailable/deleted function call but keep
13314 // the call in the AST.
13315 FunctionDecl *FDecl = (*Best)->Function;
13316 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13317 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13318 ExecConfig, /*IsExecConfig=*/false,
13319 (*Best)->IsADLCandidate);
13323 // Overload resolution failed, try to recover.
13324 SmallVector<Expr *, 8> SubExprs = {Fn};
13325 SubExprs.append(Args.begin(), Args.end());
13326 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13327 chooseRecoveryType(*CandidateSet, Best));
13330 static void markUnaddressableCandidatesUnviable(Sema &S,
13331 OverloadCandidateSet &CS) {
13332 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13333 if (I->Viable &&
13334 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13335 I->Viable = false;
13336 I->FailureKind = ovl_fail_addr_not_available;
13341 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13342 /// (which eventually refers to the declaration Func) and the call
13343 /// arguments Args/NumArgs, attempt to resolve the function call down
13344 /// to a specific function. If overload resolution succeeds, returns
13345 /// the call expression produced by overload resolution.
13346 /// Otherwise, emits diagnostics and returns ExprError.
13347 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13348 UnresolvedLookupExpr *ULE,
13349 SourceLocation LParenLoc,
13350 MultiExprArg Args,
13351 SourceLocation RParenLoc,
13352 Expr *ExecConfig,
13353 bool AllowTypoCorrection,
13354 bool CalleesAddressIsTaken) {
13355 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13356 OverloadCandidateSet::CSK_Normal);
13357 ExprResult result;
13359 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13360 &result))
13361 return result;
13363 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13364 // functions that aren't addressible are considered unviable.
13365 if (CalleesAddressIsTaken)
13366 markUnaddressableCandidatesUnviable(*this, CandidateSet);
13368 OverloadCandidateSet::iterator Best;
13369 OverloadingResult OverloadResult =
13370 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13372 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13373 ExecConfig, &CandidateSet, &Best,
13374 OverloadResult, AllowTypoCorrection);
13377 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13378 return Functions.size() > 1 ||
13379 (Functions.size() == 1 &&
13380 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13383 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13384 NestedNameSpecifierLoc NNSLoc,
13385 DeclarationNameInfo DNI,
13386 const UnresolvedSetImpl &Fns,
13387 bool PerformADL) {
13388 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13389 PerformADL, IsOverloaded(Fns),
13390 Fns.begin(), Fns.end());
13393 /// Create a unary operation that may resolve to an overloaded
13394 /// operator.
13396 /// \param OpLoc The location of the operator itself (e.g., '*').
13398 /// \param Opc The UnaryOperatorKind that describes this operator.
13400 /// \param Fns The set of non-member functions that will be
13401 /// considered by overload resolution. The caller needs to build this
13402 /// set based on the context using, e.g.,
13403 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13404 /// set should not contain any member functions; those will be added
13405 /// by CreateOverloadedUnaryOp().
13407 /// \param Input The input argument.
13408 ExprResult
13409 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13410 const UnresolvedSetImpl &Fns,
13411 Expr *Input, bool PerformADL) {
13412 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13413 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13414 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13415 // TODO: provide better source location info.
13416 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13418 if (checkPlaceholderForOverload(*this, Input))
13419 return ExprError();
13421 Expr *Args[2] = { Input, nullptr };
13422 unsigned NumArgs = 1;
13424 // For post-increment and post-decrement, add the implicit '0' as
13425 // the second argument, so that we know this is a post-increment or
13426 // post-decrement.
13427 if (Opc == UO_PostInc || Opc == UO_PostDec) {
13428 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13429 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13430 SourceLocation());
13431 NumArgs = 2;
13434 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13436 if (Input->isTypeDependent()) {
13437 if (Fns.empty())
13438 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13439 VK_PRValue, OK_Ordinary, OpLoc, false,
13440 CurFPFeatureOverrides());
13442 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13443 ExprResult Fn = CreateUnresolvedLookupExpr(
13444 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13445 if (Fn.isInvalid())
13446 return ExprError();
13447 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13448 Context.DependentTy, VK_PRValue, OpLoc,
13449 CurFPFeatureOverrides());
13452 // Build an empty overload set.
13453 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13455 // Add the candidates from the given function set.
13456 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13458 // Add operator candidates that are member functions.
13459 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13461 // Add candidates from ADL.
13462 if (PerformADL) {
13463 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13464 /*ExplicitTemplateArgs*/nullptr,
13465 CandidateSet);
13468 // Add builtin operator candidates.
13469 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13471 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13473 // Perform overload resolution.
13474 OverloadCandidateSet::iterator Best;
13475 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13476 case OR_Success: {
13477 // We found a built-in operator or an overloaded operator.
13478 FunctionDecl *FnDecl = Best->Function;
13480 if (FnDecl) {
13481 Expr *Base = nullptr;
13482 // We matched an overloaded operator. Build a call to that
13483 // operator.
13485 // Convert the arguments.
13486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13487 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13489 ExprResult InputRes =
13490 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13491 Best->FoundDecl, Method);
13492 if (InputRes.isInvalid())
13493 return ExprError();
13494 Base = Input = InputRes.get();
13495 } else {
13496 // Convert the arguments.
13497 ExprResult InputInit
13498 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13499 Context,
13500 FnDecl->getParamDecl(0)),
13501 SourceLocation(),
13502 Input);
13503 if (InputInit.isInvalid())
13504 return ExprError();
13505 Input = InputInit.get();
13508 // Build the actual expression node.
13509 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13510 Base, HadMultipleCandidates,
13511 OpLoc);
13512 if (FnExpr.isInvalid())
13513 return ExprError();
13515 // Determine the result type.
13516 QualType ResultTy = FnDecl->getReturnType();
13517 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13518 ResultTy = ResultTy.getNonLValueExprType(Context);
13520 Args[0] = Input;
13521 CallExpr *TheCall = CXXOperatorCallExpr::Create(
13522 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13523 CurFPFeatureOverrides(), Best->IsADLCandidate);
13525 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13526 return ExprError();
13528 if (CheckFunctionCall(FnDecl, TheCall,
13529 FnDecl->getType()->castAs<FunctionProtoType>()))
13530 return ExprError();
13531 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13532 } else {
13533 // We matched a built-in operator. Convert the arguments, then
13534 // break out so that we will build the appropriate built-in
13535 // operator node.
13536 ExprResult InputRes = PerformImplicitConversion(
13537 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13538 CCK_ForBuiltinOverloadedOp);
13539 if (InputRes.isInvalid())
13540 return ExprError();
13541 Input = InputRes.get();
13542 break;
13546 case OR_No_Viable_Function:
13547 // This is an erroneous use of an operator which can be overloaded by
13548 // a non-member function. Check for non-member operators which were
13549 // defined too late to be candidates.
13550 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13551 // FIXME: Recover by calling the found function.
13552 return ExprError();
13554 // No viable function; fall through to handling this as a
13555 // built-in operator, which will produce an error message for us.
13556 break;
13558 case OR_Ambiguous:
13559 CandidateSet.NoteCandidates(
13560 PartialDiagnosticAt(OpLoc,
13561 PDiag(diag::err_ovl_ambiguous_oper_unary)
13562 << UnaryOperator::getOpcodeStr(Opc)
13563 << Input->getType() << Input->getSourceRange()),
13564 *this, OCD_AmbiguousCandidates, ArgsArray,
13565 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13566 return ExprError();
13568 case OR_Deleted:
13569 CandidateSet.NoteCandidates(
13570 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13571 << UnaryOperator::getOpcodeStr(Opc)
13572 << Input->getSourceRange()),
13573 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13574 OpLoc);
13575 return ExprError();
13578 // Either we found no viable overloaded operator or we matched a
13579 // built-in operator. In either case, fall through to trying to
13580 // build a built-in operation.
13581 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13584 /// Perform lookup for an overloaded binary operator.
13585 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13586 OverloadedOperatorKind Op,
13587 const UnresolvedSetImpl &Fns,
13588 ArrayRef<Expr *> Args, bool PerformADL) {
13589 SourceLocation OpLoc = CandidateSet.getLocation();
13591 OverloadedOperatorKind ExtraOp =
13592 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13593 ? getRewrittenOverloadedOperator(Op)
13594 : OO_None;
13596 // Add the candidates from the given function set. This also adds the
13597 // rewritten candidates using these functions if necessary.
13598 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13600 // Add operator candidates that are member functions.
13601 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13602 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13603 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13604 OverloadCandidateParamOrder::Reversed);
13606 // In C++20, also add any rewritten member candidates.
13607 if (ExtraOp) {
13608 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13609 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13610 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13611 CandidateSet,
13612 OverloadCandidateParamOrder::Reversed);
13615 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13616 // performed for an assignment operator (nor for operator[] nor operator->,
13617 // which don't get here).
13618 if (Op != OO_Equal && PerformADL) {
13619 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13620 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13621 /*ExplicitTemplateArgs*/ nullptr,
13622 CandidateSet);
13623 if (ExtraOp) {
13624 DeclarationName ExtraOpName =
13625 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13626 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13627 /*ExplicitTemplateArgs*/ nullptr,
13628 CandidateSet);
13632 // Add builtin operator candidates.
13634 // FIXME: We don't add any rewritten candidates here. This is strictly
13635 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13636 // resulting in our selecting a rewritten builtin candidate. For example:
13638 // enum class E { e };
13639 // bool operator!=(E, E) requires false;
13640 // bool k = E::e != E::e;
13642 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13643 // it seems unreasonable to consider rewritten builtin candidates. A core
13644 // issue has been filed proposing to removed this requirement.
13645 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13648 /// Create a binary operation that may resolve to an overloaded
13649 /// operator.
13651 /// \param OpLoc The location of the operator itself (e.g., '+').
13653 /// \param Opc The BinaryOperatorKind that describes this operator.
13655 /// \param Fns The set of non-member functions that will be
13656 /// considered by overload resolution. The caller needs to build this
13657 /// set based on the context using, e.g.,
13658 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13659 /// set should not contain any member functions; those will be added
13660 /// by CreateOverloadedBinOp().
13662 /// \param LHS Left-hand argument.
13663 /// \param RHS Right-hand argument.
13664 /// \param PerformADL Whether to consider operator candidates found by ADL.
13665 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13666 /// C++20 operator rewrites.
13667 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13668 /// the function in question. Such a function is never a candidate in
13669 /// our overload resolution. This also enables synthesizing a three-way
13670 /// comparison from < and == as described in C++20 [class.spaceship]p1.
13671 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13672 BinaryOperatorKind Opc,
13673 const UnresolvedSetImpl &Fns, Expr *LHS,
13674 Expr *RHS, bool PerformADL,
13675 bool AllowRewrittenCandidates,
13676 FunctionDecl *DefaultedFn) {
13677 Expr *Args[2] = { LHS, RHS };
13678 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13680 if (!getLangOpts().CPlusPlus20)
13681 AllowRewrittenCandidates = false;
13683 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13685 // If either side is type-dependent, create an appropriate dependent
13686 // expression.
13687 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13688 if (Fns.empty()) {
13689 // If there are no functions to store, just build a dependent
13690 // BinaryOperator or CompoundAssignment.
13691 if (BinaryOperator::isCompoundAssignmentOp(Opc))
13692 return CompoundAssignOperator::Create(
13693 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13694 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13695 Context.DependentTy);
13696 return BinaryOperator::Create(
13697 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13698 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13701 // FIXME: save results of ADL from here?
13702 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13703 // TODO: provide better source location info in DNLoc component.
13704 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13705 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13706 ExprResult Fn = CreateUnresolvedLookupExpr(
13707 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13708 if (Fn.isInvalid())
13709 return ExprError();
13710 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13711 Context.DependentTy, VK_PRValue, OpLoc,
13712 CurFPFeatureOverrides());
13715 // Always do placeholder-like conversions on the RHS.
13716 if (checkPlaceholderForOverload(*this, Args[1]))
13717 return ExprError();
13719 // Do placeholder-like conversion on the LHS; note that we should
13720 // not get here with a PseudoObject LHS.
13721 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13722 if (checkPlaceholderForOverload(*this, Args[0]))
13723 return ExprError();
13725 // If this is the assignment operator, we only perform overload resolution
13726 // if the left-hand side is a class or enumeration type. This is actually
13727 // a hack. The standard requires that we do overload resolution between the
13728 // various built-in candidates, but as DR507 points out, this can lead to
13729 // problems. So we do it this way, which pretty much follows what GCC does.
13730 // Note that we go the traditional code path for compound assignment forms.
13731 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13732 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13734 // If this is the .* operator, which is not overloadable, just
13735 // create a built-in binary operator.
13736 if (Opc == BO_PtrMemD)
13737 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13739 // Build the overload set.
13740 OverloadCandidateSet CandidateSet(
13741 OpLoc, OverloadCandidateSet::CSK_Operator,
13742 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13743 if (DefaultedFn)
13744 CandidateSet.exclude(DefaultedFn);
13745 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13747 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13749 // Perform overload resolution.
13750 OverloadCandidateSet::iterator Best;
13751 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13752 case OR_Success: {
13753 // We found a built-in operator or an overloaded operator.
13754 FunctionDecl *FnDecl = Best->Function;
13756 bool IsReversed = Best->isReversed();
13757 if (IsReversed)
13758 std::swap(Args[0], Args[1]);
13760 if (FnDecl) {
13761 Expr *Base = nullptr;
13762 // We matched an overloaded operator. Build a call to that
13763 // operator.
13765 OverloadedOperatorKind ChosenOp =
13766 FnDecl->getDeclName().getCXXOverloadedOperator();
13768 // C++2a [over.match.oper]p9:
13769 // If a rewritten operator== candidate is selected by overload
13770 // resolution for an operator@, its return type shall be cv bool
13771 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13772 !FnDecl->getReturnType()->isBooleanType()) {
13773 bool IsExtension =
13774 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13775 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13776 : diag::err_ovl_rewrite_equalequal_not_bool)
13777 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13778 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13779 Diag(FnDecl->getLocation(), diag::note_declared_at);
13780 if (!IsExtension)
13781 return ExprError();
13784 if (AllowRewrittenCandidates && !IsReversed &&
13785 CandidateSet.getRewriteInfo().isReversible()) {
13786 // We could have reversed this operator, but didn't. Check if some
13787 // reversed form was a viable candidate, and if so, if it had a
13788 // better conversion for either parameter. If so, this call is
13789 // formally ambiguous, and allowing it is an extension.
13790 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13791 for (OverloadCandidate &Cand : CandidateSet) {
13792 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13793 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13794 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13795 if (CompareImplicitConversionSequences(
13796 *this, OpLoc, Cand.Conversions[ArgIdx],
13797 Best->Conversions[ArgIdx]) ==
13798 ImplicitConversionSequence::Better) {
13799 AmbiguousWith.push_back(Cand.Function);
13800 break;
13806 if (!AmbiguousWith.empty()) {
13807 bool AmbiguousWithSelf =
13808 AmbiguousWith.size() == 1 &&
13809 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13810 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13811 << BinaryOperator::getOpcodeStr(Opc)
13812 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13813 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13814 if (AmbiguousWithSelf) {
13815 Diag(FnDecl->getLocation(),
13816 diag::note_ovl_ambiguous_oper_binary_reversed_self);
13817 } else {
13818 Diag(FnDecl->getLocation(),
13819 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13820 for (auto *F : AmbiguousWith)
13821 Diag(F->getLocation(),
13822 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13827 // Convert the arguments.
13828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13829 // Best->Access is only meaningful for class members.
13830 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13832 ExprResult Arg1 =
13833 PerformCopyInitialization(
13834 InitializedEntity::InitializeParameter(Context,
13835 FnDecl->getParamDecl(0)),
13836 SourceLocation(), Args[1]);
13837 if (Arg1.isInvalid())
13838 return ExprError();
13840 ExprResult Arg0 =
13841 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13842 Best->FoundDecl, Method);
13843 if (Arg0.isInvalid())
13844 return ExprError();
13845 Base = Args[0] = Arg0.getAs<Expr>();
13846 Args[1] = RHS = Arg1.getAs<Expr>();
13847 } else {
13848 // Convert the arguments.
13849 ExprResult Arg0 = PerformCopyInitialization(
13850 InitializedEntity::InitializeParameter(Context,
13851 FnDecl->getParamDecl(0)),
13852 SourceLocation(), Args[0]);
13853 if (Arg0.isInvalid())
13854 return ExprError();
13856 ExprResult Arg1 =
13857 PerformCopyInitialization(
13858 InitializedEntity::InitializeParameter(Context,
13859 FnDecl->getParamDecl(1)),
13860 SourceLocation(), Args[1]);
13861 if (Arg1.isInvalid())
13862 return ExprError();
13863 Args[0] = LHS = Arg0.getAs<Expr>();
13864 Args[1] = RHS = Arg1.getAs<Expr>();
13867 // Build the actual expression node.
13868 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13869 Best->FoundDecl, Base,
13870 HadMultipleCandidates, OpLoc);
13871 if (FnExpr.isInvalid())
13872 return ExprError();
13874 // Determine the result type.
13875 QualType ResultTy = FnDecl->getReturnType();
13876 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13877 ResultTy = ResultTy.getNonLValueExprType(Context);
13879 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13880 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13881 CurFPFeatureOverrides(), Best->IsADLCandidate);
13883 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13884 FnDecl))
13885 return ExprError();
13887 ArrayRef<const Expr *> ArgsArray(Args, 2);
13888 const Expr *ImplicitThis = nullptr;
13889 // Cut off the implicit 'this'.
13890 if (isa<CXXMethodDecl>(FnDecl)) {
13891 ImplicitThis = ArgsArray[0];
13892 ArgsArray = ArgsArray.slice(1);
13895 // Check for a self move.
13896 if (Op == OO_Equal)
13897 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13899 if (ImplicitThis) {
13900 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13901 QualType ThisTypeFromDecl = Context.getPointerType(
13902 cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13904 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13905 ThisTypeFromDecl);
13908 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13909 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13910 VariadicDoesNotApply);
13912 ExprResult R = MaybeBindToTemporary(TheCall);
13913 if (R.isInvalid())
13914 return ExprError();
13916 R = CheckForImmediateInvocation(R, FnDecl);
13917 if (R.isInvalid())
13918 return ExprError();
13920 // For a rewritten candidate, we've already reversed the arguments
13921 // if needed. Perform the rest of the rewrite now.
13922 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13923 (Op == OO_Spaceship && IsReversed)) {
13924 if (Op == OO_ExclaimEqual) {
13925 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13926 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13927 } else {
13928 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13929 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13930 Expr *ZeroLiteral =
13931 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13933 Sema::CodeSynthesisContext Ctx;
13934 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13935 Ctx.Entity = FnDecl;
13936 pushCodeSynthesisContext(Ctx);
13938 R = CreateOverloadedBinOp(
13939 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13940 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
13941 /*AllowRewrittenCandidates=*/false);
13943 popCodeSynthesisContext();
13945 if (R.isInvalid())
13946 return ExprError();
13947 } else {
13948 assert(ChosenOp == Op && "unexpected operator name");
13951 // Make a note in the AST if we did any rewriting.
13952 if (Best->RewriteKind != CRK_None)
13953 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13955 return R;
13956 } else {
13957 // We matched a built-in operator. Convert the arguments, then
13958 // break out so that we will build the appropriate built-in
13959 // operator node.
13960 ExprResult ArgsRes0 = PerformImplicitConversion(
13961 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13962 AA_Passing, CCK_ForBuiltinOverloadedOp);
13963 if (ArgsRes0.isInvalid())
13964 return ExprError();
13965 Args[0] = ArgsRes0.get();
13967 ExprResult ArgsRes1 = PerformImplicitConversion(
13968 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13969 AA_Passing, CCK_ForBuiltinOverloadedOp);
13970 if (ArgsRes1.isInvalid())
13971 return ExprError();
13972 Args[1] = ArgsRes1.get();
13973 break;
13977 case OR_No_Viable_Function: {
13978 // C++ [over.match.oper]p9:
13979 // If the operator is the operator , [...] and there are no
13980 // viable functions, then the operator is assumed to be the
13981 // built-in operator and interpreted according to clause 5.
13982 if (Opc == BO_Comma)
13983 break;
13985 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13986 // compare result using '==' and '<'.
13987 if (DefaultedFn && Opc == BO_Cmp) {
13988 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13989 Args[1], DefaultedFn);
13990 if (E.isInvalid() || E.isUsable())
13991 return E;
13994 // For class as left operand for assignment or compound assignment
13995 // operator do not fall through to handling in built-in, but report that
13996 // no overloaded assignment operator found
13997 ExprResult Result = ExprError();
13998 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13999 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14000 Args, OpLoc);
14001 DeferDiagsRAII DDR(*this,
14002 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14003 if (Args[0]->getType()->isRecordType() &&
14004 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14005 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14006 << BinaryOperator::getOpcodeStr(Opc)
14007 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14008 if (Args[0]->getType()->isIncompleteType()) {
14009 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14010 << Args[0]->getType()
14011 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14013 } else {
14014 // This is an erroneous use of an operator which can be overloaded by
14015 // a non-member function. Check for non-member operators which were
14016 // defined too late to be candidates.
14017 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14018 // FIXME: Recover by calling the found function.
14019 return ExprError();
14021 // No viable function; try to create a built-in operation, which will
14022 // produce an error. Then, show the non-viable candidates.
14023 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14025 assert(Result.isInvalid() &&
14026 "C++ binary operator overloading is missing candidates!");
14027 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14028 return Result;
14031 case OR_Ambiguous:
14032 CandidateSet.NoteCandidates(
14033 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14034 << BinaryOperator::getOpcodeStr(Opc)
14035 << Args[0]->getType()
14036 << Args[1]->getType()
14037 << Args[0]->getSourceRange()
14038 << Args[1]->getSourceRange()),
14039 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14040 OpLoc);
14041 return ExprError();
14043 case OR_Deleted:
14044 if (isImplicitlyDeleted(Best->Function)) {
14045 FunctionDecl *DeletedFD = Best->Function;
14046 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14047 if (DFK.isSpecialMember()) {
14048 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14049 << Args[0]->getType() << DFK.asSpecialMember();
14050 } else {
14051 assert(DFK.isComparison());
14052 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14053 << Args[0]->getType() << DeletedFD;
14056 // The user probably meant to call this special member. Just
14057 // explain why it's deleted.
14058 NoteDeletedFunction(DeletedFD);
14059 return ExprError();
14061 CandidateSet.NoteCandidates(
14062 PartialDiagnosticAt(
14063 OpLoc, PDiag(diag::err_ovl_deleted_oper)
14064 << getOperatorSpelling(Best->Function->getDeclName()
14065 .getCXXOverloadedOperator())
14066 << Args[0]->getSourceRange()
14067 << Args[1]->getSourceRange()),
14068 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14069 OpLoc);
14070 return ExprError();
14073 // We matched a built-in operator; build it.
14074 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14077 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14078 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14079 FunctionDecl *DefaultedFn) {
14080 const ComparisonCategoryInfo *Info =
14081 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14082 // If we're not producing a known comparison category type, we can't
14083 // synthesize a three-way comparison. Let the caller diagnose this.
14084 if (!Info)
14085 return ExprResult((Expr*)nullptr);
14087 // If we ever want to perform this synthesis more generally, we will need to
14088 // apply the temporary materialization conversion to the operands.
14089 assert(LHS->isGLValue() && RHS->isGLValue() &&
14090 "cannot use prvalue expressions more than once");
14091 Expr *OrigLHS = LHS;
14092 Expr *OrigRHS = RHS;
14094 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14095 // each of them multiple times below.
14096 LHS = new (Context)
14097 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14098 LHS->getObjectKind(), LHS);
14099 RHS = new (Context)
14100 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14101 RHS->getObjectKind(), RHS);
14103 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14104 DefaultedFn);
14105 if (Eq.isInvalid())
14106 return ExprError();
14108 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14109 true, DefaultedFn);
14110 if (Less.isInvalid())
14111 return ExprError();
14113 ExprResult Greater;
14114 if (Info->isPartial()) {
14115 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14116 DefaultedFn);
14117 if (Greater.isInvalid())
14118 return ExprError();
14121 // Form the list of comparisons we're going to perform.
14122 struct Comparison {
14123 ExprResult Cmp;
14124 ComparisonCategoryResult Result;
14125 } Comparisons[4] =
14126 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14127 : ComparisonCategoryResult::Equivalent},
14128 {Less, ComparisonCategoryResult::Less},
14129 {Greater, ComparisonCategoryResult::Greater},
14130 {ExprResult(), ComparisonCategoryResult::Unordered},
14133 int I = Info->isPartial() ? 3 : 2;
14135 // Combine the comparisons with suitable conditional expressions.
14136 ExprResult Result;
14137 for (; I >= 0; --I) {
14138 // Build a reference to the comparison category constant.
14139 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14140 // FIXME: Missing a constant for a comparison category. Diagnose this?
14141 if (!VI)
14142 return ExprResult((Expr*)nullptr);
14143 ExprResult ThisResult =
14144 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14145 if (ThisResult.isInvalid())
14146 return ExprError();
14148 // Build a conditional unless this is the final case.
14149 if (Result.get()) {
14150 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14151 ThisResult.get(), Result.get());
14152 if (Result.isInvalid())
14153 return ExprError();
14154 } else {
14155 Result = ThisResult;
14159 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14160 // bind the OpaqueValueExprs before they're (repeatedly) used.
14161 Expr *SyntacticForm = BinaryOperator::Create(
14162 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14163 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14164 CurFPFeatureOverrides());
14165 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14166 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14169 static bool PrepareArgumentsForCallToObjectOfClassType(
14170 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14171 MultiExprArg Args, SourceLocation LParenLoc) {
14173 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14174 unsigned NumParams = Proto->getNumParams();
14175 unsigned NumArgsSlots =
14176 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14177 // Build the full argument list for the method call (the implicit object
14178 // parameter is placed at the beginning of the list).
14179 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14180 bool IsError = false;
14181 // Initialize the implicit object parameter.
14182 // Check the argument types.
14183 for (unsigned i = 0; i != NumParams; i++) {
14184 Expr *Arg;
14185 if (i < Args.size()) {
14186 Arg = Args[i];
14187 ExprResult InputInit =
14188 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14189 S.Context, Method->getParamDecl(i)),
14190 SourceLocation(), Arg);
14191 IsError |= InputInit.isInvalid();
14192 Arg = InputInit.getAs<Expr>();
14193 } else {
14194 ExprResult DefArg =
14195 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14196 if (DefArg.isInvalid()) {
14197 IsError = true;
14198 break;
14200 Arg = DefArg.getAs<Expr>();
14203 MethodArgs.push_back(Arg);
14205 return IsError;
14208 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14209 SourceLocation RLoc,
14210 Expr *Base,
14211 MultiExprArg ArgExpr) {
14212 SmallVector<Expr *, 2> Args;
14213 Args.push_back(Base);
14214 for (auto *e : ArgExpr) {
14215 Args.push_back(e);
14217 DeclarationName OpName =
14218 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14220 SourceRange Range = ArgExpr.empty()
14221 ? SourceRange{}
14222 : SourceRange(ArgExpr.front()->getBeginLoc(),
14223 ArgExpr.back()->getEndLoc());
14225 // If either side is type-dependent, create an appropriate dependent
14226 // expression.
14227 if (Expr::hasAnyTypeDependentArguments(Args)) {
14229 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14230 // CHECKME: no 'operator' keyword?
14231 DeclarationNameInfo OpNameInfo(OpName, LLoc);
14232 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14233 ExprResult Fn = CreateUnresolvedLookupExpr(
14234 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14235 if (Fn.isInvalid())
14236 return ExprError();
14237 // Can't add any actual overloads yet
14239 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14240 Context.DependentTy, VK_PRValue, RLoc,
14241 CurFPFeatureOverrides());
14244 // Handle placeholders
14245 UnbridgedCastsSet UnbridgedCasts;
14246 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14247 return ExprError();
14249 // Build an empty overload set.
14250 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14252 // Subscript can only be overloaded as a member function.
14254 // Add operator candidates that are member functions.
14255 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14257 // Add builtin operator candidates.
14258 if (Args.size() == 2)
14259 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14261 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14263 // Perform overload resolution.
14264 OverloadCandidateSet::iterator Best;
14265 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14266 case OR_Success: {
14267 // We found a built-in operator or an overloaded operator.
14268 FunctionDecl *FnDecl = Best->Function;
14270 if (FnDecl) {
14271 // We matched an overloaded operator. Build a call to that
14272 // operator.
14274 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14276 // Convert the arguments.
14277 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14278 SmallVector<Expr *, 2> MethodArgs;
14279 ExprResult Arg0 = PerformObjectArgumentInitialization(
14280 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14281 if (Arg0.isInvalid())
14282 return ExprError();
14284 MethodArgs.push_back(Arg0.get());
14285 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14286 *this, MethodArgs, Method, ArgExpr, LLoc);
14287 if (IsError)
14288 return ExprError();
14290 // Build the actual expression node.
14291 DeclarationNameInfo OpLocInfo(OpName, LLoc);
14292 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14293 ExprResult FnExpr = CreateFunctionRefExpr(
14294 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14295 OpLocInfo.getLoc(), OpLocInfo.getInfo());
14296 if (FnExpr.isInvalid())
14297 return ExprError();
14299 // Determine the result type
14300 QualType ResultTy = FnDecl->getReturnType();
14301 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14302 ResultTy = ResultTy.getNonLValueExprType(Context);
14304 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14305 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14306 CurFPFeatureOverrides());
14307 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14308 return ExprError();
14310 if (CheckFunctionCall(Method, TheCall,
14311 Method->getType()->castAs<FunctionProtoType>()))
14312 return ExprError();
14314 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14315 FnDecl);
14316 } else {
14317 // We matched a built-in operator. Convert the arguments, then
14318 // break out so that we will build the appropriate built-in
14319 // operator node.
14320 ExprResult ArgsRes0 = PerformImplicitConversion(
14321 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14322 AA_Passing, CCK_ForBuiltinOverloadedOp);
14323 if (ArgsRes0.isInvalid())
14324 return ExprError();
14325 Args[0] = ArgsRes0.get();
14327 ExprResult ArgsRes1 = PerformImplicitConversion(
14328 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14329 AA_Passing, CCK_ForBuiltinOverloadedOp);
14330 if (ArgsRes1.isInvalid())
14331 return ExprError();
14332 Args[1] = ArgsRes1.get();
14334 break;
14338 case OR_No_Viable_Function: {
14339 PartialDiagnostic PD =
14340 CandidateSet.empty()
14341 ? (PDiag(diag::err_ovl_no_oper)
14342 << Args[0]->getType() << /*subscript*/ 0
14343 << Args[0]->getSourceRange() << Range)
14344 : (PDiag(diag::err_ovl_no_viable_subscript)
14345 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14346 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14347 OCD_AllCandidates, ArgExpr, "[]", LLoc);
14348 return ExprError();
14351 case OR_Ambiguous:
14352 if (Args.size() == 2) {
14353 CandidateSet.NoteCandidates(
14354 PartialDiagnosticAt(
14355 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14356 << "[]" << Args[0]->getType() << Args[1]->getType()
14357 << Args[0]->getSourceRange() << Range),
14358 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14359 } else {
14360 CandidateSet.NoteCandidates(
14361 PartialDiagnosticAt(LLoc,
14362 PDiag(diag::err_ovl_ambiguous_subscript_call)
14363 << Args[0]->getType()
14364 << Args[0]->getSourceRange() << Range),
14365 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14367 return ExprError();
14369 case OR_Deleted:
14370 CandidateSet.NoteCandidates(
14371 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14372 << "[]" << Args[0]->getSourceRange()
14373 << Range),
14374 *this, OCD_AllCandidates, Args, "[]", LLoc);
14375 return ExprError();
14378 // We matched a built-in operator; build it.
14379 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14382 /// BuildCallToMemberFunction - Build a call to a member
14383 /// function. MemExpr is the expression that refers to the member
14384 /// function (and includes the object parameter), Args/NumArgs are the
14385 /// arguments to the function call (not including the object
14386 /// parameter). The caller needs to validate that the member
14387 /// expression refers to a non-static member function or an overloaded
14388 /// member function.
14389 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14390 SourceLocation LParenLoc,
14391 MultiExprArg Args,
14392 SourceLocation RParenLoc,
14393 Expr *ExecConfig, bool IsExecConfig,
14394 bool AllowRecovery) {
14395 assert(MemExprE->getType() == Context.BoundMemberTy ||
14396 MemExprE->getType() == Context.OverloadTy);
14398 // Dig out the member expression. This holds both the object
14399 // argument and the member function we're referring to.
14400 Expr *NakedMemExpr = MemExprE->IgnoreParens();
14402 // Determine whether this is a call to a pointer-to-member function.
14403 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14404 assert(op->getType() == Context.BoundMemberTy);
14405 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14407 QualType fnType =
14408 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14410 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14411 QualType resultType = proto->getCallResultType(Context);
14412 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14414 // Check that the object type isn't more qualified than the
14415 // member function we're calling.
14416 Qualifiers funcQuals = proto->getMethodQuals();
14418 QualType objectType = op->getLHS()->getType();
14419 if (op->getOpcode() == BO_PtrMemI)
14420 objectType = objectType->castAs<PointerType>()->getPointeeType();
14421 Qualifiers objectQuals = objectType.getQualifiers();
14423 Qualifiers difference = objectQuals - funcQuals;
14424 difference.removeObjCGCAttr();
14425 difference.removeAddressSpace();
14426 if (difference) {
14427 std::string qualsString = difference.getAsString();
14428 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14429 << fnType.getUnqualifiedType()
14430 << qualsString
14431 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14434 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14435 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14436 CurFPFeatureOverrides(), proto->getNumParams());
14438 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14439 call, nullptr))
14440 return ExprError();
14442 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14443 return ExprError();
14445 if (CheckOtherCall(call, proto))
14446 return ExprError();
14448 return MaybeBindToTemporary(call);
14451 // We only try to build a recovery expr at this level if we can preserve
14452 // the return type, otherwise we return ExprError() and let the caller
14453 // recover.
14454 auto BuildRecoveryExpr = [&](QualType Type) {
14455 if (!AllowRecovery)
14456 return ExprError();
14457 std::vector<Expr *> SubExprs = {MemExprE};
14458 llvm::append_range(SubExprs, Args);
14459 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14460 Type);
14462 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14463 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14464 RParenLoc, CurFPFeatureOverrides());
14466 UnbridgedCastsSet UnbridgedCasts;
14467 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14468 return ExprError();
14470 MemberExpr *MemExpr;
14471 CXXMethodDecl *Method = nullptr;
14472 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14473 NestedNameSpecifier *Qualifier = nullptr;
14474 if (isa<MemberExpr>(NakedMemExpr)) {
14475 MemExpr = cast<MemberExpr>(NakedMemExpr);
14476 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14477 FoundDecl = MemExpr->getFoundDecl();
14478 Qualifier = MemExpr->getQualifier();
14479 UnbridgedCasts.restore();
14480 } else {
14481 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14482 Qualifier = UnresExpr->getQualifier();
14484 QualType ObjectType = UnresExpr->getBaseType();
14485 Expr::Classification ObjectClassification
14486 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14487 : UnresExpr->getBase()->Classify(Context);
14489 // Add overload candidates
14490 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14491 OverloadCandidateSet::CSK_Normal);
14493 // FIXME: avoid copy.
14494 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14495 if (UnresExpr->hasExplicitTemplateArgs()) {
14496 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14497 TemplateArgs = &TemplateArgsBuffer;
14500 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14501 E = UnresExpr->decls_end(); I != E; ++I) {
14503 NamedDecl *Func = *I;
14504 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14505 if (isa<UsingShadowDecl>(Func))
14506 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14509 // Microsoft supports direct constructor calls.
14510 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14511 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14512 CandidateSet,
14513 /*SuppressUserConversions*/ false);
14514 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14515 // If explicit template arguments were provided, we can't call a
14516 // non-template member function.
14517 if (TemplateArgs)
14518 continue;
14520 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14521 ObjectClassification, Args, CandidateSet,
14522 /*SuppressUserConversions=*/false);
14523 } else {
14524 AddMethodTemplateCandidate(
14525 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14526 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14527 /*SuppressUserConversions=*/false);
14531 DeclarationName DeclName = UnresExpr->getMemberName();
14533 UnbridgedCasts.restore();
14535 OverloadCandidateSet::iterator Best;
14536 bool Succeeded = false;
14537 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14538 Best)) {
14539 case OR_Success:
14540 Method = cast<CXXMethodDecl>(Best->Function);
14541 FoundDecl = Best->FoundDecl;
14542 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14543 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14544 break;
14545 // If FoundDecl is different from Method (such as if one is a template
14546 // and the other a specialization), make sure DiagnoseUseOfDecl is
14547 // called on both.
14548 // FIXME: This would be more comprehensively addressed by modifying
14549 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14550 // being used.
14551 if (Method != FoundDecl.getDecl() &&
14552 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14553 break;
14554 Succeeded = true;
14555 break;
14557 case OR_No_Viable_Function:
14558 CandidateSet.NoteCandidates(
14559 PartialDiagnosticAt(
14560 UnresExpr->getMemberLoc(),
14561 PDiag(diag::err_ovl_no_viable_member_function_in_call)
14562 << DeclName << MemExprE->getSourceRange()),
14563 *this, OCD_AllCandidates, Args);
14564 break;
14565 case OR_Ambiguous:
14566 CandidateSet.NoteCandidates(
14567 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14568 PDiag(diag::err_ovl_ambiguous_member_call)
14569 << DeclName << MemExprE->getSourceRange()),
14570 *this, OCD_AmbiguousCandidates, Args);
14571 break;
14572 case OR_Deleted:
14573 CandidateSet.NoteCandidates(
14574 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14575 PDiag(diag::err_ovl_deleted_member_call)
14576 << DeclName << MemExprE->getSourceRange()),
14577 *this, OCD_AllCandidates, Args);
14578 break;
14580 // Overload resolution fails, try to recover.
14581 if (!Succeeded)
14582 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14584 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14586 // If overload resolution picked a static member, build a
14587 // non-member call based on that function.
14588 if (Method->isStatic()) {
14589 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14590 ExecConfig, IsExecConfig);
14593 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14596 QualType ResultType = Method->getReturnType();
14597 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14598 ResultType = ResultType.getNonLValueExprType(Context);
14600 assert(Method && "Member call to something that isn't a method?");
14601 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14602 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14603 Context, MemExprE, Args, ResultType, VK, RParenLoc,
14604 CurFPFeatureOverrides(), Proto->getNumParams());
14606 // Check for a valid return type.
14607 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14608 TheCall, Method))
14609 return BuildRecoveryExpr(ResultType);
14611 // Convert the object argument (for a non-static member function call).
14612 // We only need to do this if there was actually an overload; otherwise
14613 // it was done at lookup.
14614 if (!Method->isStatic()) {
14615 ExprResult ObjectArg =
14616 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14617 FoundDecl, Method);
14618 if (ObjectArg.isInvalid())
14619 return ExprError();
14620 MemExpr->setBase(ObjectArg.get());
14623 // Convert the rest of the arguments
14624 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14625 RParenLoc))
14626 return BuildRecoveryExpr(ResultType);
14628 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14630 if (CheckFunctionCall(Method, TheCall, Proto))
14631 return ExprError();
14633 // In the case the method to call was not selected by the overloading
14634 // resolution process, we still need to handle the enable_if attribute. Do
14635 // that here, so it will not hide previous -- and more relevant -- errors.
14636 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14637 if (const EnableIfAttr *Attr =
14638 CheckEnableIf(Method, LParenLoc, Args, true)) {
14639 Diag(MemE->getMemberLoc(),
14640 diag::err_ovl_no_viable_member_function_in_call)
14641 << Method << Method->getSourceRange();
14642 Diag(Method->getLocation(),
14643 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14644 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14645 return ExprError();
14649 if ((isa<CXXConstructorDecl>(CurContext) ||
14650 isa<CXXDestructorDecl>(CurContext)) &&
14651 TheCall->getMethodDecl()->isPure()) {
14652 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14654 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14655 MemExpr->performsVirtualDispatch(getLangOpts())) {
14656 Diag(MemExpr->getBeginLoc(),
14657 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14658 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14659 << MD->getParent();
14661 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14662 if (getLangOpts().AppleKext)
14663 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14664 << MD->getParent() << MD->getDeclName();
14668 if (CXXDestructorDecl *DD =
14669 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14670 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14671 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14672 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14673 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14674 MemExpr->getMemberLoc());
14677 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14678 TheCall->getMethodDecl());
14681 /// BuildCallToObjectOfClassType - Build a call to an object of class
14682 /// type (C++ [over.call.object]), which can end up invoking an
14683 /// overloaded function call operator (@c operator()) or performing a
14684 /// user-defined conversion on the object argument.
14685 ExprResult
14686 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14687 SourceLocation LParenLoc,
14688 MultiExprArg Args,
14689 SourceLocation RParenLoc) {
14690 if (checkPlaceholderForOverload(*this, Obj))
14691 return ExprError();
14692 ExprResult Object = Obj;
14694 UnbridgedCastsSet UnbridgedCasts;
14695 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14696 return ExprError();
14698 assert(Object.get()->getType()->isRecordType() &&
14699 "Requires object type argument");
14701 // C++ [over.call.object]p1:
14702 // If the primary-expression E in the function call syntax
14703 // evaluates to a class object of type "cv T", then the set of
14704 // candidate functions includes at least the function call
14705 // operators of T. The function call operators of T are obtained by
14706 // ordinary lookup of the name operator() in the context of
14707 // (E).operator().
14708 OverloadCandidateSet CandidateSet(LParenLoc,
14709 OverloadCandidateSet::CSK_Operator);
14710 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14712 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14713 diag::err_incomplete_object_call, Object.get()))
14714 return true;
14716 const auto *Record = Object.get()->getType()->castAs<RecordType>();
14717 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14718 LookupQualifiedName(R, Record->getDecl());
14719 R.suppressDiagnostics();
14721 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14722 Oper != OperEnd; ++Oper) {
14723 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14724 Object.get()->Classify(Context), Args, CandidateSet,
14725 /*SuppressUserConversion=*/false);
14728 // C++ [over.call.object]p2:
14729 // In addition, for each (non-explicit in C++0x) conversion function
14730 // declared in T of the form
14732 // operator conversion-type-id () cv-qualifier;
14734 // where cv-qualifier is the same cv-qualification as, or a
14735 // greater cv-qualification than, cv, and where conversion-type-id
14736 // denotes the type "pointer to function of (P1,...,Pn) returning
14737 // R", or the type "reference to pointer to function of
14738 // (P1,...,Pn) returning R", or the type "reference to function
14739 // of (P1,...,Pn) returning R", a surrogate call function [...]
14740 // is also considered as a candidate function. Similarly,
14741 // surrogate call functions are added to the set of candidate
14742 // functions for each conversion function declared in an
14743 // accessible base class provided the function is not hidden
14744 // within T by another intervening declaration.
14745 const auto &Conversions =
14746 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14747 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14748 NamedDecl *D = *I;
14749 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14750 if (isa<UsingShadowDecl>(D))
14751 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14753 // Skip over templated conversion functions; they aren't
14754 // surrogates.
14755 if (isa<FunctionTemplateDecl>(D))
14756 continue;
14758 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14759 if (!Conv->isExplicit()) {
14760 // Strip the reference type (if any) and then the pointer type (if
14761 // any) to get down to what might be a function type.
14762 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14763 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14764 ConvType = ConvPtrType->getPointeeType();
14766 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14768 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14769 Object.get(), Args, CandidateSet);
14774 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14776 // Perform overload resolution.
14777 OverloadCandidateSet::iterator Best;
14778 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14779 Best)) {
14780 case OR_Success:
14781 // Overload resolution succeeded; we'll build the appropriate call
14782 // below.
14783 break;
14785 case OR_No_Viable_Function: {
14786 PartialDiagnostic PD =
14787 CandidateSet.empty()
14788 ? (PDiag(diag::err_ovl_no_oper)
14789 << Object.get()->getType() << /*call*/ 1
14790 << Object.get()->getSourceRange())
14791 : (PDiag(diag::err_ovl_no_viable_object_call)
14792 << Object.get()->getType() << Object.get()->getSourceRange());
14793 CandidateSet.NoteCandidates(
14794 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14795 OCD_AllCandidates, Args);
14796 break;
14798 case OR_Ambiguous:
14799 CandidateSet.NoteCandidates(
14800 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14801 PDiag(diag::err_ovl_ambiguous_object_call)
14802 << Object.get()->getType()
14803 << Object.get()->getSourceRange()),
14804 *this, OCD_AmbiguousCandidates, Args);
14805 break;
14807 case OR_Deleted:
14808 CandidateSet.NoteCandidates(
14809 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14810 PDiag(diag::err_ovl_deleted_object_call)
14811 << Object.get()->getType()
14812 << Object.get()->getSourceRange()),
14813 *this, OCD_AllCandidates, Args);
14814 break;
14817 if (Best == CandidateSet.end())
14818 return true;
14820 UnbridgedCasts.restore();
14822 if (Best->Function == nullptr) {
14823 // Since there is no function declaration, this is one of the
14824 // surrogate candidates. Dig out the conversion function.
14825 CXXConversionDecl *Conv
14826 = cast<CXXConversionDecl>(
14827 Best->Conversions[0].UserDefined.ConversionFunction);
14829 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14830 Best->FoundDecl);
14831 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14832 return ExprError();
14833 assert(Conv == Best->FoundDecl.getDecl() &&
14834 "Found Decl & conversion-to-functionptr should be same, right?!");
14835 // We selected one of the surrogate functions that converts the
14836 // object parameter to a function pointer. Perform the conversion
14837 // on the object argument, then let BuildCallExpr finish the job.
14839 // Create an implicit member expr to refer to the conversion operator.
14840 // and then call it.
14841 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14842 Conv, HadMultipleCandidates);
14843 if (Call.isInvalid())
14844 return ExprError();
14845 // Record usage of conversion in an implicit cast.
14846 Call = ImplicitCastExpr::Create(
14847 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14848 nullptr, VK_PRValue, CurFPFeatureOverrides());
14850 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14853 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14855 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14856 // that calls this method, using Object for the implicit object
14857 // parameter and passing along the remaining arguments.
14858 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14860 // An error diagnostic has already been printed when parsing the declaration.
14861 if (Method->isInvalidDecl())
14862 return ExprError();
14864 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14865 unsigned NumParams = Proto->getNumParams();
14867 DeclarationNameInfo OpLocInfo(
14868 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14869 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14870 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14871 Obj, HadMultipleCandidates,
14872 OpLocInfo.getLoc(),
14873 OpLocInfo.getInfo());
14874 if (NewFn.isInvalid())
14875 return true;
14877 SmallVector<Expr *, 8> MethodArgs;
14878 MethodArgs.reserve(NumParams + 1);
14880 bool IsError = false;
14882 // Initialize the implicit object parameter.
14883 ExprResult ObjRes =
14884 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14885 Best->FoundDecl, Method);
14886 if (ObjRes.isInvalid())
14887 IsError = true;
14888 else
14889 Object = ObjRes;
14890 MethodArgs.push_back(Object.get());
14892 IsError |= PrepareArgumentsForCallToObjectOfClassType(
14893 *this, MethodArgs, Method, Args, LParenLoc);
14895 // If this is a variadic call, handle args passed through "...".
14896 if (Proto->isVariadic()) {
14897 // Promote the arguments (C99 6.5.2.2p7).
14898 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14899 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14900 nullptr);
14901 IsError |= Arg.isInvalid();
14902 MethodArgs.push_back(Arg.get());
14906 if (IsError)
14907 return true;
14909 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14911 // Once we've built TheCall, all of the expressions are properly owned.
14912 QualType ResultTy = Method->getReturnType();
14913 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14914 ResultTy = ResultTy.getNonLValueExprType(Context);
14916 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14917 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14918 CurFPFeatureOverrides());
14920 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14921 return true;
14923 if (CheckFunctionCall(Method, TheCall, Proto))
14924 return true;
14926 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14929 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14930 /// (if one exists), where @c Base is an expression of class type and
14931 /// @c Member is the name of the member we're trying to find.
14932 ExprResult
14933 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14934 bool *NoArrowOperatorFound) {
14935 assert(Base->getType()->isRecordType() &&
14936 "left-hand side must have class type");
14938 if (checkPlaceholderForOverload(*this, Base))
14939 return ExprError();
14941 SourceLocation Loc = Base->getExprLoc();
14943 // C++ [over.ref]p1:
14945 // [...] An expression x->m is interpreted as (x.operator->())->m
14946 // for a class object x of type T if T::operator->() exists and if
14947 // the operator is selected as the best match function by the
14948 // overload resolution mechanism (13.3).
14949 DeclarationName OpName =
14950 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14951 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14953 if (RequireCompleteType(Loc, Base->getType(),
14954 diag::err_typecheck_incomplete_tag, Base))
14955 return ExprError();
14957 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14958 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14959 R.suppressDiagnostics();
14961 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14962 Oper != OperEnd; ++Oper) {
14963 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14964 None, CandidateSet, /*SuppressUserConversion=*/false);
14967 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14969 // Perform overload resolution.
14970 OverloadCandidateSet::iterator Best;
14971 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14972 case OR_Success:
14973 // Overload resolution succeeded; we'll build the call below.
14974 break;
14976 case OR_No_Viable_Function: {
14977 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14978 if (CandidateSet.empty()) {
14979 QualType BaseType = Base->getType();
14980 if (NoArrowOperatorFound) {
14981 // Report this specific error to the caller instead of emitting a
14982 // diagnostic, as requested.
14983 *NoArrowOperatorFound = true;
14984 return ExprError();
14986 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14987 << BaseType << Base->getSourceRange();
14988 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14989 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14990 << FixItHint::CreateReplacement(OpLoc, ".");
14992 } else
14993 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14994 << "operator->" << Base->getSourceRange();
14995 CandidateSet.NoteCandidates(*this, Base, Cands);
14996 return ExprError();
14998 case OR_Ambiguous:
14999 CandidateSet.NoteCandidates(
15000 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15001 << "->" << Base->getType()
15002 << Base->getSourceRange()),
15003 *this, OCD_AmbiguousCandidates, Base);
15004 return ExprError();
15006 case OR_Deleted:
15007 CandidateSet.NoteCandidates(
15008 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15009 << "->" << Base->getSourceRange()),
15010 *this, OCD_AllCandidates, Base);
15011 return ExprError();
15014 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15016 // Convert the object parameter.
15017 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15018 ExprResult BaseResult =
15019 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15020 Best->FoundDecl, Method);
15021 if (BaseResult.isInvalid())
15022 return ExprError();
15023 Base = BaseResult.get();
15025 // Build the operator call.
15026 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15027 Base, HadMultipleCandidates, OpLoc);
15028 if (FnExpr.isInvalid())
15029 return ExprError();
15031 QualType ResultTy = Method->getReturnType();
15032 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15033 ResultTy = ResultTy.getNonLValueExprType(Context);
15034 CXXOperatorCallExpr *TheCall =
15035 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15036 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15038 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15039 return ExprError();
15041 if (CheckFunctionCall(Method, TheCall,
15042 Method->getType()->castAs<FunctionProtoType>()))
15043 return ExprError();
15045 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15048 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15049 /// a literal operator described by the provided lookup results.
15050 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15051 DeclarationNameInfo &SuffixInfo,
15052 ArrayRef<Expr*> Args,
15053 SourceLocation LitEndLoc,
15054 TemplateArgumentListInfo *TemplateArgs) {
15055 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15057 OverloadCandidateSet CandidateSet(UDSuffixLoc,
15058 OverloadCandidateSet::CSK_Normal);
15059 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15060 TemplateArgs);
15062 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15064 // Perform overload resolution. This will usually be trivial, but might need
15065 // to perform substitutions for a literal operator template.
15066 OverloadCandidateSet::iterator Best;
15067 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15068 case OR_Success:
15069 case OR_Deleted:
15070 break;
15072 case OR_No_Viable_Function:
15073 CandidateSet.NoteCandidates(
15074 PartialDiagnosticAt(UDSuffixLoc,
15075 PDiag(diag::err_ovl_no_viable_function_in_call)
15076 << R.getLookupName()),
15077 *this, OCD_AllCandidates, Args);
15078 return ExprError();
15080 case OR_Ambiguous:
15081 CandidateSet.NoteCandidates(
15082 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15083 << R.getLookupName()),
15084 *this, OCD_AmbiguousCandidates, Args);
15085 return ExprError();
15088 FunctionDecl *FD = Best->Function;
15089 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15090 nullptr, HadMultipleCandidates,
15091 SuffixInfo.getLoc(),
15092 SuffixInfo.getInfo());
15093 if (Fn.isInvalid())
15094 return true;
15096 // Check the argument types. This should almost always be a no-op, except
15097 // that array-to-pointer decay is applied to string literals.
15098 Expr *ConvArgs[2];
15099 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15100 ExprResult InputInit = PerformCopyInitialization(
15101 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15102 SourceLocation(), Args[ArgIdx]);
15103 if (InputInit.isInvalid())
15104 return true;
15105 ConvArgs[ArgIdx] = InputInit.get();
15108 QualType ResultTy = FD->getReturnType();
15109 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15110 ResultTy = ResultTy.getNonLValueExprType(Context);
15112 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15113 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15114 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15116 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15117 return ExprError();
15119 if (CheckFunctionCall(FD, UDL, nullptr))
15120 return ExprError();
15122 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15125 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15126 /// given LookupResult is non-empty, it is assumed to describe a member which
15127 /// will be invoked. Otherwise, the function will be found via argument
15128 /// dependent lookup.
15129 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15130 /// otherwise CallExpr is set to ExprError() and some non-success value
15131 /// is returned.
15132 Sema::ForRangeStatus
15133 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15134 SourceLocation RangeLoc,
15135 const DeclarationNameInfo &NameInfo,
15136 LookupResult &MemberLookup,
15137 OverloadCandidateSet *CandidateSet,
15138 Expr *Range, ExprResult *CallExpr) {
15139 Scope *S = nullptr;
15141 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15142 if (!MemberLookup.empty()) {
15143 ExprResult MemberRef =
15144 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15145 /*IsPtr=*/false, CXXScopeSpec(),
15146 /*TemplateKWLoc=*/SourceLocation(),
15147 /*FirstQualifierInScope=*/nullptr,
15148 MemberLookup,
15149 /*TemplateArgs=*/nullptr, S);
15150 if (MemberRef.isInvalid()) {
15151 *CallExpr = ExprError();
15152 return FRS_DiagnosticIssued;
15154 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15155 if (CallExpr->isInvalid()) {
15156 *CallExpr = ExprError();
15157 return FRS_DiagnosticIssued;
15159 } else {
15160 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15161 NestedNameSpecifierLoc(),
15162 NameInfo, UnresolvedSet<0>());
15163 if (FnR.isInvalid())
15164 return FRS_DiagnosticIssued;
15165 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15167 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15168 CandidateSet, CallExpr);
15169 if (CandidateSet->empty() || CandidateSetError) {
15170 *CallExpr = ExprError();
15171 return FRS_NoViableFunction;
15173 OverloadCandidateSet::iterator Best;
15174 OverloadingResult OverloadResult =
15175 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15177 if (OverloadResult == OR_No_Viable_Function) {
15178 *CallExpr = ExprError();
15179 return FRS_NoViableFunction;
15181 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15182 Loc, nullptr, CandidateSet, &Best,
15183 OverloadResult,
15184 /*AllowTypoCorrection=*/false);
15185 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15186 *CallExpr = ExprError();
15187 return FRS_DiagnosticIssued;
15190 return FRS_Success;
15194 /// FixOverloadedFunctionReference - E is an expression that refers to
15195 /// a C++ overloaded function (possibly with some parentheses and
15196 /// perhaps a '&' around it). We have resolved the overloaded function
15197 /// to the function declaration Fn, so patch up the expression E to
15198 /// refer (possibly indirectly) to Fn. Returns the new expr.
15199 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15200 FunctionDecl *Fn) {
15201 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15202 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15203 Found, Fn);
15204 if (SubExpr == PE->getSubExpr())
15205 return PE;
15207 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15210 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15211 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15212 Found, Fn);
15213 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15214 SubExpr->getType()) &&
15215 "Implicit cast type cannot be determined from overload");
15216 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15217 if (SubExpr == ICE->getSubExpr())
15218 return ICE;
15220 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15221 SubExpr, nullptr, ICE->getValueKind(),
15222 CurFPFeatureOverrides());
15225 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15226 if (!GSE->isResultDependent()) {
15227 Expr *SubExpr =
15228 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15229 if (SubExpr == GSE->getResultExpr())
15230 return GSE;
15232 // Replace the resulting type information before rebuilding the generic
15233 // selection expression.
15234 ArrayRef<Expr *> A = GSE->getAssocExprs();
15235 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15236 unsigned ResultIdx = GSE->getResultIndex();
15237 AssocExprs[ResultIdx] = SubExpr;
15239 return GenericSelectionExpr::Create(
15240 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15241 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15242 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15243 ResultIdx);
15245 // Rather than fall through to the unreachable, return the original generic
15246 // selection expression.
15247 return GSE;
15250 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15251 assert(UnOp->getOpcode() == UO_AddrOf &&
15252 "Can only take the address of an overloaded function");
15253 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15254 if (Method->isStatic()) {
15255 // Do nothing: static member functions aren't any different
15256 // from non-member functions.
15257 } else {
15258 // Fix the subexpression, which really has to be an
15259 // UnresolvedLookupExpr holding an overloaded member function
15260 // or template.
15261 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15262 Found, Fn);
15263 if (SubExpr == UnOp->getSubExpr())
15264 return UnOp;
15266 assert(isa<DeclRefExpr>(SubExpr)
15267 && "fixed to something other than a decl ref");
15268 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15269 && "fixed to a member ref with no nested name qualifier");
15271 // We have taken the address of a pointer to member
15272 // function. Perform the computation here so that we get the
15273 // appropriate pointer to member type.
15274 QualType ClassType
15275 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15276 QualType MemPtrType
15277 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15278 // Under the MS ABI, lock down the inheritance model now.
15279 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15280 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15282 return UnaryOperator::Create(
15283 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15284 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15287 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15288 Found, Fn);
15289 if (SubExpr == UnOp->getSubExpr())
15290 return UnOp;
15292 // FIXME: This can't currently fail, but in principle it could.
15293 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15294 .get();
15297 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15298 // FIXME: avoid copy.
15299 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15300 if (ULE->hasExplicitTemplateArgs()) {
15301 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15302 TemplateArgs = &TemplateArgsBuffer;
15305 QualType Type = Fn->getType();
15306 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15308 // FIXME: Duplicated from BuildDeclarationNameExpr.
15309 if (unsigned BID = Fn->getBuiltinID()) {
15310 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15311 Type = Context.BuiltinFnTy;
15312 ValueKind = VK_PRValue;
15316 DeclRefExpr *DRE = BuildDeclRefExpr(
15317 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15318 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15319 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15320 return DRE;
15323 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15324 // FIXME: avoid copy.
15325 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15326 if (MemExpr->hasExplicitTemplateArgs()) {
15327 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15328 TemplateArgs = &TemplateArgsBuffer;
15331 Expr *Base;
15333 // If we're filling in a static method where we used to have an
15334 // implicit member access, rewrite to a simple decl ref.
15335 if (MemExpr->isImplicitAccess()) {
15336 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15337 DeclRefExpr *DRE = BuildDeclRefExpr(
15338 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15339 MemExpr->getQualifierLoc(), Found.getDecl(),
15340 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15341 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15342 return DRE;
15343 } else {
15344 SourceLocation Loc = MemExpr->getMemberLoc();
15345 if (MemExpr->getQualifier())
15346 Loc = MemExpr->getQualifierLoc().getBeginLoc();
15347 Base =
15348 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15350 } else
15351 Base = MemExpr->getBase();
15353 ExprValueKind valueKind;
15354 QualType type;
15355 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15356 valueKind = VK_LValue;
15357 type = Fn->getType();
15358 } else {
15359 valueKind = VK_PRValue;
15360 type = Context.BoundMemberTy;
15363 return BuildMemberExpr(
15364 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15365 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15366 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15367 type, valueKind, OK_Ordinary, TemplateArgs);
15370 llvm_unreachable("Invalid reference to overloaded function");
15373 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15374 DeclAccessPair Found,
15375 FunctionDecl *Fn) {
15376 return FixOverloadedFunctionReference(E.get(), Found, Fn);
15379 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15380 FunctionDecl *Function) {
15381 if (!PartialOverloading || !Function)
15382 return true;
15383 if (Function->isVariadic())
15384 return false;
15385 if (const auto *Proto =
15386 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15387 if (Proto->isTemplateVariadic())
15388 return false;
15389 if (auto *Pattern = Function->getTemplateInstantiationPattern())
15390 if (const auto *Proto =
15391 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15392 if (Proto->isTemplateVariadic())
15393 return false;
15394 return true;