1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/ASTLambda.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DependenceFlags.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/DiagnosticOptions.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/Template.h"
37#include "clang/Sema/TemplateDeduction.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/SmallVector.h"
44#include "llvm/Support/Casting.h"
45#include <algorithm>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
53using AllowedExplicit = Sema::AllowedExplicit;
54
55static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
56 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
62static ExprResult CreateFunctionRefExpr(
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
81 S.MarkDeclRefReferenced(E: DRE, Base);
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT: FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(DRE->getType()),
89 CK: CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
94 StandardConversionSequence &SCS,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
98static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
99 QualType &ToType,
100 bool InOverloadResolution,
101 StandardConversionSequence &SCS,
102 bool CStyle);
103static OverloadingResult
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 UserDefinedConversionSequence& User,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
110static ImplicitConversionSequence::CompareKind
111CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
115static ImplicitConversionSequence::CompareKind
116CompareQualificationConversions(Sema &S,
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
120static ImplicitConversionSequence::CompareKind
121CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
127ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
128 static const ImplicitConversionRank Rank[] = {
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
133 ICR_Exact_Match,
134 ICR_Exact_Match,
135 ICR_Promotion,
136 ICR_Promotion,
137 ICR_Promotion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_OCL_Scalar_Widening,
151 ICR_Complex_Real_Conversion,
152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Writeback_Conversion,
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
161 ICR_C_Conversion,
162 ICR_C_Conversion_Extension,
163 ICR_Conversion,
164 ICR_Conversion,
165 ICR_Conversion,
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
173static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
174 static const char *const Name[] = {
175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
179 "Function pointer conversion",
180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
183 "Complex promotion",
184 "Integral conversion",
185 "Floating conversion",
186 "Complex conversion",
187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
190 "Boolean conversion",
191 "Compatible-types conversion",
192 "Derived-to-base conversion",
193 "Vector conversion",
194 "SVE Vector conversion",
195 "RVV Vector conversion",
196 "Vector splat",
197 "Complex-real conversion",
198 "Block Pointer conversion",
199 "Transparent Union Conversion",
200 "Writeback conversion",
201 "OpenCL Zero Event Conversion",
202 "OpenCL Zero Queue Conversion",
203 "C specific type conversion",
204 "Incompatible pointer conversion",
205 "Fixed point conversion",
206 "HLSL vector truncation",
207 "Non-decaying array conversion",
208 };
209 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
210 return Name[Kind];
211}
212
213/// StandardConversionSequence - Set the standard conversion
214/// sequence to the identity conversion.
215void StandardConversionSequence::setAsIdentityConversion() {
216 First = ICK_Identity;
217 Second = ICK_Identity;
218 Element = ICK_Identity;
219 Third = ICK_Identity;
220 DeprecatedStringLiteralToCharPtr = false;
221 QualificationIncludesObjCLifetime = false;
222 ReferenceBinding = false;
223 DirectBinding = false;
224 IsLvalueReference = true;
225 BindsToFunctionLvalue = false;
226 BindsToRvalue = false;
227 BindsImplicitObjectArgumentWithoutRefQualifier = false;
228 ObjCLifetimeConversionBinding = false;
229 CopyConstructor = nullptr;
230}
231
232/// getRank - Retrieve the rank of this standard conversion sequence
233/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
234/// implicit conversions.
235ImplicitConversionRank StandardConversionSequence::getRank() const {
236 ImplicitConversionRank Rank = ICR_Exact_Match;
237 if (GetConversionRank(Kind: First) > Rank)
238 Rank = GetConversionRank(Kind: First);
239 if (GetConversionRank(Kind: Second) > Rank)
240 Rank = GetConversionRank(Kind: Second);
241 if (GetConversionRank(Kind: Element) > Rank)
242 Rank = GetConversionRank(Kind: Element);
243 if (GetConversionRank(Kind: Third) > Rank)
244 Rank = GetConversionRank(Kind: Third);
245 return Rank;
246}
247
248/// isPointerConversionToBool - Determines whether this conversion is
249/// a conversion of a pointer or pointer-to-member to bool. This is
250/// used as part of the ranking of standard conversion sequences
251/// (C++ 13.3.3.2p4).
252bool StandardConversionSequence::isPointerConversionToBool() const {
253 // Note that FromType has not necessarily been transformed by the
254 // array-to-pointer or function-to-pointer implicit conversions, so
255 // check for their presence as well as checking whether FromType is
256 // a pointer.
257 if (getToType(Idx: 1)->isBooleanType() &&
258 (getFromType()->isPointerType() ||
259 getFromType()->isMemberPointerType() ||
260 getFromType()->isObjCObjectPointerType() ||
261 getFromType()->isBlockPointerType() ||
262 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
263 return true;
264
265 return false;
266}
267
268/// isPointerConversionToVoidPointer - Determines whether this
269/// conversion is a conversion of a pointer to a void pointer. This is
270/// used as part of the ranking of standard conversion sequences (C++
271/// 13.3.3.2p4).
272bool
273StandardConversionSequence::
274isPointerConversionToVoidPointer(ASTContext& Context) const {
275 QualType FromType = getFromType();
276 QualType ToType = getToType(Idx: 1);
277
278 // Note that FromType has not necessarily been transformed by the
279 // array-to-pointer implicit conversion, so check for its presence
280 // and redo the conversion to get a pointer.
281 if (First == ICK_Array_To_Pointer)
282 FromType = Context.getArrayDecayedType(T: FromType);
283
284 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
285 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
286 return ToPtrType->getPointeeType()->isVoidType();
287
288 return false;
289}
290
291/// Skip any implicit casts which could be either part of a narrowing conversion
292/// or after one in an implicit conversion.
293static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
294 const Expr *Converted) {
295 // We can have cleanups wrapping the converted expression; these need to be
296 // preserved so that destructors run if necessary.
297 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
298 Expr *Inner =
299 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
300 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
301 objects: EWC->getObjects());
302 }
303
304 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
305 switch (ICE->getCastKind()) {
306 case CK_NoOp:
307 case CK_IntegralCast:
308 case CK_IntegralToBoolean:
309 case CK_IntegralToFloating:
310 case CK_BooleanToSignedIntegral:
311 case CK_FloatingToIntegral:
312 case CK_FloatingToBoolean:
313 case CK_FloatingCast:
314 Converted = ICE->getSubExpr();
315 continue;
316
317 default:
318 return Converted;
319 }
320 }
321
322 return Converted;
323}
324
325/// Check if this standard conversion sequence represents a narrowing
326/// conversion, according to C++11 [dcl.init.list]p7.
327///
328/// \param Ctx The AST context.
329/// \param Converted The result of applying this standard conversion sequence.
330/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
331/// value of the expression prior to the narrowing conversion.
332/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
333/// type of the expression prior to the narrowing conversion.
334/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
335/// from floating point types to integral types should be ignored.
336NarrowingKind StandardConversionSequence::getNarrowingKind(
337 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
338 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
339 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
340 "narrowing check outside C++");
341
342 // C++11 [dcl.init.list]p7:
343 // A narrowing conversion is an implicit conversion ...
344 QualType FromType = getToType(Idx: 0);
345 QualType ToType = getToType(Idx: 1);
346
347 // A conversion to an enumeration type is narrowing if the conversion to
348 // the underlying type is narrowing. This only arises for expressions of
349 // the form 'Enum{init}'.
350 if (auto *ET = ToType->getAs<EnumType>())
351 ToType = ET->getDecl()->getIntegerType();
352
353 switch (Second) {
354 // 'bool' is an integral type; dispatch to the right place to handle it.
355 case ICK_Boolean_Conversion:
356 if (FromType->isRealFloatingType())
357 goto FloatingIntegralConversion;
358 if (FromType->isIntegralOrUnscopedEnumerationType())
359 goto IntegralConversion;
360 // -- from a pointer type or pointer-to-member type to bool, or
361 return NK_Type_Narrowing;
362
363 // -- from a floating-point type to an integer type, or
364 //
365 // -- from an integer type or unscoped enumeration type to a floating-point
366 // type, except where the source is a constant expression and the actual
367 // value after conversion will fit into the target type and will produce
368 // the original value when converted back to the original type, or
369 case ICK_Floating_Integral:
370 FloatingIntegralConversion:
371 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
372 return NK_Type_Narrowing;
373 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
374 ToType->isRealFloatingType()) {
375 if (IgnoreFloatToIntegralConversion)
376 return NK_Not_Narrowing;
377 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
378 assert(Initializer && "Unknown conversion expression");
379
380 // If it's value-dependent, we can't tell whether it's narrowing.
381 if (Initializer->isValueDependent())
382 return NK_Dependent_Narrowing;
383
384 if (std::optional<llvm::APSInt> IntConstantValue =
385 Initializer->getIntegerConstantExpr(Ctx)) {
386 // Convert the integer to the floating type.
387 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
388 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
389 RM: llvm::APFloat::rmNearestTiesToEven);
390 // And back.
391 llvm::APSInt ConvertedValue = *IntConstantValue;
392 bool ignored;
393 Result.convertToInteger(Result&: ConvertedValue,
394 RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
395 // If the resulting value is different, this was a narrowing conversion.
396 if (*IntConstantValue != ConvertedValue) {
397 ConstantValue = APValue(*IntConstantValue);
398 ConstantType = Initializer->getType();
399 return NK_Constant_Narrowing;
400 }
401 } else {
402 // Variables are always narrowings.
403 return NK_Variable_Narrowing;
404 }
405 }
406 return NK_Not_Narrowing;
407
408 // -- from long double to double or float, or from double to float, except
409 // where the source is a constant expression and the actual value after
410 // conversion is within the range of values that can be represented (even
411 // if it cannot be represented exactly), or
412 case ICK_Floating_Conversion:
413 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
414 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
415 // FromType is larger than ToType.
416 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
422 Expr::EvalResult R;
423 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
424 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)) {
425 // Constant!
426 if (Ctx.getLangOpts().C23)
427 ConstantValue = R.Val;
428 assert(ConstantValue.isFloat());
429 llvm::APFloat FloatVal = ConstantValue.getFloat();
430 // Convert the source value into the target type.
431 bool ignored;
432 llvm::APFloat Converted = FloatVal;
433 llvm::APFloat::opStatus ConvertStatus =
434 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
435 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
436 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
437 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
438 if (Ctx.getLangOpts().C23) {
439 if (FloatVal.isNaN() && Converted.isNaN() &&
440 !FloatVal.isSignaling() && !Converted.isSignaling()) {
441 // Quiet NaNs are considered the same value, regardless of
442 // payloads.
443 return NK_Not_Narrowing;
444 }
445 // For normal values, check exact equality.
446 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
447 ConstantType = Initializer->getType();
448 return NK_Constant_Narrowing;
449 }
450 } else {
451 // If there was no overflow, the source value is within the range of
452 // values that can be represented.
453 if (ConvertStatus & llvm::APFloat::opOverflow) {
454 ConstantType = Initializer->getType();
455 return NK_Constant_Narrowing;
456 }
457 }
458 } else {
459 return NK_Variable_Narrowing;
460 }
461 }
462 return NK_Not_Narrowing;
463
464 // -- from an integer type or unscoped enumeration type to an integer type
465 // that cannot represent all the values of the original type, except where
466 // the source is a constant expression and the actual value after
467 // conversion will fit into the target type and will produce the original
468 // value when converted back to the original type.
469 case ICK_Integral_Conversion:
470 IntegralConversion: {
471 assert(FromType->isIntegralOrUnscopedEnumerationType());
472 assert(ToType->isIntegralOrUnscopedEnumerationType());
473 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
474 const unsigned FromWidth = Ctx.getIntWidth(T: FromType);
475 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
476 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
477
478 if (FromWidth > ToWidth ||
479 (FromWidth == ToWidth && FromSigned != ToSigned) ||
480 (FromSigned && !ToSigned)) {
481 // Not all values of FromType can be represented in ToType.
482 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
483
484 // If it's value-dependent, we can't tell whether it's narrowing.
485 if (Initializer->isValueDependent())
486 return NK_Dependent_Narrowing;
487
488 std::optional<llvm::APSInt> OptInitializerValue;
489 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
490 // Such conversions on variables are always narrowing.
491 return NK_Variable_Narrowing;
492 }
493 llvm::APSInt &InitializerValue = *OptInitializerValue;
494 bool Narrowing = false;
495 if (FromWidth < ToWidth) {
496 // Negative -> unsigned is narrowing. Otherwise, more bits is never
497 // narrowing.
498 if (InitializerValue.isSigned() && InitializerValue.isNegative())
499 Narrowing = true;
500 } else {
501 // Add a bit to the InitializerValue so we don't have to worry about
502 // signed vs. unsigned comparisons.
503 InitializerValue = InitializerValue.extend(
504 width: InitializerValue.getBitWidth() + 1);
505 // Convert the initializer to and from the target width and signed-ness.
506 llvm::APSInt ConvertedValue = InitializerValue;
507 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
508 ConvertedValue.setIsSigned(ToSigned);
509 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
510 ConvertedValue.setIsSigned(InitializerValue.isSigned());
511 // If the result is different, this was a narrowing conversion.
512 if (ConvertedValue != InitializerValue)
513 Narrowing = true;
514 }
515 if (Narrowing) {
516 ConstantType = Initializer->getType();
517 ConstantValue = APValue(InitializerValue);
518 return NK_Constant_Narrowing;
519 }
520 }
521 return NK_Not_Narrowing;
522 }
523 case ICK_Complex_Real:
524 if (FromType->isComplexType() && !ToType->isComplexType())
525 return NK_Type_Narrowing;
526 return NK_Not_Narrowing;
527
528 case ICK_Floating_Promotion:
529 if (Ctx.getLangOpts().C23) {
530 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
531 Expr::EvalResult R;
532 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
533 ConstantValue = R.Val;
534 assert(ConstantValue.isFloat());
535 llvm::APFloat FloatVal = ConstantValue.getFloat();
536 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
537 // value, the unqualified versions of the type of the initializer and
538 // the corresponding real type of the object declared shall be
539 // compatible.
540 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
541 ConstantType = Initializer->getType();
542 return NK_Constant_Narrowing;
543 }
544 }
545 }
546 return NK_Not_Narrowing;
547 default:
548 // Other kinds of conversions are not narrowings.
549 return NK_Not_Narrowing;
550 }
551}
552
553/// dump - Print this standard conversion sequence to standard
554/// error. Useful for debugging overloading issues.
555LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
556 raw_ostream &OS = llvm::errs();
557 bool PrintedSomething = false;
558 if (First != ICK_Identity) {
559 OS << GetImplicitConversionName(Kind: First);
560 PrintedSomething = true;
561 }
562
563 if (Second != ICK_Identity) {
564 if (PrintedSomething) {
565 OS << " -> ";
566 }
567 OS << GetImplicitConversionName(Kind: Second);
568
569 if (CopyConstructor) {
570 OS << " (by copy constructor)";
571 } else if (DirectBinding) {
572 OS << " (direct reference binding)";
573 } else if (ReferenceBinding) {
574 OS << " (reference binding)";
575 }
576 PrintedSomething = true;
577 }
578
579 if (Third != ICK_Identity) {
580 if (PrintedSomething) {
581 OS << " -> ";
582 }
583 OS << GetImplicitConversionName(Kind: Third);
584 PrintedSomething = true;
585 }
586
587 if (!PrintedSomething) {
588 OS << "No conversions required";
589 }
590}
591
592/// dump - Print this user-defined conversion sequence to standard
593/// error. Useful for debugging overloading issues.
594void UserDefinedConversionSequence::dump() const {
595 raw_ostream &OS = llvm::errs();
596 if (Before.First || Before.Second || Before.Third) {
597 Before.dump();
598 OS << " -> ";
599 }
600 if (ConversionFunction)
601 OS << '\'' << *ConversionFunction << '\'';
602 else
603 OS << "aggregate initialization";
604 if (After.First || After.Second || After.Third) {
605 OS << " -> ";
606 After.dump();
607 }
608}
609
610/// dump - Print this implicit conversion sequence to standard
611/// error. Useful for debugging overloading issues.
612void ImplicitConversionSequence::dump() const {
613 raw_ostream &OS = llvm::errs();
614 if (hasInitializerListContainerType())
615 OS << "Worst list element conversion: ";
616 switch (ConversionKind) {
617 case StandardConversion:
618 OS << "Standard conversion: ";
619 Standard.dump();
620 break;
621 case UserDefinedConversion:
622 OS << "User-defined conversion: ";
623 UserDefined.dump();
624 break;
625 case EllipsisConversion:
626 OS << "Ellipsis conversion";
627 break;
628 case AmbiguousConversion:
629 OS << "Ambiguous conversion";
630 break;
631 case BadConversion:
632 OS << "Bad conversion";
633 break;
634 }
635
636 OS << "\n";
637}
638
639void AmbiguousConversionSequence::construct() {
640 new (&conversions()) ConversionSet();
641}
642
643void AmbiguousConversionSequence::destruct() {
644 conversions().~ConversionSet();
645}
646
647void
648AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
649 FromTypePtr = O.FromTypePtr;
650 ToTypePtr = O.ToTypePtr;
651 new (&conversions()) ConversionSet(O.conversions());
652}
653
654namespace {
655 // Structure used by DeductionFailureInfo to store
656 // template argument information.
657 struct DFIArguments {
658 TemplateArgument FirstArg;
659 TemplateArgument SecondArg;
660 };
661 // Structure used by DeductionFailureInfo to store
662 // template parameter and template argument information.
663 struct DFIParamWithArguments : DFIArguments {
664 TemplateParameter Param;
665 };
666 // Structure used by DeductionFailureInfo to store template argument
667 // information and the index of the problematic call argument.
668 struct DFIDeducedMismatchArgs : DFIArguments {
669 TemplateArgumentList *TemplateArgs;
670 unsigned CallArgIndex;
671 };
672 // Structure used by DeductionFailureInfo to store information about
673 // unsatisfied constraints.
674 struct CNSInfo {
675 TemplateArgumentList *TemplateArgs;
676 ConstraintSatisfaction Satisfaction;
677 };
678}
679
680/// Convert from Sema's representation of template deduction information
681/// to the form used in overload-candidate information.
682DeductionFailureInfo
683clang::MakeDeductionFailureInfo(ASTContext &Context,
684 TemplateDeductionResult TDK,
685 TemplateDeductionInfo &Info) {
686 DeductionFailureInfo Result;
687 Result.Result = static_cast<unsigned>(TDK);
688 Result.HasDiagnostic = false;
689 switch (TDK) {
690 case TemplateDeductionResult::Invalid:
691 case TemplateDeductionResult::InstantiationDepth:
692 case TemplateDeductionResult::TooManyArguments:
693 case TemplateDeductionResult::TooFewArguments:
694 case TemplateDeductionResult::MiscellaneousDeductionFailure:
695 case TemplateDeductionResult::CUDATargetMismatch:
696 Result.Data = nullptr;
697 break;
698
699 case TemplateDeductionResult::Incomplete:
700 case TemplateDeductionResult::InvalidExplicitArguments:
701 Result.Data = Info.Param.getOpaqueValue();
702 break;
703
704 case TemplateDeductionResult::DeducedMismatch:
705 case TemplateDeductionResult::DeducedMismatchNested: {
706 // FIXME: Should allocate from normal heap so that we can free this later.
707 auto *Saved = new (Context) DFIDeducedMismatchArgs;
708 Saved->FirstArg = Info.FirstArg;
709 Saved->SecondArg = Info.SecondArg;
710 Saved->TemplateArgs = Info.takeSugared();
711 Saved->CallArgIndex = Info.CallArgIndex;
712 Result.Data = Saved;
713 break;
714 }
715
716 case TemplateDeductionResult::NonDeducedMismatch: {
717 // FIXME: Should allocate from normal heap so that we can free this later.
718 DFIArguments *Saved = new (Context) DFIArguments;
719 Saved->FirstArg = Info.FirstArg;
720 Saved->SecondArg = Info.SecondArg;
721 Result.Data = Saved;
722 break;
723 }
724
725 case TemplateDeductionResult::IncompletePack:
726 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
727 case TemplateDeductionResult::Inconsistent:
728 case TemplateDeductionResult::Underqualified: {
729 // FIXME: Should allocate from normal heap so that we can free this later.
730 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
731 Saved->Param = Info.Param;
732 Saved->FirstArg = Info.FirstArg;
733 Saved->SecondArg = Info.SecondArg;
734 Result.Data = Saved;
735 break;
736 }
737
738 case TemplateDeductionResult::SubstitutionFailure:
739 Result.Data = Info.takeSugared();
740 if (Info.hasSFINAEDiagnostic()) {
741 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
742 SourceLocation(), PartialDiagnostic::NullDiagnostic());
743 Info.takeSFINAEDiagnostic(PD&: *Diag);
744 Result.HasDiagnostic = true;
745 }
746 break;
747
748 case TemplateDeductionResult::ConstraintsNotSatisfied: {
749 CNSInfo *Saved = new (Context) CNSInfo;
750 Saved->TemplateArgs = Info.takeSugared();
751 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
752 Result.Data = Saved;
753 break;
754 }
755
756 case TemplateDeductionResult::Success:
757 case TemplateDeductionResult::NonDependentConversionFailure:
758 case TemplateDeductionResult::AlreadyDiagnosed:
759 llvm_unreachable("not a deduction failure");
760 }
761
762 return Result;
763}
764
765void DeductionFailureInfo::Destroy() {
766 switch (static_cast<TemplateDeductionResult>(Result)) {
767 case TemplateDeductionResult::Success:
768 case TemplateDeductionResult::Invalid:
769 case TemplateDeductionResult::InstantiationDepth:
770 case TemplateDeductionResult::Incomplete:
771 case TemplateDeductionResult::TooManyArguments:
772 case TemplateDeductionResult::TooFewArguments:
773 case TemplateDeductionResult::InvalidExplicitArguments:
774 case TemplateDeductionResult::CUDATargetMismatch:
775 case TemplateDeductionResult::NonDependentConversionFailure:
776 break;
777
778 case TemplateDeductionResult::IncompletePack:
779 case TemplateDeductionResult::Inconsistent:
780 case TemplateDeductionResult::Underqualified:
781 case TemplateDeductionResult::DeducedMismatch:
782 case TemplateDeductionResult::DeducedMismatchNested:
783 case TemplateDeductionResult::NonDeducedMismatch:
784 // FIXME: Destroy the data?
785 Data = nullptr;
786 break;
787
788 case TemplateDeductionResult::SubstitutionFailure:
789 // FIXME: Destroy the template argument list?
790 Data = nullptr;
791 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
792 Diag->~PartialDiagnosticAt();
793 HasDiagnostic = false;
794 }
795 break;
796
797 case TemplateDeductionResult::ConstraintsNotSatisfied:
798 // FIXME: Destroy the template argument list?
799 Data = nullptr;
800 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
801 Diag->~PartialDiagnosticAt();
802 HasDiagnostic = false;
803 }
804 break;
805
806 // Unhandled
807 case TemplateDeductionResult::MiscellaneousDeductionFailure:
808 case TemplateDeductionResult::AlreadyDiagnosed:
809 break;
810 }
811}
812
813PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
814 if (HasDiagnostic)
815 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
816 return nullptr;
817}
818
819TemplateParameter DeductionFailureInfo::getTemplateParameter() {
820 switch (static_cast<TemplateDeductionResult>(Result)) {
821 case TemplateDeductionResult::Success:
822 case TemplateDeductionResult::Invalid:
823 case TemplateDeductionResult::InstantiationDepth:
824 case TemplateDeductionResult::TooManyArguments:
825 case TemplateDeductionResult::TooFewArguments:
826 case TemplateDeductionResult::SubstitutionFailure:
827 case TemplateDeductionResult::DeducedMismatch:
828 case TemplateDeductionResult::DeducedMismatchNested:
829 case TemplateDeductionResult::NonDeducedMismatch:
830 case TemplateDeductionResult::CUDATargetMismatch:
831 case TemplateDeductionResult::NonDependentConversionFailure:
832 case TemplateDeductionResult::ConstraintsNotSatisfied:
833 return TemplateParameter();
834
835 case TemplateDeductionResult::Incomplete:
836 case TemplateDeductionResult::InvalidExplicitArguments:
837 return TemplateParameter::getFromOpaqueValue(VP: Data);
838
839 case TemplateDeductionResult::IncompletePack:
840 case TemplateDeductionResult::Inconsistent:
841 case TemplateDeductionResult::Underqualified:
842 return static_cast<DFIParamWithArguments*>(Data)->Param;
843
844 // Unhandled
845 case TemplateDeductionResult::MiscellaneousDeductionFailure:
846 case TemplateDeductionResult::AlreadyDiagnosed:
847 break;
848 }
849
850 return TemplateParameter();
851}
852
853TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
854 switch (static_cast<TemplateDeductionResult>(Result)) {
855 case TemplateDeductionResult::Success:
856 case TemplateDeductionResult::Invalid:
857 case TemplateDeductionResult::InstantiationDepth:
858 case TemplateDeductionResult::TooManyArguments:
859 case TemplateDeductionResult::TooFewArguments:
860 case TemplateDeductionResult::Incomplete:
861 case TemplateDeductionResult::IncompletePack:
862 case TemplateDeductionResult::InvalidExplicitArguments:
863 case TemplateDeductionResult::Inconsistent:
864 case TemplateDeductionResult::Underqualified:
865 case TemplateDeductionResult::NonDeducedMismatch:
866 case TemplateDeductionResult::CUDATargetMismatch:
867 case TemplateDeductionResult::NonDependentConversionFailure:
868 return nullptr;
869
870 case TemplateDeductionResult::DeducedMismatch:
871 case TemplateDeductionResult::DeducedMismatchNested:
872 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
873
874 case TemplateDeductionResult::SubstitutionFailure:
875 return static_cast<TemplateArgumentList*>(Data);
876
877 case TemplateDeductionResult::ConstraintsNotSatisfied:
878 return static_cast<CNSInfo*>(Data)->TemplateArgs;
879
880 // Unhandled
881 case TemplateDeductionResult::MiscellaneousDeductionFailure:
882 case TemplateDeductionResult::AlreadyDiagnosed:
883 break;
884 }
885
886 return nullptr;
887}
888
889const TemplateArgument *DeductionFailureInfo::getFirstArg() {
890 switch (static_cast<TemplateDeductionResult>(Result)) {
891 case TemplateDeductionResult::Success:
892 case TemplateDeductionResult::Invalid:
893 case TemplateDeductionResult::InstantiationDepth:
894 case TemplateDeductionResult::Incomplete:
895 case TemplateDeductionResult::TooManyArguments:
896 case TemplateDeductionResult::TooFewArguments:
897 case TemplateDeductionResult::InvalidExplicitArguments:
898 case TemplateDeductionResult::SubstitutionFailure:
899 case TemplateDeductionResult::CUDATargetMismatch:
900 case TemplateDeductionResult::NonDependentConversionFailure:
901 case TemplateDeductionResult::ConstraintsNotSatisfied:
902 return nullptr;
903
904 case TemplateDeductionResult::IncompletePack:
905 case TemplateDeductionResult::Inconsistent:
906 case TemplateDeductionResult::Underqualified:
907 case TemplateDeductionResult::DeducedMismatch:
908 case TemplateDeductionResult::DeducedMismatchNested:
909 case TemplateDeductionResult::NonDeducedMismatch:
910 return &static_cast<DFIArguments*>(Data)->FirstArg;
911
912 // Unhandled
913 case TemplateDeductionResult::MiscellaneousDeductionFailure:
914 case TemplateDeductionResult::AlreadyDiagnosed:
915 break;
916 }
917
918 return nullptr;
919}
920
921const TemplateArgument *DeductionFailureInfo::getSecondArg() {
922 switch (static_cast<TemplateDeductionResult>(Result)) {
923 case TemplateDeductionResult::Success:
924 case TemplateDeductionResult::Invalid:
925 case TemplateDeductionResult::InstantiationDepth:
926 case TemplateDeductionResult::Incomplete:
927 case TemplateDeductionResult::IncompletePack:
928 case TemplateDeductionResult::TooManyArguments:
929 case TemplateDeductionResult::TooFewArguments:
930 case TemplateDeductionResult::InvalidExplicitArguments:
931 case TemplateDeductionResult::SubstitutionFailure:
932 case TemplateDeductionResult::CUDATargetMismatch:
933 case TemplateDeductionResult::NonDependentConversionFailure:
934 case TemplateDeductionResult::ConstraintsNotSatisfied:
935 return nullptr;
936
937 case TemplateDeductionResult::Inconsistent:
938 case TemplateDeductionResult::Underqualified:
939 case TemplateDeductionResult::DeducedMismatch:
940 case TemplateDeductionResult::DeducedMismatchNested:
941 case TemplateDeductionResult::NonDeducedMismatch:
942 return &static_cast<DFIArguments*>(Data)->SecondArg;
943
944 // Unhandled
945 case TemplateDeductionResult::MiscellaneousDeductionFailure:
946 case TemplateDeductionResult::AlreadyDiagnosed:
947 break;
948 }
949
950 return nullptr;
951}
952
953std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
954 switch (static_cast<TemplateDeductionResult>(Result)) {
955 case TemplateDeductionResult::DeducedMismatch:
956 case TemplateDeductionResult::DeducedMismatchNested:
957 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
958
959 default:
960 return std::nullopt;
961 }
962}
963
964static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
965 const FunctionDecl *Y) {
966 if (!X || !Y)
967 return false;
968 if (X->getNumParams() != Y->getNumParams())
969 return false;
970 // FIXME: when do rewritten comparison operators
971 // with explicit object parameters correspond?
972 // https://cplusplus.github.io/CWG/issues/2797.html
973 for (unsigned I = 0; I < X->getNumParams(); ++I)
974 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
975 T2: Y->getParamDecl(i: I)->getType()))
976 return false;
977 if (auto *FTX = X->getDescribedFunctionTemplate()) {
978 auto *FTY = Y->getDescribedFunctionTemplate();
979 if (!FTY)
980 return false;
981 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
982 Y: FTY->getTemplateParameters()))
983 return false;
984 }
985 return true;
986}
987
988static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
989 Expr *FirstOperand, FunctionDecl *EqFD) {
990 assert(EqFD->getOverloadedOperator() ==
991 OverloadedOperatorKind::OO_EqualEqual);
992 // C++2a [over.match.oper]p4:
993 // A non-template function or function template F named operator== is a
994 // rewrite target with first operand o unless a search for the name operator!=
995 // in the scope S from the instantiation context of the operator expression
996 // finds a function or function template that would correspond
997 // ([basic.scope.scope]) to F if its name were operator==, where S is the
998 // scope of the class type of o if F is a class member, and the namespace
999 // scope of which F is a member otherwise. A function template specialization
1000 // named operator== is a rewrite target if its function template is a rewrite
1001 // target.
1002 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1003 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1004 if (isa<CXXMethodDecl>(Val: EqFD)) {
1005 // If F is a class member, search scope is class type of first operand.
1006 QualType RHS = FirstOperand->getType();
1007 auto *RHSRec = RHS->getAs<RecordType>();
1008 if (!RHSRec)
1009 return true;
1010 LookupResult Members(S, NotEqOp, OpLoc,
1011 Sema::LookupNameKind::LookupMemberName);
1012 S.LookupQualifiedName(Members, RHSRec->getDecl());
1013 Members.suppressAccessDiagnostics();
1014 for (NamedDecl *Op : Members)
1015 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1016 return false;
1017 return true;
1018 }
1019 // Otherwise the search scope is the namespace scope of which F is a member.
1020 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1021 auto *NotEqFD = Op->getAsFunction();
1022 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1023 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1024 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1025 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
1026 cast<Decl>(Op->getLexicalDeclContext())))
1027 return false;
1028 }
1029 return true;
1030}
1031
1032bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1033 OverloadedOperatorKind Op) {
1034 if (!AllowRewrittenCandidates)
1035 return false;
1036 return Op == OO_EqualEqual || Op == OO_Spaceship;
1037}
1038
1039bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1040 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1041 auto Op = FD->getOverloadedOperator();
1042 if (!allowsReversed(Op))
1043 return false;
1044 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1045 assert(OriginalArgs.size() == 2);
1046 if (!shouldAddReversedEqEq(
1047 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1048 return false;
1049 }
1050 // Don't bother adding a reversed candidate that can never be a better
1051 // match than the non-reversed version.
1052 return FD->getNumNonObjectParams() != 2 ||
1053 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1054 T2: FD->getParamDecl(i: 1)->getType()) ||
1055 FD->hasAttr<EnableIfAttr>();
1056}
1057
1058void OverloadCandidateSet::destroyCandidates() {
1059 for (iterator i = begin(), e = end(); i != e; ++i) {
1060 for (auto &C : i->Conversions)
1061 C.~ImplicitConversionSequence();
1062 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1063 i->DeductionFailure.Destroy();
1064 }
1065}
1066
1067void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1068 destroyCandidates();
1069 SlabAllocator.Reset();
1070 NumInlineBytesUsed = 0;
1071 Candidates.clear();
1072 Functions.clear();
1073 Kind = CSK;
1074}
1075
1076namespace {
1077 class UnbridgedCastsSet {
1078 struct Entry {
1079 Expr **Addr;
1080 Expr *Saved;
1081 };
1082 SmallVector<Entry, 2> Entries;
1083
1084 public:
1085 void save(Sema &S, Expr *&E) {
1086 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1087 Entry entry = { .Addr: &E, .Saved: E };
1088 Entries.push_back(Elt: entry);
1089 E = S.stripARCUnbridgedCast(e: E);
1090 }
1091
1092 void restore() {
1093 for (SmallVectorImpl<Entry>::iterator
1094 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1095 *i->Addr = i->Saved;
1096 }
1097 };
1098}
1099
1100/// checkPlaceholderForOverload - Do any interesting placeholder-like
1101/// preprocessing on the given expression.
1102///
1103/// \param unbridgedCasts a collection to which to add unbridged casts;
1104/// without this, they will be immediately diagnosed as errors
1105///
1106/// Return true on unrecoverable error.
1107static bool
1108checkPlaceholderForOverload(Sema &S, Expr *&E,
1109 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1110 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1111 // We can't handle overloaded expressions here because overload
1112 // resolution might reasonably tweak them.
1113 if (placeholder->getKind() == BuiltinType::Overload) return false;
1114
1115 // If the context potentially accepts unbridged ARC casts, strip
1116 // the unbridged cast and add it to the collection for later restoration.
1117 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1118 unbridgedCasts) {
1119 unbridgedCasts->save(S, E);
1120 return false;
1121 }
1122
1123 // Go ahead and check everything else.
1124 ExprResult result = S.CheckPlaceholderExpr(E);
1125 if (result.isInvalid())
1126 return true;
1127
1128 E = result.get();
1129 return false;
1130 }
1131
1132 // Nothing to do.
1133 return false;
1134}
1135
1136/// checkArgPlaceholdersForOverload - Check a set of call operands for
1137/// placeholders.
1138static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1139 UnbridgedCastsSet &unbridged) {
1140 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1141 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1142 return true;
1143
1144 return false;
1145}
1146
1147/// Determine whether the given New declaration is an overload of the
1148/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1149/// New and Old cannot be overloaded, e.g., if New has the same signature as
1150/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1151/// functions (or function templates) at all. When it does return Ovl_Match or
1152/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1153/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1154/// declaration.
1155///
1156/// Example: Given the following input:
1157///
1158/// void f(int, float); // #1
1159/// void f(int, int); // #2
1160/// int f(int, int); // #3
1161///
1162/// When we process #1, there is no previous declaration of "f", so IsOverload
1163/// will not be used.
1164///
1165/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1166/// the parameter types, we see that #1 and #2 are overloaded (since they have
1167/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1168/// unchanged.
1169///
1170/// When we process #3, Old is an overload set containing #1 and #2. We compare
1171/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1172/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1173/// functions are not part of the signature), IsOverload returns Ovl_Match and
1174/// MatchedDecl will be set to point to the FunctionDecl for #2.
1175///
1176/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1177/// by a using declaration. The rules for whether to hide shadow declarations
1178/// ignore some properties which otherwise figure into a function template's
1179/// signature.
1180Sema::OverloadKind
1181Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1182 NamedDecl *&Match, bool NewIsUsingDecl) {
1183 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1184 I != E; ++I) {
1185 NamedDecl *OldD = *I;
1186
1187 bool OldIsUsingDecl = false;
1188 if (isa<UsingShadowDecl>(Val: OldD)) {
1189 OldIsUsingDecl = true;
1190
1191 // We can always introduce two using declarations into the same
1192 // context, even if they have identical signatures.
1193 if (NewIsUsingDecl) continue;
1194
1195 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1196 }
1197
1198 // A using-declaration does not conflict with another declaration
1199 // if one of them is hidden.
1200 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1201 continue;
1202
1203 // If either declaration was introduced by a using declaration,
1204 // we'll need to use slightly different rules for matching.
1205 // Essentially, these rules are the normal rules, except that
1206 // function templates hide function templates with different
1207 // return types or template parameter lists.
1208 bool UseMemberUsingDeclRules =
1209 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1210 !New->getFriendObjectKind();
1211
1212 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1213 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1214 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1215 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1216 continue;
1217 }
1218
1219 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1220 !shouldLinkPossiblyHiddenDecl(*I, New))
1221 continue;
1222
1223 Match = *I;
1224 return Ovl_Match;
1225 }
1226
1227 // Builtins that have custom typechecking or have a reference should
1228 // not be overloadable or redeclarable.
1229 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1230 Match = *I;
1231 return Ovl_NonFunction;
1232 }
1233 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1234 // We can overload with these, which can show up when doing
1235 // redeclaration checks for UsingDecls.
1236 assert(Old.getLookupKind() == LookupUsingDeclName);
1237 } else if (isa<TagDecl>(Val: OldD)) {
1238 // We can always overload with tags by hiding them.
1239 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1240 // Optimistically assume that an unresolved using decl will
1241 // overload; if it doesn't, we'll have to diagnose during
1242 // template instantiation.
1243 //
1244 // Exception: if the scope is dependent and this is not a class
1245 // member, the using declaration can only introduce an enumerator.
1246 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1247 Match = *I;
1248 return Ovl_NonFunction;
1249 }
1250 } else {
1251 // (C++ 13p1):
1252 // Only function declarations can be overloaded; object and type
1253 // declarations cannot be overloaded.
1254 Match = *I;
1255 return Ovl_NonFunction;
1256 }
1257 }
1258
1259 // C++ [temp.friend]p1:
1260 // For a friend function declaration that is not a template declaration:
1261 // -- if the name of the friend is a qualified or unqualified template-id,
1262 // [...], otherwise
1263 // -- if the name of the friend is a qualified-id and a matching
1264 // non-template function is found in the specified class or namespace,
1265 // the friend declaration refers to that function, otherwise,
1266 // -- if the name of the friend is a qualified-id and a matching function
1267 // template is found in the specified class or namespace, the friend
1268 // declaration refers to the deduced specialization of that function
1269 // template, otherwise
1270 // -- the name shall be an unqualified-id [...]
1271 // If we get here for a qualified friend declaration, we've just reached the
1272 // third bullet. If the type of the friend is dependent, skip this lookup
1273 // until instantiation.
1274 if (New->getFriendObjectKind() && New->getQualifier() &&
1275 !New->getDescribedFunctionTemplate() &&
1276 !New->getDependentSpecializationInfo() &&
1277 !New->getType()->isDependentType()) {
1278 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1279 TemplateSpecResult.addAllDecls(Other: Old);
1280 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1281 /*QualifiedFriend*/true)) {
1282 New->setInvalidDecl();
1283 return Ovl_Overload;
1284 }
1285
1286 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1287 return Ovl_Match;
1288 }
1289
1290 return Ovl_Overload;
1291}
1292
1293static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1294 FunctionDecl *Old,
1295 bool UseMemberUsingDeclRules,
1296 bool ConsiderCudaAttrs,
1297 bool UseOverrideRules = false) {
1298 // C++ [basic.start.main]p2: This function shall not be overloaded.
1299 if (New->isMain())
1300 return false;
1301
1302 // MSVCRT user defined entry points cannot be overloaded.
1303 if (New->isMSVCRTEntryPoint())
1304 return false;
1305
1306 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1307 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1308
1309 // C++ [temp.fct]p2:
1310 // A function template can be overloaded with other function templates
1311 // and with normal (non-template) functions.
1312 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1313 return true;
1314
1315 // Is the function New an overload of the function Old?
1316 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1317 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1318
1319 // Compare the signatures (C++ 1.3.10) of the two functions to
1320 // determine whether they are overloads. If we find any mismatch
1321 // in the signature, they are overloads.
1322
1323 // If either of these functions is a K&R-style function (no
1324 // prototype), then we consider them to have matching signatures.
1325 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1326 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1327 return false;
1328
1329 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1330 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1331
1332 // The signature of a function includes the types of its
1333 // parameters (C++ 1.3.10), which includes the presence or absence
1334 // of the ellipsis; see C++ DR 357).
1335 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1336 return true;
1337
1338 // For member-like friends, the enclosing class is part of the signature.
1339 if ((New->isMemberLikeConstrainedFriend() ||
1340 Old->isMemberLikeConstrainedFriend()) &&
1341 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1342 return true;
1343
1344 // Compare the parameter lists.
1345 // This can only be done once we have establish that friend functions
1346 // inhabit the same context, otherwise we might tried to instantiate
1347 // references to non-instantiated entities during constraint substitution.
1348 // GH78101.
1349 if (NewTemplate) {
1350 // C++ [temp.over.link]p4:
1351 // The signature of a function template consists of its function
1352 // signature, its return type and its template parameter list. The names
1353 // of the template parameters are significant only for establishing the
1354 // relationship between the template parameters and the rest of the
1355 // signature.
1356 //
1357 // We check the return type and template parameter lists for function
1358 // templates first; the remaining checks follow.
1359 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1360 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1361 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1362 bool SameReturnType = SemaRef.Context.hasSameType(
1363 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1364 // FIXME(GH58571): Match template parameter list even for non-constrained
1365 // template heads. This currently ensures that the code prior to C++20 is
1366 // not newly broken.
1367 bool ConstraintsInTemplateHead =
1368 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1369 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1370 // C++ [namespace.udecl]p11:
1371 // The set of declarations named by a using-declarator that inhabits a
1372 // class C does not include member functions and member function
1373 // templates of a base class that "correspond" to (and thus would
1374 // conflict with) a declaration of a function or function template in
1375 // C.
1376 // Comparing return types is not required for the "correspond" check to
1377 // decide whether a member introduced by a shadow declaration is hidden.
1378 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1379 !SameTemplateParameterList)
1380 return true;
1381 if (!UseMemberUsingDeclRules &&
1382 (!SameTemplateParameterList || !SameReturnType))
1383 return true;
1384 }
1385
1386 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1387 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1388
1389 int OldParamsOffset = 0;
1390 int NewParamsOffset = 0;
1391
1392 // When determining if a method is an overload from a base class, act as if
1393 // the implicit object parameter are of the same type.
1394
1395 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1396 if (M->isExplicitObjectMemberFunction())
1397 return Q;
1398
1399 // We do not allow overloading based off of '__restrict'.
1400 Q.removeRestrict();
1401
1402 // We may not have applied the implicit const for a constexpr member
1403 // function yet (because we haven't yet resolved whether this is a static
1404 // or non-static member function). Add it now, on the assumption that this
1405 // is a redeclaration of OldMethod.
1406 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1407 (M->isConstexpr() || M->isConsteval()) &&
1408 !isa<CXXConstructorDecl>(Val: NewMethod))
1409 Q.addConst();
1410 return Q;
1411 };
1412
1413 auto CompareType = [&](QualType Base, QualType D) {
1414 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1415 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1416
1417 auto DS = D.getNonReferenceType().getCanonicalType().split();
1418 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1419
1420 if (BS.Quals != DS.Quals)
1421 return false;
1422
1423 if (OldMethod->isImplicitObjectMemberFunction() &&
1424 OldMethod->getParent() != NewMethod->getParent()) {
1425 QualType ParentType =
1426 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1427 .getCanonicalType();
1428 if (ParentType.getTypePtr() != BS.Ty)
1429 return false;
1430 BS.Ty = DS.Ty;
1431 }
1432
1433 // FIXME: should we ignore some type attributes here?
1434 if (BS.Ty != DS.Ty)
1435 return false;
1436
1437 if (Base->isLValueReferenceType())
1438 return D->isLValueReferenceType();
1439 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1440 };
1441
1442 // If the function is a class member, its signature includes the
1443 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1444 auto DiagnoseInconsistentRefQualifiers = [&]() {
1445 if (SemaRef.LangOpts.CPlusPlus23)
1446 return false;
1447 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1448 return false;
1449 if (OldMethod->isExplicitObjectMemberFunction() ||
1450 NewMethod->isExplicitObjectMemberFunction())
1451 return false;
1452 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1453 NewMethod->getRefQualifier() == RQ_None)) {
1454 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1455 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1456 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1457 return true;
1458 }
1459 return false;
1460 };
1461
1462 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1463 OldParamsOffset++;
1464 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1465 NewParamsOffset++;
1466
1467 if (OldType->getNumParams() - OldParamsOffset !=
1468 NewType->getNumParams() - NewParamsOffset ||
1469 !SemaRef.FunctionParamTypesAreEqual(
1470 {OldType->param_type_begin() + OldParamsOffset,
1471 OldType->param_type_end()},
1472 {NewType->param_type_begin() + NewParamsOffset,
1473 NewType->param_type_end()},
1474 nullptr)) {
1475 return true;
1476 }
1477
1478 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1479 !OldMethod->isStatic()) {
1480 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1481 const CXXMethodDecl *New) {
1482 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1483 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1484
1485 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1486 return F->getRefQualifier() == RQ_None &&
1487 !F->isExplicitObjectMemberFunction();
1488 };
1489
1490 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1491 CompareType(OldObjectType.getNonReferenceType(),
1492 NewObjectType.getNonReferenceType()))
1493 return true;
1494 return CompareType(OldObjectType, NewObjectType);
1495 }(OldMethod, NewMethod);
1496
1497 if (!HaveCorrespondingObjectParameters) {
1498 if (DiagnoseInconsistentRefQualifiers())
1499 return true;
1500 // CWG2554
1501 // and, if at least one is an explicit object member function, ignoring
1502 // object parameters
1503 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1504 !OldMethod->isExplicitObjectMemberFunction()))
1505 return true;
1506 }
1507 }
1508
1509 if (!UseOverrideRules) {
1510 Expr *NewRC = New->getTrailingRequiresClause(),
1511 *OldRC = Old->getTrailingRequiresClause();
1512 if ((NewRC != nullptr) != (OldRC != nullptr))
1513 return true;
1514
1515 if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1516 return true;
1517 }
1518
1519 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1520 NewMethod->isImplicitObjectMemberFunction()) {
1521 if (DiagnoseInconsistentRefQualifiers())
1522 return true;
1523 }
1524
1525 // Though pass_object_size is placed on parameters and takes an argument, we
1526 // consider it to be a function-level modifier for the sake of function
1527 // identity. Either the function has one or more parameters with
1528 // pass_object_size or it doesn't.
1529 if (functionHasPassObjectSizeParams(FD: New) !=
1530 functionHasPassObjectSizeParams(FD: Old))
1531 return true;
1532
1533 // enable_if attributes are an order-sensitive part of the signature.
1534 for (specific_attr_iterator<EnableIfAttr>
1535 NewI = New->specific_attr_begin<EnableIfAttr>(),
1536 NewE = New->specific_attr_end<EnableIfAttr>(),
1537 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1538 OldE = Old->specific_attr_end<EnableIfAttr>();
1539 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1540 if (NewI == NewE || OldI == OldE)
1541 return true;
1542 llvm::FoldingSetNodeID NewID, OldID;
1543 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1544 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1545 if (NewID != OldID)
1546 return true;
1547 }
1548
1549 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1550 // Don't allow overloading of destructors. (In theory we could, but it
1551 // would be a giant change to clang.)
1552 if (!isa<CXXDestructorDecl>(Val: New)) {
1553 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1554 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1555 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1556 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1557 "Unexpected invalid target.");
1558
1559 // Allow overloading of functions with same signature and different CUDA
1560 // target attributes.
1561 if (NewTarget != OldTarget)
1562 return true;
1563 }
1564 }
1565 }
1566
1567 // The signatures match; this is not an overload.
1568 return false;
1569}
1570
1571bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1572 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1573 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1574 ConsiderCudaAttrs);
1575}
1576
1577bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1578 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1579 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1580 /*UseMemberUsingDeclRules=*/false,
1581 /*ConsiderCudaAttrs=*/true,
1582 /*UseOverrideRules=*/true);
1583}
1584
1585/// Tries a user-defined conversion from From to ToType.
1586///
1587/// Produces an implicit conversion sequence for when a standard conversion
1588/// is not an option. See TryImplicitConversion for more information.
1589static ImplicitConversionSequence
1590TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1591 bool SuppressUserConversions,
1592 AllowedExplicit AllowExplicit,
1593 bool InOverloadResolution,
1594 bool CStyle,
1595 bool AllowObjCWritebackConversion,
1596 bool AllowObjCConversionOnExplicit) {
1597 ImplicitConversionSequence ICS;
1598
1599 if (SuppressUserConversions) {
1600 // We're not in the case above, so there is no conversion that
1601 // we can perform.
1602 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1603 return ICS;
1604 }
1605
1606 // Attempt user-defined conversion.
1607 OverloadCandidateSet Conversions(From->getExprLoc(),
1608 OverloadCandidateSet::CSK_Normal);
1609 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1610 Conversions, AllowExplicit,
1611 AllowObjCConversionOnExplicit)) {
1612 case OR_Success:
1613 case OR_Deleted:
1614 ICS.setUserDefined();
1615 // C++ [over.ics.user]p4:
1616 // A conversion of an expression of class type to the same class
1617 // type is given Exact Match rank, and a conversion of an
1618 // expression of class type to a base class of that type is
1619 // given Conversion rank, in spite of the fact that a copy
1620 // constructor (i.e., a user-defined conversion function) is
1621 // called for those cases.
1622 if (CXXConstructorDecl *Constructor
1623 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1624 QualType FromCanon
1625 = S.Context.getCanonicalType(T: From->getType().getUnqualifiedType());
1626 QualType ToCanon
1627 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1628 if (Constructor->isCopyConstructor() &&
1629 (FromCanon == ToCanon ||
1630 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1631 // Turn this into a "standard" conversion sequence, so that it
1632 // gets ranked with standard conversion sequences.
1633 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1634 ICS.setStandard();
1635 ICS.Standard.setAsIdentityConversion();
1636 ICS.Standard.setFromType(From->getType());
1637 ICS.Standard.setAllToTypes(ToType);
1638 ICS.Standard.CopyConstructor = Constructor;
1639 ICS.Standard.FoundCopyConstructor = Found;
1640 if (ToCanon != FromCanon)
1641 ICS.Standard.Second = ICK_Derived_To_Base;
1642 }
1643 }
1644 break;
1645
1646 case OR_Ambiguous:
1647 ICS.setAmbiguous();
1648 ICS.Ambiguous.setFromType(From->getType());
1649 ICS.Ambiguous.setToType(ToType);
1650 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1651 Cand != Conversions.end(); ++Cand)
1652 if (Cand->Best)
1653 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1654 break;
1655
1656 // Fall through.
1657 case OR_No_Viable_Function:
1658 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1659 break;
1660 }
1661
1662 return ICS;
1663}
1664
1665/// TryImplicitConversion - Attempt to perform an implicit conversion
1666/// from the given expression (Expr) to the given type (ToType). This
1667/// function returns an implicit conversion sequence that can be used
1668/// to perform the initialization. Given
1669///
1670/// void f(float f);
1671/// void g(int i) { f(i); }
1672///
1673/// this routine would produce an implicit conversion sequence to
1674/// describe the initialization of f from i, which will be a standard
1675/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1676/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1677//
1678/// Note that this routine only determines how the conversion can be
1679/// performed; it does not actually perform the conversion. As such,
1680/// it will not produce any diagnostics if no conversion is available,
1681/// but will instead return an implicit conversion sequence of kind
1682/// "BadConversion".
1683///
1684/// If @p SuppressUserConversions, then user-defined conversions are
1685/// not permitted.
1686/// If @p AllowExplicit, then explicit user-defined conversions are
1687/// permitted.
1688///
1689/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1690/// writeback conversion, which allows __autoreleasing id* parameters to
1691/// be initialized with __strong id* or __weak id* arguments.
1692static ImplicitConversionSequence
1693TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1694 bool SuppressUserConversions,
1695 AllowedExplicit AllowExplicit,
1696 bool InOverloadResolution,
1697 bool CStyle,
1698 bool AllowObjCWritebackConversion,
1699 bool AllowObjCConversionOnExplicit) {
1700 ImplicitConversionSequence ICS;
1701 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1702 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1703 ICS.setStandard();
1704 return ICS;
1705 }
1706
1707 if (!S.getLangOpts().CPlusPlus) {
1708 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1709 return ICS;
1710 }
1711
1712 // C++ [over.ics.user]p4:
1713 // A conversion of an expression of class type to the same class
1714 // type is given Exact Match rank, and a conversion of an
1715 // expression of class type to a base class of that type is
1716 // given Conversion rank, in spite of the fact that a copy/move
1717 // constructor (i.e., a user-defined conversion function) is
1718 // called for those cases.
1719 QualType FromType = From->getType();
1720 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1721 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1722 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1723 ICS.setStandard();
1724 ICS.Standard.setAsIdentityConversion();
1725 ICS.Standard.setFromType(FromType);
1726 ICS.Standard.setAllToTypes(ToType);
1727
1728 // We don't actually check at this point whether there is a valid
1729 // copy/move constructor, since overloading just assumes that it
1730 // exists. When we actually perform initialization, we'll find the
1731 // appropriate constructor to copy the returned object, if needed.
1732 ICS.Standard.CopyConstructor = nullptr;
1733
1734 // Determine whether this is considered a derived-to-base conversion.
1735 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1736 ICS.Standard.Second = ICK_Derived_To_Base;
1737
1738 return ICS;
1739 }
1740
1741 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1742 AllowExplicit, InOverloadResolution, CStyle,
1743 AllowObjCWritebackConversion,
1744 AllowObjCConversionOnExplicit);
1745}
1746
1747ImplicitConversionSequence
1748Sema::TryImplicitConversion(Expr *From, QualType ToType,
1749 bool SuppressUserConversions,
1750 AllowedExplicit AllowExplicit,
1751 bool InOverloadResolution,
1752 bool CStyle,
1753 bool AllowObjCWritebackConversion) {
1754 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1755 AllowExplicit, InOverloadResolution, CStyle,
1756 AllowObjCWritebackConversion,
1757 /*AllowObjCConversionOnExplicit=*/false);
1758}
1759
1760/// PerformImplicitConversion - Perform an implicit conversion of the
1761/// expression From to the type ToType. Returns the
1762/// converted expression. Flavor is the kind of conversion we're
1763/// performing, used in the error message. If @p AllowExplicit,
1764/// explicit user-defined conversions are permitted.
1765ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1766 AssignmentAction Action,
1767 bool AllowExplicit) {
1768 if (checkPlaceholderForOverload(S&: *this, E&: From))
1769 return ExprError();
1770
1771 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1772 bool AllowObjCWritebackConversion
1773 = getLangOpts().ObjCAutoRefCount &&
1774 (Action == AA_Passing || Action == AA_Sending);
1775 if (getLangOpts().ObjC)
1776 CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1777 SrcType: From->getType(), SrcExpr&: From);
1778 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1779 S&: *this, From, ToType,
1780 /*SuppressUserConversions=*/false,
1781 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1782 /*InOverloadResolution=*/false,
1783 /*CStyle=*/false, AllowObjCWritebackConversion,
1784 /*AllowObjCConversionOnExplicit=*/false);
1785 return PerformImplicitConversion(From, ToType, ICS, Action);
1786}
1787
1788/// Determine whether the conversion from FromType to ToType is a valid
1789/// conversion that strips "noexcept" or "noreturn" off the nested function
1790/// type.
1791bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1792 QualType &ResultTy) {
1793 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1794 return false;
1795
1796 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1797 // or F(t noexcept) -> F(t)
1798 // where F adds one of the following at most once:
1799 // - a pointer
1800 // - a member pointer
1801 // - a block pointer
1802 // Changes here need matching changes in FindCompositePointerType.
1803 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1804 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1805 Type::TypeClass TyClass = CanTo->getTypeClass();
1806 if (TyClass != CanFrom->getTypeClass()) return false;
1807 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1808 if (TyClass == Type::Pointer) {
1809 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1810 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1811 } else if (TyClass == Type::BlockPointer) {
1812 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1813 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1814 } else if (TyClass == Type::MemberPointer) {
1815 auto ToMPT = CanTo.castAs<MemberPointerType>();
1816 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1817 // A function pointer conversion cannot change the class of the function.
1818 if (ToMPT->getClass() != FromMPT->getClass())
1819 return false;
1820 CanTo = ToMPT->getPointeeType();
1821 CanFrom = FromMPT->getPointeeType();
1822 } else {
1823 return false;
1824 }
1825
1826 TyClass = CanTo->getTypeClass();
1827 if (TyClass != CanFrom->getTypeClass()) return false;
1828 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1829 return false;
1830 }
1831
1832 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1833 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1834
1835 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1836 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1837
1838 bool Changed = false;
1839
1840 // Drop 'noreturn' if not present in target type.
1841 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1842 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1843 Changed = true;
1844 }
1845
1846 // Drop 'noexcept' if not present in target type.
1847 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn)) {
1848 const auto *ToFPT = cast<FunctionProtoType>(Val: ToFn);
1849 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1850 FromFn = cast<FunctionType>(
1851 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1852 ESI: EST_None)
1853 .getTypePtr());
1854 Changed = true;
1855 }
1856
1857 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1858 // only if the ExtParameterInfo lists of the two function prototypes can be
1859 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1860 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1861 bool CanUseToFPT, CanUseFromFPT;
1862 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
1863 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
1864 CanUseToFPT && !CanUseFromFPT) {
1865 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1866 ExtInfo.ExtParameterInfos =
1867 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1868 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
1869 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
1870 FromFn = QT->getAs<FunctionType>();
1871 Changed = true;
1872 }
1873 }
1874
1875 if (!Changed)
1876 return false;
1877
1878 assert(QualType(FromFn, 0).isCanonical());
1879 if (QualType(FromFn, 0) != CanTo) return false;
1880
1881 ResultTy = ToType;
1882 return true;
1883}
1884
1885/// Determine whether the conversion from FromType to ToType is a valid
1886/// floating point conversion.
1887///
1888static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1889 QualType ToType) {
1890 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1891 return false;
1892 // FIXME: disable conversions between long double, __ibm128 and __float128
1893 // if their representation is different until there is back end support
1894 // We of course allow this conversion if long double is really double.
1895
1896 // Conversions between bfloat16 and float16 are currently not supported.
1897 if ((FromType->isBFloat16Type() &&
1898 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1899 (ToType->isBFloat16Type() &&
1900 (FromType->isFloat16Type() || FromType->isHalfType())))
1901 return false;
1902
1903 // Conversions between IEEE-quad and IBM-extended semantics are not
1904 // permitted.
1905 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
1906 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
1907 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1908 &ToSem == &llvm::APFloat::IEEEquad()) ||
1909 (&FromSem == &llvm::APFloat::IEEEquad() &&
1910 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1911 return false;
1912 return true;
1913}
1914
1915static bool IsVectorElementConversion(Sema &S, QualType FromType,
1916 QualType ToType,
1917 ImplicitConversionKind &ICK, Expr *From) {
1918 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1919 return true;
1920
1921 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1922 ICK = ICK_Floating_Promotion;
1923 return true;
1924 }
1925
1926 if (IsFloatingPointConversion(S, FromType, ToType)) {
1927 ICK = ICK_Floating_Conversion;
1928 return true;
1929 }
1930
1931 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1932 ICK = ICK_Boolean_Conversion;
1933 return true;
1934 }
1935
1936 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
1937 (FromType->isIntegralOrUnscopedEnumerationType() &&
1938 ToType->isRealFloatingType())) {
1939 ICK = ICK_Floating_Integral;
1940 return true;
1941 }
1942
1943 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1944 ICK = ICK_Integral_Promotion;
1945 return true;
1946 }
1947
1948 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1949 ToType->isIntegralType(Ctx: S.Context)) {
1950 ICK = ICK_Integral_Conversion;
1951 return true;
1952 }
1953
1954 return false;
1955}
1956
1957/// Determine whether the conversion from FromType to ToType is a valid
1958/// vector conversion.
1959///
1960/// \param ICK Will be set to the vector conversion kind, if this is a vector
1961/// conversion.
1962static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1963 ImplicitConversionKind &ICK,
1964 ImplicitConversionKind &ElConv, Expr *From,
1965 bool InOverloadResolution, bool CStyle) {
1966 // We need at least one of these types to be a vector type to have a vector
1967 // conversion.
1968 if (!ToType->isVectorType() && !FromType->isVectorType())
1969 return false;
1970
1971 // Identical types require no conversions.
1972 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1973 return false;
1974
1975 // There are no conversions between extended vector types, only identity.
1976 if (ToType->isExtVectorType()) {
1977 if (FromType->isExtVectorType()) {
1978 // HLSL allows implicit truncation of vector types.
1979 if (S.getLangOpts().HLSL) {
1980 unsigned FromElts = FromType->getAs<VectorType>()->getNumElements();
1981 unsigned ToElts = ToType->getAs<VectorType>()->getNumElements();
1982 if (FromElts < ToElts)
1983 return false;
1984 if (FromElts == ToElts)
1985 ICK = ICK_Identity;
1986 else
1987 ICK = ICK_HLSL_Vector_Truncation;
1988
1989 QualType FromElTy = FromType->getAs<VectorType>()->getElementType();
1990 QualType ToElTy = ToType->getAs<VectorType>()->getElementType();
1991 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
1992 return true;
1993 return IsVectorElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK&: ElConv, From);
1994 }
1995 // There are no conversions between extended vector types other than the
1996 // identity conversion.
1997 return false;
1998 }
1999
2000 // Vector splat from any arithmetic type to a vector.
2001 if (FromType->isArithmeticType()) {
2002 ICK = ICK_Vector_Splat;
2003 return true;
2004 }
2005 }
2006
2007 if (ToType->isSVESizelessBuiltinType() ||
2008 FromType->isSVESizelessBuiltinType())
2009 if (S.Context.areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2010 S.Context.areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2011 ICK = ICK_SVE_Vector_Conversion;
2012 return true;
2013 }
2014
2015 if (ToType->isRVVSizelessBuiltinType() ||
2016 FromType->isRVVSizelessBuiltinType())
2017 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2018 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2019 ICK = ICK_RVV_Vector_Conversion;
2020 return true;
2021 }
2022
2023 // We can perform the conversion between vector types in the following cases:
2024 // 1)vector types are equivalent AltiVec and GCC vector types
2025 // 2)lax vector conversions are permitted and the vector types are of the
2026 // same size
2027 // 3)the destination type does not have the ARM MVE strict-polymorphism
2028 // attribute, which inhibits lax vector conversion for overload resolution
2029 // only
2030 if (ToType->isVectorType() && FromType->isVectorType()) {
2031 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2032 (S.isLaxVectorConversion(FromType, ToType) &&
2033 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2034 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2035 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2036 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2037 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2038 !InOverloadResolution && !CStyle) {
2039 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2040 << FromType << ToType;
2041 }
2042 ICK = ICK_Vector_Conversion;
2043 return true;
2044 }
2045 }
2046
2047 return false;
2048}
2049
2050static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2051 bool InOverloadResolution,
2052 StandardConversionSequence &SCS,
2053 bool CStyle);
2054
2055/// IsStandardConversion - Determines whether there is a standard
2056/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2057/// expression From to the type ToType. Standard conversion sequences
2058/// only consider non-class types; for conversions that involve class
2059/// types, use TryImplicitConversion. If a conversion exists, SCS will
2060/// contain the standard conversion sequence required to perform this
2061/// conversion and this routine will return true. Otherwise, this
2062/// routine will return false and the value of SCS is unspecified.
2063static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2064 bool InOverloadResolution,
2065 StandardConversionSequence &SCS,
2066 bool CStyle,
2067 bool AllowObjCWritebackConversion) {
2068 QualType FromType = From->getType();
2069
2070 // Standard conversions (C++ [conv])
2071 SCS.setAsIdentityConversion();
2072 SCS.IncompatibleObjC = false;
2073 SCS.setFromType(FromType);
2074 SCS.CopyConstructor = nullptr;
2075
2076 // There are no standard conversions for class types in C++, so
2077 // abort early. When overloading in C, however, we do permit them.
2078 if (S.getLangOpts().CPlusPlus &&
2079 (FromType->isRecordType() || ToType->isRecordType()))
2080 return false;
2081
2082 // The first conversion can be an lvalue-to-rvalue conversion,
2083 // array-to-pointer conversion, or function-to-pointer conversion
2084 // (C++ 4p1).
2085
2086 if (FromType == S.Context.OverloadTy) {
2087 DeclAccessPair AccessPair;
2088 if (FunctionDecl *Fn
2089 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2090 Found&: AccessPair)) {
2091 // We were able to resolve the address of the overloaded function,
2092 // so we can convert to the type of that function.
2093 FromType = Fn->getType();
2094 SCS.setFromType(FromType);
2095
2096 // we can sometimes resolve &foo<int> regardless of ToType, so check
2097 // if the type matches (identity) or we are converting to bool
2098 if (!S.Context.hasSameUnqualifiedType(
2099 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2100 QualType resultTy;
2101 // if the function type matches except for [[noreturn]], it's ok
2102 if (!S.IsFunctionConversion(FromType,
2103 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), ResultTy&: resultTy))
2104 // otherwise, only a boolean conversion is standard
2105 if (!ToType->isBooleanType())
2106 return false;
2107 }
2108
2109 // Check if the "from" expression is taking the address of an overloaded
2110 // function and recompute the FromType accordingly. Take advantage of the
2111 // fact that non-static member functions *must* have such an address-of
2112 // expression.
2113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2114 if (Method && !Method->isStatic() &&
2115 !Method->isExplicitObjectMemberFunction()) {
2116 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2117 "Non-unary operator on non-static member address");
2118 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2119 == UO_AddrOf &&
2120 "Non-address-of operator on non-static member address");
2121 const Type *ClassType
2122 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
2123 FromType = S.Context.getMemberPointerType(T: FromType, Cls: ClassType);
2124 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2125 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2126 UO_AddrOf &&
2127 "Non-address-of operator for overloaded function expression");
2128 FromType = S.Context.getPointerType(T: FromType);
2129 }
2130 } else {
2131 return false;
2132 }
2133 }
2134 // Lvalue-to-rvalue conversion (C++11 4.1):
2135 // A glvalue (3.10) of a non-function, non-array type T can
2136 // be converted to a prvalue.
2137 bool argIsLValue = From->isGLValue();
2138 if (argIsLValue && !FromType->canDecayToPointerType() &&
2139 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2140 SCS.First = ICK_Lvalue_To_Rvalue;
2141
2142 // C11 6.3.2.1p2:
2143 // ... if the lvalue has atomic type, the value has the non-atomic version
2144 // of the type of the lvalue ...
2145 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2146 FromType = Atomic->getValueType();
2147
2148 // If T is a non-class type, the type of the rvalue is the
2149 // cv-unqualified version of T. Otherwise, the type of the rvalue
2150 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2151 // just strip the qualifiers because they don't matter.
2152 FromType = FromType.getUnqualifiedType();
2153 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2154 ToType->isArrayParameterType()) {
2155 // HLSL constant array parameters do not decay, so if the argument is a
2156 // constant array and the parameter is an ArrayParameterType we have special
2157 // handling here.
2158 FromType = S.Context.getArrayParameterType(Ty: FromType);
2159 if (S.Context.getCanonicalType(T: FromType) !=
2160 S.Context.getCanonicalType(T: ToType))
2161 return false;
2162
2163 SCS.First = ICK_HLSL_Array_RValue;
2164 SCS.setAllToTypes(ToType);
2165 return true;
2166 } else if (FromType->isArrayType()) {
2167 // Array-to-pointer conversion (C++ 4.2)
2168 SCS.First = ICK_Array_To_Pointer;
2169
2170 // An lvalue or rvalue of type "array of N T" or "array of unknown
2171 // bound of T" can be converted to an rvalue of type "pointer to
2172 // T" (C++ 4.2p1).
2173 FromType = S.Context.getArrayDecayedType(T: FromType);
2174
2175 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2176 // This conversion is deprecated in C++03 (D.4)
2177 SCS.DeprecatedStringLiteralToCharPtr = true;
2178
2179 // For the purpose of ranking in overload resolution
2180 // (13.3.3.1.1), this conversion is considered an
2181 // array-to-pointer conversion followed by a qualification
2182 // conversion (4.4). (C++ 4.2p2)
2183 SCS.Second = ICK_Identity;
2184 SCS.Third = ICK_Qualification;
2185 SCS.QualificationIncludesObjCLifetime = false;
2186 SCS.setAllToTypes(FromType);
2187 return true;
2188 }
2189 } else if (FromType->isFunctionType() && argIsLValue) {
2190 // Function-to-pointer conversion (C++ 4.3).
2191 SCS.First = ICK_Function_To_Pointer;
2192
2193 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2194 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2195 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2196 return false;
2197
2198 // An lvalue of function type T can be converted to an rvalue of
2199 // type "pointer to T." The result is a pointer to the
2200 // function. (C++ 4.3p1).
2201 FromType = S.Context.getPointerType(T: FromType);
2202 } else {
2203 // We don't require any conversions for the first step.
2204 SCS.First = ICK_Identity;
2205 }
2206 SCS.setToType(Idx: 0, T: FromType);
2207
2208 // The second conversion can be an integral promotion, floating
2209 // point promotion, integral conversion, floating point conversion,
2210 // floating-integral conversion, pointer conversion,
2211 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2212 // For overloading in C, this can also be a "compatible-type"
2213 // conversion.
2214 bool IncompatibleObjC = false;
2215 ImplicitConversionKind SecondICK = ICK_Identity;
2216 ImplicitConversionKind ElementICK = ICK_Identity;
2217 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2218 // The unqualified versions of the types are the same: there's no
2219 // conversion to do.
2220 SCS.Second = ICK_Identity;
2221 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2222 // Integral promotion (C++ 4.5).
2223 SCS.Second = ICK_Integral_Promotion;
2224 FromType = ToType.getUnqualifiedType();
2225 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2226 // Floating point promotion (C++ 4.6).
2227 SCS.Second = ICK_Floating_Promotion;
2228 FromType = ToType.getUnqualifiedType();
2229 } else if (S.IsComplexPromotion(FromType, ToType)) {
2230 // Complex promotion (Clang extension)
2231 SCS.Second = ICK_Complex_Promotion;
2232 FromType = ToType.getUnqualifiedType();
2233 } else if (ToType->isBooleanType() &&
2234 (FromType->isArithmeticType() ||
2235 FromType->isAnyPointerType() ||
2236 FromType->isBlockPointerType() ||
2237 FromType->isMemberPointerType())) {
2238 // Boolean conversions (C++ 4.12).
2239 SCS.Second = ICK_Boolean_Conversion;
2240 FromType = S.Context.BoolTy;
2241 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2242 ToType->isIntegralType(Ctx: S.Context)) {
2243 // Integral conversions (C++ 4.7).
2244 SCS.Second = ICK_Integral_Conversion;
2245 FromType = ToType.getUnqualifiedType();
2246 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2247 // Complex conversions (C99 6.3.1.6)
2248 SCS.Second = ICK_Complex_Conversion;
2249 FromType = ToType.getUnqualifiedType();
2250 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2251 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2252 // Complex-real conversions (C99 6.3.1.7)
2253 SCS.Second = ICK_Complex_Real;
2254 FromType = ToType.getUnqualifiedType();
2255 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2256 // Floating point conversions (C++ 4.8).
2257 SCS.Second = ICK_Floating_Conversion;
2258 FromType = ToType.getUnqualifiedType();
2259 } else if ((FromType->isRealFloatingType() &&
2260 ToType->isIntegralType(Ctx: S.Context)) ||
2261 (FromType->isIntegralOrUnscopedEnumerationType() &&
2262 ToType->isRealFloatingType())) {
2263
2264 // Floating-integral conversions (C++ 4.9).
2265 SCS.Second = ICK_Floating_Integral;
2266 FromType = ToType.getUnqualifiedType();
2267 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2268 SCS.Second = ICK_Block_Pointer_Conversion;
2269 } else if (AllowObjCWritebackConversion &&
2270 S.isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2271 SCS.Second = ICK_Writeback_Conversion;
2272 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2273 ConvertedType&: FromType, IncompatibleObjC)) {
2274 // Pointer conversions (C++ 4.10).
2275 SCS.Second = ICK_Pointer_Conversion;
2276 SCS.IncompatibleObjC = IncompatibleObjC;
2277 FromType = FromType.getUnqualifiedType();
2278 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2279 InOverloadResolution, ConvertedType&: FromType)) {
2280 // Pointer to member conversions (4.11).
2281 SCS.Second = ICK_Pointer_Member;
2282 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: ElementICK,
2283 From, InOverloadResolution, CStyle)) {
2284 SCS.Second = SecondICK;
2285 SCS.Element = ElementICK;
2286 FromType = ToType.getUnqualifiedType();
2287 } else if (!S.getLangOpts().CPlusPlus &&
2288 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2289 // Compatible conversions (Clang extension for C function overloading)
2290 SCS.Second = ICK_Compatible_Conversion;
2291 FromType = ToType.getUnqualifiedType();
2292 } else if (IsTransparentUnionStandardConversion(
2293 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2294 SCS.Second = ICK_TransparentUnionConversion;
2295 FromType = ToType;
2296 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2297 CStyle)) {
2298 // tryAtomicConversion has updated the standard conversion sequence
2299 // appropriately.
2300 return true;
2301 } else if (ToType->isEventT() &&
2302 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2303 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2304 SCS.Second = ICK_Zero_Event_Conversion;
2305 FromType = ToType;
2306 } else if (ToType->isQueueT() &&
2307 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2308 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2309 SCS.Second = ICK_Zero_Queue_Conversion;
2310 FromType = ToType;
2311 } else if (ToType->isSamplerT() &&
2312 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2313 SCS.Second = ICK_Compatible_Conversion;
2314 FromType = ToType;
2315 } else if ((ToType->isFixedPointType() &&
2316 FromType->isConvertibleToFixedPointType()) ||
2317 (FromType->isFixedPointType() &&
2318 ToType->isConvertibleToFixedPointType())) {
2319 SCS.Second = ICK_Fixed_Point_Conversion;
2320 FromType = ToType;
2321 } else {
2322 // No second conversion required.
2323 SCS.Second = ICK_Identity;
2324 }
2325 SCS.setToType(Idx: 1, T: FromType);
2326
2327 // The third conversion can be a function pointer conversion or a
2328 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2329 bool ObjCLifetimeConversion;
2330 if (S.IsFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2331 // Function pointer conversions (removing 'noexcept') including removal of
2332 // 'noreturn' (Clang extension).
2333 SCS.Third = ICK_Function_Conversion;
2334 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2335 ObjCLifetimeConversion)) {
2336 SCS.Third = ICK_Qualification;
2337 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2338 FromType = ToType;
2339 } else {
2340 // No conversion required
2341 SCS.Third = ICK_Identity;
2342 }
2343
2344 // C++ [over.best.ics]p6:
2345 // [...] Any difference in top-level cv-qualification is
2346 // subsumed by the initialization itself and does not constitute
2347 // a conversion. [...]
2348 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2349 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2350 if (CanonFrom.getLocalUnqualifiedType()
2351 == CanonTo.getLocalUnqualifiedType() &&
2352 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2353 FromType = ToType;
2354 CanonFrom = CanonTo;
2355 }
2356
2357 SCS.setToType(Idx: 2, T: FromType);
2358
2359 if (CanonFrom == CanonTo)
2360 return true;
2361
2362 // If we have not converted the argument type to the parameter type,
2363 // this is a bad conversion sequence, unless we're resolving an overload in C.
2364 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2365 return false;
2366
2367 ExprResult ER = ExprResult{From};
2368 Sema::AssignConvertType Conv =
2369 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2370 /*Diagnose=*/false,
2371 /*DiagnoseCFAudited=*/false,
2372 /*ConvertRHS=*/false);
2373 ImplicitConversionKind SecondConv;
2374 switch (Conv) {
2375 case Sema::Compatible:
2376 SecondConv = ICK_C_Only_Conversion;
2377 break;
2378 // For our purposes, discarding qualifiers is just as bad as using an
2379 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2380 // qualifiers, as well.
2381 case Sema::CompatiblePointerDiscardsQualifiers:
2382 case Sema::IncompatiblePointer:
2383 case Sema::IncompatiblePointerSign:
2384 SecondConv = ICK_Incompatible_Pointer_Conversion;
2385 break;
2386 default:
2387 return false;
2388 }
2389
2390 // First can only be an lvalue conversion, so we pretend that this was the
2391 // second conversion. First should already be valid from earlier in the
2392 // function.
2393 SCS.Second = SecondConv;
2394 SCS.setToType(Idx: 1, T: ToType);
2395
2396 // Third is Identity, because Second should rank us worse than any other
2397 // conversion. This could also be ICK_Qualification, but it's simpler to just
2398 // lump everything in with the second conversion, and we don't gain anything
2399 // from making this ICK_Qualification.
2400 SCS.Third = ICK_Identity;
2401 SCS.setToType(Idx: 2, T: ToType);
2402 return true;
2403}
2404
2405static bool
2406IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2407 QualType &ToType,
2408 bool InOverloadResolution,
2409 StandardConversionSequence &SCS,
2410 bool CStyle) {
2411
2412 const RecordType *UT = ToType->getAsUnionType();
2413 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2414 return false;
2415 // The field to initialize within the transparent union.
2416 RecordDecl *UD = UT->getDecl();
2417 // It's compatible if the expression matches any of the fields.
2418 for (const auto *it : UD->fields()) {
2419 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2420 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2421 ToType = it->getType();
2422 return true;
2423 }
2424 }
2425 return false;
2426}
2427
2428/// IsIntegralPromotion - Determines whether the conversion from the
2429/// expression From (whose potentially-adjusted type is FromType) to
2430/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2431/// sets PromotedType to the promoted type.
2432bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2433 const BuiltinType *To = ToType->getAs<BuiltinType>();
2434 // All integers are built-in.
2435 if (!To) {
2436 return false;
2437 }
2438
2439 // An rvalue of type char, signed char, unsigned char, short int, or
2440 // unsigned short int can be converted to an rvalue of type int if
2441 // int can represent all the values of the source type; otherwise,
2442 // the source rvalue can be converted to an rvalue of type unsigned
2443 // int (C++ 4.5p1).
2444 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2445 !FromType->isEnumeralType()) {
2446 if ( // We can promote any signed, promotable integer type to an int
2447 (FromType->isSignedIntegerType() ||
2448 // We can promote any unsigned integer type whose size is
2449 // less than int to an int.
2450 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2451 return To->getKind() == BuiltinType::Int;
2452 }
2453
2454 return To->getKind() == BuiltinType::UInt;
2455 }
2456
2457 // C++11 [conv.prom]p3:
2458 // A prvalue of an unscoped enumeration type whose underlying type is not
2459 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2460 // following types that can represent all the values of the enumeration
2461 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2462 // unsigned int, long int, unsigned long int, long long int, or unsigned
2463 // long long int. If none of the types in that list can represent all the
2464 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2465 // type can be converted to an rvalue a prvalue of the extended integer type
2466 // with lowest integer conversion rank (4.13) greater than the rank of long
2467 // long in which all the values of the enumeration can be represented. If
2468 // there are two such extended types, the signed one is chosen.
2469 // C++11 [conv.prom]p4:
2470 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2471 // can be converted to a prvalue of its underlying type. Moreover, if
2472 // integral promotion can be applied to its underlying type, a prvalue of an
2473 // unscoped enumeration type whose underlying type is fixed can also be
2474 // converted to a prvalue of the promoted underlying type.
2475 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2476 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2477 // provided for a scoped enumeration.
2478 if (FromEnumType->getDecl()->isScoped())
2479 return false;
2480
2481 // We can perform an integral promotion to the underlying type of the enum,
2482 // even if that's not the promoted type. Note that the check for promoting
2483 // the underlying type is based on the type alone, and does not consider
2484 // the bitfield-ness of the actual source expression.
2485 if (FromEnumType->getDecl()->isFixed()) {
2486 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2487 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2488 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2489 }
2490
2491 // We have already pre-calculated the promotion type, so this is trivial.
2492 if (ToType->isIntegerType() &&
2493 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2494 return Context.hasSameUnqualifiedType(
2495 T1: ToType, T2: FromEnumType->getDecl()->getPromotionType());
2496
2497 // C++ [conv.prom]p5:
2498 // If the bit-field has an enumerated type, it is treated as any other
2499 // value of that type for promotion purposes.
2500 //
2501 // ... so do not fall through into the bit-field checks below in C++.
2502 if (getLangOpts().CPlusPlus)
2503 return false;
2504 }
2505
2506 // C++0x [conv.prom]p2:
2507 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2508 // to an rvalue a prvalue of the first of the following types that can
2509 // represent all the values of its underlying type: int, unsigned int,
2510 // long int, unsigned long int, long long int, or unsigned long long int.
2511 // If none of the types in that list can represent all the values of its
2512 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2513 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2514 // type.
2515 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2516 ToType->isIntegerType()) {
2517 // Determine whether the type we're converting from is signed or
2518 // unsigned.
2519 bool FromIsSigned = FromType->isSignedIntegerType();
2520 uint64_t FromSize = Context.getTypeSize(T: FromType);
2521
2522 // The types we'll try to promote to, in the appropriate
2523 // order. Try each of these types.
2524 QualType PromoteTypes[6] = {
2525 Context.IntTy, Context.UnsignedIntTy,
2526 Context.LongTy, Context.UnsignedLongTy ,
2527 Context.LongLongTy, Context.UnsignedLongLongTy
2528 };
2529 for (int Idx = 0; Idx < 6; ++Idx) {
2530 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2531 if (FromSize < ToSize ||
2532 (FromSize == ToSize &&
2533 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2534 // We found the type that we can promote to. If this is the
2535 // type we wanted, we have a promotion. Otherwise, no
2536 // promotion.
2537 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2538 }
2539 }
2540 }
2541
2542 // An rvalue for an integral bit-field (9.6) can be converted to an
2543 // rvalue of type int if int can represent all the values of the
2544 // bit-field; otherwise, it can be converted to unsigned int if
2545 // unsigned int can represent all the values of the bit-field. If
2546 // the bit-field is larger yet, no integral promotion applies to
2547 // it. If the bit-field has an enumerated type, it is treated as any
2548 // other value of that type for promotion purposes (C++ 4.5p3).
2549 // FIXME: We should delay checking of bit-fields until we actually perform the
2550 // conversion.
2551 //
2552 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2553 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2554 // bit-fields and those whose underlying type is larger than int) for GCC
2555 // compatibility.
2556 if (From) {
2557 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2558 std::optional<llvm::APSInt> BitWidth;
2559 if (FromType->isIntegralType(Ctx: Context) &&
2560 (BitWidth =
2561 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2562 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2563 ToSize = Context.getTypeSize(T: ToType);
2564
2565 // Are we promoting to an int from a bitfield that fits in an int?
2566 if (*BitWidth < ToSize ||
2567 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2568 return To->getKind() == BuiltinType::Int;
2569 }
2570
2571 // Are we promoting to an unsigned int from an unsigned bitfield
2572 // that fits into an unsigned int?
2573 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2574 return To->getKind() == BuiltinType::UInt;
2575 }
2576
2577 return false;
2578 }
2579 }
2580 }
2581
2582 // An rvalue of type bool can be converted to an rvalue of type int,
2583 // with false becoming zero and true becoming one (C++ 4.5p4).
2584 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2585 return true;
2586 }
2587
2588 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2589 // integral type.
2590 if (Context.getLangOpts().HLSL)
2591 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2592
2593 return false;
2594}
2595
2596/// IsFloatingPointPromotion - Determines whether the conversion from
2597/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2598/// returns true and sets PromotedType to the promoted type.
2599bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2600 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2601 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2602 /// An rvalue of type float can be converted to an rvalue of type
2603 /// double. (C++ 4.6p1).
2604 if (FromBuiltin->getKind() == BuiltinType::Float &&
2605 ToBuiltin->getKind() == BuiltinType::Double)
2606 return true;
2607
2608 // C99 6.3.1.5p1:
2609 // When a float is promoted to double or long double, or a
2610 // double is promoted to long double [...].
2611 if (!getLangOpts().CPlusPlus &&
2612 (FromBuiltin->getKind() == BuiltinType::Float ||
2613 FromBuiltin->getKind() == BuiltinType::Double) &&
2614 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2615 ToBuiltin->getKind() == BuiltinType::Float128 ||
2616 ToBuiltin->getKind() == BuiltinType::Ibm128))
2617 return true;
2618
2619 // Half can be promoted to float.
2620 if (!getLangOpts().NativeHalfType &&
2621 FromBuiltin->getKind() == BuiltinType::Half &&
2622 ToBuiltin->getKind() == BuiltinType::Float)
2623 return true;
2624 }
2625
2626 return false;
2627}
2628
2629/// Determine if a conversion is a complex promotion.
2630///
2631/// A complex promotion is defined as a complex -> complex conversion
2632/// where the conversion between the underlying real types is a
2633/// floating-point or integral promotion.
2634bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2635 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2636 if (!FromComplex)
2637 return false;
2638
2639 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2640 if (!ToComplex)
2641 return false;
2642
2643 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2644 ToType: ToComplex->getElementType()) ||
2645 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2646 ToType: ToComplex->getElementType());
2647}
2648
2649/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2650/// the pointer type FromPtr to a pointer to type ToPointee, with the
2651/// same type qualifiers as FromPtr has on its pointee type. ToType,
2652/// if non-empty, will be a pointer to ToType that may or may not have
2653/// the right set of qualifiers on its pointee.
2654///
2655static QualType
2656BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2657 QualType ToPointee, QualType ToType,
2658 ASTContext &Context,
2659 bool StripObjCLifetime = false) {
2660 assert((FromPtr->getTypeClass() == Type::Pointer ||
2661 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2662 "Invalid similarly-qualified pointer type");
2663
2664 /// Conversions to 'id' subsume cv-qualifier conversions.
2665 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2666 return ToType.getUnqualifiedType();
2667
2668 QualType CanonFromPointee
2669 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2670 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2671 Qualifiers Quals = CanonFromPointee.getQualifiers();
2672
2673 if (StripObjCLifetime)
2674 Quals.removeObjCLifetime();
2675
2676 // Exact qualifier match -> return the pointer type we're converting to.
2677 if (CanonToPointee.getLocalQualifiers() == Quals) {
2678 // ToType is exactly what we need. Return it.
2679 if (!ToType.isNull())
2680 return ToType.getUnqualifiedType();
2681
2682 // Build a pointer to ToPointee. It has the right qualifiers
2683 // already.
2684 if (isa<ObjCObjectPointerType>(Val: ToType))
2685 return Context.getObjCObjectPointerType(OIT: ToPointee);
2686 return Context.getPointerType(T: ToPointee);
2687 }
2688
2689 // Just build a canonical type that has the right qualifiers.
2690 QualType QualifiedCanonToPointee
2691 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
2692
2693 if (isa<ObjCObjectPointerType>(Val: ToType))
2694 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
2695 return Context.getPointerType(T: QualifiedCanonToPointee);
2696}
2697
2698static bool isNullPointerConstantForConversion(Expr *Expr,
2699 bool InOverloadResolution,
2700 ASTContext &Context) {
2701 // Handle value-dependent integral null pointer constants correctly.
2702 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2703 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2704 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2705 return !InOverloadResolution;
2706
2707 return Expr->isNullPointerConstant(Ctx&: Context,
2708 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2709 : Expr::NPC_ValueDependentIsNull);
2710}
2711
2712/// IsPointerConversion - Determines whether the conversion of the
2713/// expression From, which has the (possibly adjusted) type FromType,
2714/// can be converted to the type ToType via a pointer conversion (C++
2715/// 4.10). If so, returns true and places the converted type (that
2716/// might differ from ToType in its cv-qualifiers at some level) into
2717/// ConvertedType.
2718///
2719/// This routine also supports conversions to and from block pointers
2720/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2721/// pointers to interfaces. FIXME: Once we've determined the
2722/// appropriate overloading rules for Objective-C, we may want to
2723/// split the Objective-C checks into a different routine; however,
2724/// GCC seems to consider all of these conversions to be pointer
2725/// conversions, so for now they live here. IncompatibleObjC will be
2726/// set if the conversion is an allowed Objective-C conversion that
2727/// should result in a warning.
2728bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2729 bool InOverloadResolution,
2730 QualType& ConvertedType,
2731 bool &IncompatibleObjC) {
2732 IncompatibleObjC = false;
2733 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2734 IncompatibleObjC))
2735 return true;
2736
2737 // Conversion from a null pointer constant to any Objective-C pointer type.
2738 if (ToType->isObjCObjectPointerType() &&
2739 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2740 ConvertedType = ToType;
2741 return true;
2742 }
2743
2744 // Blocks: Block pointers can be converted to void*.
2745 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2746 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2747 ConvertedType = ToType;
2748 return true;
2749 }
2750 // Blocks: A null pointer constant can be converted to a block
2751 // pointer type.
2752 if (ToType->isBlockPointerType() &&
2753 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2754 ConvertedType = ToType;
2755 return true;
2756 }
2757
2758 // If the left-hand-side is nullptr_t, the right side can be a null
2759 // pointer constant.
2760 if (ToType->isNullPtrType() &&
2761 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2762 ConvertedType = ToType;
2763 return true;
2764 }
2765
2766 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2767 if (!ToTypePtr)
2768 return false;
2769
2770 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2771 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2772 ConvertedType = ToType;
2773 return true;
2774 }
2775
2776 // Beyond this point, both types need to be pointers
2777 // , including objective-c pointers.
2778 QualType ToPointeeType = ToTypePtr->getPointeeType();
2779 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2780 !getLangOpts().ObjCAutoRefCount) {
2781 ConvertedType = BuildSimilarlyQualifiedPointerType(
2782 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2783 Context);
2784 return true;
2785 }
2786 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2787 if (!FromTypePtr)
2788 return false;
2789
2790 QualType FromPointeeType = FromTypePtr->getPointeeType();
2791
2792 // If the unqualified pointee types are the same, this can't be a
2793 // pointer conversion, so don't do all of the work below.
2794 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
2795 return false;
2796
2797 // An rvalue of type "pointer to cv T," where T is an object type,
2798 // can be converted to an rvalue of type "pointer to cv void" (C++
2799 // 4.10p2).
2800 if (FromPointeeType->isIncompleteOrObjectType() &&
2801 ToPointeeType->isVoidType()) {
2802 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2803 ToPointeeType,
2804 ToType, Context,
2805 /*StripObjCLifetime=*/true);
2806 return true;
2807 }
2808
2809 // MSVC allows implicit function to void* type conversion.
2810 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2811 ToPointeeType->isVoidType()) {
2812 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2813 ToPointeeType,
2814 ToType, Context);
2815 return true;
2816 }
2817
2818 // When we're overloading in C, we allow a special kind of pointer
2819 // conversion for compatible-but-not-identical pointee types.
2820 if (!getLangOpts().CPlusPlus &&
2821 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
2822 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2823 ToPointeeType,
2824 ToType, Context);
2825 return true;
2826 }
2827
2828 // C++ [conv.ptr]p3:
2829 //
2830 // An rvalue of type "pointer to cv D," where D is a class type,
2831 // can be converted to an rvalue of type "pointer to cv B," where
2832 // B is a base class (clause 10) of D. If B is an inaccessible
2833 // (clause 11) or ambiguous (10.2) base class of D, a program that
2834 // necessitates this conversion is ill-formed. The result of the
2835 // conversion is a pointer to the base class sub-object of the
2836 // derived class object. The null pointer value is converted to
2837 // the null pointer value of the destination type.
2838 //
2839 // Note that we do not check for ambiguity or inaccessibility
2840 // here. That is handled by CheckPointerConversion.
2841 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2842 ToPointeeType->isRecordType() &&
2843 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
2844 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2845 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2846 ToPointeeType,
2847 ToType, Context);
2848 return true;
2849 }
2850
2851 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2852 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
2853 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2854 ToPointeeType,
2855 ToType, Context);
2856 return true;
2857 }
2858
2859 return false;
2860}
2861
2862/// Adopt the given qualifiers for the given type.
2863static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2864 Qualifiers TQs = T.getQualifiers();
2865
2866 // Check whether qualifiers already match.
2867 if (TQs == Qs)
2868 return T;
2869
2870 if (Qs.compatiblyIncludes(other: TQs))
2871 return Context.getQualifiedType(T, Qs);
2872
2873 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
2874}
2875
2876/// isObjCPointerConversion - Determines whether this is an
2877/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2878/// with the same arguments and return values.
2879bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2880 QualType& ConvertedType,
2881 bool &IncompatibleObjC) {
2882 if (!getLangOpts().ObjC)
2883 return false;
2884
2885 // The set of qualifiers on the type we're converting from.
2886 Qualifiers FromQualifiers = FromType.getQualifiers();
2887
2888 // First, we handle all conversions on ObjC object pointer types.
2889 const ObjCObjectPointerType* ToObjCPtr =
2890 ToType->getAs<ObjCObjectPointerType>();
2891 const ObjCObjectPointerType *FromObjCPtr =
2892 FromType->getAs<ObjCObjectPointerType>();
2893
2894 if (ToObjCPtr && FromObjCPtr) {
2895 // If the pointee types are the same (ignoring qualifications),
2896 // then this is not a pointer conversion.
2897 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
2898 T2: FromObjCPtr->getPointeeType()))
2899 return false;
2900
2901 // Conversion between Objective-C pointers.
2902 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
2903 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2904 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2905 if (getLangOpts().CPlusPlus && LHS && RHS &&
2906 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2907 other: FromObjCPtr->getPointeeType()))
2908 return false;
2909 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2910 ToObjCPtr->getPointeeType(),
2911 ToType, Context);
2912 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2913 return true;
2914 }
2915
2916 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
2917 // Okay: this is some kind of implicit downcast of Objective-C
2918 // interfaces, which is permitted. However, we're going to
2919 // complain about it.
2920 IncompatibleObjC = true;
2921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2922 ToObjCPtr->getPointeeType(),
2923 ToType, Context);
2924 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2925 return true;
2926 }
2927 }
2928 // Beyond this point, both types need to be C pointers or block pointers.
2929 QualType ToPointeeType;
2930 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2931 ToPointeeType = ToCPtr->getPointeeType();
2932 else if (const BlockPointerType *ToBlockPtr =
2933 ToType->getAs<BlockPointerType>()) {
2934 // Objective C++: We're able to convert from a pointer to any object
2935 // to a block pointer type.
2936 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2937 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
2938 return true;
2939 }
2940 ToPointeeType = ToBlockPtr->getPointeeType();
2941 }
2942 else if (FromType->getAs<BlockPointerType>() &&
2943 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2944 // Objective C++: We're able to convert from a block pointer type to a
2945 // pointer to any object.
2946 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
2947 return true;
2948 }
2949 else
2950 return false;
2951
2952 QualType FromPointeeType;
2953 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2954 FromPointeeType = FromCPtr->getPointeeType();
2955 else if (const BlockPointerType *FromBlockPtr =
2956 FromType->getAs<BlockPointerType>())
2957 FromPointeeType = FromBlockPtr->getPointeeType();
2958 else
2959 return false;
2960
2961 // If we have pointers to pointers, recursively check whether this
2962 // is an Objective-C conversion.
2963 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2964 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
2965 IncompatibleObjC)) {
2966 // We always complain about this conversion.
2967 IncompatibleObjC = true;
2968 ConvertedType = Context.getPointerType(T: ConvertedType);
2969 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2970 return true;
2971 }
2972 // Allow conversion of pointee being objective-c pointer to another one;
2973 // as in I* to id.
2974 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2975 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2976 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
2977 IncompatibleObjC)) {
2978
2979 ConvertedType = Context.getPointerType(T: ConvertedType);
2980 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
2981 return true;
2982 }
2983
2984 // If we have pointers to functions or blocks, check whether the only
2985 // differences in the argument and result types are in Objective-C
2986 // pointer conversions. If so, we permit the conversion (but
2987 // complain about it).
2988 const FunctionProtoType *FromFunctionType
2989 = FromPointeeType->getAs<FunctionProtoType>();
2990 const FunctionProtoType *ToFunctionType
2991 = ToPointeeType->getAs<FunctionProtoType>();
2992 if (FromFunctionType && ToFunctionType) {
2993 // If the function types are exactly the same, this isn't an
2994 // Objective-C pointer conversion.
2995 if (Context.getCanonicalType(T: FromPointeeType)
2996 == Context.getCanonicalType(T: ToPointeeType))
2997 return false;
2998
2999 // Perform the quick checks that will tell us whether these
3000 // function types are obviously different.
3001 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3002 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3003 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3004 return false;
3005
3006 bool HasObjCConversion = false;
3007 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3008 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3009 // Okay, the types match exactly. Nothing to do.
3010 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3011 ToType: ToFunctionType->getReturnType(),
3012 ConvertedType, IncompatibleObjC)) {
3013 // Okay, we have an Objective-C pointer conversion.
3014 HasObjCConversion = true;
3015 } else {
3016 // Function types are too different. Abort.
3017 return false;
3018 }
3019
3020 // Check argument types.
3021 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3022 ArgIdx != NumArgs; ++ArgIdx) {
3023 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3024 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3025 if (Context.getCanonicalType(T: FromArgType)
3026 == Context.getCanonicalType(T: ToArgType)) {
3027 // Okay, the types match exactly. Nothing to do.
3028 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3029 ConvertedType, IncompatibleObjC)) {
3030 // Okay, we have an Objective-C pointer conversion.
3031 HasObjCConversion = true;
3032 } else {
3033 // Argument types are too different. Abort.
3034 return false;
3035 }
3036 }
3037
3038 if (HasObjCConversion) {
3039 // We had an Objective-C conversion. Allow this pointer
3040 // conversion, but complain about it.
3041 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3042 IncompatibleObjC = true;
3043 return true;
3044 }
3045 }
3046
3047 return false;
3048}
3049
3050/// Determine whether this is an Objective-C writeback conversion,
3051/// used for parameter passing when performing automatic reference counting.
3052///
3053/// \param FromType The type we're converting form.
3054///
3055/// \param ToType The type we're converting to.
3056///
3057/// \param ConvertedType The type that will be produced after applying
3058/// this conversion.
3059bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
3060 QualType &ConvertedType) {
3061 if (!getLangOpts().ObjCAutoRefCount ||
3062 Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
3063 return false;
3064
3065 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
3066 QualType ToPointee;
3067 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
3068 ToPointee = ToPointer->getPointeeType();
3069 else
3070 return false;
3071
3072 Qualifiers ToQuals = ToPointee.getQualifiers();
3073 if (!ToPointee->isObjCLifetimeType() ||
3074 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
3075 !ToQuals.withoutObjCLifetime().empty())
3076 return false;
3077
3078 // Argument must be a pointer to __strong to __weak.
3079 QualType FromPointee;
3080 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
3081 FromPointee = FromPointer->getPointeeType();
3082 else
3083 return false;
3084
3085 Qualifiers FromQuals = FromPointee.getQualifiers();
3086 if (!FromPointee->isObjCLifetimeType() ||
3087 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
3088 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
3089 return false;
3090
3091 // Make sure that we have compatible qualifiers.
3092 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
3093 if (!ToQuals.compatiblyIncludes(other: FromQuals))
3094 return false;
3095
3096 // Remove qualifiers from the pointee type we're converting from; they
3097 // aren't used in the compatibility check belong, and we'll be adding back
3098 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
3099 FromPointee = FromPointee.getUnqualifiedType();
3100
3101 // The unqualified form of the pointee types must be compatible.
3102 ToPointee = ToPointee.getUnqualifiedType();
3103 bool IncompatibleObjC;
3104 if (Context.typesAreCompatible(T1: FromPointee, T2: ToPointee))
3105 FromPointee = ToPointee;
3106 else if (!isObjCPointerConversion(FromType: FromPointee, ToType: ToPointee, ConvertedType&: FromPointee,
3107 IncompatibleObjC))
3108 return false;
3109
3110 /// Construct the type we're converting to, which is a pointer to
3111 /// __autoreleasing pointee.
3112 FromPointee = Context.getQualifiedType(T: FromPointee, Qs: FromQuals);
3113 ConvertedType = Context.getPointerType(T: FromPointee);
3114 return true;
3115}
3116
3117bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3118 QualType& ConvertedType) {
3119 QualType ToPointeeType;
3120 if (const BlockPointerType *ToBlockPtr =
3121 ToType->getAs<BlockPointerType>())
3122 ToPointeeType = ToBlockPtr->getPointeeType();
3123 else
3124 return false;
3125
3126 QualType FromPointeeType;
3127 if (const BlockPointerType *FromBlockPtr =
3128 FromType->getAs<BlockPointerType>())
3129 FromPointeeType = FromBlockPtr->getPointeeType();
3130 else
3131 return false;
3132 // We have pointer to blocks, check whether the only
3133 // differences in the argument and result types are in Objective-C
3134 // pointer conversions. If so, we permit the conversion.
3135
3136 const FunctionProtoType *FromFunctionType
3137 = FromPointeeType->getAs<FunctionProtoType>();
3138 const FunctionProtoType *ToFunctionType
3139 = ToPointeeType->getAs<FunctionProtoType>();
3140
3141 if (!FromFunctionType || !ToFunctionType)
3142 return false;
3143
3144 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3145 return true;
3146
3147 // Perform the quick checks that will tell us whether these
3148 // function types are obviously different.
3149 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3150 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3151 return false;
3152
3153 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3154 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3155 if (FromEInfo != ToEInfo)
3156 return false;
3157
3158 bool IncompatibleObjC = false;
3159 if (Context.hasSameType(FromFunctionType->getReturnType(),
3160 ToFunctionType->getReturnType())) {
3161 // Okay, the types match exactly. Nothing to do.
3162 } else {
3163 QualType RHS = FromFunctionType->getReturnType();
3164 QualType LHS = ToFunctionType->getReturnType();
3165 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3166 !RHS.hasQualifiers() && LHS.hasQualifiers())
3167 LHS = LHS.getUnqualifiedType();
3168
3169 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3170 // OK exact match.
3171 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3172 ConvertedType, IncompatibleObjC)) {
3173 if (IncompatibleObjC)
3174 return false;
3175 // Okay, we have an Objective-C pointer conversion.
3176 }
3177 else
3178 return false;
3179 }
3180
3181 // Check argument types.
3182 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3183 ArgIdx != NumArgs; ++ArgIdx) {
3184 IncompatibleObjC = false;
3185 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3186 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3187 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3188 // Okay, the types match exactly. Nothing to do.
3189 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3190 ConvertedType, IncompatibleObjC)) {
3191 if (IncompatibleObjC)
3192 return false;
3193 // Okay, we have an Objective-C pointer conversion.
3194 } else
3195 // Argument types are too different. Abort.
3196 return false;
3197 }
3198
3199 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3200 bool CanUseToFPT, CanUseFromFPT;
3201 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3202 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3203 NewParamInfos))
3204 return false;
3205
3206 ConvertedType = ToType;
3207 return true;
3208}
3209
3210enum {
3211 ft_default,
3212 ft_different_class,
3213 ft_parameter_arity,
3214 ft_parameter_mismatch,
3215 ft_return_type,
3216 ft_qualifer_mismatch,
3217 ft_noexcept
3218};
3219
3220/// Attempts to get the FunctionProtoType from a Type. Handles
3221/// MemberFunctionPointers properly.
3222static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3223 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3224 return FPT;
3225
3226 if (auto *MPT = FromType->getAs<MemberPointerType>())
3227 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3228
3229 return nullptr;
3230}
3231
3232/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3233/// function types. Catches different number of parameter, mismatch in
3234/// parameter types, and different return types.
3235void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3236 QualType FromType, QualType ToType) {
3237 // If either type is not valid, include no extra info.
3238 if (FromType.isNull() || ToType.isNull()) {
3239 PDiag << ft_default;
3240 return;
3241 }
3242
3243 // Get the function type from the pointers.
3244 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3245 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3246 *ToMember = ToType->castAs<MemberPointerType>();
3247 if (!Context.hasSameType(T1: FromMember->getClass(), T2: ToMember->getClass())) {
3248 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3249 << QualType(FromMember->getClass(), 0);
3250 return;
3251 }
3252 FromType = FromMember->getPointeeType();
3253 ToType = ToMember->getPointeeType();
3254 }
3255
3256 if (FromType->isPointerType())
3257 FromType = FromType->getPointeeType();
3258 if (ToType->isPointerType())
3259 ToType = ToType->getPointeeType();
3260
3261 // Remove references.
3262 FromType = FromType.getNonReferenceType();
3263 ToType = ToType.getNonReferenceType();
3264
3265 // Don't print extra info for non-specialized template functions.
3266 if (FromType->isInstantiationDependentType() &&
3267 !FromType->getAs<TemplateSpecializationType>()) {
3268 PDiag << ft_default;
3269 return;
3270 }
3271
3272 // No extra info for same types.
3273 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3274 PDiag << ft_default;
3275 return;
3276 }
3277
3278 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3279 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3280
3281 // Both types need to be function types.
3282 if (!FromFunction || !ToFunction) {
3283 PDiag << ft_default;
3284 return;
3285 }
3286
3287 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3288 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3289 << FromFunction->getNumParams();
3290 return;
3291 }
3292
3293 // Handle different parameter types.
3294 unsigned ArgPos;
3295 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3296 PDiag << ft_parameter_mismatch << ArgPos + 1
3297 << ToFunction->getParamType(i: ArgPos)
3298 << FromFunction->getParamType(i: ArgPos);
3299 return;
3300 }
3301
3302 // Handle different return type.
3303 if (!Context.hasSameType(FromFunction->getReturnType(),
3304 ToFunction->getReturnType())) {
3305 PDiag << ft_return_type << ToFunction->getReturnType()
3306 << FromFunction->getReturnType();
3307 return;
3308 }
3309
3310 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3311 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3312 << FromFunction->getMethodQuals();
3313 return;
3314 }
3315
3316 // Handle exception specification differences on canonical type (in C++17
3317 // onwards).
3318 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3319 ->isNothrow() !=
3320 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3321 ->isNothrow()) {
3322 PDiag << ft_noexcept;
3323 return;
3324 }
3325
3326 // Unable to find a difference, so add no extra info.
3327 PDiag << ft_default;
3328}
3329
3330/// FunctionParamTypesAreEqual - This routine checks two function proto types
3331/// for equality of their parameter types. Caller has already checked that
3332/// they have same number of parameters. If the parameters are different,
3333/// ArgPos will have the parameter index of the first different parameter.
3334/// If `Reversed` is true, the parameters of `NewType` will be compared in
3335/// reverse order. That's useful if one of the functions is being used as a C++20
3336/// synthesized operator overload with a reversed parameter order.
3337bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3338 ArrayRef<QualType> New, unsigned *ArgPos,
3339 bool Reversed) {
3340 assert(llvm::size(Old) == llvm::size(New) &&
3341 "Can't compare parameters of functions with different number of "
3342 "parameters!");
3343
3344 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3345 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3346 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3347
3348 // Ignore address spaces in pointee type. This is to disallow overloading
3349 // on __ptr32/__ptr64 address spaces.
3350 QualType OldType =
3351 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3352 QualType NewType =
3353 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3354
3355 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3356 if (ArgPos)
3357 *ArgPos = Idx;
3358 return false;
3359 }
3360 }
3361 return true;
3362}
3363
3364bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3365 const FunctionProtoType *NewType,
3366 unsigned *ArgPos, bool Reversed) {
3367 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3368 New: NewType->param_types(), ArgPos, Reversed);
3369}
3370
3371bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3372 const FunctionDecl *NewFunction,
3373 unsigned *ArgPos,
3374 bool Reversed) {
3375
3376 if (OldFunction->getNumNonObjectParams() !=
3377 NewFunction->getNumNonObjectParams())
3378 return false;
3379
3380 unsigned OldIgnore =
3381 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3382 unsigned NewIgnore =
3383 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3384
3385 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3386 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3387
3388 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3389 NewPT->param_types().slice(NewIgnore),
3390 ArgPos, Reversed);
3391}
3392
3393/// CheckPointerConversion - Check the pointer conversion from the
3394/// expression From to the type ToType. This routine checks for
3395/// ambiguous or inaccessible derived-to-base pointer
3396/// conversions for which IsPointerConversion has already returned
3397/// true. It returns true and produces a diagnostic if there was an
3398/// error, or returns false otherwise.
3399bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3400 CastKind &Kind,
3401 CXXCastPath& BasePath,
3402 bool IgnoreBaseAccess,
3403 bool Diagnose) {
3404 QualType FromType = From->getType();
3405 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3406
3407 Kind = CK_BitCast;
3408
3409 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3410 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3411 Expr::NPCK_ZeroExpression) {
3412 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3413 DiagRuntimeBehavior(From->getExprLoc(), From,
3414 PDiag(diag::warn_impcast_bool_to_null_pointer)
3415 << ToType << From->getSourceRange());
3416 else if (!isUnevaluatedContext())
3417 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3418 << ToType << From->getSourceRange();
3419 }
3420 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3421 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3422 QualType FromPointeeType = FromPtrType->getPointeeType(),
3423 ToPointeeType = ToPtrType->getPointeeType();
3424
3425 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3426 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3427 // We must have a derived-to-base conversion. Check an
3428 // ambiguous or inaccessible conversion.
3429 unsigned InaccessibleID = 0;
3430 unsigned AmbiguousID = 0;
3431 if (Diagnose) {
3432 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3433 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3434 }
3435 if (CheckDerivedToBaseConversion(
3436 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3437 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3438 &BasePath, IgnoreBaseAccess))
3439 return true;
3440
3441 // The conversion was successful.
3442 Kind = CK_DerivedToBase;
3443 }
3444
3445 if (Diagnose && !IsCStyleOrFunctionalCast &&
3446 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3447 assert(getLangOpts().MSVCCompat &&
3448 "this should only be possible with MSVCCompat!");
3449 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3450 << From->getSourceRange();
3451 }
3452 }
3453 } else if (const ObjCObjectPointerType *ToPtrType =
3454 ToType->getAs<ObjCObjectPointerType>()) {
3455 if (const ObjCObjectPointerType *FromPtrType =
3456 FromType->getAs<ObjCObjectPointerType>()) {
3457 // Objective-C++ conversions are always okay.
3458 // FIXME: We should have a different class of conversions for the
3459 // Objective-C++ implicit conversions.
3460 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3461 return false;
3462 } else if (FromType->isBlockPointerType()) {
3463 Kind = CK_BlockPointerToObjCPointerCast;
3464 } else {
3465 Kind = CK_CPointerToObjCPointerCast;
3466 }
3467 } else if (ToType->isBlockPointerType()) {
3468 if (!FromType->isBlockPointerType())
3469 Kind = CK_AnyPointerToBlockPointerCast;
3470 }
3471
3472 // We shouldn't fall into this case unless it's valid for other
3473 // reasons.
3474 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3475 Kind = CK_NullToPointer;
3476
3477 return false;
3478}
3479
3480/// IsMemberPointerConversion - Determines whether the conversion of the
3481/// expression From, which has the (possibly adjusted) type FromType, can be
3482/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3483/// If so, returns true and places the converted type (that might differ from
3484/// ToType in its cv-qualifiers at some level) into ConvertedType.
3485bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3486 QualType ToType,
3487 bool InOverloadResolution,
3488 QualType &ConvertedType) {
3489 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3490 if (!ToTypePtr)
3491 return false;
3492
3493 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3494 if (From->isNullPointerConstant(Ctx&: Context,
3495 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3496 : Expr::NPC_ValueDependentIsNull)) {
3497 ConvertedType = ToType;
3498 return true;
3499 }
3500
3501 // Otherwise, both types have to be member pointers.
3502 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3503 if (!FromTypePtr)
3504 return false;
3505
3506 // A pointer to member of B can be converted to a pointer to member of D,
3507 // where D is derived from B (C++ 4.11p2).
3508 QualType FromClass(FromTypePtr->getClass(), 0);
3509 QualType ToClass(ToTypePtr->getClass(), 0);
3510
3511 if (!Context.hasSameUnqualifiedType(T1: FromClass, T2: ToClass) &&
3512 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3513 ConvertedType = Context.getMemberPointerType(T: FromTypePtr->getPointeeType(),
3514 Cls: ToClass.getTypePtr());
3515 return true;
3516 }
3517
3518 return false;
3519}
3520
3521/// CheckMemberPointerConversion - Check the member pointer conversion from the
3522/// expression From to the type ToType. This routine checks for ambiguous or
3523/// virtual or inaccessible base-to-derived member pointer conversions
3524/// for which IsMemberPointerConversion has already returned true. It returns
3525/// true and produces a diagnostic if there was an error, or returns false
3526/// otherwise.
3527bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3528 CastKind &Kind,
3529 CXXCastPath &BasePath,
3530 bool IgnoreBaseAccess) {
3531 QualType FromType = From->getType();
3532 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3533 if (!FromPtrType) {
3534 // This must be a null pointer to member pointer conversion
3535 assert(From->isNullPointerConstant(Context,
3536 Expr::NPC_ValueDependentIsNull) &&
3537 "Expr must be null pointer constant!");
3538 Kind = CK_NullToMemberPointer;
3539 return false;
3540 }
3541
3542 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3543 assert(ToPtrType && "No member pointer cast has a target type "
3544 "that is not a member pointer.");
3545
3546 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3547 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3548
3549 // FIXME: What about dependent types?
3550 assert(FromClass->isRecordType() && "Pointer into non-class.");
3551 assert(ToClass->isRecordType() && "Pointer into non-class.");
3552
3553 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3554 /*DetectVirtual=*/true);
3555 bool DerivationOkay =
3556 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3557 assert(DerivationOkay &&
3558 "Should not have been called if derivation isn't OK.");
3559 (void)DerivationOkay;
3560
3561 if (Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: FromClass).
3562 getUnqualifiedType())) {
3563 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3564 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3565 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3566 return true;
3567 }
3568
3569 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3570 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3571 << FromClass << ToClass << QualType(VBase, 0)
3572 << From->getSourceRange();
3573 return true;
3574 }
3575
3576 if (!IgnoreBaseAccess)
3577 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3578 Paths.front(),
3579 diag::err_downcast_from_inaccessible_base);
3580
3581 // Must be a base to derived member conversion.
3582 BuildBasePathArray(Paths, BasePath);
3583 Kind = CK_BaseToDerivedMemberPointer;
3584 return false;
3585}
3586
3587/// Determine whether the lifetime conversion between the two given
3588/// qualifiers sets is nontrivial.
3589static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3590 Qualifiers ToQuals) {
3591 // Converting anything to const __unsafe_unretained is trivial.
3592 if (ToQuals.hasConst() &&
3593 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3594 return false;
3595
3596 return true;
3597}
3598
3599/// Perform a single iteration of the loop for checking if a qualification
3600/// conversion is valid.
3601///
3602/// Specifically, check whether any change between the qualifiers of \p
3603/// FromType and \p ToType is permissible, given knowledge about whether every
3604/// outer layer is const-qualified.
3605static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3606 bool CStyle, bool IsTopLevel,
3607 bool &PreviousToQualsIncludeConst,
3608 bool &ObjCLifetimeConversion) {
3609 Qualifiers FromQuals = FromType.getQualifiers();
3610 Qualifiers ToQuals = ToType.getQualifiers();
3611
3612 // Ignore __unaligned qualifier.
3613 FromQuals.removeUnaligned();
3614
3615 // Objective-C ARC:
3616 // Check Objective-C lifetime conversions.
3617 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3618 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3619 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3620 ObjCLifetimeConversion = true;
3621 FromQuals.removeObjCLifetime();
3622 ToQuals.removeObjCLifetime();
3623 } else {
3624 // Qualification conversions cannot cast between different
3625 // Objective-C lifetime qualifiers.
3626 return false;
3627 }
3628 }
3629
3630 // Allow addition/removal of GC attributes but not changing GC attributes.
3631 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3632 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3633 FromQuals.removeObjCGCAttr();
3634 ToQuals.removeObjCGCAttr();
3635 }
3636
3637 // -- for every j > 0, if const is in cv 1,j then const is in cv
3638 // 2,j, and similarly for volatile.
3639 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals))
3640 return false;
3641
3642 // If address spaces mismatch:
3643 // - in top level it is only valid to convert to addr space that is a
3644 // superset in all cases apart from C-style casts where we allow
3645 // conversions between overlapping address spaces.
3646 // - in non-top levels it is not a valid conversion.
3647 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3648 (!IsTopLevel ||
3649 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals) ||
3650 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals)))))
3651 return false;
3652
3653 // -- if the cv 1,j and cv 2,j are different, then const is in
3654 // every cv for 0 < k < j.
3655 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3656 !PreviousToQualsIncludeConst)
3657 return false;
3658
3659 // The following wording is from C++20, where the result of the conversion
3660 // is T3, not T2.
3661 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3662 // "array of unknown bound of"
3663 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3664 return false;
3665
3666 // -- if the resulting P3,i is different from P1,i [...], then const is
3667 // added to every cv 3_k for 0 < k < i.
3668 if (!CStyle && FromType->isConstantArrayType() &&
3669 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3670 return false;
3671
3672 // Keep track of whether all prior cv-qualifiers in the "to" type
3673 // include const.
3674 PreviousToQualsIncludeConst =
3675 PreviousToQualsIncludeConst && ToQuals.hasConst();
3676 return true;
3677}
3678
3679/// IsQualificationConversion - Determines whether the conversion from
3680/// an rvalue of type FromType to ToType is a qualification conversion
3681/// (C++ 4.4).
3682///
3683/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3684/// when the qualification conversion involves a change in the Objective-C
3685/// object lifetime.
3686bool
3687Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3688 bool CStyle, bool &ObjCLifetimeConversion) {
3689 FromType = Context.getCanonicalType(T: FromType);
3690 ToType = Context.getCanonicalType(T: ToType);
3691 ObjCLifetimeConversion = false;
3692
3693 // If FromType and ToType are the same type, this is not a
3694 // qualification conversion.
3695 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3696 return false;
3697
3698 // (C++ 4.4p4):
3699 // A conversion can add cv-qualifiers at levels other than the first
3700 // in multi-level pointers, subject to the following rules: [...]
3701 bool PreviousToQualsIncludeConst = true;
3702 bool UnwrappedAnyPointer = false;
3703 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3704 if (!isQualificationConversionStep(
3705 FromType, ToType, CStyle, IsTopLevel: !UnwrappedAnyPointer,
3706 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3707 return false;
3708 UnwrappedAnyPointer = true;
3709 }
3710
3711 // We are left with FromType and ToType being the pointee types
3712 // after unwrapping the original FromType and ToType the same number
3713 // of times. If we unwrapped any pointers, and if FromType and
3714 // ToType have the same unqualified type (since we checked
3715 // qualifiers above), then this is a qualification conversion.
3716 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3717}
3718
3719/// - Determine whether this is a conversion from a scalar type to an
3720/// atomic type.
3721///
3722/// If successful, updates \c SCS's second and third steps in the conversion
3723/// sequence to finish the conversion.
3724static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3725 bool InOverloadResolution,
3726 StandardConversionSequence &SCS,
3727 bool CStyle) {
3728 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3729 if (!ToAtomic)
3730 return false;
3731
3732 StandardConversionSequence InnerSCS;
3733 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3734 InOverloadResolution, SCS&: InnerSCS,
3735 CStyle, /*AllowObjCWritebackConversion=*/false))
3736 return false;
3737
3738 SCS.Second = InnerSCS.Second;
3739 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3740 SCS.Third = InnerSCS.Third;
3741 SCS.QualificationIncludesObjCLifetime
3742 = InnerSCS.QualificationIncludesObjCLifetime;
3743 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3744 return true;
3745}
3746
3747static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3748 CXXConstructorDecl *Constructor,
3749 QualType Type) {
3750 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3751 if (CtorType->getNumParams() > 0) {
3752 QualType FirstArg = CtorType->getParamType(0);
3753 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
3754 return true;
3755 }
3756 return false;
3757}
3758
3759static OverloadingResult
3760IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3761 CXXRecordDecl *To,
3762 UserDefinedConversionSequence &User,
3763 OverloadCandidateSet &CandidateSet,
3764 bool AllowExplicit) {
3765 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3766 for (auto *D : S.LookupConstructors(Class: To)) {
3767 auto Info = getConstructorInfo(ND: D);
3768 if (!Info)
3769 continue;
3770
3771 bool Usable = !Info.Constructor->isInvalidDecl() &&
3772 S.isInitListConstructor(Info.Constructor);
3773 if (Usable) {
3774 bool SuppressUserConversions = false;
3775 if (Info.ConstructorTmpl)
3776 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3777 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
3778 CandidateSet, SuppressUserConversions,
3779 /*PartialOverloading*/ false,
3780 AllowExplicit);
3781 else
3782 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3783 CandidateSet, SuppressUserConversions,
3784 /*PartialOverloading*/ false, AllowExplicit);
3785 }
3786 }
3787
3788 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3789
3790 OverloadCandidateSet::iterator Best;
3791 switch (auto Result =
3792 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3793 case OR_Deleted:
3794 case OR_Success: {
3795 // Record the standard conversion we used and the conversion function.
3796 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
3797 QualType ThisType = Constructor->getFunctionObjectParameterType();
3798 // Initializer lists don't have conversions as such.
3799 User.Before.setAsIdentityConversion();
3800 User.HadMultipleCandidates = HadMultipleCandidates;
3801 User.ConversionFunction = Constructor;
3802 User.FoundConversionFunction = Best->FoundDecl;
3803 User.After.setAsIdentityConversion();
3804 User.After.setFromType(ThisType);
3805 User.After.setAllToTypes(ToType);
3806 return Result;
3807 }
3808
3809 case OR_No_Viable_Function:
3810 return OR_No_Viable_Function;
3811 case OR_Ambiguous:
3812 return OR_Ambiguous;
3813 }
3814
3815 llvm_unreachable("Invalid OverloadResult!");
3816}
3817
3818/// Determines whether there is a user-defined conversion sequence
3819/// (C++ [over.ics.user]) that converts expression From to the type
3820/// ToType. If such a conversion exists, User will contain the
3821/// user-defined conversion sequence that performs such a conversion
3822/// and this routine will return true. Otherwise, this routine returns
3823/// false and User is unspecified.
3824///
3825/// \param AllowExplicit true if the conversion should consider C++0x
3826/// "explicit" conversion functions as well as non-explicit conversion
3827/// functions (C++0x [class.conv.fct]p2).
3828///
3829/// \param AllowObjCConversionOnExplicit true if the conversion should
3830/// allow an extra Objective-C pointer conversion on uses of explicit
3831/// constructors. Requires \c AllowExplicit to also be set.
3832static OverloadingResult
3833IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3834 UserDefinedConversionSequence &User,
3835 OverloadCandidateSet &CandidateSet,
3836 AllowedExplicit AllowExplicit,
3837 bool AllowObjCConversionOnExplicit) {
3838 assert(AllowExplicit != AllowedExplicit::None ||
3839 !AllowObjCConversionOnExplicit);
3840 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3841
3842 // Whether we will only visit constructors.
3843 bool ConstructorsOnly = false;
3844
3845 // If the type we are conversion to is a class type, enumerate its
3846 // constructors.
3847 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3848 // C++ [over.match.ctor]p1:
3849 // When objects of class type are direct-initialized (8.5), or
3850 // copy-initialized from an expression of the same or a
3851 // derived class type (8.5), overload resolution selects the
3852 // constructor. [...] For copy-initialization, the candidate
3853 // functions are all the converting constructors (12.3.1) of
3854 // that class. The argument list is the expression-list within
3855 // the parentheses of the initializer.
3856 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
3857 (From->getType()->getAs<RecordType>() &&
3858 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3859 ConstructorsOnly = true;
3860
3861 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
3862 // We're not going to find any constructors.
3863 } else if (CXXRecordDecl *ToRecordDecl
3864 = dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
3865
3866 Expr **Args = &From;
3867 unsigned NumArgs = 1;
3868 bool ListInitializing = false;
3869 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
3870 // But first, see if there is an init-list-constructor that will work.
3871 OverloadingResult Result = IsInitializerListConstructorConversion(
3872 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
3873 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3874 if (Result != OR_No_Viable_Function)
3875 return Result;
3876 // Never mind.
3877 CandidateSet.clear(
3878 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3879
3880 // If we're list-initializing, we pass the individual elements as
3881 // arguments, not the entire list.
3882 Args = InitList->getInits();
3883 NumArgs = InitList->getNumInits();
3884 ListInitializing = true;
3885 }
3886
3887 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
3888 auto Info = getConstructorInfo(ND: D);
3889 if (!Info)
3890 continue;
3891
3892 bool Usable = !Info.Constructor->isInvalidDecl();
3893 if (!ListInitializing)
3894 Usable = Usable && Info.Constructor->isConvertingConstructor(
3895 /*AllowExplicit*/ true);
3896 if (Usable) {
3897 bool SuppressUserConversions = !ConstructorsOnly;
3898 // C++20 [over.best.ics.general]/4.5:
3899 // if the target is the first parameter of a constructor [of class
3900 // X] and the constructor [...] is a candidate by [...] the second
3901 // phase of [over.match.list] when the initializer list has exactly
3902 // one element that is itself an initializer list, [...] and the
3903 // conversion is to X or reference to cv X, user-defined conversion
3904 // sequences are not cnosidered.
3905 if (SuppressUserConversions && ListInitializing) {
3906 SuppressUserConversions =
3907 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
3908 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
3909 Type: ToType);
3910 }
3911 if (Info.ConstructorTmpl)
3912 S.AddTemplateOverloadCandidate(
3913 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3914 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
3915 CandidateSet, SuppressUserConversions,
3916 /*PartialOverloading*/ false,
3917 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3918 else
3919 // Allow one user-defined conversion when user specifies a
3920 // From->ToType conversion via an static cast (c-style, etc).
3921 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3922 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3923 SuppressUserConversions,
3924 /*PartialOverloading*/ false,
3925 AllowExplicit == AllowedExplicit::All);
3926 }
3927 }
3928 }
3929 }
3930
3931 // Enumerate conversion functions, if we're allowed to.
3932 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
3933 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
3934 // No conversion functions from incomplete types.
3935 } else if (const RecordType *FromRecordType =
3936 From->getType()->getAs<RecordType>()) {
3937 if (CXXRecordDecl *FromRecordDecl
3938 = dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
3939 // Add all of the conversion functions as candidates.
3940 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3941 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3942 DeclAccessPair FoundDecl = I.getPair();
3943 NamedDecl *D = FoundDecl.getDecl();
3944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3945 if (isa<UsingShadowDecl>(Val: D))
3946 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
3947
3948 CXXConversionDecl *Conv;
3949 FunctionTemplateDecl *ConvTemplate;
3950 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
3951 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
3952 else
3953 Conv = cast<CXXConversionDecl>(Val: D);
3954
3955 if (ConvTemplate)
3956 S.AddTemplateConversionCandidate(
3957 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
3958 CandidateSet, AllowObjCConversionOnExplicit,
3959 AllowExplicit: AllowExplicit != AllowedExplicit::None);
3960 else
3961 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
3962 CandidateSet, AllowObjCConversionOnExplicit,
3963 AllowExplicit: AllowExplicit != AllowedExplicit::None);
3964 }
3965 }
3966 }
3967
3968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3969
3970 OverloadCandidateSet::iterator Best;
3971 switch (auto Result =
3972 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3973 case OR_Success:
3974 case OR_Deleted:
3975 // Record the standard conversion we used and the conversion function.
3976 if (CXXConstructorDecl *Constructor
3977 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
3978 // C++ [over.ics.user]p1:
3979 // If the user-defined conversion is specified by a
3980 // constructor (12.3.1), the initial standard conversion
3981 // sequence converts the source type to the type required by
3982 // the argument of the constructor.
3983 //
3984 if (isa<InitListExpr>(Val: From)) {
3985 // Initializer lists don't have conversions as such.
3986 User.Before.setAsIdentityConversion();
3987 } else {
3988 if (Best->Conversions[0].isEllipsis())
3989 User.EllipsisConversion = true;
3990 else {
3991 User.Before = Best->Conversions[0].Standard;
3992 User.EllipsisConversion = false;
3993 }
3994 }
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3996 User.ConversionFunction = Constructor;
3997 User.FoundConversionFunction = Best->FoundDecl;
3998 User.After.setAsIdentityConversion();
3999 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003 if (CXXConversionDecl *Conversion
4004 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4005 // C++ [over.ics.user]p1:
4006 //
4007 // [...] If the user-defined conversion is specified by a
4008 // conversion function (12.3.2), the initial standard
4009 // conversion sequence converts the source type to the
4010 // implicit object parameter of the conversion function.
4011 User.Before = Best->Conversions[0].Standard;
4012 User.HadMultipleCandidates = HadMultipleCandidates;
4013 User.ConversionFunction = Conversion;
4014 User.FoundConversionFunction = Best->FoundDecl;
4015 User.EllipsisConversion = false;
4016
4017 // C++ [over.ics.user]p2:
4018 // The second standard conversion sequence converts the
4019 // result of the user-defined conversion to the target type
4020 // for the sequence. Since an implicit conversion sequence
4021 // is an initialization, the special rules for
4022 // initialization by user-defined conversion apply when
4023 // selecting the best user-defined conversion for a
4024 // user-defined conversion sequence (see 13.3.3 and
4025 // 13.3.3.1).
4026 User.After = Best->FinalConversion;
4027 return Result;
4028 }
4029 llvm_unreachable("Not a constructor or conversion function?");
4030
4031 case OR_No_Viable_Function:
4032 return OR_No_Viable_Function;
4033
4034 case OR_Ambiguous:
4035 return OR_Ambiguous;
4036 }
4037
4038 llvm_unreachable("Invalid OverloadResult!");
4039}
4040
4041bool
4042Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4043 ImplicitConversionSequence ICS;
4044 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4045 OverloadCandidateSet::CSK_Normal);
4046 OverloadingResult OvResult =
4047 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4048 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4049
4050 if (!(OvResult == OR_Ambiguous ||
4051 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4052 return false;
4053
4054 auto Cands = CandidateSet.CompleteCandidates(
4055 S&: *this,
4056 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4057 Args: From);
4058 if (OvResult == OR_Ambiguous)
4059 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4060 << From->getType() << ToType << From->getSourceRange();
4061 else { // OR_No_Viable_Function && !CandidateSet.empty()
4062 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4063 diag::err_typecheck_nonviable_condition_incomplete,
4064 From->getType(), From->getSourceRange()))
4065 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4066 << false << From->getType() << From->getSourceRange() << ToType;
4067 }
4068
4069 CandidateSet.NoteCandidates(
4070 S&: *this, Args: From, Cands);
4071 return true;
4072}
4073
4074// Helper for compareConversionFunctions that gets the FunctionType that the
4075// conversion-operator return value 'points' to, or nullptr.
4076static const FunctionType *
4077getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4078 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4079 const PointerType *RetPtrTy =
4080 ConvFuncTy->getReturnType()->getAs<PointerType>();
4081
4082 if (!RetPtrTy)
4083 return nullptr;
4084
4085 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4086}
4087
4088/// Compare the user-defined conversion functions or constructors
4089/// of two user-defined conversion sequences to determine whether any ordering
4090/// is possible.
4091static ImplicitConversionSequence::CompareKind
4092compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4093 FunctionDecl *Function2) {
4094 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4095 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4096 if (!Conv1 || !Conv2)
4097 return ImplicitConversionSequence::Indistinguishable;
4098
4099 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4100 return ImplicitConversionSequence::Indistinguishable;
4101
4102 // Objective-C++:
4103 // If both conversion functions are implicitly-declared conversions from
4104 // a lambda closure type to a function pointer and a block pointer,
4105 // respectively, always prefer the conversion to a function pointer,
4106 // because the function pointer is more lightweight and is more likely
4107 // to keep code working.
4108 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4109 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4110 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4111 if (Block1 != Block2)
4112 return Block1 ? ImplicitConversionSequence::Worse
4113 : ImplicitConversionSequence::Better;
4114 }
4115
4116 // In order to support multiple calling conventions for the lambda conversion
4117 // operator (such as when the free and member function calling convention is
4118 // different), prefer the 'free' mechanism, followed by the calling-convention
4119 // of operator(). The latter is in place to support the MSVC-like solution of
4120 // defining ALL of the possible conversions in regards to calling-convention.
4121 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4122 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4123
4124 if (Conv1FuncRet && Conv2FuncRet &&
4125 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4126 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4127 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4128
4129 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4130 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4131
4132 CallingConv CallOpCC =
4133 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4134 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4135 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4136 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4137 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4138
4139 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4140 for (CallingConv CC : PrefOrder) {
4141 if (Conv1CC == CC)
4142 return ImplicitConversionSequence::Better;
4143 if (Conv2CC == CC)
4144 return ImplicitConversionSequence::Worse;
4145 }
4146 }
4147
4148 return ImplicitConversionSequence::Indistinguishable;
4149}
4150
4151static bool hasDeprecatedStringLiteralToCharPtrConversion(
4152 const ImplicitConversionSequence &ICS) {
4153 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4154 (ICS.isUserDefined() &&
4155 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4156}
4157
4158/// CompareImplicitConversionSequences - Compare two implicit
4159/// conversion sequences to determine whether one is better than the
4160/// other or if they are indistinguishable (C++ 13.3.3.2).
4161static ImplicitConversionSequence::CompareKind
4162CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4163 const ImplicitConversionSequence& ICS1,
4164 const ImplicitConversionSequence& ICS2)
4165{
4166 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4167 // conversion sequences (as defined in 13.3.3.1)
4168 // -- a standard conversion sequence (13.3.3.1.1) is a better
4169 // conversion sequence than a user-defined conversion sequence or
4170 // an ellipsis conversion sequence, and
4171 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4172 // conversion sequence than an ellipsis conversion sequence
4173 // (13.3.3.1.3).
4174 //
4175 // C++0x [over.best.ics]p10:
4176 // For the purpose of ranking implicit conversion sequences as
4177 // described in 13.3.3.2, the ambiguous conversion sequence is
4178 // treated as a user-defined sequence that is indistinguishable
4179 // from any other user-defined conversion sequence.
4180
4181 // String literal to 'char *' conversion has been deprecated in C++03. It has
4182 // been removed from C++11. We still accept this conversion, if it happens at
4183 // the best viable function. Otherwise, this conversion is considered worse
4184 // than ellipsis conversion. Consider this as an extension; this is not in the
4185 // standard. For example:
4186 //
4187 // int &f(...); // #1
4188 // void f(char*); // #2
4189 // void g() { int &r = f("foo"); }
4190 //
4191 // In C++03, we pick #2 as the best viable function.
4192 // In C++11, we pick #1 as the best viable function, because ellipsis
4193 // conversion is better than string-literal to char* conversion (since there
4194 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4195 // convert arguments, #2 would be the best viable function in C++11.
4196 // If the best viable function has this conversion, a warning will be issued
4197 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4198
4199 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4200 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4201 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4202 // Ill-formedness must not differ
4203 ICS1.isBad() == ICS2.isBad())
4204 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4205 ? ImplicitConversionSequence::Worse
4206 : ImplicitConversionSequence::Better;
4207
4208 if (ICS1.getKindRank() < ICS2.getKindRank())
4209 return ImplicitConversionSequence::Better;
4210 if (ICS2.getKindRank() < ICS1.getKindRank())
4211 return ImplicitConversionSequence::Worse;
4212
4213 // The following checks require both conversion sequences to be of
4214 // the same kind.
4215 if (ICS1.getKind() != ICS2.getKind())
4216 return ImplicitConversionSequence::Indistinguishable;
4217
4218 ImplicitConversionSequence::CompareKind Result =
4219 ImplicitConversionSequence::Indistinguishable;
4220
4221 // Two implicit conversion sequences of the same form are
4222 // indistinguishable conversion sequences unless one of the
4223 // following rules apply: (C++ 13.3.3.2p3):
4224
4225 // List-initialization sequence L1 is a better conversion sequence than
4226 // list-initialization sequence L2 if:
4227 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4228 // if not that,
4229 // — L1 and L2 convert to arrays of the same element type, and either the
4230 // number of elements n_1 initialized by L1 is less than the number of
4231 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4232 // an array of unknown bound and L1 does not,
4233 // even if one of the other rules in this paragraph would otherwise apply.
4234 if (!ICS1.isBad()) {
4235 bool StdInit1 = false, StdInit2 = false;
4236 if (ICS1.hasInitializerListContainerType())
4237 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4238 Element: nullptr);
4239 if (ICS2.hasInitializerListContainerType())
4240 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4241 Element: nullptr);
4242 if (StdInit1 != StdInit2)
4243 return StdInit1 ? ImplicitConversionSequence::Better
4244 : ImplicitConversionSequence::Worse;
4245
4246 if (ICS1.hasInitializerListContainerType() &&
4247 ICS2.hasInitializerListContainerType())
4248 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4249 T: ICS1.getInitializerListContainerType()))
4250 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4251 T: ICS2.getInitializerListContainerType())) {
4252 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4253 T2: CAT2->getElementType())) {
4254 // Both to arrays of the same element type
4255 if (CAT1->getSize() != CAT2->getSize())
4256 // Different sized, the smaller wins
4257 return CAT1->getSize().ult(RHS: CAT2->getSize())
4258 ? ImplicitConversionSequence::Better
4259 : ImplicitConversionSequence::Worse;
4260 if (ICS1.isInitializerListOfIncompleteArray() !=
4261 ICS2.isInitializerListOfIncompleteArray())
4262 // One is incomplete, it loses
4263 return ICS2.isInitializerListOfIncompleteArray()
4264 ? ImplicitConversionSequence::Better
4265 : ImplicitConversionSequence::Worse;
4266 }
4267 }
4268 }
4269
4270 if (ICS1.isStandard())
4271 // Standard conversion sequence S1 is a better conversion sequence than
4272 // standard conversion sequence S2 if [...]
4273 Result = CompareStandardConversionSequences(S, Loc,
4274 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4275 else if (ICS1.isUserDefined()) {
4276 // User-defined conversion sequence U1 is a better conversion
4277 // sequence than another user-defined conversion sequence U2 if
4278 // they contain the same user-defined conversion function or
4279 // constructor and if the second standard conversion sequence of
4280 // U1 is better than the second standard conversion sequence of
4281 // U2 (C++ 13.3.3.2p3).
4282 if (ICS1.UserDefined.ConversionFunction ==
4283 ICS2.UserDefined.ConversionFunction)
4284 Result = CompareStandardConversionSequences(S, Loc,
4285 SCS1: ICS1.UserDefined.After,
4286 SCS2: ICS2.UserDefined.After);
4287 else
4288 Result = compareConversionFunctions(S,
4289 Function1: ICS1.UserDefined.ConversionFunction,
4290 Function2: ICS2.UserDefined.ConversionFunction);
4291 }
4292
4293 return Result;
4294}
4295
4296// Per 13.3.3.2p3, compare the given standard conversion sequences to
4297// determine if one is a proper subset of the other.
4298static ImplicitConversionSequence::CompareKind
4299compareStandardConversionSubsets(ASTContext &Context,
4300 const StandardConversionSequence& SCS1,
4301 const StandardConversionSequence& SCS2) {
4302 ImplicitConversionSequence::CompareKind Result
4303 = ImplicitConversionSequence::Indistinguishable;
4304
4305 // the identity conversion sequence is considered to be a subsequence of
4306 // any non-identity conversion sequence
4307 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4308 return ImplicitConversionSequence::Better;
4309 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4310 return ImplicitConversionSequence::Worse;
4311
4312 if (SCS1.Second != SCS2.Second) {
4313 if (SCS1.Second == ICK_Identity)
4314 Result = ImplicitConversionSequence::Better;
4315 else if (SCS2.Second == ICK_Identity)
4316 Result = ImplicitConversionSequence::Worse;
4317 else
4318 return ImplicitConversionSequence::Indistinguishable;
4319 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4320 return ImplicitConversionSequence::Indistinguishable;
4321
4322 if (SCS1.Third == SCS2.Third) {
4323 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4324 : ImplicitConversionSequence::Indistinguishable;
4325 }
4326
4327 if (SCS1.Third == ICK_Identity)
4328 return Result == ImplicitConversionSequence::Worse
4329 ? ImplicitConversionSequence::Indistinguishable
4330 : ImplicitConversionSequence::Better;
4331
4332 if (SCS2.Third == ICK_Identity)
4333 return Result == ImplicitConversionSequence::Better
4334 ? ImplicitConversionSequence::Indistinguishable
4335 : ImplicitConversionSequence::Worse;
4336
4337 return ImplicitConversionSequence::Indistinguishable;
4338}
4339
4340/// Determine whether one of the given reference bindings is better
4341/// than the other based on what kind of bindings they are.
4342static bool
4343isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4344 const StandardConversionSequence &SCS2) {
4345 // C++0x [over.ics.rank]p3b4:
4346 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4347 // implicit object parameter of a non-static member function declared
4348 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4349 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4350 // lvalue reference to a function lvalue and S2 binds an rvalue
4351 // reference*.
4352 //
4353 // FIXME: Rvalue references. We're going rogue with the above edits,
4354 // because the semantics in the current C++0x working paper (N3225 at the
4355 // time of this writing) break the standard definition of std::forward
4356 // and std::reference_wrapper when dealing with references to functions.
4357 // Proposed wording changes submitted to CWG for consideration.
4358 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4359 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4360 return false;
4361
4362 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4363 SCS2.IsLvalueReference) ||
4364 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4365 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4366}
4367
4368enum class FixedEnumPromotion {
4369 None,
4370 ToUnderlyingType,
4371 ToPromotedUnderlyingType
4372};
4373
4374/// Returns kind of fixed enum promotion the \a SCS uses.
4375static FixedEnumPromotion
4376getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4377
4378 if (SCS.Second != ICK_Integral_Promotion)
4379 return FixedEnumPromotion::None;
4380
4381 QualType FromType = SCS.getFromType();
4382 if (!FromType->isEnumeralType())
4383 return FixedEnumPromotion::None;
4384
4385 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4386 if (!Enum->isFixed())
4387 return FixedEnumPromotion::None;
4388
4389 QualType UnderlyingType = Enum->getIntegerType();
4390 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4391 return FixedEnumPromotion::ToUnderlyingType;
4392
4393 return FixedEnumPromotion::ToPromotedUnderlyingType;
4394}
4395
4396/// CompareStandardConversionSequences - Compare two standard
4397/// conversion sequences to determine whether one is better than the
4398/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4399static ImplicitConversionSequence::CompareKind
4400CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4401 const StandardConversionSequence& SCS1,
4402 const StandardConversionSequence& SCS2)
4403{
4404 // Standard conversion sequence S1 is a better conversion sequence
4405 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4406
4407 // -- S1 is a proper subsequence of S2 (comparing the conversion
4408 // sequences in the canonical form defined by 13.3.3.1.1,
4409 // excluding any Lvalue Transformation; the identity conversion
4410 // sequence is considered to be a subsequence of any
4411 // non-identity conversion sequence) or, if not that,
4412 if (ImplicitConversionSequence::CompareKind CK
4413 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4414 return CK;
4415
4416 // -- the rank of S1 is better than the rank of S2 (by the rules
4417 // defined below), or, if not that,
4418 ImplicitConversionRank Rank1 = SCS1.getRank();
4419 ImplicitConversionRank Rank2 = SCS2.getRank();
4420 if (Rank1 < Rank2)
4421 return ImplicitConversionSequence::Better;
4422 else if (Rank2 < Rank1)
4423 return ImplicitConversionSequence::Worse;
4424
4425 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4426 // are indistinguishable unless one of the following rules
4427 // applies:
4428
4429 // A conversion that is not a conversion of a pointer, or
4430 // pointer to member, to bool is better than another conversion
4431 // that is such a conversion.
4432 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4433 return SCS2.isPointerConversionToBool()
4434 ? ImplicitConversionSequence::Better
4435 : ImplicitConversionSequence::Worse;
4436
4437 // C++14 [over.ics.rank]p4b2:
4438 // This is retroactively applied to C++11 by CWG 1601.
4439 //
4440 // A conversion that promotes an enumeration whose underlying type is fixed
4441 // to its underlying type is better than one that promotes to the promoted
4442 // underlying type, if the two are different.
4443 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4444 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4445 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4446 FEP1 != FEP2)
4447 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4448 ? ImplicitConversionSequence::Better
4449 : ImplicitConversionSequence::Worse;
4450
4451 // C++ [over.ics.rank]p4b2:
4452 //
4453 // If class B is derived directly or indirectly from class A,
4454 // conversion of B* to A* is better than conversion of B* to
4455 // void*, and conversion of A* to void* is better than conversion
4456 // of B* to void*.
4457 bool SCS1ConvertsToVoid
4458 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4459 bool SCS2ConvertsToVoid
4460 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4461 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4462 // Exactly one of the conversion sequences is a conversion to
4463 // a void pointer; it's the worse conversion.
4464 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4465 : ImplicitConversionSequence::Worse;
4466 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4467 // Neither conversion sequence converts to a void pointer; compare
4468 // their derived-to-base conversions.
4469 if (ImplicitConversionSequence::CompareKind DerivedCK
4470 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4471 return DerivedCK;
4472 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4473 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4474 // Both conversion sequences are conversions to void
4475 // pointers. Compare the source types to determine if there's an
4476 // inheritance relationship in their sources.
4477 QualType FromType1 = SCS1.getFromType();
4478 QualType FromType2 = SCS2.getFromType();
4479
4480 // Adjust the types we're converting from via the array-to-pointer
4481 // conversion, if we need to.
4482 if (SCS1.First == ICK_Array_To_Pointer)
4483 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4484 if (SCS2.First == ICK_Array_To_Pointer)
4485 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4486
4487 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4488 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4489
4490 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4491 return ImplicitConversionSequence::Better;
4492 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4493 return ImplicitConversionSequence::Worse;
4494
4495 // Objective-C++: If one interface is more specific than the
4496 // other, it is the better one.
4497 const ObjCObjectPointerType* FromObjCPtr1
4498 = FromType1->getAs<ObjCObjectPointerType>();
4499 const ObjCObjectPointerType* FromObjCPtr2
4500 = FromType2->getAs<ObjCObjectPointerType>();
4501 if (FromObjCPtr1 && FromObjCPtr2) {
4502 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4503 RHSOPT: FromObjCPtr2);
4504 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4505 RHSOPT: FromObjCPtr1);
4506 if (AssignLeft != AssignRight) {
4507 return AssignLeft? ImplicitConversionSequence::Better
4508 : ImplicitConversionSequence::Worse;
4509 }
4510 }
4511 }
4512
4513 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4514 // Check for a better reference binding based on the kind of bindings.
4515 if (isBetterReferenceBindingKind(SCS1, SCS2))
4516 return ImplicitConversionSequence::Better;
4517 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4518 return ImplicitConversionSequence::Worse;
4519 }
4520
4521 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4522 // bullet 3).
4523 if (ImplicitConversionSequence::CompareKind QualCK
4524 = CompareQualificationConversions(S, SCS1, SCS2))
4525 return QualCK;
4526
4527 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4528 // C++ [over.ics.rank]p3b4:
4529 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4530 // which the references refer are the same type except for
4531 // top-level cv-qualifiers, and the type to which the reference
4532 // initialized by S2 refers is more cv-qualified than the type
4533 // to which the reference initialized by S1 refers.
4534 QualType T1 = SCS1.getToType(Idx: 2);
4535 QualType T2 = SCS2.getToType(Idx: 2);
4536 T1 = S.Context.getCanonicalType(T: T1);
4537 T2 = S.Context.getCanonicalType(T: T2);
4538 Qualifiers T1Quals, T2Quals;
4539 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4540 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4541 if (UnqualT1 == UnqualT2) {
4542 // Objective-C++ ARC: If the references refer to objects with different
4543 // lifetimes, prefer bindings that don't change lifetime.
4544 if (SCS1.ObjCLifetimeConversionBinding !=
4545 SCS2.ObjCLifetimeConversionBinding) {
4546 return SCS1.ObjCLifetimeConversionBinding
4547 ? ImplicitConversionSequence::Worse
4548 : ImplicitConversionSequence::Better;
4549 }
4550
4551 // If the type is an array type, promote the element qualifiers to the
4552 // type for comparison.
4553 if (isa<ArrayType>(Val: T1) && T1Quals)
4554 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4555 if (isa<ArrayType>(Val: T2) && T2Quals)
4556 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4557 if (T2.isMoreQualifiedThan(other: T1))
4558 return ImplicitConversionSequence::Better;
4559 if (T1.isMoreQualifiedThan(other: T2))
4560 return ImplicitConversionSequence::Worse;
4561 }
4562 }
4563
4564 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4565 // floating-to-integral conversion if the integral conversion
4566 // is between types of the same size.
4567 // For example:
4568 // void f(float);
4569 // void f(int);
4570 // int main {
4571 // long a;
4572 // f(a);
4573 // }
4574 // Here, MSVC will call f(int) instead of generating a compile error
4575 // as clang will do in standard mode.
4576 if (S.getLangOpts().MSVCCompat &&
4577 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4578 SCS1.Second == ICK_Integral_Conversion &&
4579 SCS2.Second == ICK_Floating_Integral &&
4580 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4581 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4582 return ImplicitConversionSequence::Better;
4583
4584 // Prefer a compatible vector conversion over a lax vector conversion
4585 // For example:
4586 //
4587 // typedef float __v4sf __attribute__((__vector_size__(16)));
4588 // void f(vector float);
4589 // void f(vector signed int);
4590 // int main() {
4591 // __v4sf a;
4592 // f(a);
4593 // }
4594 // Here, we'd like to choose f(vector float) and not
4595 // report an ambiguous call error
4596 if (SCS1.Second == ICK_Vector_Conversion &&
4597 SCS2.Second == ICK_Vector_Conversion) {
4598 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4600 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4601 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4602
4603 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4604 return SCS1IsCompatibleVectorConversion
4605 ? ImplicitConversionSequence::Better
4606 : ImplicitConversionSequence::Worse;
4607 }
4608
4609 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4610 SCS2.Second == ICK_SVE_Vector_Conversion) {
4611 bool SCS1IsCompatibleSVEVectorConversion =
4612 S.Context.areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4613 bool SCS2IsCompatibleSVEVectorConversion =
4614 S.Context.areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4615
4616 if (SCS1IsCompatibleSVEVectorConversion !=
4617 SCS2IsCompatibleSVEVectorConversion)
4618 return SCS1IsCompatibleSVEVectorConversion
4619 ? ImplicitConversionSequence::Better
4620 : ImplicitConversionSequence::Worse;
4621 }
4622
4623 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4624 SCS2.Second == ICK_RVV_Vector_Conversion) {
4625 bool SCS1IsCompatibleRVVVectorConversion =
4626 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4627 bool SCS2IsCompatibleRVVVectorConversion =
4628 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4629
4630 if (SCS1IsCompatibleRVVVectorConversion !=
4631 SCS2IsCompatibleRVVVectorConversion)
4632 return SCS1IsCompatibleRVVVectorConversion
4633 ? ImplicitConversionSequence::Better
4634 : ImplicitConversionSequence::Worse;
4635 }
4636
4637 return ImplicitConversionSequence::Indistinguishable;
4638}
4639
4640/// CompareQualificationConversions - Compares two standard conversion
4641/// sequences to determine whether they can be ranked based on their
4642/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4643static ImplicitConversionSequence::CompareKind
4644CompareQualificationConversions(Sema &S,
4645 const StandardConversionSequence& SCS1,
4646 const StandardConversionSequence& SCS2) {
4647 // C++ [over.ics.rank]p3:
4648 // -- S1 and S2 differ only in their qualification conversion and
4649 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4650 // [C++98]
4651 // [...] and the cv-qualification signature of type T1 is a proper subset
4652 // of the cv-qualification signature of type T2, and S1 is not the
4653 // deprecated string literal array-to-pointer conversion (4.2).
4654 // [C++2a]
4655 // [...] where T1 can be converted to T2 by a qualification conversion.
4656 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4657 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4658 return ImplicitConversionSequence::Indistinguishable;
4659
4660 // FIXME: the example in the standard doesn't use a qualification
4661 // conversion (!)
4662 QualType T1 = SCS1.getToType(Idx: 2);
4663 QualType T2 = SCS2.getToType(Idx: 2);
4664 T1 = S.Context.getCanonicalType(T: T1);
4665 T2 = S.Context.getCanonicalType(T: T2);
4666 assert(!T1->isReferenceType() && !T2->isReferenceType());
4667 Qualifiers T1Quals, T2Quals;
4668 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4669 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4670
4671 // If the types are the same, we won't learn anything by unwrapping
4672 // them.
4673 if (UnqualT1 == UnqualT2)
4674 return ImplicitConversionSequence::Indistinguishable;
4675
4676 // Don't ever prefer a standard conversion sequence that uses the deprecated
4677 // string literal array to pointer conversion.
4678 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4679 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4680
4681 // Objective-C++ ARC:
4682 // Prefer qualification conversions not involving a change in lifetime
4683 // to qualification conversions that do change lifetime.
4684 if (SCS1.QualificationIncludesObjCLifetime &&
4685 !SCS2.QualificationIncludesObjCLifetime)
4686 CanPick1 = false;
4687 if (SCS2.QualificationIncludesObjCLifetime &&
4688 !SCS1.QualificationIncludesObjCLifetime)
4689 CanPick2 = false;
4690
4691 bool ObjCLifetimeConversion;
4692 if (CanPick1 &&
4693 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
4694 CanPick1 = false;
4695 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4696 // directions, so we can't short-cut this second check in general.
4697 if (CanPick2 &&
4698 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
4699 CanPick2 = false;
4700
4701 if (CanPick1 != CanPick2)
4702 return CanPick1 ? ImplicitConversionSequence::Better
4703 : ImplicitConversionSequence::Worse;
4704 return ImplicitConversionSequence::Indistinguishable;
4705}
4706
4707/// CompareDerivedToBaseConversions - Compares two standard conversion
4708/// sequences to determine whether they can be ranked based on their
4709/// various kinds of derived-to-base conversions (C++
4710/// [over.ics.rank]p4b3). As part of these checks, we also look at
4711/// conversions between Objective-C interface types.
4712static ImplicitConversionSequence::CompareKind
4713CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4714 const StandardConversionSequence& SCS1,
4715 const StandardConversionSequence& SCS2) {
4716 QualType FromType1 = SCS1.getFromType();
4717 QualType ToType1 = SCS1.getToType(Idx: 1);
4718 QualType FromType2 = SCS2.getFromType();
4719 QualType ToType2 = SCS2.getToType(Idx: 1);
4720
4721 // Adjust the types we're converting from via the array-to-pointer
4722 // conversion, if we need to.
4723 if (SCS1.First == ICK_Array_To_Pointer)
4724 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4725 if (SCS2.First == ICK_Array_To_Pointer)
4726 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4727
4728 // Canonicalize all of the types.
4729 FromType1 = S.Context.getCanonicalType(T: FromType1);
4730 ToType1 = S.Context.getCanonicalType(T: ToType1);
4731 FromType2 = S.Context.getCanonicalType(T: FromType2);
4732 ToType2 = S.Context.getCanonicalType(T: ToType2);
4733
4734 // C++ [over.ics.rank]p4b3:
4735 //
4736 // If class B is derived directly or indirectly from class A and
4737 // class C is derived directly or indirectly from B,
4738 //
4739 // Compare based on pointer conversions.
4740 if (SCS1.Second == ICK_Pointer_Conversion &&
4741 SCS2.Second == ICK_Pointer_Conversion &&
4742 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4743 FromType1->isPointerType() && FromType2->isPointerType() &&
4744 ToType1->isPointerType() && ToType2->isPointerType()) {
4745 QualType FromPointee1 =
4746 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4747 QualType ToPointee1 =
4748 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4749 QualType FromPointee2 =
4750 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4751 QualType ToPointee2 =
4752 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4753
4754 // -- conversion of C* to B* is better than conversion of C* to A*,
4755 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4756 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4757 return ImplicitConversionSequence::Better;
4758 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4759 return ImplicitConversionSequence::Worse;
4760 }
4761
4762 // -- conversion of B* to A* is better than conversion of C* to A*,
4763 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4764 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4765 return ImplicitConversionSequence::Better;
4766 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4767 return ImplicitConversionSequence::Worse;
4768 }
4769 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4770 SCS2.Second == ICK_Pointer_Conversion) {
4771 const ObjCObjectPointerType *FromPtr1
4772 = FromType1->getAs<ObjCObjectPointerType>();
4773 const ObjCObjectPointerType *FromPtr2
4774 = FromType2->getAs<ObjCObjectPointerType>();
4775 const ObjCObjectPointerType *ToPtr1
4776 = ToType1->getAs<ObjCObjectPointerType>();
4777 const ObjCObjectPointerType *ToPtr2
4778 = ToType2->getAs<ObjCObjectPointerType>();
4779
4780 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4781 // Apply the same conversion ranking rules for Objective-C pointer types
4782 // that we do for C++ pointers to class types. However, we employ the
4783 // Objective-C pseudo-subtyping relationship used for assignment of
4784 // Objective-C pointer types.
4785 bool FromAssignLeft
4786 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
4787 bool FromAssignRight
4788 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
4789 bool ToAssignLeft
4790 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
4791 bool ToAssignRight
4792 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
4793
4794 // A conversion to an a non-id object pointer type or qualified 'id'
4795 // type is better than a conversion to 'id'.
4796 if (ToPtr1->isObjCIdType() &&
4797 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4798 return ImplicitConversionSequence::Worse;
4799 if (ToPtr2->isObjCIdType() &&
4800 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4801 return ImplicitConversionSequence::Better;
4802
4803 // A conversion to a non-id object pointer type is better than a
4804 // conversion to a qualified 'id' type
4805 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4806 return ImplicitConversionSequence::Worse;
4807 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4808 return ImplicitConversionSequence::Better;
4809
4810 // A conversion to an a non-Class object pointer type or qualified 'Class'
4811 // type is better than a conversion to 'Class'.
4812 if (ToPtr1->isObjCClassType() &&
4813 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4814 return ImplicitConversionSequence::Worse;
4815 if (ToPtr2->isObjCClassType() &&
4816 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4817 return ImplicitConversionSequence::Better;
4818
4819 // A conversion to a non-Class object pointer type is better than a
4820 // conversion to a qualified 'Class' type.
4821 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4822 return ImplicitConversionSequence::Worse;
4823 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4824 return ImplicitConversionSequence::Better;
4825
4826 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4827 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
4828 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4829 (ToAssignLeft != ToAssignRight)) {
4830 if (FromPtr1->isSpecialized()) {
4831 // "conversion of B<A> * to B * is better than conversion of B * to
4832 // C *.
4833 bool IsFirstSame =
4834 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4835 bool IsSecondSame =
4836 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4837 if (IsFirstSame) {
4838 if (!IsSecondSame)
4839 return ImplicitConversionSequence::Better;
4840 } else if (IsSecondSame)
4841 return ImplicitConversionSequence::Worse;
4842 }
4843 return ToAssignLeft? ImplicitConversionSequence::Worse
4844 : ImplicitConversionSequence::Better;
4845 }
4846
4847 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4848 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
4849 (FromAssignLeft != FromAssignRight))
4850 return FromAssignLeft? ImplicitConversionSequence::Better
4851 : ImplicitConversionSequence::Worse;
4852 }
4853 }
4854
4855 // Ranking of member-pointer types.
4856 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4857 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4858 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4859 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4860 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4861 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4862 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4863 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4864 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4865 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4866 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4867 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4868 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4869 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4870 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4871 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4872 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4873 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4874 return ImplicitConversionSequence::Worse;
4875 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4876 return ImplicitConversionSequence::Better;
4877 }
4878 // conversion of B::* to C::* is better than conversion of A::* to C::*
4879 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4880 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4881 return ImplicitConversionSequence::Better;
4882 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4883 return ImplicitConversionSequence::Worse;
4884 }
4885 }
4886
4887 if (SCS1.Second == ICK_Derived_To_Base) {
4888 // -- conversion of C to B is better than conversion of C to A,
4889 // -- binding of an expression of type C to a reference of type
4890 // B& is better than binding an expression of type C to a
4891 // reference of type A&,
4892 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
4893 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
4894 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
4895 return ImplicitConversionSequence::Better;
4896 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
4897 return ImplicitConversionSequence::Worse;
4898 }
4899
4900 // -- conversion of B to A is better than conversion of C to A.
4901 // -- binding of an expression of type B to a reference of type
4902 // A& is better than binding an expression of type C to a
4903 // reference of type A&,
4904 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
4905 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
4906 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
4907 return ImplicitConversionSequence::Better;
4908 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
4909 return ImplicitConversionSequence::Worse;
4910 }
4911 }
4912
4913 return ImplicitConversionSequence::Indistinguishable;
4914}
4915
4916static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4917 if (!T.getQualifiers().hasUnaligned())
4918 return T;
4919
4920 Qualifiers Q;
4921 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
4922 Q.removeUnaligned();
4923 return Ctx.getQualifiedType(T, Qs: Q);
4924}
4925
4926/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4927/// determine whether they are reference-compatible,
4928/// reference-related, or incompatible, for use in C++ initialization by
4929/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4930/// type, and the first type (T1) is the pointee type of the reference
4931/// type being initialized.
4932Sema::ReferenceCompareResult
4933Sema::CompareReferenceRelationship(SourceLocation Loc,
4934 QualType OrigT1, QualType OrigT2,
4935 ReferenceConversions *ConvOut) {
4936 assert(!OrigT1->isReferenceType() &&
4937 "T1 must be the pointee type of the reference type");
4938 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4939
4940 QualType T1 = Context.getCanonicalType(T: OrigT1);
4941 QualType T2 = Context.getCanonicalType(T: OrigT2);
4942 Qualifiers T1Quals, T2Quals;
4943 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4944 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4945
4946 ReferenceConversions ConvTmp;
4947 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4948 Conv = ReferenceConversions();
4949
4950 // C++2a [dcl.init.ref]p4:
4951 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4952 // reference-related to "cv2 T2" if T1 is similar to T2, or
4953 // T1 is a base class of T2.
4954 // "cv1 T1" is reference-compatible with "cv2 T2" if
4955 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4956 // "pointer to cv1 T1" via a standard conversion sequence.
4957
4958 // Check for standard conversions we can apply to pointers: derived-to-base
4959 // conversions, ObjC pointer conversions, and function pointer conversions.
4960 // (Qualification conversions are checked last.)
4961 QualType ConvertedT2;
4962 if (UnqualT1 == UnqualT2) {
4963 // Nothing to do.
4964 } else if (isCompleteType(Loc, T: OrigT2) &&
4965 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
4966 Conv |= ReferenceConversions::DerivedToBase;
4967 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4968 UnqualT2->isObjCObjectOrInterfaceType() &&
4969 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
4970 Conv |= ReferenceConversions::ObjC;
4971 else if (UnqualT2->isFunctionType() &&
4972 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1, ResultTy&: ConvertedT2)) {
4973 Conv |= ReferenceConversions::Function;
4974 // No need to check qualifiers; function types don't have them.
4975 return Ref_Compatible;
4976 }
4977 bool ConvertedReferent = Conv != 0;
4978
4979 // We can have a qualification conversion. Compute whether the types are
4980 // similar at the same time.
4981 bool PreviousToQualsIncludeConst = true;
4982 bool TopLevel = true;
4983 do {
4984 if (T1 == T2)
4985 break;
4986
4987 // We will need a qualification conversion.
4988 Conv |= ReferenceConversions::Qualification;
4989
4990 // Track whether we performed a qualification conversion anywhere other
4991 // than the top level. This matters for ranking reference bindings in
4992 // overload resolution.
4993 if (!TopLevel)
4994 Conv |= ReferenceConversions::NestedQualification;
4995
4996 // MS compiler ignores __unaligned qualifier for references; do the same.
4997 T1 = withoutUnaligned(Ctx&: Context, T: T1);
4998 T2 = withoutUnaligned(Ctx&: Context, T: T2);
4999
5000 // If we find a qualifier mismatch, the types are not reference-compatible,
5001 // but are still be reference-related if they're similar.
5002 bool ObjCLifetimeConversion = false;
5003 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5004 PreviousToQualsIncludeConst,
5005 ObjCLifetimeConversion))
5006 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5007 ? Ref_Related
5008 : Ref_Incompatible;
5009
5010 // FIXME: Should we track this for any level other than the first?
5011 if (ObjCLifetimeConversion)
5012 Conv |= ReferenceConversions::ObjCLifetime;
5013
5014 TopLevel = false;
5015 } while (Context.UnwrapSimilarTypes(T1, T2));
5016
5017 // At this point, if the types are reference-related, we must either have the
5018 // same inner type (ignoring qualifiers), or must have already worked out how
5019 // to convert the referent.
5020 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5021 ? Ref_Compatible
5022 : Ref_Incompatible;
5023}
5024
5025/// Look for a user-defined conversion to a value reference-compatible
5026/// with DeclType. Return true if something definite is found.
5027static bool
5028FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5029 QualType DeclType, SourceLocation DeclLoc,
5030 Expr *Init, QualType T2, bool AllowRvalues,
5031 bool AllowExplicit) {
5032 assert(T2->isRecordType() && "Can only find conversions of record types.");
5033 auto *T2RecordDecl = cast<CXXRecordDecl>(Val: T2->castAs<RecordType>()->getDecl());
5034
5035 OverloadCandidateSet CandidateSet(
5036 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5037 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5038 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5039 NamedDecl *D = *I;
5040 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5041 if (isa<UsingShadowDecl>(Val: D))
5042 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5043
5044 FunctionTemplateDecl *ConvTemplate
5045 = dyn_cast<FunctionTemplateDecl>(Val: D);
5046 CXXConversionDecl *Conv;
5047 if (ConvTemplate)
5048 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5049 else
5050 Conv = cast<CXXConversionDecl>(Val: D);
5051
5052 if (AllowRvalues) {
5053 // If we are initializing an rvalue reference, don't permit conversion
5054 // functions that return lvalues.
5055 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5056 const ReferenceType *RefType
5057 = Conv->getConversionType()->getAs<LValueReferenceType>();
5058 if (RefType && !RefType->getPointeeType()->isFunctionType())
5059 continue;
5060 }
5061
5062 if (!ConvTemplate &&
5063 S.CompareReferenceRelationship(
5064 Loc: DeclLoc,
5065 OrigT1: Conv->getConversionType()
5066 .getNonReferenceType()
5067 .getUnqualifiedType(),
5068 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5069 Sema::Ref_Incompatible)
5070 continue;
5071 } else {
5072 // If the conversion function doesn't return a reference type,
5073 // it can't be considered for this conversion. An rvalue reference
5074 // is only acceptable if its referencee is a function type.
5075
5076 const ReferenceType *RefType =
5077 Conv->getConversionType()->getAs<ReferenceType>();
5078 if (!RefType ||
5079 (!RefType->isLValueReferenceType() &&
5080 !RefType->getPointeeType()->isFunctionType()))
5081 continue;
5082 }
5083
5084 if (ConvTemplate)
5085 S.AddTemplateConversionCandidate(
5086 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5087 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5088 else
5089 S.AddConversionCandidate(
5090 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5091 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5092 }
5093
5094 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5095
5096 OverloadCandidateSet::iterator Best;
5097 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5098 case OR_Success:
5099 // C++ [over.ics.ref]p1:
5100 //
5101 // [...] If the parameter binds directly to the result of
5102 // applying a conversion function to the argument
5103 // expression, the implicit conversion sequence is a
5104 // user-defined conversion sequence (13.3.3.1.2), with the
5105 // second standard conversion sequence either an identity
5106 // conversion or, if the conversion function returns an
5107 // entity of a type that is a derived class of the parameter
5108 // type, a derived-to-base Conversion.
5109 if (!Best->FinalConversion.DirectBinding)
5110 return false;
5111
5112 ICS.setUserDefined();
5113 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5114 ICS.UserDefined.After = Best->FinalConversion;
5115 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5116 ICS.UserDefined.ConversionFunction = Best->Function;
5117 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5118 ICS.UserDefined.EllipsisConversion = false;
5119 assert(ICS.UserDefined.After.ReferenceBinding &&
5120 ICS.UserDefined.After.DirectBinding &&
5121 "Expected a direct reference binding!");
5122 return true;
5123
5124 case OR_Ambiguous:
5125 ICS.setAmbiguous();
5126 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5127 Cand != CandidateSet.end(); ++Cand)
5128 if (Cand->Best)
5129 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5130 return true;
5131
5132 case OR_No_Viable_Function:
5133 case OR_Deleted:
5134 // There was no suitable conversion, or we found a deleted
5135 // conversion; continue with other checks.
5136 return false;
5137 }
5138
5139 llvm_unreachable("Invalid OverloadResult!");
5140}
5141
5142/// Compute an implicit conversion sequence for reference
5143/// initialization.
5144static ImplicitConversionSequence
5145TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5146 SourceLocation DeclLoc,
5147 bool SuppressUserConversions,
5148 bool AllowExplicit) {
5149 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5150
5151 // Most paths end in a failed conversion.
5152 ImplicitConversionSequence ICS;
5153 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5154
5155 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5156 QualType T2 = Init->getType();
5157
5158 // If the initializer is the address of an overloaded function, try
5159 // to resolve the overloaded function. If all goes well, T2 is the
5160 // type of the resulting function.
5161 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5162 DeclAccessPair Found;
5163 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5164 Complain: false, Found))
5165 T2 = Fn->getType();
5166 }
5167
5168 // Compute some basic properties of the types and the initializer.
5169 bool isRValRef = DeclType->isRValueReferenceType();
5170 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5171
5172 Sema::ReferenceConversions RefConv;
5173 Sema::ReferenceCompareResult RefRelationship =
5174 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5175
5176 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5177 ICS.setStandard();
5178 ICS.Standard.First = ICK_Identity;
5179 // FIXME: A reference binding can be a function conversion too. We should
5180 // consider that when ordering reference-to-function bindings.
5181 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5182 ? ICK_Derived_To_Base
5183 : (RefConv & Sema::ReferenceConversions::ObjC)
5184 ? ICK_Compatible_Conversion
5185 : ICK_Identity;
5186 ICS.Standard.Element = ICK_Identity;
5187 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5188 // a reference binding that performs a non-top-level qualification
5189 // conversion as a qualification conversion, not as an identity conversion.
5190 ICS.Standard.Third = (RefConv &
5191 Sema::ReferenceConversions::NestedQualification)
5192 ? ICK_Qualification
5193 : ICK_Identity;
5194 ICS.Standard.setFromType(T2);
5195 ICS.Standard.setToType(Idx: 0, T: T2);
5196 ICS.Standard.setToType(Idx: 1, T: T1);
5197 ICS.Standard.setToType(Idx: 2, T: T1);
5198 ICS.Standard.ReferenceBinding = true;
5199 ICS.Standard.DirectBinding = BindsDirectly;
5200 ICS.Standard.IsLvalueReference = !isRValRef;
5201 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5202 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5203 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5204 ICS.Standard.ObjCLifetimeConversionBinding =
5205 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5206 ICS.Standard.CopyConstructor = nullptr;
5207 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5208 };
5209
5210 // C++0x [dcl.init.ref]p5:
5211 // A reference to type "cv1 T1" is initialized by an expression
5212 // of type "cv2 T2" as follows:
5213
5214 // -- If reference is an lvalue reference and the initializer expression
5215 if (!isRValRef) {
5216 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5217 // reference-compatible with "cv2 T2," or
5218 //
5219 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5220 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5221 // C++ [over.ics.ref]p1:
5222 // When a parameter of reference type binds directly (8.5.3)
5223 // to an argument expression, the implicit conversion sequence
5224 // is the identity conversion, unless the argument expression
5225 // has a type that is a derived class of the parameter type,
5226 // in which case the implicit conversion sequence is a
5227 // derived-to-base Conversion (13.3.3.1).
5228 SetAsReferenceBinding(/*BindsDirectly=*/true);
5229
5230 // Nothing more to do: the inaccessibility/ambiguity check for
5231 // derived-to-base conversions is suppressed when we're
5232 // computing the implicit conversion sequence (C++
5233 // [over.best.ics]p2).
5234 return ICS;
5235 }
5236
5237 // -- has a class type (i.e., T2 is a class type), where T1 is
5238 // not reference-related to T2, and can be implicitly
5239 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5240 // is reference-compatible with "cv3 T3" 92) (this
5241 // conversion is selected by enumerating the applicable
5242 // conversion functions (13.3.1.6) and choosing the best
5243 // one through overload resolution (13.3)),
5244 if (!SuppressUserConversions && T2->isRecordType() &&
5245 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5246 RefRelationship == Sema::Ref_Incompatible) {
5247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5248 Init, T2, /*AllowRvalues=*/false,
5249 AllowExplicit))
5250 return ICS;
5251 }
5252 }
5253
5254 // -- Otherwise, the reference shall be an lvalue reference to a
5255 // non-volatile const type (i.e., cv1 shall be const), or the reference
5256 // shall be an rvalue reference.
5257 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5258 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5259 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5260 return ICS;
5261 }
5262
5263 // -- If the initializer expression
5264 //
5265 // -- is an xvalue, class prvalue, array prvalue or function
5266 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5267 if (RefRelationship == Sema::Ref_Compatible &&
5268 (InitCategory.isXValue() ||
5269 (InitCategory.isPRValue() &&
5270 (T2->isRecordType() || T2->isArrayType())) ||
5271 (InitCategory.isLValue() && T2->isFunctionType()))) {
5272 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5273 // binding unless we're binding to a class prvalue.
5274 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5275 // allow the use of rvalue references in C++98/03 for the benefit of
5276 // standard library implementors; therefore, we need the xvalue check here.
5277 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5278 !(InitCategory.isPRValue() || T2->isRecordType()));
5279 return ICS;
5280 }
5281
5282 // -- has a class type (i.e., T2 is a class type), where T1 is not
5283 // reference-related to T2, and can be implicitly converted to
5284 // an xvalue, class prvalue, or function lvalue of type
5285 // "cv3 T3", where "cv1 T1" is reference-compatible with
5286 // "cv3 T3",
5287 //
5288 // then the reference is bound to the value of the initializer
5289 // expression in the first case and to the result of the conversion
5290 // in the second case (or, in either case, to an appropriate base
5291 // class subobject).
5292 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5293 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5294 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5295 Init, T2, /*AllowRvalues=*/true,
5296 AllowExplicit)) {
5297 // In the second case, if the reference is an rvalue reference
5298 // and the second standard conversion sequence of the
5299 // user-defined conversion sequence includes an lvalue-to-rvalue
5300 // conversion, the program is ill-formed.
5301 if (ICS.isUserDefined() && isRValRef &&
5302 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5303 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5304
5305 return ICS;
5306 }
5307
5308 // A temporary of function type cannot be created; don't even try.
5309 if (T1->isFunctionType())
5310 return ICS;
5311
5312 // -- Otherwise, a temporary of type "cv1 T1" is created and
5313 // initialized from the initializer expression using the
5314 // rules for a non-reference copy initialization (8.5). The
5315 // reference is then bound to the temporary. If T1 is
5316 // reference-related to T2, cv1 must be the same
5317 // cv-qualification as, or greater cv-qualification than,
5318 // cv2; otherwise, the program is ill-formed.
5319 if (RefRelationship == Sema::Ref_Related) {
5320 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5321 // we would be reference-compatible or reference-compatible with
5322 // added qualification. But that wasn't the case, so the reference
5323 // initialization fails.
5324 //
5325 // Note that we only want to check address spaces and cvr-qualifiers here.
5326 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5327 Qualifiers T1Quals = T1.getQualifiers();
5328 Qualifiers T2Quals = T2.getQualifiers();
5329 T1Quals.removeObjCGCAttr();
5330 T1Quals.removeObjCLifetime();
5331 T2Quals.removeObjCGCAttr();
5332 T2Quals.removeObjCLifetime();
5333 // MS compiler ignores __unaligned qualifier for references; do the same.
5334 T1Quals.removeUnaligned();
5335 T2Quals.removeUnaligned();
5336 if (!T1Quals.compatiblyIncludes(other: T2Quals))
5337 return ICS;
5338 }
5339
5340 // If at least one of the types is a class type, the types are not
5341 // related, and we aren't allowed any user conversions, the
5342 // reference binding fails. This case is important for breaking
5343 // recursion, since TryImplicitConversion below will attempt to
5344 // create a temporary through the use of a copy constructor.
5345 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5346 (T1->isRecordType() || T2->isRecordType()))
5347 return ICS;
5348
5349 // If T1 is reference-related to T2 and the reference is an rvalue
5350 // reference, the initializer expression shall not be an lvalue.
5351 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5352 Init->Classify(Ctx&: S.Context).isLValue()) {
5353 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5354 return ICS;
5355 }
5356
5357 // C++ [over.ics.ref]p2:
5358 // When a parameter of reference type is not bound directly to
5359 // an argument expression, the conversion sequence is the one
5360 // required to convert the argument expression to the
5361 // underlying type of the reference according to
5362 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5363 // to copy-initializing a temporary of the underlying type with
5364 // the argument expression. Any difference in top-level
5365 // cv-qualification is subsumed by the initialization itself
5366 // and does not constitute a conversion.
5367 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5368 AllowExplicit: AllowedExplicit::None,
5369 /*InOverloadResolution=*/false,
5370 /*CStyle=*/false,
5371 /*AllowObjCWritebackConversion=*/false,
5372 /*AllowObjCConversionOnExplicit=*/false);
5373
5374 // Of course, that's still a reference binding.
5375 if (ICS.isStandard()) {
5376 ICS.Standard.ReferenceBinding = true;
5377 ICS.Standard.IsLvalueReference = !isRValRef;
5378 ICS.Standard.BindsToFunctionLvalue = false;
5379 ICS.Standard.BindsToRvalue = true;
5380 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5381 ICS.Standard.ObjCLifetimeConversionBinding = false;
5382 } else if (ICS.isUserDefined()) {
5383 const ReferenceType *LValRefType =
5384 ICS.UserDefined.ConversionFunction->getReturnType()
5385 ->getAs<LValueReferenceType>();
5386
5387 // C++ [over.ics.ref]p3:
5388 // Except for an implicit object parameter, for which see 13.3.1, a
5389 // standard conversion sequence cannot be formed if it requires [...]
5390 // binding an rvalue reference to an lvalue other than a function
5391 // lvalue.
5392 // Note that the function case is not possible here.
5393 if (isRValRef && LValRefType) {
5394 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5395 return ICS;
5396 }
5397
5398 ICS.UserDefined.After.ReferenceBinding = true;
5399 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5400 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5401 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5402 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5403 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5404 }
5405
5406 return ICS;
5407}
5408
5409static ImplicitConversionSequence
5410TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5411 bool SuppressUserConversions,
5412 bool InOverloadResolution,
5413 bool AllowObjCWritebackConversion,
5414 bool AllowExplicit = false);
5415
5416/// TryListConversion - Try to copy-initialize a value of type ToType from the
5417/// initializer list From.
5418static ImplicitConversionSequence
5419TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5420 bool SuppressUserConversions,
5421 bool InOverloadResolution,
5422 bool AllowObjCWritebackConversion) {
5423 // C++11 [over.ics.list]p1:
5424 // When an argument is an initializer list, it is not an expression and
5425 // special rules apply for converting it to a parameter type.
5426
5427 ImplicitConversionSequence Result;
5428 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5429
5430 // We need a complete type for what follows. With one C++20 exception,
5431 // incomplete types can never be initialized from init lists.
5432 QualType InitTy = ToType;
5433 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5434 if (AT && S.getLangOpts().CPlusPlus20)
5435 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5436 // C++20 allows list initialization of an incomplete array type.
5437 InitTy = IAT->getElementType();
5438 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5439 return Result;
5440
5441 // C++20 [over.ics.list]/2:
5442 // If the initializer list is a designated-initializer-list, a conversion
5443 // is only possible if the parameter has an aggregate type
5444 //
5445 // FIXME: The exception for reference initialization here is not part of the
5446 // language rules, but follow other compilers in adding it as a tentative DR
5447 // resolution.
5448 bool IsDesignatedInit = From->hasDesignatedInit();
5449 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5450 IsDesignatedInit)
5451 return Result;
5452
5453 // Per DR1467:
5454 // If the parameter type is a class X and the initializer list has a single
5455 // element of type cv U, where U is X or a class derived from X, the
5456 // implicit conversion sequence is the one required to convert the element
5457 // to the parameter type.
5458 //
5459 // Otherwise, if the parameter type is a character array [... ]
5460 // and the initializer list has a single element that is an
5461 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5462 // implicit conversion sequence is the identity conversion.
5463 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5464 if (ToType->isRecordType()) {
5465 QualType InitType = From->getInit(Init: 0)->getType();
5466 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5467 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5468 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5469 SuppressUserConversions,
5470 InOverloadResolution,
5471 AllowObjCWritebackConversion);
5472 }
5473
5474 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5475 InitializedEntity Entity =
5476 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5477 /*Consumed=*/false);
5478 if (S.CanPerformCopyInitialization(Entity, From)) {
5479 Result.setStandard();
5480 Result.Standard.setAsIdentityConversion();
5481 Result.Standard.setFromType(ToType);
5482 Result.Standard.setAllToTypes(ToType);
5483 return Result;
5484 }
5485 }
5486 }
5487
5488 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5489 // C++11 [over.ics.list]p2:
5490 // If the parameter type is std::initializer_list<X> or "array of X" and
5491 // all the elements can be implicitly converted to X, the implicit
5492 // conversion sequence is the worst conversion necessary to convert an
5493 // element of the list to X.
5494 //
5495 // C++14 [over.ics.list]p3:
5496 // Otherwise, if the parameter type is "array of N X", if the initializer
5497 // list has exactly N elements or if it has fewer than N elements and X is
5498 // default-constructible, and if all the elements of the initializer list
5499 // can be implicitly converted to X, the implicit conversion sequence is
5500 // the worst conversion necessary to convert an element of the list to X.
5501 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5502 unsigned e = From->getNumInits();
5503 ImplicitConversionSequence DfltElt;
5504 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5505 ToType: QualType());
5506 QualType ContTy = ToType;
5507 bool IsUnbounded = false;
5508 if (AT) {
5509 InitTy = AT->getElementType();
5510 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5511 if (CT->getSize().ult(RHS: e)) {
5512 // Too many inits, fatally bad
5513 Result.setBad(BadConversionSequence::too_many_initializers, From,
5514 ToType);
5515 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5516 return Result;
5517 }
5518 if (CT->getSize().ugt(RHS: e)) {
5519 // Need an init from empty {}, is there one?
5520 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5521 From->getEndLoc());
5522 EmptyList.setType(S.Context.VoidTy);
5523 DfltElt = TryListConversion(
5524 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5525 InOverloadResolution, AllowObjCWritebackConversion);
5526 if (DfltElt.isBad()) {
5527 // No {} init, fatally bad
5528 Result.setBad(BadConversionSequence::too_few_initializers, From,
5529 ToType);
5530 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5531 return Result;
5532 }
5533 }
5534 } else {
5535 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5536 IsUnbounded = true;
5537 if (!e) {
5538 // Cannot convert to zero-sized.
5539 Result.setBad(BadConversionSequence::too_few_initializers, From,
5540 ToType);
5541 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5542 return Result;
5543 }
5544 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5545 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5546 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5547 }
5548 }
5549
5550 Result.setStandard();
5551 Result.Standard.setAsIdentityConversion();
5552 Result.Standard.setFromType(InitTy);
5553 Result.Standard.setAllToTypes(InitTy);
5554 for (unsigned i = 0; i < e; ++i) {
5555 Expr *Init = From->getInit(Init: i);
5556 ImplicitConversionSequence ICS = TryCopyInitialization(
5557 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5558 AllowObjCWritebackConversion);
5559
5560 // Keep the worse conversion seen so far.
5561 // FIXME: Sequences are not totally ordered, so 'worse' can be
5562 // ambiguous. CWG has been informed.
5563 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5564 ICS2: Result) ==
5565 ImplicitConversionSequence::Worse) {
5566 Result = ICS;
5567 // Bail as soon as we find something unconvertible.
5568 if (Result.isBad()) {
5569 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5570 return Result;
5571 }
5572 }
5573 }
5574
5575 // If we needed any implicit {} initialization, compare that now.
5576 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5577 // has been informed that this might not be the best thing.
5578 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5579 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5580 ImplicitConversionSequence::Worse)
5581 Result = DfltElt;
5582 // Record the type being initialized so that we may compare sequences
5583 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5584 return Result;
5585 }
5586
5587 // C++14 [over.ics.list]p4:
5588 // C++11 [over.ics.list]p3:
5589 // Otherwise, if the parameter is a non-aggregate class X and overload
5590 // resolution chooses a single best constructor [...] the implicit
5591 // conversion sequence is a user-defined conversion sequence. If multiple
5592 // constructors are viable but none is better than the others, the
5593 // implicit conversion sequence is a user-defined conversion sequence.
5594 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5595 // This function can deal with initializer lists.
5596 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5597 AllowedExplicit::None,
5598 InOverloadResolution, /*CStyle=*/false,
5599 AllowObjCWritebackConversion,
5600 /*AllowObjCConversionOnExplicit=*/false);
5601 }
5602
5603 // C++14 [over.ics.list]p5:
5604 // C++11 [over.ics.list]p4:
5605 // Otherwise, if the parameter has an aggregate type which can be
5606 // initialized from the initializer list [...] the implicit conversion
5607 // sequence is a user-defined conversion sequence.
5608 if (ToType->isAggregateType()) {
5609 // Type is an aggregate, argument is an init list. At this point it comes
5610 // down to checking whether the initialization works.
5611 // FIXME: Find out whether this parameter is consumed or not.
5612 InitializedEntity Entity =
5613 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5614 /*Consumed=*/false);
5615 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5616 From)) {
5617 Result.setUserDefined();
5618 Result.UserDefined.Before.setAsIdentityConversion();
5619 // Initializer lists don't have a type.
5620 Result.UserDefined.Before.setFromType(QualType());
5621 Result.UserDefined.Before.setAllToTypes(QualType());
5622
5623 Result.UserDefined.After.setAsIdentityConversion();
5624 Result.UserDefined.After.setFromType(ToType);
5625 Result.UserDefined.After.setAllToTypes(ToType);
5626 Result.UserDefined.ConversionFunction = nullptr;
5627 }
5628 return Result;
5629 }
5630
5631 // C++14 [over.ics.list]p6:
5632 // C++11 [over.ics.list]p5:
5633 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5634 if (ToType->isReferenceType()) {
5635 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5636 // mention initializer lists in any way. So we go by what list-
5637 // initialization would do and try to extrapolate from that.
5638
5639 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5640
5641 // If the initializer list has a single element that is reference-related
5642 // to the parameter type, we initialize the reference from that.
5643 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5644 Expr *Init = From->getInit(Init: 0);
5645
5646 QualType T2 = Init->getType();
5647
5648 // If the initializer is the address of an overloaded function, try
5649 // to resolve the overloaded function. If all goes well, T2 is the
5650 // type of the resulting function.
5651 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5652 DeclAccessPair Found;
5653 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5654 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5655 T2 = Fn->getType();
5656 }
5657
5658 // Compute some basic properties of the types and the initializer.
5659 Sema::ReferenceCompareResult RefRelationship =
5660 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5661
5662 if (RefRelationship >= Sema::Ref_Related) {
5663 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5664 SuppressUserConversions,
5665 /*AllowExplicit=*/false);
5666 }
5667 }
5668
5669 // Otherwise, we bind the reference to a temporary created from the
5670 // initializer list.
5671 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5672 InOverloadResolution,
5673 AllowObjCWritebackConversion);
5674 if (Result.isFailure())
5675 return Result;
5676 assert(!Result.isEllipsis() &&
5677 "Sub-initialization cannot result in ellipsis conversion.");
5678
5679 // Can we even bind to a temporary?
5680 if (ToType->isRValueReferenceType() ||
5681 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5682 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5683 Result.UserDefined.After;
5684 SCS.ReferenceBinding = true;
5685 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5686 SCS.BindsToRvalue = true;
5687 SCS.BindsToFunctionLvalue = false;
5688 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5689 SCS.ObjCLifetimeConversionBinding = false;
5690 } else
5691 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5692 From, ToType);
5693 return Result;
5694 }
5695
5696 // C++14 [over.ics.list]p7:
5697 // C++11 [over.ics.list]p6:
5698 // Otherwise, if the parameter type is not a class:
5699 if (!ToType->isRecordType()) {
5700 // - if the initializer list has one element that is not itself an
5701 // initializer list, the implicit conversion sequence is the one
5702 // required to convert the element to the parameter type.
5703 unsigned NumInits = From->getNumInits();
5704 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)))
5705 Result = TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5706 SuppressUserConversions,
5707 InOverloadResolution,
5708 AllowObjCWritebackConversion);
5709 // - if the initializer list has no elements, the implicit conversion
5710 // sequence is the identity conversion.
5711 else if (NumInits == 0) {
5712 Result.setStandard();
5713 Result.Standard.setAsIdentityConversion();
5714 Result.Standard.setFromType(ToType);
5715 Result.Standard.setAllToTypes(ToType);
5716 }
5717 return Result;
5718 }
5719
5720 // C++14 [over.ics.list]p8:
5721 // C++11 [over.ics.list]p7:
5722 // In all cases other than those enumerated above, no conversion is possible
5723 return Result;
5724}
5725
5726/// TryCopyInitialization - Try to copy-initialize a value of type
5727/// ToType from the expression From. Return the implicit conversion
5728/// sequence required to pass this argument, which may be a bad
5729/// conversion sequence (meaning that the argument cannot be passed to
5730/// a parameter of this type). If @p SuppressUserConversions, then we
5731/// do not permit any user-defined conversion sequences.
5732static ImplicitConversionSequence
5733TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5734 bool SuppressUserConversions,
5735 bool InOverloadResolution,
5736 bool AllowObjCWritebackConversion,
5737 bool AllowExplicit) {
5738 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
5739 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
5740 InOverloadResolution,AllowObjCWritebackConversion);
5741
5742 if (ToType->isReferenceType())
5743 return TryReferenceInit(S, From, ToType,
5744 /*FIXME:*/ From->getBeginLoc(),
5745 SuppressUserConversions, AllowExplicit);
5746
5747 return TryImplicitConversion(S, From, ToType,
5748 SuppressUserConversions,
5749 AllowExplicit: AllowedExplicit::None,
5750 InOverloadResolution,
5751 /*CStyle=*/false,
5752 AllowObjCWritebackConversion,
5753 /*AllowObjCConversionOnExplicit=*/false);
5754}
5755
5756static bool TryCopyInitialization(const CanQualType FromQTy,
5757 const CanQualType ToQTy,
5758 Sema &S,
5759 SourceLocation Loc,
5760 ExprValueKind FromVK) {
5761 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5762 ImplicitConversionSequence ICS =
5763 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5764
5765 return !ICS.isBad();
5766}
5767
5768/// TryObjectArgumentInitialization - Try to initialize the object
5769/// parameter of the given member function (@c Method) from the
5770/// expression @p From.
5771static ImplicitConversionSequence TryObjectArgumentInitialization(
5772 Sema &S, SourceLocation Loc, QualType FromType,
5773 Expr::Classification FromClassification, CXXMethodDecl *Method,
5774 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5775 QualType ExplicitParameterType = QualType(),
5776 bool SuppressUserConversion = false) {
5777
5778 // We need to have an object of class type.
5779 if (const auto *PT = FromType->getAs<PointerType>()) {
5780 FromType = PT->getPointeeType();
5781
5782 // When we had a pointer, it's implicitly dereferenced, so we
5783 // better have an lvalue.
5784 assert(FromClassification.isLValue());
5785 }
5786
5787 auto ValueKindFromClassification = [](Expr::Classification C) {
5788 if (C.isPRValue())
5789 return clang::VK_PRValue;
5790 if (C.isXValue())
5791 return VK_XValue;
5792 return clang::VK_LValue;
5793 };
5794
5795 if (Method->isExplicitObjectMemberFunction()) {
5796 if (ExplicitParameterType.isNull())
5797 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5798 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5799 ValueKindFromClassification(FromClassification));
5800 ImplicitConversionSequence ICS = TryCopyInitialization(
5801 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5802 /*InOverloadResolution=*/true, false);
5803 if (ICS.isBad())
5804 ICS.Bad.FromExpr = nullptr;
5805 return ICS;
5806 }
5807
5808 assert(FromType->isRecordType());
5809
5810 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5811 // C++98 [class.dtor]p2:
5812 // A destructor can be invoked for a const, volatile or const volatile
5813 // object.
5814 // C++98 [over.match.funcs]p4:
5815 // For static member functions, the implicit object parameter is considered
5816 // to match any object (since if the function is selected, the object is
5817 // discarded).
5818 Qualifiers Quals = Method->getMethodQualifiers();
5819 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
5820 Quals.addConst();
5821 Quals.addVolatile();
5822 }
5823
5824 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
5825
5826 // Set up the conversion sequence as a "bad" conversion, to allow us
5827 // to exit early.
5828 ImplicitConversionSequence ICS;
5829
5830 // C++0x [over.match.funcs]p4:
5831 // For non-static member functions, the type of the implicit object
5832 // parameter is
5833 //
5834 // - "lvalue reference to cv X" for functions declared without a
5835 // ref-qualifier or with the & ref-qualifier
5836 // - "rvalue reference to cv X" for functions declared with the &&
5837 // ref-qualifier
5838 //
5839 // where X is the class of which the function is a member and cv is the
5840 // cv-qualification on the member function declaration.
5841 //
5842 // However, when finding an implicit conversion sequence for the argument, we
5843 // are not allowed to perform user-defined conversions
5844 // (C++ [over.match.funcs]p5). We perform a simplified version of
5845 // reference binding here, that allows class rvalues to bind to
5846 // non-constant references.
5847
5848 // First check the qualifiers.
5849 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
5850 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5851 if (ImplicitParamType.getCVRQualifiers() !=
5852 FromTypeCanon.getLocalCVRQualifiers() &&
5853 !ImplicitParamType.isAtLeastAsQualifiedAs(
5854 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon))) {
5855 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5856 FromType, ToType: ImplicitParamType);
5857 return ICS;
5858 }
5859
5860 if (FromTypeCanon.hasAddressSpace()) {
5861 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5862 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5863 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType)) {
5864 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5865 FromType, ToType: ImplicitParamType);
5866 return ICS;
5867 }
5868 }
5869
5870 // Check that we have either the same type or a derived type. It
5871 // affects the conversion rank.
5872 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
5873 ImplicitConversionKind SecondKind;
5874 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5875 SecondKind = ICK_Identity;
5876 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
5877 SecondKind = ICK_Derived_To_Base;
5878 } else if (!Method->isExplicitObjectMemberFunction()) {
5879 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
5880 FromType, ToType: ImplicitParamType);
5881 return ICS;
5882 }
5883
5884 // Check the ref-qualifier.
5885 switch (Method->getRefQualifier()) {
5886 case RQ_None:
5887 // Do nothing; we don't care about lvalueness or rvalueness.
5888 break;
5889
5890 case RQ_LValue:
5891 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5892 // non-const lvalue reference cannot bind to an rvalue
5893 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5894 ToType: ImplicitParamType);
5895 return ICS;
5896 }
5897 break;
5898
5899 case RQ_RValue:
5900 if (!FromClassification.isRValue()) {
5901 // rvalue reference cannot bind to an lvalue
5902 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5903 ToType: ImplicitParamType);
5904 return ICS;
5905 }
5906 break;
5907 }
5908
5909 // Success. Mark this as a reference binding.
5910 ICS.setStandard();
5911 ICS.Standard.setAsIdentityConversion();
5912 ICS.Standard.Second = SecondKind;
5913 ICS.Standard.setFromType(FromType);
5914 ICS.Standard.setAllToTypes(ImplicitParamType);
5915 ICS.Standard.ReferenceBinding = true;
5916 ICS.Standard.DirectBinding = true;
5917 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5918 ICS.Standard.BindsToFunctionLvalue = false;
5919 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5920 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5921 = (Method->getRefQualifier() == RQ_None);
5922 return ICS;
5923}
5924
5925/// PerformObjectArgumentInitialization - Perform initialization of
5926/// the implicit object parameter for the given Method with the given
5927/// expression.
5928ExprResult Sema::PerformImplicitObjectArgumentInitialization(
5929 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5930 CXXMethodDecl *Method) {
5931 QualType FromRecordType, DestType;
5932 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5933
5934 Expr::Classification FromClassification;
5935 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5936 FromRecordType = PT->getPointeeType();
5937 DestType = Method->getThisType();
5938 FromClassification = Expr::Classification::makeSimpleLValue();
5939 } else {
5940 FromRecordType = From->getType();
5941 DestType = ImplicitParamRecordType;
5942 FromClassification = From->Classify(Ctx&: Context);
5943
5944 // When performing member access on a prvalue, materialize a temporary.
5945 if (From->isPRValue()) {
5946 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
5947 BoundToLvalueReference: Method->getRefQualifier() !=
5948 RefQualifierKind::RQ_RValue);
5949 }
5950 }
5951
5952 // Note that we always use the true parent context when performing
5953 // the actual argument initialization.
5954 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5955 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5956 Method->getParent());
5957 if (ICS.isBad()) {
5958 switch (ICS.Bad.Kind) {
5959 case BadConversionSequence::bad_qualifiers: {
5960 Qualifiers FromQs = FromRecordType.getQualifiers();
5961 Qualifiers ToQs = DestType.getQualifiers();
5962 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5963 if (CVR) {
5964 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5965 << Method->getDeclName() << FromRecordType << (CVR - 1)
5966 << From->getSourceRange();
5967 Diag(Method->getLocation(), diag::note_previous_decl)
5968 << Method->getDeclName();
5969 return ExprError();
5970 }
5971 break;
5972 }
5973
5974 case BadConversionSequence::lvalue_ref_to_rvalue:
5975 case BadConversionSequence::rvalue_ref_to_lvalue: {
5976 bool IsRValueQualified =
5977 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5978 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5979 << Method->getDeclName() << FromClassification.isRValue()
5980 << IsRValueQualified;
5981 Diag(Method->getLocation(), diag::note_previous_decl)
5982 << Method->getDeclName();
5983 return ExprError();
5984 }
5985
5986 case BadConversionSequence::no_conversion:
5987 case BadConversionSequence::unrelated_class:
5988 break;
5989
5990 case BadConversionSequence::too_few_initializers:
5991 case BadConversionSequence::too_many_initializers:
5992 llvm_unreachable("Lists are not objects");
5993 }
5994
5995 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5996 << ImplicitParamRecordType << FromRecordType
5997 << From->getSourceRange();
5998 }
5999
6000 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6001 ExprResult FromRes =
6002 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6003 if (FromRes.isInvalid())
6004 return ExprError();
6005 From = FromRes.get();
6006 }
6007
6008 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6009 CastKind CK;
6010 QualType PteeTy = DestType->getPointeeType();
6011 LangAS DestAS =
6012 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6013 if (FromRecordType.getAddressSpace() != DestAS)
6014 CK = CK_AddressSpaceConversion;
6015 else
6016 CK = CK_NoOp;
6017 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6018 }
6019 return From;
6020}
6021
6022/// TryContextuallyConvertToBool - Attempt to contextually convert the
6023/// expression From to bool (C++0x [conv]p3).
6024static ImplicitConversionSequence
6025TryContextuallyConvertToBool(Sema &S, Expr *From) {
6026 // C++ [dcl.init]/17.8:
6027 // - Otherwise, if the initialization is direct-initialization, the source
6028 // type is std::nullptr_t, and the destination type is bool, the initial
6029 // value of the object being initialized is false.
6030 if (From->getType()->isNullPtrType())
6031 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6032 DestType: S.Context.BoolTy,
6033 NeedLValToRVal: From->isGLValue());
6034
6035 // All other direct-initialization of bool is equivalent to an implicit
6036 // conversion to bool in which explicit conversions are permitted.
6037 return TryImplicitConversion(S, From, S.Context.BoolTy,
6038 /*SuppressUserConversions=*/false,
6039 AllowedExplicit::Conversions,
6040 /*InOverloadResolution=*/false,
6041 /*CStyle=*/false,
6042 /*AllowObjCWritebackConversion=*/false,
6043 /*AllowObjCConversionOnExplicit=*/false);
6044}
6045
6046/// PerformContextuallyConvertToBool - Perform a contextual conversion
6047/// of the expression From to bool (C++0x [conv]p3).
6048ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6049 if (checkPlaceholderForOverload(S&: *this, E&: From))
6050 return ExprError();
6051
6052 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6053 if (!ICS.isBad())
6054 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
6055
6056 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6057 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6058 << From->getType() << From->getSourceRange();
6059 return ExprError();
6060}
6061
6062/// Check that the specified conversion is permitted in a converted constant
6063/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6064/// is acceptable.
6065static bool CheckConvertedConstantConversions(Sema &S,
6066 StandardConversionSequence &SCS) {
6067 // Since we know that the target type is an integral or unscoped enumeration
6068 // type, most conversion kinds are impossible. All possible First and Third
6069 // conversions are fine.
6070 switch (SCS.Second) {
6071 case ICK_Identity:
6072 case ICK_Integral_Promotion:
6073 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6074 case ICK_Zero_Queue_Conversion:
6075 return true;
6076
6077 case ICK_Boolean_Conversion:
6078 // Conversion from an integral or unscoped enumeration type to bool is
6079 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6080 // conversion, so we allow it in a converted constant expression.
6081 //
6082 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6083 // a lot of popular code. We should at least add a warning for this
6084 // (non-conforming) extension.
6085 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6086 SCS.getToType(Idx: 2)->isBooleanType();
6087
6088 case ICK_Pointer_Conversion:
6089 case ICK_Pointer_Member:
6090 // C++1z: null pointer conversions and null member pointer conversions are
6091 // only permitted if the source type is std::nullptr_t.
6092 return SCS.getFromType()->isNullPtrType();
6093
6094 case ICK_Floating_Promotion:
6095 case ICK_Complex_Promotion:
6096 case ICK_Floating_Conversion:
6097 case ICK_Complex_Conversion:
6098 case ICK_Floating_Integral:
6099 case ICK_Compatible_Conversion:
6100 case ICK_Derived_To_Base:
6101 case ICK_Vector_Conversion:
6102 case ICK_SVE_Vector_Conversion:
6103 case ICK_RVV_Vector_Conversion:
6104 case ICK_Vector_Splat:
6105 case ICK_Complex_Real:
6106 case ICK_Block_Pointer_Conversion:
6107 case ICK_TransparentUnionConversion:
6108 case ICK_Writeback_Conversion:
6109 case ICK_Zero_Event_Conversion:
6110 case ICK_C_Only_Conversion:
6111 case ICK_Incompatible_Pointer_Conversion:
6112 case ICK_Fixed_Point_Conversion:
6113 case ICK_HLSL_Vector_Truncation:
6114 return false;
6115
6116 case ICK_Lvalue_To_Rvalue:
6117 case ICK_Array_To_Pointer:
6118 case ICK_Function_To_Pointer:
6119 case ICK_HLSL_Array_RValue:
6120 llvm_unreachable("found a first conversion kind in Second");
6121
6122 case ICK_Function_Conversion:
6123 case ICK_Qualification:
6124 llvm_unreachable("found a third conversion kind in Second");
6125
6126 case ICK_Num_Conversion_Kinds:
6127 break;
6128 }
6129
6130 llvm_unreachable("unknown conversion kind");
6131}
6132
6133/// BuildConvertedConstantExpression - Check that the expression From is a
6134/// converted constant expression of type T, perform the conversion but
6135/// does not evaluate the expression
6136static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6137 QualType T,
6138 Sema::CCEKind CCE,
6139 NamedDecl *Dest,
6140 APValue &PreNarrowingValue) {
6141 assert(S.getLangOpts().CPlusPlus11 &&
6142 "converted constant expression outside C++11");
6143
6144 if (checkPlaceholderForOverload(S, E&: From))
6145 return ExprError();
6146
6147 // C++1z [expr.const]p3:
6148 // A converted constant expression of type T is an expression,
6149 // implicitly converted to type T, where the converted
6150 // expression is a constant expression and the implicit conversion
6151 // sequence contains only [... list of conversions ...].
6152 ImplicitConversionSequence ICS =
6153 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
6154 ? TryContextuallyConvertToBool(S, From)
6155 : TryCopyInitialization(S, From, ToType: T,
6156 /*SuppressUserConversions=*/false,
6157 /*InOverloadResolution=*/false,
6158 /*AllowObjCWritebackConversion=*/false,
6159 /*AllowExplicit=*/false);
6160 StandardConversionSequence *SCS = nullptr;
6161 switch (ICS.getKind()) {
6162 case ImplicitConversionSequence::StandardConversion:
6163 SCS = &ICS.Standard;
6164 break;
6165 case ImplicitConversionSequence::UserDefinedConversion:
6166 if (T->isRecordType())
6167 SCS = &ICS.UserDefined.Before;
6168 else
6169 SCS = &ICS.UserDefined.After;
6170 break;
6171 case ImplicitConversionSequence::AmbiguousConversion:
6172 case ImplicitConversionSequence::BadConversion:
6173 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6174 return S.Diag(From->getBeginLoc(),
6175 diag::err_typecheck_converted_constant_expression)
6176 << From->getType() << From->getSourceRange() << T;
6177 return ExprError();
6178
6179 case ImplicitConversionSequence::EllipsisConversion:
6180 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6181 llvm_unreachable("bad conversion in converted constant expression");
6182 }
6183
6184 // Check that we would only use permitted conversions.
6185 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6186 return S.Diag(From->getBeginLoc(),
6187 diag::err_typecheck_converted_constant_expression_disallowed)
6188 << From->getType() << From->getSourceRange() << T;
6189 }
6190 // [...] and where the reference binding (if any) binds directly.
6191 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6192 return S.Diag(From->getBeginLoc(),
6193 diag::err_typecheck_converted_constant_expression_indirect)
6194 << From->getType() << From->getSourceRange() << T;
6195 }
6196 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6197 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6198 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6199 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6200 // case explicitly.
6201 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6202 return S.Diag(From->getBeginLoc(),
6203 diag::err_reference_bind_to_bitfield_in_cce)
6204 << From->getSourceRange();
6205 }
6206
6207 // Usually we can simply apply the ImplicitConversionSequence we formed
6208 // earlier, but that's not guaranteed to work when initializing an object of
6209 // class type.
6210 ExprResult Result;
6211 if (T->isRecordType()) {
6212 assert(CCE == Sema::CCEK_TemplateArg &&
6213 "unexpected class type converted constant expr");
6214 Result = S.PerformCopyInitialization(
6215 Entity: InitializedEntity::InitializeTemplateParameter(
6216 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6217 EqualLoc: SourceLocation(), Init: From);
6218 } else {
6219 Result = S.PerformImplicitConversion(From, ToType: T, ICS, Action: Sema::AA_Converting);
6220 }
6221 if (Result.isInvalid())
6222 return Result;
6223
6224 // C++2a [intro.execution]p5:
6225 // A full-expression is [...] a constant-expression [...]
6226 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6227 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6228 IsTemplateArgument: CCE == Sema::CCEKind::CCEK_TemplateArg);
6229 if (Result.isInvalid())
6230 return Result;
6231
6232 // Check for a narrowing implicit conversion.
6233 bool ReturnPreNarrowingValue = false;
6234 QualType PreNarrowingType;
6235 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6236 ConstantType&: PreNarrowingType)) {
6237 case NK_Dependent_Narrowing:
6238 // Implicit conversion to a narrower type, but the expression is
6239 // value-dependent so we can't tell whether it's actually narrowing.
6240 case NK_Variable_Narrowing:
6241 // Implicit conversion to a narrower type, and the value is not a constant
6242 // expression. We'll diagnose this in a moment.
6243 case NK_Not_Narrowing:
6244 break;
6245
6246 case NK_Constant_Narrowing:
6247 if (CCE == Sema::CCEK_ArrayBound &&
6248 PreNarrowingType->isIntegralOrEnumerationType() &&
6249 PreNarrowingValue.isInt()) {
6250 // Don't diagnose array bound narrowing here; we produce more precise
6251 // errors by allowing the un-narrowed value through.
6252 ReturnPreNarrowingValue = true;
6253 break;
6254 }
6255 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6256 << CCE << /*Constant*/ 1
6257 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6258 break;
6259
6260 case NK_Type_Narrowing:
6261 // FIXME: It would be better to diagnose that the expression is not a
6262 // constant expression.
6263 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6264 << CCE << /*Constant*/ 0 << From->getType() << T;
6265 break;
6266 }
6267 if (!ReturnPreNarrowingValue)
6268 PreNarrowingValue = {};
6269
6270 return Result;
6271}
6272
6273/// CheckConvertedConstantExpression - Check that the expression From is a
6274/// converted constant expression of type T, perform the conversion and produce
6275/// the converted expression, per C++11 [expr.const]p3.
6276static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6277 QualType T, APValue &Value,
6278 Sema::CCEKind CCE,
6279 bool RequireInt,
6280 NamedDecl *Dest) {
6281
6282 APValue PreNarrowingValue;
6283 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6284 PreNarrowingValue);
6285 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6286 Value = APValue();
6287 return Result;
6288 }
6289 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6290 RequireInt, PreNarrowingValue);
6291}
6292
6293ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6294 CCEKind CCE,
6295 NamedDecl *Dest) {
6296 APValue PreNarrowingValue;
6297 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6298 PreNarrowingValue);
6299}
6300
6301ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6302 APValue &Value, CCEKind CCE,
6303 NamedDecl *Dest) {
6304 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6305 Dest);
6306}
6307
6308ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6309 llvm::APSInt &Value,
6310 CCEKind CCE) {
6311 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6312
6313 APValue V;
6314 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6315 /*Dest=*/nullptr);
6316 if (!R.isInvalid() && !R.get()->isValueDependent())
6317 Value = V.getInt();
6318 return R;
6319}
6320
6321/// EvaluateConvertedConstantExpression - Evaluate an Expression
6322/// That is a converted constant expression
6323/// (which was built with BuildConvertedConstantExpression)
6324ExprResult
6325Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6326 Sema::CCEKind CCE, bool RequireInt,
6327 const APValue &PreNarrowingValue) {
6328
6329 ExprResult Result = E;
6330 // Check the expression is a constant expression.
6331 SmallVector<PartialDiagnosticAt, 8> Notes;
6332 Expr::EvalResult Eval;
6333 Eval.Diag = &Notes;
6334
6335 ConstantExprKind Kind;
6336 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6337 Kind = ConstantExprKind::ClassTemplateArgument;
6338 else if (CCE == Sema::CCEK_TemplateArg)
6339 Kind = ConstantExprKind::NonClassTemplateArgument;
6340 else
6341 Kind = ConstantExprKind::Normal;
6342
6343 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6344 (RequireInt && !Eval.Val.isInt())) {
6345 // The expression can't be folded, so we can't keep it at this position in
6346 // the AST.
6347 Result = ExprError();
6348 } else {
6349 Value = Eval.Val;
6350
6351 if (Notes.empty()) {
6352 // It's a constant expression.
6353 Expr *E = Result.get();
6354 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6355 // We expect a ConstantExpr to have a value associated with it
6356 // by this point.
6357 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6358 "ConstantExpr has no value associated with it");
6359 (void)CE;
6360 } else {
6361 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6362 }
6363 if (!PreNarrowingValue.isAbsent())
6364 Value = std::move(PreNarrowingValue);
6365 return E;
6366 }
6367 }
6368
6369 // It's not a constant expression. Produce an appropriate diagnostic.
6370 if (Notes.size() == 1 &&
6371 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6372 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6373 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6374 diag::note_constexpr_invalid_template_arg) {
6375 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6376 for (unsigned I = 0; I < Notes.size(); ++I)
6377 Diag(Notes[I].first, Notes[I].second);
6378 } else {
6379 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6380 << CCE << E->getSourceRange();
6381 for (unsigned I = 0; I < Notes.size(); ++I)
6382 Diag(Notes[I].first, Notes[I].second);
6383 }
6384 return ExprError();
6385}
6386
6387/// dropPointerConversions - If the given standard conversion sequence
6388/// involves any pointer conversions, remove them. This may change
6389/// the result type of the conversion sequence.
6390static void dropPointerConversion(StandardConversionSequence &SCS) {
6391 if (SCS.Second == ICK_Pointer_Conversion) {
6392 SCS.Second = ICK_Identity;
6393 SCS.Element = ICK_Identity;
6394 SCS.Third = ICK_Identity;
6395 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6396 }
6397}
6398
6399/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6400/// convert the expression From to an Objective-C pointer type.
6401static ImplicitConversionSequence
6402TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6403 // Do an implicit conversion to 'id'.
6404 QualType Ty = S.Context.getObjCIdType();
6405 ImplicitConversionSequence ICS
6406 = TryImplicitConversion(S, From, ToType: Ty,
6407 // FIXME: Are these flags correct?
6408 /*SuppressUserConversions=*/false,
6409 AllowExplicit: AllowedExplicit::Conversions,
6410 /*InOverloadResolution=*/false,
6411 /*CStyle=*/false,
6412 /*AllowObjCWritebackConversion=*/false,
6413 /*AllowObjCConversionOnExplicit=*/true);
6414
6415 // Strip off any final conversions to 'id'.
6416 switch (ICS.getKind()) {
6417 case ImplicitConversionSequence::BadConversion:
6418 case ImplicitConversionSequence::AmbiguousConversion:
6419 case ImplicitConversionSequence::EllipsisConversion:
6420 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6421 break;
6422
6423 case ImplicitConversionSequence::UserDefinedConversion:
6424 dropPointerConversion(SCS&: ICS.UserDefined.After);
6425 break;
6426
6427 case ImplicitConversionSequence::StandardConversion:
6428 dropPointerConversion(SCS&: ICS.Standard);
6429 break;
6430 }
6431
6432 return ICS;
6433}
6434
6435/// PerformContextuallyConvertToObjCPointer - Perform a contextual
6436/// conversion of the expression From to an Objective-C pointer type.
6437/// Returns a valid but null ExprResult if no conversion sequence exists.
6438ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6439 if (checkPlaceholderForOverload(S&: *this, E&: From))
6440 return ExprError();
6441
6442 QualType Ty = Context.getObjCIdType();
6443 ImplicitConversionSequence ICS =
6444 TryContextuallyConvertToObjCPointer(S&: *this, From);
6445 if (!ICS.isBad())
6446 return PerformImplicitConversion(From, ToType: Ty, ICS, Action: AA_Converting);
6447 return ExprResult();
6448}
6449
6450static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6451 const Expr *Base = nullptr;
6452 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6453 "expected a member expression");
6454
6455 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6456 M && !M->isImplicitAccess())
6457 Base = M->getBase();
6458 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6459 M && !M->isImplicitAccess())
6460 Base = M->getBase();
6461
6462 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6463
6464 if (T->isPointerType())
6465 T = T->getPointeeType();
6466
6467 return T;
6468}
6469
6470static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6471 const FunctionDecl *Fun) {
6472 QualType ObjType = Obj->getType();
6473 if (ObjType->isPointerType()) {
6474 ObjType = ObjType->getPointeeType();
6475 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6476 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6477 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6478 }
6479 if (Obj->Classify(Ctx&: S.getASTContext()).isPRValue()) {
6480 Obj = S.CreateMaterializeTemporaryExpr(
6481 T: ObjType, Temporary: Obj,
6482 BoundToLvalueReference: !Fun->getParamDecl(i: 0)->getType()->isRValueReferenceType());
6483 }
6484 return Obj;
6485}
6486
6487ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6488 FunctionDecl *Fun) {
6489 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6490 return S.PerformCopyInitialization(
6491 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6492 EqualLoc: Obj->getExprLoc(), Init: Obj);
6493}
6494
6495static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6496 Expr *Object, MultiExprArg &Args,
6497 SmallVectorImpl<Expr *> &NewArgs) {
6498 assert(Method->isExplicitObjectMemberFunction() &&
6499 "Method is not an explicit member function");
6500 assert(NewArgs.empty() && "NewArgs should be empty");
6501 NewArgs.reserve(N: Args.size() + 1);
6502 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6503 NewArgs.push_back(Elt: This);
6504 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6505 Args = NewArgs;
6506}
6507
6508/// Determine whether the provided type is an integral type, or an enumeration
6509/// type of a permitted flavor.
6510bool Sema::ICEConvertDiagnoser::match(QualType T) {
6511 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6512 : T->isIntegralOrUnscopedEnumerationType();
6513}
6514
6515static ExprResult
6516diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6517 Sema::ContextualImplicitConverter &Converter,
6518 QualType T, UnresolvedSetImpl &ViableConversions) {
6519
6520 if (Converter.Suppress)
6521 return ExprError();
6522
6523 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6524 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6525 CXXConversionDecl *Conv =
6526 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6527 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6528 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6529 }
6530 return From;
6531}
6532
6533static bool
6534diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6535 Sema::ContextualImplicitConverter &Converter,
6536 QualType T, bool HadMultipleCandidates,
6537 UnresolvedSetImpl &ExplicitConversions) {
6538 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6539 DeclAccessPair Found = ExplicitConversions[0];
6540 CXXConversionDecl *Conversion =
6541 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6542
6543 // The user probably meant to invoke the given explicit
6544 // conversion; use it.
6545 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6546 std::string TypeStr;
6547 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6548
6549 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6550 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6551 Code: "static_cast<" + TypeStr + ">(")
6552 << FixItHint::CreateInsertion(
6553 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6554 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6555
6556 // If we aren't in a SFINAE context, build a call to the
6557 // explicit conversion function.
6558 if (SemaRef.isSFINAEContext())
6559 return true;
6560
6561 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6562 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6563 HadMultipleCandidates);
6564 if (Result.isInvalid())
6565 return true;
6566
6567 // Replace the conversion with a RecoveryExpr, so we don't try to
6568 // instantiate it later, but can further diagnose here.
6569 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6570 SubExprs: From, T: Result.get()->getType());
6571 if (Result.isInvalid())
6572 return true;
6573 From = Result.get();
6574 }
6575 return false;
6576}
6577
6578static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6579 Sema::ContextualImplicitConverter &Converter,
6580 QualType T, bool HadMultipleCandidates,
6581 DeclAccessPair &Found) {
6582 CXXConversionDecl *Conversion =
6583 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6584 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6585
6586 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6587 if (!Converter.SuppressConversion) {
6588 if (SemaRef.isSFINAEContext())
6589 return true;
6590
6591 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6592 << From->getSourceRange();
6593 }
6594
6595 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6596 HadMultipleCandidates);
6597 if (Result.isInvalid())
6598 return true;
6599 // Record usage of conversion in an implicit cast.
6600 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6601 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6602 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6603 FPO: SemaRef.CurFPFeatureOverrides());
6604 return false;
6605}
6606
6607static ExprResult finishContextualImplicitConversion(
6608 Sema &SemaRef, SourceLocation Loc, Expr *From,
6609 Sema::ContextualImplicitConverter &Converter) {
6610 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6611 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6612 << From->getSourceRange();
6613
6614 return SemaRef.DefaultLvalueConversion(E: From);
6615}
6616
6617static void
6618collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6619 UnresolvedSetImpl &ViableConversions,
6620 OverloadCandidateSet &CandidateSet) {
6621 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6622 DeclAccessPair FoundDecl = ViableConversions[I];
6623 NamedDecl *D = FoundDecl.getDecl();
6624 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6625 if (isa<UsingShadowDecl>(Val: D))
6626 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6627
6628 CXXConversionDecl *Conv;
6629 FunctionTemplateDecl *ConvTemplate;
6630 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
6631 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6632 else
6633 Conv = cast<CXXConversionDecl>(Val: D);
6634
6635 if (ConvTemplate)
6636 SemaRef.AddTemplateConversionCandidate(
6637 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6638 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6639 else
6640 SemaRef.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From,
6641 ToType, CandidateSet,
6642 /*AllowObjCConversionOnExplicit=*/false,
6643 /*AllowExplicit*/ true);
6644 }
6645}
6646
6647/// Attempt to convert the given expression to a type which is accepted
6648/// by the given converter.
6649///
6650/// This routine will attempt to convert an expression of class type to a
6651/// type accepted by the specified converter. In C++11 and before, the class
6652/// must have a single non-explicit conversion function converting to a matching
6653/// type. In C++1y, there can be multiple such conversion functions, but only
6654/// one target type.
6655///
6656/// \param Loc The source location of the construct that requires the
6657/// conversion.
6658///
6659/// \param From The expression we're converting from.
6660///
6661/// \param Converter Used to control and diagnose the conversion process.
6662///
6663/// \returns The expression, converted to an integral or enumeration type if
6664/// successful.
6665ExprResult Sema::PerformContextualImplicitConversion(
6666 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6667 // We can't perform any more checking for type-dependent expressions.
6668 if (From->isTypeDependent())
6669 return From;
6670
6671 // Process placeholders immediately.
6672 if (From->hasPlaceholderType()) {
6673 ExprResult result = CheckPlaceholderExpr(E: From);
6674 if (result.isInvalid())
6675 return result;
6676 From = result.get();
6677 }
6678
6679 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6680 ExprResult Converted = DefaultLvalueConversion(E: From);
6681 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6682 // If the expression already has a matching type, we're golden.
6683 if (Converter.match(T))
6684 return Converted;
6685
6686 // FIXME: Check for missing '()' if T is a function type?
6687
6688 // We can only perform contextual implicit conversions on objects of class
6689 // type.
6690 const RecordType *RecordTy = T->getAs<RecordType>();
6691 if (!RecordTy || !getLangOpts().CPlusPlus) {
6692 if (!Converter.Suppress)
6693 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
6694 return From;
6695 }
6696
6697 // We must have a complete class type.
6698 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6699 ContextualImplicitConverter &Converter;
6700 Expr *From;
6701
6702 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6703 : Converter(Converter), From(From) {}
6704
6705 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6706 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6707 }
6708 } IncompleteDiagnoser(Converter, From);
6709
6710 if (Converter.Suppress ? !isCompleteType(Loc, T)
6711 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
6712 return From;
6713
6714 // Look for a conversion to an integral or enumeration type.
6715 UnresolvedSet<4>
6716 ViableConversions; // These are *potentially* viable in C++1y.
6717 UnresolvedSet<4> ExplicitConversions;
6718 const auto &Conversions =
6719 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getVisibleConversionFunctions();
6720
6721 bool HadMultipleCandidates =
6722 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
6723
6724 // To check that there is only one target type, in C++1y:
6725 QualType ToType;
6726 bool HasUniqueTargetType = true;
6727
6728 // Collect explicit or viable (potentially in C++1y) conversions.
6729 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6730 NamedDecl *D = (*I)->getUnderlyingDecl();
6731 CXXConversionDecl *Conversion;
6732 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6733 if (ConvTemplate) {
6734 if (getLangOpts().CPlusPlus14)
6735 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6736 else
6737 continue; // C++11 does not consider conversion operator templates(?).
6738 } else
6739 Conversion = cast<CXXConversionDecl>(Val: D);
6740
6741 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6742 "Conversion operator templates are considered potentially "
6743 "viable in C++1y");
6744
6745 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6746 if (Converter.match(T: CurToType) || ConvTemplate) {
6747
6748 if (Conversion->isExplicit()) {
6749 // FIXME: For C++1y, do we need this restriction?
6750 // cf. diagnoseNoViableConversion()
6751 if (!ConvTemplate)
6752 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6753 } else {
6754 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6755 if (ToType.isNull())
6756 ToType = CurToType.getUnqualifiedType();
6757 else if (HasUniqueTargetType &&
6758 (CurToType.getUnqualifiedType() != ToType))
6759 HasUniqueTargetType = false;
6760 }
6761 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6762 }
6763 }
6764 }
6765
6766 if (getLangOpts().CPlusPlus14) {
6767 // C++1y [conv]p6:
6768 // ... An expression e of class type E appearing in such a context
6769 // is said to be contextually implicitly converted to a specified
6770 // type T and is well-formed if and only if e can be implicitly
6771 // converted to a type T that is determined as follows: E is searched
6772 // for conversion functions whose return type is cv T or reference to
6773 // cv T such that T is allowed by the context. There shall be
6774 // exactly one such T.
6775
6776 // If no unique T is found:
6777 if (ToType.isNull()) {
6778 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6779 HadMultipleCandidates,
6780 ExplicitConversions))
6781 return ExprError();
6782 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6783 }
6784
6785 // If more than one unique Ts are found:
6786 if (!HasUniqueTargetType)
6787 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6788 ViableConversions);
6789
6790 // If one unique T is found:
6791 // First, build a candidate set from the previously recorded
6792 // potentially viable conversions.
6793 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6794 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
6795 CandidateSet);
6796
6797 // Then, perform overload resolution over the candidate set.
6798 OverloadCandidateSet::iterator Best;
6799 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
6800 case OR_Success: {
6801 // Apply this conversion.
6802 DeclAccessPair Found =
6803 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6804 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6805 HadMultipleCandidates, Found))
6806 return ExprError();
6807 break;
6808 }
6809 case OR_Ambiguous:
6810 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6811 ViableConversions);
6812 case OR_No_Viable_Function:
6813 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6814 HadMultipleCandidates,
6815 ExplicitConversions))
6816 return ExprError();
6817 [[fallthrough]];
6818 case OR_Deleted:
6819 // We'll complain below about a non-integral condition type.
6820 break;
6821 }
6822 } else {
6823 switch (ViableConversions.size()) {
6824 case 0: {
6825 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6826 HadMultipleCandidates,
6827 ExplicitConversions))
6828 return ExprError();
6829
6830 // We'll complain below about a non-integral condition type.
6831 break;
6832 }
6833 case 1: {
6834 // Apply this conversion.
6835 DeclAccessPair Found = ViableConversions[0];
6836 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6837 HadMultipleCandidates, Found))
6838 return ExprError();
6839 break;
6840 }
6841 default:
6842 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6843 ViableConversions);
6844 }
6845 }
6846
6847 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6848}
6849
6850/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6851/// an acceptable non-member overloaded operator for a call whose
6852/// arguments have types T1 (and, if non-empty, T2). This routine
6853/// implements the check in C++ [over.match.oper]p3b2 concerning
6854/// enumeration types.
6855static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6856 FunctionDecl *Fn,
6857 ArrayRef<Expr *> Args) {
6858 QualType T1 = Args[0]->getType();
6859 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6860
6861 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6862 return true;
6863
6864 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6865 return true;
6866
6867 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6868 if (Proto->getNumParams() < 1)
6869 return false;
6870
6871 if (T1->isEnumeralType()) {
6872 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6873 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
6874 return true;
6875 }
6876
6877 if (Proto->getNumParams() < 2)
6878 return false;
6879
6880 if (!T2.isNull() && T2->isEnumeralType()) {
6881 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6882 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
6883 return true;
6884 }
6885
6886 return false;
6887}
6888
6889static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
6890 if (FD->isTargetMultiVersionDefault())
6891 return false;
6892
6893 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6894 return FD->isTargetMultiVersion();
6895
6896 if (!FD->isMultiVersion())
6897 return false;
6898
6899 // Among multiple target versions consider either the default,
6900 // or the first non-default in the absence of default version.
6901 unsigned SeenAt = 0;
6902 unsigned I = 0;
6903 bool HasDefault = false;
6904 FD->getASTContext().forEachMultiversionedFunctionVersion(
6905 FD, [&](const FunctionDecl *CurFD) {
6906 if (FD == CurFD)
6907 SeenAt = I;
6908 else if (CurFD->isTargetMultiVersionDefault())
6909 HasDefault = true;
6910 ++I;
6911 });
6912 return HasDefault || SeenAt != 0;
6913}
6914
6915/// AddOverloadCandidate - Adds the given function to the set of
6916/// candidate functions, using the given function call arguments. If
6917/// @p SuppressUserConversions, then don't allow user-defined
6918/// conversions via constructors or conversion operators.
6919///
6920/// \param PartialOverloading true if we are performing "partial" overloading
6921/// based on an incomplete set of function arguments. This feature is used by
6922/// code completion.
6923void Sema::AddOverloadCandidate(
6924 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6925 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6926 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6927 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6928 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6929 const FunctionProtoType *Proto
6930 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6931 assert(Proto && "Functions without a prototype cannot be overloaded");
6932 assert(!Function->getDescribedFunctionTemplate() &&
6933 "Use AddTemplateOverloadCandidate for function templates");
6934
6935 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
6936 if (!isa<CXXConstructorDecl>(Val: Method)) {
6937 // If we get here, it's because we're calling a member function
6938 // that is named without a member access expression (e.g.,
6939 // "this->f") that was either written explicitly or created
6940 // implicitly. This can happen with a qualified call to a member
6941 // function, e.g., X::f(). We use an empty type for the implied
6942 // object argument (C++ [over.call.func]p3), and the acting context
6943 // is irrelevant.
6944 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
6945 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
6946 CandidateSet, SuppressUserConversions,
6947 PartialOverloading, EarlyConversions, PO);
6948 return;
6949 }
6950 // We treat a constructor like a non-member function, since its object
6951 // argument doesn't participate in overload resolution.
6952 }
6953
6954 if (!CandidateSet.isNewCandidate(Function, PO))
6955 return;
6956
6957 // C++11 [class.copy]p11: [DR1402]
6958 // A defaulted move constructor that is defined as deleted is ignored by
6959 // overload resolution.
6960 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
6961 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6962 Constructor->isMoveConstructor())
6963 return;
6964
6965 // Overload resolution is always an unevaluated context.
6966 EnterExpressionEvaluationContext Unevaluated(
6967 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6968
6969 // C++ [over.match.oper]p3:
6970 // if no operand has a class type, only those non-member functions in the
6971 // lookup set that have a first parameter of type T1 or "reference to
6972 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6973 // is a right operand) a second parameter of type T2 or "reference to
6974 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6975 // candidate functions.
6976 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6977 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
6978 return;
6979
6980 // Add this candidate
6981 OverloadCandidate &Candidate =
6982 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
6983 Candidate.FoundDecl = FoundDecl;
6984 Candidate.Function = Function;
6985 Candidate.Viable = true;
6986 Candidate.RewriteKind =
6987 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
6988 Candidate.IsSurrogate = false;
6989 Candidate.IsADLCandidate = IsADLCandidate;
6990 Candidate.IgnoreObjectArgument = false;
6991 Candidate.ExplicitCallArguments = Args.size();
6992
6993 // Explicit functions are not actually candidates at all if we're not
6994 // allowing them in this context, but keep them around so we can point
6995 // to them in diagnostics.
6996 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6997 Candidate.Viable = false;
6998 Candidate.FailureKind = ovl_fail_explicit;
6999 return;
7000 }
7001
7002 // Functions with internal linkage are only viable in the same module unit.
7003 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7004 /// FIXME: Currently, the semantics of linkage in clang is slightly
7005 /// different from the semantics in C++ spec. In C++ spec, only names
7006 /// have linkage. So that all entities of the same should share one
7007 /// linkage. But in clang, different entities of the same could have
7008 /// different linkage.
7009 NamedDecl *ND = Function;
7010 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
7011 ND = SpecInfo->getTemplate();
7012
7013 if (ND->getFormalLinkage() == Linkage::Internal) {
7014 Candidate.Viable = false;
7015 Candidate.FailureKind = ovl_fail_module_mismatched;
7016 return;
7017 }
7018 }
7019
7020 if (isNonViableMultiVersionOverload(FD: Function)) {
7021 Candidate.Viable = false;
7022 Candidate.FailureKind = ovl_non_default_multiversion_function;
7023 return;
7024 }
7025
7026 if (Constructor) {
7027 // C++ [class.copy]p3:
7028 // A member function template is never instantiated to perform the copy
7029 // of a class object to an object of its class type.
7030 QualType ClassType = Context.getTypeDeclType(Decl: Constructor->getParent());
7031 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7032 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7033 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7034 ClassType))) {
7035 Candidate.Viable = false;
7036 Candidate.FailureKind = ovl_fail_illegal_constructor;
7037 return;
7038 }
7039
7040 // C++ [over.match.funcs]p8: (proposed DR resolution)
7041 // A constructor inherited from class type C that has a first parameter
7042 // of type "reference to P" (including such a constructor instantiated
7043 // from a template) is excluded from the set of candidate functions when
7044 // constructing an object of type cv D if the argument list has exactly
7045 // one argument and D is reference-related to P and P is reference-related
7046 // to C.
7047 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7048 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7049 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7050 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7051 QualType C = Context.getRecordType(Decl: Constructor->getParent());
7052 QualType D = Context.getRecordType(Shadow->getParent());
7053 SourceLocation Loc = Args.front()->getExprLoc();
7054 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7055 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7056 Candidate.Viable = false;
7057 Candidate.FailureKind = ovl_fail_inhctor_slice;
7058 return;
7059 }
7060 }
7061
7062 // Check that the constructor is capable of constructing an object in the
7063 // destination address space.
7064 if (!Qualifiers::isAddressSpaceSupersetOf(
7065 Constructor->getMethodQualifiers().getAddressSpace(),
7066 CandidateSet.getDestAS())) {
7067 Candidate.Viable = false;
7068 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7069 }
7070 }
7071
7072 unsigned NumParams = Proto->getNumParams();
7073
7074 // (C++ 13.3.2p2): A candidate function having fewer than m
7075 // parameters is viable only if it has an ellipsis in its parameter
7076 // list (8.3.5).
7077 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7078 !Proto->isVariadic() &&
7079 shouldEnforceArgLimit(PartialOverloading, Function)) {
7080 Candidate.Viable = false;
7081 Candidate.FailureKind = ovl_fail_too_many_arguments;
7082 return;
7083 }
7084
7085 // (C++ 13.3.2p2): A candidate function having more than m parameters
7086 // is viable only if the (m+1)st parameter has a default argument
7087 // (8.3.6). For the purposes of overload resolution, the
7088 // parameter list is truncated on the right, so that there are
7089 // exactly m parameters.
7090 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7091 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7092 !PartialOverloading) {
7093 // Not enough arguments.
7094 Candidate.Viable = false;
7095 Candidate.FailureKind = ovl_fail_too_few_arguments;
7096 return;
7097 }
7098
7099 // (CUDA B.1): Check for invalid calls between targets.
7100 if (getLangOpts().CUDA) {
7101 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7102 // Skip the check for callers that are implicit members, because in this
7103 // case we may not yet know what the member's target is; the target is
7104 // inferred for the member automatically, based on the bases and fields of
7105 // the class.
7106 if (!(Caller && Caller->isImplicit()) &&
7107 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7108 Candidate.Viable = false;
7109 Candidate.FailureKind = ovl_fail_bad_target;
7110 return;
7111 }
7112 }
7113
7114 if (Function->getTrailingRequiresClause()) {
7115 ConstraintSatisfaction Satisfaction;
7116 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7117 /*ForOverloadResolution*/ true) ||
7118 !Satisfaction.IsSatisfied) {
7119 Candidate.Viable = false;
7120 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7121 return;
7122 }
7123 }
7124
7125 // Determine the implicit conversion sequences for each of the
7126 // arguments.
7127 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7128 unsigned ConvIdx =
7129 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7130 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7131 // We already formed a conversion sequence for this parameter during
7132 // template argument deduction.
7133 } else if (ArgIdx < NumParams) {
7134 // (C++ 13.3.2p3): for F to be a viable function, there shall
7135 // exist for each argument an implicit conversion sequence
7136 // (13.3.3.1) that converts that argument to the corresponding
7137 // parameter of F.
7138 QualType ParamType = Proto->getParamType(i: ArgIdx);
7139 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7140 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7141 /*InOverloadResolution=*/true,
7142 /*AllowObjCWritebackConversion=*/
7143 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7144 if (Candidate.Conversions[ConvIdx].isBad()) {
7145 Candidate.Viable = false;
7146 Candidate.FailureKind = ovl_fail_bad_conversion;
7147 return;
7148 }
7149 } else {
7150 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7151 // argument for which there is no corresponding parameter is
7152 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7153 Candidate.Conversions[ConvIdx].setEllipsis();
7154 }
7155 }
7156
7157 if (EnableIfAttr *FailedAttr =
7158 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7159 Candidate.Viable = false;
7160 Candidate.FailureKind = ovl_fail_enable_if;
7161 Candidate.DeductionFailure.Data = FailedAttr;
7162 return;
7163 }
7164}
7165
7166ObjCMethodDecl *
7167Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7168 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7169 if (Methods.size() <= 1)
7170 return nullptr;
7171
7172 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7173 bool Match = true;
7174 ObjCMethodDecl *Method = Methods[b];
7175 unsigned NumNamedArgs = Sel.getNumArgs();
7176 // Method might have more arguments than selector indicates. This is due
7177 // to addition of c-style arguments in method.
7178 if (Method->param_size() > NumNamedArgs)
7179 NumNamedArgs = Method->param_size();
7180 if (Args.size() < NumNamedArgs)
7181 continue;
7182
7183 for (unsigned i = 0; i < NumNamedArgs; i++) {
7184 // We can't do any type-checking on a type-dependent argument.
7185 if (Args[i]->isTypeDependent()) {
7186 Match = false;
7187 break;
7188 }
7189
7190 ParmVarDecl *param = Method->parameters()[i];
7191 Expr *argExpr = Args[i];
7192 assert(argExpr && "SelectBestMethod(): missing expression");
7193
7194 // Strip the unbridged-cast placeholder expression off unless it's
7195 // a consumed argument.
7196 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7197 !param->hasAttr<CFConsumedAttr>())
7198 argExpr = stripARCUnbridgedCast(e: argExpr);
7199
7200 // If the parameter is __unknown_anytype, move on to the next method.
7201 if (param->getType() == Context.UnknownAnyTy) {
7202 Match = false;
7203 break;
7204 }
7205
7206 ImplicitConversionSequence ConversionState
7207 = TryCopyInitialization(*this, argExpr, param->getType(),
7208 /*SuppressUserConversions*/false,
7209 /*InOverloadResolution=*/true,
7210 /*AllowObjCWritebackConversion=*/
7211 getLangOpts().ObjCAutoRefCount,
7212 /*AllowExplicit*/false);
7213 // This function looks for a reasonably-exact match, so we consider
7214 // incompatible pointer conversions to be a failure here.
7215 if (ConversionState.isBad() ||
7216 (ConversionState.isStandard() &&
7217 ConversionState.Standard.Second ==
7218 ICK_Incompatible_Pointer_Conversion)) {
7219 Match = false;
7220 break;
7221 }
7222 }
7223 // Promote additional arguments to variadic methods.
7224 if (Match && Method->isVariadic()) {
7225 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7226 if (Args[i]->isTypeDependent()) {
7227 Match = false;
7228 break;
7229 }
7230 ExprResult Arg = DefaultVariadicArgumentPromotion(E: Args[i], CT: VariadicMethod,
7231 FDecl: nullptr);
7232 if (Arg.isInvalid()) {
7233 Match = false;
7234 break;
7235 }
7236 }
7237 } else {
7238 // Check for extra arguments to non-variadic methods.
7239 if (Args.size() != NumNamedArgs)
7240 Match = false;
7241 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7242 // Special case when selectors have no argument. In this case, select
7243 // one with the most general result type of 'id'.
7244 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7245 QualType ReturnT = Methods[b]->getReturnType();
7246 if (ReturnT->isObjCIdType())
7247 return Methods[b];
7248 }
7249 }
7250 }
7251
7252 if (Match)
7253 return Method;
7254 }
7255 return nullptr;
7256}
7257
7258static bool convertArgsForAvailabilityChecks(
7259 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7260 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7261 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7262 if (ThisArg) {
7263 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7264 assert(!isa<CXXConstructorDecl>(Method) &&
7265 "Shouldn't have `this` for ctors!");
7266 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7267 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7268 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7269 if (R.isInvalid())
7270 return false;
7271 ConvertedThis = R.get();
7272 } else {
7273 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7274 (void)MD;
7275 assert((MissingImplicitThis || MD->isStatic() ||
7276 isa<CXXConstructorDecl>(MD)) &&
7277 "Expected `this` for non-ctor instance methods");
7278 }
7279 ConvertedThis = nullptr;
7280 }
7281
7282 // Ignore any variadic arguments. Converting them is pointless, since the
7283 // user can't refer to them in the function condition.
7284 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7285
7286 // Convert the arguments.
7287 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7288 ExprResult R;
7289 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7290 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7291 EqualLoc: SourceLocation(), Init: Args[I]);
7292
7293 if (R.isInvalid())
7294 return false;
7295
7296 ConvertedArgs.push_back(Elt: R.get());
7297 }
7298
7299 if (Trap.hasErrorOccurred())
7300 return false;
7301
7302 // Push default arguments if needed.
7303 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7304 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7305 ParmVarDecl *P = Function->getParamDecl(i);
7306 if (!P->hasDefaultArg())
7307 return false;
7308 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7309 if (R.isInvalid())
7310 return false;
7311 ConvertedArgs.push_back(Elt: R.get());
7312 }
7313
7314 if (Trap.hasErrorOccurred())
7315 return false;
7316 }
7317 return true;
7318}
7319
7320EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7321 SourceLocation CallLoc,
7322 ArrayRef<Expr *> Args,
7323 bool MissingImplicitThis) {
7324 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7325 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7326 return nullptr;
7327
7328 SFINAETrap Trap(*this);
7329 SmallVector<Expr *, 16> ConvertedArgs;
7330 // FIXME: We should look into making enable_if late-parsed.
7331 Expr *DiscardedThis;
7332 if (!convertArgsForAvailabilityChecks(
7333 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7334 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7335 return *EnableIfAttrs.begin();
7336
7337 for (auto *EIA : EnableIfAttrs) {
7338 APValue Result;
7339 // FIXME: This doesn't consider value-dependent cases, because doing so is
7340 // very difficult. Ideally, we should handle them more gracefully.
7341 if (EIA->getCond()->isValueDependent() ||
7342 !EIA->getCond()->EvaluateWithSubstitution(
7343 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7344 return EIA;
7345
7346 if (!Result.isInt() || !Result.getInt().getBoolValue())
7347 return EIA;
7348 }
7349 return nullptr;
7350}
7351
7352template <typename CheckFn>
7353static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7354 bool ArgDependent, SourceLocation Loc,
7355 CheckFn &&IsSuccessful) {
7356 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7357 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7358 if (ArgDependent == DIA->getArgDependent())
7359 Attrs.push_back(DIA);
7360 }
7361
7362 // Common case: No diagnose_if attributes, so we can quit early.
7363 if (Attrs.empty())
7364 return false;
7365
7366 auto WarningBegin = std::stable_partition(
7367 Attrs.begin(), Attrs.end(),
7368 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7369
7370 // Note that diagnose_if attributes are late-parsed, so they appear in the
7371 // correct order (unlike enable_if attributes).
7372 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7373 IsSuccessful);
7374 if (ErrAttr != WarningBegin) {
7375 const DiagnoseIfAttr *DIA = *ErrAttr;
7376 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7377 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7378 << DIA->getParent() << DIA->getCond()->getSourceRange();
7379 return true;
7380 }
7381
7382 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7383 if (IsSuccessful(DIA)) {
7384 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7385 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7386 << DIA->getParent() << DIA->getCond()->getSourceRange();
7387 }
7388
7389 return false;
7390}
7391
7392bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7393 const Expr *ThisArg,
7394 ArrayRef<const Expr *> Args,
7395 SourceLocation Loc) {
7396 return diagnoseDiagnoseIfAttrsWith(
7397 *this, Function, /*ArgDependent=*/true, Loc,
7398 [&](const DiagnoseIfAttr *DIA) {
7399 APValue Result;
7400 // It's sane to use the same Args for any redecl of this function, since
7401 // EvaluateWithSubstitution only cares about the position of each
7402 // argument in the arg list, not the ParmVarDecl* it maps to.
7403 if (!DIA->getCond()->EvaluateWithSubstitution(
7404 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7405 return false;
7406 return Result.isInt() && Result.getInt().getBoolValue();
7407 });
7408}
7409
7410bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7411 SourceLocation Loc) {
7412 return diagnoseDiagnoseIfAttrsWith(
7413 S&: *this, ND, /*ArgDependent=*/false, Loc,
7414 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7415 bool Result;
7416 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7417 Result;
7418 });
7419}
7420
7421/// Add all of the function declarations in the given function set to
7422/// the overload candidate set.
7423void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7424 ArrayRef<Expr *> Args,
7425 OverloadCandidateSet &CandidateSet,
7426 TemplateArgumentListInfo *ExplicitTemplateArgs,
7427 bool SuppressUserConversions,
7428 bool PartialOverloading,
7429 bool FirstArgumentIsBase) {
7430 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7431 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7432 ArrayRef<Expr *> FunctionArgs = Args;
7433
7434 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7435 FunctionDecl *FD =
7436 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7437
7438 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7439 QualType ObjectType;
7440 Expr::Classification ObjectClassification;
7441 if (Args.size() > 0) {
7442 if (Expr *E = Args[0]) {
7443 // Use the explicit base to restrict the lookup:
7444 ObjectType = E->getType();
7445 // Pointers in the object arguments are implicitly dereferenced, so we
7446 // always classify them as l-values.
7447 if (!ObjectType.isNull() && ObjectType->isPointerType())
7448 ObjectClassification = Expr::Classification::makeSimpleLValue();
7449 else
7450 ObjectClassification = E->Classify(Ctx&: Context);
7451 } // .. else there is an implicit base.
7452 FunctionArgs = Args.slice(N: 1);
7453 }
7454 if (FunTmpl) {
7455 AddMethodTemplateCandidate(
7456 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7457 ActingContext: cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7458 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7459 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7460 PartialOverloading);
7461 } else {
7462 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7463 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7464 ObjectClassification, Args: FunctionArgs, CandidateSet,
7465 SuppressUserConversions, PartialOverloading);
7466 }
7467 } else {
7468 // This branch handles both standalone functions and static methods.
7469
7470 // Slice the first argument (which is the base) when we access
7471 // static method as non-static.
7472 if (Args.size() > 0 &&
7473 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7474 !isa<CXXConstructorDecl>(Val: FD)))) {
7475 assert(cast<CXXMethodDecl>(FD)->isStatic());
7476 FunctionArgs = Args.slice(N: 1);
7477 }
7478 if (FunTmpl) {
7479 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7480 ExplicitTemplateArgs, Args: FunctionArgs,
7481 CandidateSet, SuppressUserConversions,
7482 PartialOverloading);
7483 } else {
7484 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7485 SuppressUserConversions, PartialOverloading);
7486 }
7487 }
7488 }
7489}
7490
7491/// AddMethodCandidate - Adds a named decl (which is some kind of
7492/// method) as a method candidate to the given overload set.
7493void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7494 Expr::Classification ObjectClassification,
7495 ArrayRef<Expr *> Args,
7496 OverloadCandidateSet &CandidateSet,
7497 bool SuppressUserConversions,
7498 OverloadCandidateParamOrder PO) {
7499 NamedDecl *Decl = FoundDecl.getDecl();
7500 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7501
7502 if (isa<UsingShadowDecl>(Val: Decl))
7503 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7504
7505 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7506 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7507 "Expected a member function template");
7508 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7509 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7510 ObjectClassification, Args, CandidateSet,
7511 SuppressUserConversions, PartialOverloading: false, PO);
7512 } else {
7513 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7514 ObjectType, ObjectClassification, Args, CandidateSet,
7515 SuppressUserConversions, PartialOverloading: false, EarlyConversions: std::nullopt, PO);
7516 }
7517}
7518
7519/// AddMethodCandidate - Adds the given C++ member function to the set
7520/// of candidate functions, using the given function call arguments
7521/// and the object argument (@c Object). For example, in a call
7522/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7523/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7524/// allow user-defined conversions via constructors or conversion
7525/// operators.
7526void
7527Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7528 CXXRecordDecl *ActingContext, QualType ObjectType,
7529 Expr::Classification ObjectClassification,
7530 ArrayRef<Expr *> Args,
7531 OverloadCandidateSet &CandidateSet,
7532 bool SuppressUserConversions,
7533 bool PartialOverloading,
7534 ConversionSequenceList EarlyConversions,
7535 OverloadCandidateParamOrder PO) {
7536 const FunctionProtoType *Proto
7537 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7538 assert(Proto && "Methods without a prototype cannot be overloaded");
7539 assert(!isa<CXXConstructorDecl>(Method) &&
7540 "Use AddOverloadCandidate for constructors");
7541
7542 if (!CandidateSet.isNewCandidate(Method, PO))
7543 return;
7544
7545 // C++11 [class.copy]p23: [DR1402]
7546 // A defaulted move assignment operator that is defined as deleted is
7547 // ignored by overload resolution.
7548 if (Method->isDefaulted() && Method->isDeleted() &&
7549 Method->isMoveAssignmentOperator())
7550 return;
7551
7552 // Overload resolution is always an unevaluated context.
7553 EnterExpressionEvaluationContext Unevaluated(
7554 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7555
7556 // Add this candidate
7557 OverloadCandidate &Candidate =
7558 CandidateSet.addCandidate(NumConversions: Args.size() + 1, Conversions: EarlyConversions);
7559 Candidate.FoundDecl = FoundDecl;
7560 Candidate.Function = Method;
7561 Candidate.RewriteKind =
7562 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7563 Candidate.IsSurrogate = false;
7564 Candidate.IgnoreObjectArgument = false;
7565 Candidate.ExplicitCallArguments = Args.size();
7566
7567 unsigned NumParams = Method->getNumExplicitParams();
7568 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7569
7570 // (C++ 13.3.2p2): A candidate function having fewer than m
7571 // parameters is viable only if it has an ellipsis in its parameter
7572 // list (8.3.5).
7573 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7574 !Proto->isVariadic() &&
7575 shouldEnforceArgLimit(PartialOverloading, Method)) {
7576 Candidate.Viable = false;
7577 Candidate.FailureKind = ovl_fail_too_many_arguments;
7578 return;
7579 }
7580
7581 // (C++ 13.3.2p2): A candidate function having more than m parameters
7582 // is viable only if the (m+1)st parameter has a default argument
7583 // (8.3.6). For the purposes of overload resolution, the
7584 // parameter list is truncated on the right, so that there are
7585 // exactly m parameters.
7586 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7587 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7588 // Not enough arguments.
7589 Candidate.Viable = false;
7590 Candidate.FailureKind = ovl_fail_too_few_arguments;
7591 return;
7592 }
7593
7594 Candidate.Viable = true;
7595
7596 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7597 if (ObjectType.isNull())
7598 Candidate.IgnoreObjectArgument = true;
7599 else if (Method->isStatic()) {
7600 // [over.best.ics.general]p8
7601 // When the parameter is the implicit object parameter of a static member
7602 // function, the implicit conversion sequence is a standard conversion
7603 // sequence that is neither better nor worse than any other standard
7604 // conversion sequence.
7605 //
7606 // This is a rule that was introduced in C++23 to support static lambdas. We
7607 // apply it retroactively because we want to support static lambdas as an
7608 // extension and it doesn't hurt previous code.
7609 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7610 } else {
7611 // Determine the implicit conversion sequence for the object
7612 // parameter.
7613 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7614 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7615 Method, ActingContext, /*InOverloadResolution=*/true);
7616 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7617 Candidate.Viable = false;
7618 Candidate.FailureKind = ovl_fail_bad_conversion;
7619 return;
7620 }
7621 }
7622
7623 // (CUDA B.1): Check for invalid calls between targets.
7624 if (getLangOpts().CUDA)
7625 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7626 Method)) {
7627 Candidate.Viable = false;
7628 Candidate.FailureKind = ovl_fail_bad_target;
7629 return;
7630 }
7631
7632 if (Method->getTrailingRequiresClause()) {
7633 ConstraintSatisfaction Satisfaction;
7634 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7635 /*ForOverloadResolution*/ true) ||
7636 !Satisfaction.IsSatisfied) {
7637 Candidate.Viable = false;
7638 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7639 return;
7640 }
7641 }
7642
7643 // Determine the implicit conversion sequences for each of the
7644 // arguments.
7645 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7646 unsigned ConvIdx =
7647 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7648 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7649 // We already formed a conversion sequence for this parameter during
7650 // template argument deduction.
7651 } else if (ArgIdx < NumParams) {
7652 // (C++ 13.3.2p3): for F to be a viable function, there shall
7653 // exist for each argument an implicit conversion sequence
7654 // (13.3.3.1) that converts that argument to the corresponding
7655 // parameter of F.
7656 QualType ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
7657 Candidate.Conversions[ConvIdx]
7658 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
7659 SuppressUserConversions,
7660 /*InOverloadResolution=*/true,
7661 /*AllowObjCWritebackConversion=*/
7662 getLangOpts().ObjCAutoRefCount);
7663 if (Candidate.Conversions[ConvIdx].isBad()) {
7664 Candidate.Viable = false;
7665 Candidate.FailureKind = ovl_fail_bad_conversion;
7666 return;
7667 }
7668 } else {
7669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7670 // argument for which there is no corresponding parameter is
7671 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7672 Candidate.Conversions[ConvIdx].setEllipsis();
7673 }
7674 }
7675
7676 if (EnableIfAttr *FailedAttr =
7677 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7678 Candidate.Viable = false;
7679 Candidate.FailureKind = ovl_fail_enable_if;
7680 Candidate.DeductionFailure.Data = FailedAttr;
7681 return;
7682 }
7683
7684 if (isNonViableMultiVersionOverload(Method)) {
7685 Candidate.Viable = false;
7686 Candidate.FailureKind = ovl_non_default_multiversion_function;
7687 }
7688}
7689
7690/// Add a C++ member function template as a candidate to the candidate
7691/// set, using template argument deduction to produce an appropriate member
7692/// function template specialization.
7693void Sema::AddMethodTemplateCandidate(
7694 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7695 CXXRecordDecl *ActingContext,
7696 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7697 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7698 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7699 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7700 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7701 return;
7702
7703 // C++ [over.match.funcs]p7:
7704 // In each case where a candidate is a function template, candidate
7705 // function template specializations are generated using template argument
7706 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7707 // candidate functions in the usual way.113) A given name can refer to one
7708 // or more function templates and also to a set of overloaded non-template
7709 // functions. In such a case, the candidate functions generated from each
7710 // function template are combined with the set of non-template candidate
7711 // functions.
7712 TemplateDeductionInfo Info(CandidateSet.getLocation());
7713 FunctionDecl *Specialization = nullptr;
7714 ConversionSequenceList Conversions;
7715 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7716 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7717 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7718 ObjectClassification,
7719 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes) {
7720 return CheckNonDependentConversions(
7721 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7722 SuppressUserConversions, ActingContext, ObjectType,
7723 ObjectClassification, PO);
7724 });
7725 Result != TemplateDeductionResult::Success) {
7726 OverloadCandidate &Candidate =
7727 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
7728 Candidate.FoundDecl = FoundDecl;
7729 Candidate.Function = MethodTmpl->getTemplatedDecl();
7730 Candidate.Viable = false;
7731 Candidate.RewriteKind =
7732 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
7733 Candidate.IsSurrogate = false;
7734 Candidate.IgnoreObjectArgument =
7735 cast<CXXMethodDecl>(Val: Candidate.Function)->isStatic() ||
7736 ObjectType.isNull();
7737 Candidate.ExplicitCallArguments = Args.size();
7738 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7739 Candidate.FailureKind = ovl_fail_bad_conversion;
7740 else {
7741 Candidate.FailureKind = ovl_fail_bad_deduction;
7742 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result,
7743 Info);
7744 }
7745 return;
7746 }
7747
7748 // Add the function template specialization produced by template argument
7749 // deduction as a candidate.
7750 assert(Specialization && "Missing member function template specialization?");
7751 assert(isa<CXXMethodDecl>(Specialization) &&
7752 "Specialization is not a member function?");
7753 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl,
7754 ActingContext, ObjectType, ObjectClassification, Args,
7755 CandidateSet, SuppressUserConversions, PartialOverloading,
7756 EarlyConversions: Conversions, PO);
7757}
7758
7759/// Determine whether a given function template has a simple explicit specifier
7760/// or a non-value-dependent explicit-specification that evaluates to true.
7761static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7762 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
7763}
7764
7765/// Add a C++ function template specialization as a candidate
7766/// in the candidate set, using template argument deduction to produce
7767/// an appropriate function template specialization.
7768void Sema::AddTemplateOverloadCandidate(
7769 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7770 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7771 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7772 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7773 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7774 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7775 return;
7776
7777 // If the function template has a non-dependent explicit specification,
7778 // exclude it now if appropriate; we are not permitted to perform deduction
7779 // and substitution in this case.
7780 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
7781 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7782 Candidate.FoundDecl = FoundDecl;
7783 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7784 Candidate.Viable = false;
7785 Candidate.FailureKind = ovl_fail_explicit;
7786 return;
7787 }
7788
7789 // C++ [over.match.funcs]p7:
7790 // In each case where a candidate is a function template, candidate
7791 // function template specializations are generated using template argument
7792 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7793 // candidate functions in the usual way.113) A given name can refer to one
7794 // or more function templates and also to a set of overloaded non-template
7795 // functions. In such a case, the candidate functions generated from each
7796 // function template are combined with the set of non-template candidate
7797 // functions.
7798 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7799 FunctionTemplate->getTemplateDepth());
7800 FunctionDecl *Specialization = nullptr;
7801 ConversionSequenceList Conversions;
7802 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7803 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7804 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
7805 /*ObjectType=*/QualType(),
7806 /*ObjectClassification=*/Expr::Classification(),
7807 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes) {
7808 return CheckNonDependentConversions(
7809 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7810 SuppressUserConversions, ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
7811 });
7812 Result != TemplateDeductionResult::Success) {
7813 OverloadCandidate &Candidate =
7814 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
7815 Candidate.FoundDecl = FoundDecl;
7816 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7817 Candidate.Viable = false;
7818 Candidate.RewriteKind =
7819 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
7820 Candidate.IsSurrogate = false;
7821 Candidate.IsADLCandidate = IsADLCandidate;
7822 // Ignore the object argument if there is one, since we don't have an object
7823 // type.
7824 Candidate.IgnoreObjectArgument =
7825 isa<CXXMethodDecl>(Val: Candidate.Function) &&
7826 !isa<CXXConstructorDecl>(Val: Candidate.Function);
7827 Candidate.ExplicitCallArguments = Args.size();
7828 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7829 Candidate.FailureKind = ovl_fail_bad_conversion;
7830 else {
7831 Candidate.FailureKind = ovl_fail_bad_deduction;
7832 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result,
7833 Info);
7834 }
7835 return;
7836 }
7837
7838 // Add the function template specialization produced by template argument
7839 // deduction as a candidate.
7840 assert(Specialization && "Missing function template specialization?");
7841 AddOverloadCandidate(
7842 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7843 PartialOverloading, AllowExplicit,
7844 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
7845 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity);
7846}
7847
7848/// Check that implicit conversion sequences can be formed for each argument
7849/// whose corresponding parameter has a non-dependent type, per DR1391's
7850/// [temp.deduct.call]p10.
7851bool Sema::CheckNonDependentConversions(
7852 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7853 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7854 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7855 CXXRecordDecl *ActingContext, QualType ObjectType,
7856 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7857 // FIXME: The cases in which we allow explicit conversions for constructor
7858 // arguments never consider calling a constructor template. It's not clear
7859 // that is correct.
7860 const bool AllowExplicit = false;
7861
7862 auto *FD = FunctionTemplate->getTemplatedDecl();
7863 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
7864 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Val: Method);
7865 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7866
7867 Conversions =
7868 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
7869
7870 // Overload resolution is always an unevaluated context.
7871 EnterExpressionEvaluationContext Unevaluated(
7872 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7873
7874 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7875 // require that, but this check should never result in a hard error, and
7876 // overload resolution is permitted to sidestep instantiations.
7877 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
7878 !ObjectType.isNull()) {
7879 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7880 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7881 !ParamTypes[0]->isDependentType()) {
7882 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7883 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7884 Method, ActingContext, /*InOverloadResolution=*/true,
7885 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7886 : QualType());
7887 if (Conversions[ConvIdx].isBad())
7888 return true;
7889 }
7890 }
7891
7892 unsigned Offset =
7893 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7894
7895 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
7896 I != N; ++I) {
7897 QualType ParamType = ParamTypes[I + Offset];
7898 if (!ParamType->isDependentType()) {
7899 unsigned ConvIdx;
7900 if (PO == OverloadCandidateParamOrder::Reversed) {
7901 ConvIdx = Args.size() - 1 - I;
7902 assert(Args.size() + ThisConversions == 2 &&
7903 "number of args (including 'this') must be exactly 2 for "
7904 "reversed order");
7905 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7906 // would also be 0. 'this' got ConvIdx = 1 previously.
7907 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7908 } else {
7909 // For members, 'this' got ConvIdx = 0 previously.
7910 ConvIdx = ThisConversions + I;
7911 }
7912 Conversions[ConvIdx]
7913 = TryCopyInitialization(S&: *this, From: Args[I], ToType: ParamType,
7914 SuppressUserConversions,
7915 /*InOverloadResolution=*/true,
7916 /*AllowObjCWritebackConversion=*/
7917 getLangOpts().ObjCAutoRefCount,
7918 AllowExplicit);
7919 if (Conversions[ConvIdx].isBad())
7920 return true;
7921 }
7922 }
7923
7924 return false;
7925}
7926
7927/// Determine whether this is an allowable conversion from the result
7928/// of an explicit conversion operator to the expected type, per C++
7929/// [over.match.conv]p1 and [over.match.ref]p1.
7930///
7931/// \param ConvType The return type of the conversion function.
7932///
7933/// \param ToType The type we are converting to.
7934///
7935/// \param AllowObjCPointerConversion Allow a conversion from one
7936/// Objective-C pointer to another.
7937///
7938/// \returns true if the conversion is allowable, false otherwise.
7939static bool isAllowableExplicitConversion(Sema &S,
7940 QualType ConvType, QualType ToType,
7941 bool AllowObjCPointerConversion) {
7942 QualType ToNonRefType = ToType.getNonReferenceType();
7943
7944 // Easy case: the types are the same.
7945 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
7946 return true;
7947
7948 // Allow qualification conversions.
7949 bool ObjCLifetimeConversion;
7950 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
7951 ObjCLifetimeConversion))
7952 return true;
7953
7954 // If we're not allowed to consider Objective-C pointer conversions,
7955 // we're done.
7956 if (!AllowObjCPointerConversion)
7957 return false;
7958
7959 // Is this an Objective-C pointer conversion?
7960 bool IncompatibleObjC = false;
7961 QualType ConvertedType;
7962 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
7963 IncompatibleObjC);
7964}
7965
7966/// AddConversionCandidate - Add a C++ conversion function as a
7967/// candidate in the candidate set (C++ [over.match.conv],
7968/// C++ [over.match.copy]). From is the expression we're converting from,
7969/// and ToType is the type that we're eventually trying to convert to
7970/// (which may or may not be the same type as the type that the
7971/// conversion function produces).
7972void Sema::AddConversionCandidate(
7973 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7974 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7975 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7976 bool AllowExplicit, bool AllowResultConversion) {
7977 assert(!Conversion->getDescribedFunctionTemplate() &&
7978 "Conversion function templates use AddTemplateConversionCandidate");
7979 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7980 if (!CandidateSet.isNewCandidate(Conversion))
7981 return;
7982
7983 // If the conversion function has an undeduced return type, trigger its
7984 // deduction now.
7985 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7986 if (DeduceReturnType(Conversion, From->getExprLoc()))
7987 return;
7988 ConvType = Conversion->getConversionType().getNonReferenceType();
7989 }
7990
7991 // If we don't allow any conversion of the result type, ignore conversion
7992 // functions that don't convert to exactly (possibly cv-qualified) T.
7993 if (!AllowResultConversion &&
7994 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
7995 return;
7996
7997 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7998 // operator is only a candidate if its return type is the target type or
7999 // can be converted to the target type with a qualification conversion.
8000 //
8001 // FIXME: Include such functions in the candidate list and explain why we
8002 // can't select them.
8003 if (Conversion->isExplicit() &&
8004 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8005 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8006 return;
8007
8008 // Overload resolution is always an unevaluated context.
8009 EnterExpressionEvaluationContext Unevaluated(
8010 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8011
8012 // Add this candidate
8013 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8014 Candidate.FoundDecl = FoundDecl;
8015 Candidate.Function = Conversion;
8016 Candidate.IsSurrogate = false;
8017 Candidate.IgnoreObjectArgument = false;
8018 Candidate.FinalConversion.setAsIdentityConversion();
8019 Candidate.FinalConversion.setFromType(ConvType);
8020 Candidate.FinalConversion.setAllToTypes(ToType);
8021 Candidate.Viable = true;
8022 Candidate.ExplicitCallArguments = 1;
8023
8024 // Explicit functions are not actually candidates at all if we're not
8025 // allowing them in this context, but keep them around so we can point
8026 // to them in diagnostics.
8027 if (!AllowExplicit && Conversion->isExplicit()) {
8028 Candidate.Viable = false;
8029 Candidate.FailureKind = ovl_fail_explicit;
8030 return;
8031 }
8032
8033 // C++ [over.match.funcs]p4:
8034 // For conversion functions, the function is considered to be a member of
8035 // the class of the implicit implied object argument for the purpose of
8036 // defining the type of the implicit object parameter.
8037 //
8038 // Determine the implicit conversion sequence for the implicit
8039 // object parameter.
8040 QualType ObjectType = From->getType();
8041 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8042 ObjectType = FromPtrType->getPointeeType();
8043 const auto *ConversionContext =
8044 cast<CXXRecordDecl>(Val: ObjectType->castAs<RecordType>()->getDecl());
8045
8046 // C++23 [over.best.ics.general]
8047 // However, if the target is [...]
8048 // - the object parameter of a user-defined conversion function
8049 // [...] user-defined conversion sequences are not considered.
8050 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8051 *this, CandidateSet.getLocation(), From->getType(),
8052 From->Classify(Ctx&: Context), Conversion, ConversionContext,
8053 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8054 /*SuppressUserConversion*/ true);
8055
8056 if (Candidate.Conversions[0].isBad()) {
8057 Candidate.Viable = false;
8058 Candidate.FailureKind = ovl_fail_bad_conversion;
8059 return;
8060 }
8061
8062 if (Conversion->getTrailingRequiresClause()) {
8063 ConstraintSatisfaction Satisfaction;
8064 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8065 !Satisfaction.IsSatisfied) {
8066 Candidate.Viable = false;
8067 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8068 return;
8069 }
8070 }
8071
8072 // We won't go through a user-defined type conversion function to convert a
8073 // derived to base as such conversions are given Conversion Rank. They only
8074 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8075 QualType FromCanon
8076 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8077 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8078 if (FromCanon == ToCanon ||
8079 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8080 Candidate.Viable = false;
8081 Candidate.FailureKind = ovl_fail_trivial_conversion;
8082 return;
8083 }
8084
8085 // To determine what the conversion from the result of calling the
8086 // conversion function to the type we're eventually trying to
8087 // convert to (ToType), we need to synthesize a call to the
8088 // conversion function and attempt copy initialization from it. This
8089 // makes sure that we get the right semantics with respect to
8090 // lvalues/rvalues and the type. Fortunately, we can allocate this
8091 // call on the stack and we don't need its arguments to be
8092 // well-formed.
8093 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8094 VK_LValue, From->getBeginLoc());
8095 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8096 Context.getPointerType(Conversion->getType()),
8097 CK_FunctionToPointerDecay, &ConversionRef,
8098 VK_PRValue, FPOptionsOverride());
8099
8100 QualType ConversionType = Conversion->getConversionType();
8101 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8102 Candidate.Viable = false;
8103 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8104 return;
8105 }
8106
8107 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8108
8109 // Note that it is safe to allocate CallExpr on the stack here because
8110 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8111 // allocator).
8112 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8113
8114 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8115 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8116 Mem: Buffer, Fn: &ConversionFn, Ty: CallResultType, VK, RParenLoc: From->getBeginLoc());
8117
8118 ImplicitConversionSequence ICS =
8119 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8120 /*SuppressUserConversions=*/true,
8121 /*InOverloadResolution=*/false,
8122 /*AllowObjCWritebackConversion=*/false);
8123
8124 switch (ICS.getKind()) {
8125 case ImplicitConversionSequence::StandardConversion:
8126 Candidate.FinalConversion = ICS.Standard;
8127
8128 // C++ [over.ics.user]p3:
8129 // If the user-defined conversion is specified by a specialization of a
8130 // conversion function template, the second standard conversion sequence
8131 // shall have exact match rank.
8132 if (Conversion->getPrimaryTemplate() &&
8133 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8134 Candidate.Viable = false;
8135 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8136 return;
8137 }
8138
8139 // C++0x [dcl.init.ref]p5:
8140 // In the second case, if the reference is an rvalue reference and
8141 // the second standard conversion sequence of the user-defined
8142 // conversion sequence includes an lvalue-to-rvalue conversion, the
8143 // program is ill-formed.
8144 if (ToType->isRValueReferenceType() &&
8145 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8146 Candidate.Viable = false;
8147 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8148 return;
8149 }
8150 break;
8151
8152 case ImplicitConversionSequence::BadConversion:
8153 Candidate.Viable = false;
8154 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8155 return;
8156
8157 default:
8158 llvm_unreachable(
8159 "Can only end up with a standard conversion sequence or failure");
8160 }
8161
8162 if (EnableIfAttr *FailedAttr =
8163 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8164 Candidate.Viable = false;
8165 Candidate.FailureKind = ovl_fail_enable_if;
8166 Candidate.DeductionFailure.Data = FailedAttr;
8167 return;
8168 }
8169
8170 if (isNonViableMultiVersionOverload(Conversion)) {
8171 Candidate.Viable = false;
8172 Candidate.FailureKind = ovl_non_default_multiversion_function;
8173 }
8174}
8175
8176/// Adds a conversion function template specialization
8177/// candidate to the overload set, using template argument deduction
8178/// to deduce the template arguments of the conversion function
8179/// template from the type that we are converting to (C++
8180/// [temp.deduct.conv]).
8181void Sema::AddTemplateConversionCandidate(
8182 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8183 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8184 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8185 bool AllowExplicit, bool AllowResultConversion) {
8186 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8187 "Only conversion function templates permitted here");
8188
8189 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8190 return;
8191
8192 // If the function template has a non-dependent explicit specification,
8193 // exclude it now if appropriate; we are not permitted to perform deduction
8194 // and substitution in this case.
8195 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8196 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8197 Candidate.FoundDecl = FoundDecl;
8198 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8199 Candidate.Viable = false;
8200 Candidate.FailureKind = ovl_fail_explicit;
8201 return;
8202 }
8203
8204 QualType ObjectType = From->getType();
8205 Expr::Classification ObjectClassification = From->Classify(Ctx&: getASTContext());
8206
8207 TemplateDeductionInfo Info(CandidateSet.getLocation());
8208 CXXConversionDecl *Specialization = nullptr;
8209 if (TemplateDeductionResult Result = DeduceTemplateArguments(
8210 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8211 Specialization, Info);
8212 Result != TemplateDeductionResult::Success) {
8213 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8214 Candidate.FoundDecl = FoundDecl;
8215 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8216 Candidate.Viable = false;
8217 Candidate.FailureKind = ovl_fail_bad_deduction;
8218 Candidate.IsSurrogate = false;
8219 Candidate.IgnoreObjectArgument = false;
8220 Candidate.ExplicitCallArguments = 1;
8221 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, TDK: Result,
8222 Info);
8223 return;
8224 }
8225
8226 // Add the conversion function template specialization produced by
8227 // template argument deduction as a candidate.
8228 assert(Specialization && "Missing function template specialization?");
8229 AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext: ActingDC, From, ToType,
8230 CandidateSet, AllowObjCConversionOnExplicit,
8231 AllowExplicit, AllowResultConversion);
8232}
8233
8234/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8235/// converts the given @c Object to a function pointer via the
8236/// conversion function @c Conversion, and then attempts to call it
8237/// with the given arguments (C++ [over.call.object]p2-4). Proto is
8238/// the type of function that we'll eventually be calling.
8239void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8240 DeclAccessPair FoundDecl,
8241 CXXRecordDecl *ActingContext,
8242 const FunctionProtoType *Proto,
8243 Expr *Object,
8244 ArrayRef<Expr *> Args,
8245 OverloadCandidateSet& CandidateSet) {
8246 if (!CandidateSet.isNewCandidate(Conversion))
8247 return;
8248
8249 // Overload resolution is always an unevaluated context.
8250 EnterExpressionEvaluationContext Unevaluated(
8251 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8252
8253 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8254 Candidate.FoundDecl = FoundDecl;
8255 Candidate.Function = nullptr;
8256 Candidate.Surrogate = Conversion;
8257 Candidate.Viable = true;
8258 Candidate.IsSurrogate = true;
8259 Candidate.IgnoreObjectArgument = false;
8260 Candidate.ExplicitCallArguments = Args.size();
8261
8262 // Determine the implicit conversion sequence for the implicit
8263 // object parameter.
8264 ImplicitConversionSequence ObjectInit;
8265 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8266 ObjectInit = TryCopyInitialization(*this, Object,
8267 Conversion->getParamDecl(0)->getType(),
8268 /*SuppressUserConversions=*/false,
8269 /*InOverloadResolution=*/true, false);
8270 } else {
8271 ObjectInit = TryObjectArgumentInitialization(
8272 *this, CandidateSet.getLocation(), Object->getType(),
8273 Object->Classify(Ctx&: Context), Conversion, ActingContext);
8274 }
8275
8276 if (ObjectInit.isBad()) {
8277 Candidate.Viable = false;
8278 Candidate.FailureKind = ovl_fail_bad_conversion;
8279 Candidate.Conversions[0] = ObjectInit;
8280 return;
8281 }
8282
8283 // The first conversion is actually a user-defined conversion whose
8284 // first conversion is ObjectInit's standard conversion (which is
8285 // effectively a reference binding). Record it as such.
8286 Candidate.Conversions[0].setUserDefined();
8287 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8288 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8289 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8290 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8291 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8292 Candidate.Conversions[0].UserDefined.After
8293 = Candidate.Conversions[0].UserDefined.Before;
8294 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8295
8296 // Find the
8297 unsigned NumParams = Proto->getNumParams();
8298
8299 // (C++ 13.3.2p2): A candidate function having fewer than m
8300 // parameters is viable only if it has an ellipsis in its parameter
8301 // list (8.3.5).
8302 if (Args.size() > NumParams && !Proto->isVariadic()) {
8303 Candidate.Viable = false;
8304 Candidate.FailureKind = ovl_fail_too_many_arguments;
8305 return;
8306 }
8307
8308 // Function types don't have any default arguments, so just check if
8309 // we have enough arguments.
8310 if (Args.size() < NumParams) {
8311 // Not enough arguments.
8312 Candidate.Viable = false;
8313 Candidate.FailureKind = ovl_fail_too_few_arguments;
8314 return;
8315 }
8316
8317 // Determine the implicit conversion sequences for each of the
8318 // arguments.
8319 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8320 if (ArgIdx < NumParams) {
8321 // (C++ 13.3.2p3): for F to be a viable function, there shall
8322 // exist for each argument an implicit conversion sequence
8323 // (13.3.3.1) that converts that argument to the corresponding
8324 // parameter of F.
8325 QualType ParamType = Proto->getParamType(i: ArgIdx);
8326 Candidate.Conversions[ArgIdx + 1]
8327 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8328 /*SuppressUserConversions=*/false,
8329 /*InOverloadResolution=*/false,
8330 /*AllowObjCWritebackConversion=*/
8331 getLangOpts().ObjCAutoRefCount);
8332 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8333 Candidate.Viable = false;
8334 Candidate.FailureKind = ovl_fail_bad_conversion;
8335 return;
8336 }
8337 } else {
8338 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8339 // argument for which there is no corresponding parameter is
8340 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8341 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8342 }
8343 }
8344
8345 if (Conversion->getTrailingRequiresClause()) {
8346 ConstraintSatisfaction Satisfaction;
8347 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8348 /*ForOverloadResolution*/ true) ||
8349 !Satisfaction.IsSatisfied) {
8350 Candidate.Viable = false;
8351 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8352 return;
8353 }
8354 }
8355
8356 if (EnableIfAttr *FailedAttr =
8357 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8358 Candidate.Viable = false;
8359 Candidate.FailureKind = ovl_fail_enable_if;
8360 Candidate.DeductionFailure.Data = FailedAttr;
8361 return;
8362 }
8363}
8364
8365/// Add all of the non-member operator function declarations in the given
8366/// function set to the overload candidate set.
8367void Sema::AddNonMemberOperatorCandidates(
8368 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8369 OverloadCandidateSet &CandidateSet,
8370 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8371 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8372 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8373 ArrayRef<Expr *> FunctionArgs = Args;
8374
8375 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8376 FunctionDecl *FD =
8377 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8378
8379 // Don't consider rewritten functions if we're not rewriting.
8380 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8381 continue;
8382
8383 assert(!isa<CXXMethodDecl>(FD) &&
8384 "unqualified operator lookup found a member function");
8385
8386 if (FunTmpl) {
8387 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8388 Args: FunctionArgs, CandidateSet);
8389 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8390 AddTemplateOverloadCandidate(
8391 FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8392 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, SuppressUserConversions: false, PartialOverloading: false,
8393 AllowExplicit: true, IsADLCandidate: ADLCallKind::NotADL, PO: OverloadCandidateParamOrder::Reversed);
8394 } else {
8395 if (ExplicitTemplateArgs)
8396 continue;
8397 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8398 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8399 AddOverloadCandidate(
8400 Function: FD, FoundDecl: F.getPair(), Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8401 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: std::nullopt,
8402 PO: OverloadCandidateParamOrder::Reversed);
8403 }
8404 }
8405}
8406
8407/// Add overload candidates for overloaded operators that are
8408/// member functions.
8409///
8410/// Add the overloaded operator candidates that are member functions
8411/// for the operator Op that was used in an operator expression such
8412/// as "x Op y". , Args/NumArgs provides the operator arguments, and
8413/// CandidateSet will store the added overload candidates. (C++
8414/// [over.match.oper]).
8415void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8416 SourceLocation OpLoc,
8417 ArrayRef<Expr *> Args,
8418 OverloadCandidateSet &CandidateSet,
8419 OverloadCandidateParamOrder PO) {
8420 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8421
8422 // C++ [over.match.oper]p3:
8423 // For a unary operator @ with an operand of a type whose
8424 // cv-unqualified version is T1, and for a binary operator @ with
8425 // a left operand of a type whose cv-unqualified version is T1 and
8426 // a right operand of a type whose cv-unqualified version is T2,
8427 // three sets of candidate functions, designated member
8428 // candidates, non-member candidates and built-in candidates, are
8429 // constructed as follows:
8430 QualType T1 = Args[0]->getType();
8431
8432 // -- If T1 is a complete class type or a class currently being
8433 // defined, the set of member candidates is the result of the
8434 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8435 // the set of member candidates is empty.
8436 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8437 // Complete the type if it can be completed.
8438 if (!isCompleteType(Loc: OpLoc, T: T1) && !T1Rec->isBeingDefined())
8439 return;
8440 // If the type is neither complete nor being defined, bail out now.
8441 if (!T1Rec->getDecl()->getDefinition())
8442 return;
8443
8444 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8445 LookupQualifiedName(Operators, T1Rec->getDecl());
8446 Operators.suppressAccessDiagnostics();
8447
8448 for (LookupResult::iterator Oper = Operators.begin(),
8449 OperEnd = Operators.end();
8450 Oper != OperEnd; ++Oper) {
8451 if (Oper->getAsFunction() &&
8452 PO == OverloadCandidateParamOrder::Reversed &&
8453 !CandidateSet.getRewriteInfo().shouldAddReversed(
8454 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8455 continue;
8456 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8457 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8458 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8459 }
8460 }
8461}
8462
8463/// AddBuiltinCandidate - Add a candidate for a built-in
8464/// operator. ResultTy and ParamTys are the result and parameter types
8465/// of the built-in candidate, respectively. Args and NumArgs are the
8466/// arguments being passed to the candidate. IsAssignmentOperator
8467/// should be true when this built-in candidate is an assignment
8468/// operator. NumContextualBoolArguments is the number of arguments
8469/// (at the beginning of the argument list) that will be contextually
8470/// converted to bool.
8471void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8472 OverloadCandidateSet& CandidateSet,
8473 bool IsAssignmentOperator,
8474 unsigned NumContextualBoolArguments) {
8475 // Overload resolution is always an unevaluated context.
8476 EnterExpressionEvaluationContext Unevaluated(
8477 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8478
8479 // Add this candidate
8480 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8481 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8482 Candidate.Function = nullptr;
8483 Candidate.IsSurrogate = false;
8484 Candidate.IgnoreObjectArgument = false;
8485 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8486
8487 // Determine the implicit conversion sequences for each of the
8488 // arguments.
8489 Candidate.Viable = true;
8490 Candidate.ExplicitCallArguments = Args.size();
8491 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8492 // C++ [over.match.oper]p4:
8493 // For the built-in assignment operators, conversions of the
8494 // left operand are restricted as follows:
8495 // -- no temporaries are introduced to hold the left operand, and
8496 // -- no user-defined conversions are applied to the left
8497 // operand to achieve a type match with the left-most
8498 // parameter of a built-in candidate.
8499 //
8500 // We block these conversions by turning off user-defined
8501 // conversions, since that is the only way that initialization of
8502 // a reference to a non-class type can occur from something that
8503 // is not of the same type.
8504 if (ArgIdx < NumContextualBoolArguments) {
8505 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8506 "Contextual conversion to bool requires bool type");
8507 Candidate.Conversions[ArgIdx]
8508 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
8509 } else {
8510 Candidate.Conversions[ArgIdx]
8511 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
8512 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
8513 /*InOverloadResolution=*/false,
8514 /*AllowObjCWritebackConversion=*/
8515 getLangOpts().ObjCAutoRefCount);
8516 }
8517 if (Candidate.Conversions[ArgIdx].isBad()) {
8518 Candidate.Viable = false;
8519 Candidate.FailureKind = ovl_fail_bad_conversion;
8520 break;
8521 }
8522 }
8523}
8524
8525namespace {
8526
8527/// BuiltinCandidateTypeSet - A set of types that will be used for the
8528/// candidate operator functions for built-in operators (C++
8529/// [over.built]). The types are separated into pointer types and
8530/// enumeration types.
8531class BuiltinCandidateTypeSet {
8532 /// TypeSet - A set of types.
8533 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8534
8535 /// PointerTypes - The set of pointer types that will be used in the
8536 /// built-in candidates.
8537 TypeSet PointerTypes;
8538
8539 /// MemberPointerTypes - The set of member pointer types that will be
8540 /// used in the built-in candidates.
8541 TypeSet MemberPointerTypes;
8542
8543 /// EnumerationTypes - The set of enumeration types that will be
8544 /// used in the built-in candidates.
8545 TypeSet EnumerationTypes;
8546
8547 /// The set of vector types that will be used in the built-in
8548 /// candidates.
8549 TypeSet VectorTypes;
8550
8551 /// The set of matrix types that will be used in the built-in
8552 /// candidates.
8553 TypeSet MatrixTypes;
8554
8555 /// The set of _BitInt types that will be used in the built-in candidates.
8556 TypeSet BitIntTypes;
8557
8558 /// A flag indicating non-record types are viable candidates
8559 bool HasNonRecordTypes;
8560
8561 /// A flag indicating whether either arithmetic or enumeration types
8562 /// were present in the candidate set.
8563 bool HasArithmeticOrEnumeralTypes;
8564
8565 /// A flag indicating whether the nullptr type was present in the
8566 /// candidate set.
8567 bool HasNullPtrType;
8568
8569 /// Sema - The semantic analysis instance where we are building the
8570 /// candidate type set.
8571 Sema &SemaRef;
8572
8573 /// Context - The AST context in which we will build the type sets.
8574 ASTContext &Context;
8575
8576 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8577 const Qualifiers &VisibleQuals);
8578 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8579
8580public:
8581 /// iterator - Iterates through the types that are part of the set.
8582 typedef TypeSet::iterator iterator;
8583
8584 BuiltinCandidateTypeSet(Sema &SemaRef)
8585 : HasNonRecordTypes(false),
8586 HasArithmeticOrEnumeralTypes(false),
8587 HasNullPtrType(false),
8588 SemaRef(SemaRef),
8589 Context(SemaRef.Context) { }
8590
8591 void AddTypesConvertedFrom(QualType Ty,
8592 SourceLocation Loc,
8593 bool AllowUserConversions,
8594 bool AllowExplicitConversions,
8595 const Qualifiers &VisibleTypeConversionsQuals);
8596
8597 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8598 llvm::iterator_range<iterator> member_pointer_types() {
8599 return MemberPointerTypes;
8600 }
8601 llvm::iterator_range<iterator> enumeration_types() {
8602 return EnumerationTypes;
8603 }
8604 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8605 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8606 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8607
8608 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
8609 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8610 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8611 bool hasNullPtrType() const { return HasNullPtrType; }
8612};
8613
8614} // end anonymous namespace
8615
8616/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8617/// the set of pointer types along with any more-qualified variants of
8618/// that type. For example, if @p Ty is "int const *", this routine
8619/// will add "int const *", "int const volatile *", "int const
8620/// restrict *", and "int const volatile restrict *" to the set of
8621/// pointer types. Returns true if the add of @p Ty itself succeeded,
8622/// false otherwise.
8623///
8624/// FIXME: what to do about extended qualifiers?
8625bool
8626BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8627 const Qualifiers &VisibleQuals) {
8628
8629 // Insert this type.
8630 if (!PointerTypes.insert(X: Ty))
8631 return false;
8632
8633 QualType PointeeTy;
8634 const PointerType *PointerTy = Ty->getAs<PointerType>();
8635 bool buildObjCPtr = false;
8636 if (!PointerTy) {
8637 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8638 PointeeTy = PTy->getPointeeType();
8639 buildObjCPtr = true;
8640 } else {
8641 PointeeTy = PointerTy->getPointeeType();
8642 }
8643
8644 // Don't add qualified variants of arrays. For one, they're not allowed
8645 // (the qualifier would sink to the element type), and for another, the
8646 // only overload situation where it matters is subscript or pointer +- int,
8647 // and those shouldn't have qualifier variants anyway.
8648 if (PointeeTy->isArrayType())
8649 return true;
8650
8651 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8652 bool hasVolatile = VisibleQuals.hasVolatile();
8653 bool hasRestrict = VisibleQuals.hasRestrict();
8654
8655 // Iterate through all strict supersets of BaseCVR.
8656 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8657 if ((CVR | BaseCVR) != CVR) continue;
8658 // Skip over volatile if no volatile found anywhere in the types.
8659 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8660
8661 // Skip over restrict if no restrict found anywhere in the types, or if
8662 // the type cannot be restrict-qualified.
8663 if ((CVR & Qualifiers::Restrict) &&
8664 (!hasRestrict ||
8665 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8666 continue;
8667
8668 // Build qualified pointee type.
8669 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8670
8671 // Build qualified pointer type.
8672 QualType QPointerTy;
8673 if (!buildObjCPtr)
8674 QPointerTy = Context.getPointerType(T: QPointeeTy);
8675 else
8676 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
8677
8678 // Insert qualified pointer type.
8679 PointerTypes.insert(X: QPointerTy);
8680 }
8681
8682 return true;
8683}
8684
8685/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8686/// to the set of pointer types along with any more-qualified variants of
8687/// that type. For example, if @p Ty is "int const *", this routine
8688/// will add "int const *", "int const volatile *", "int const
8689/// restrict *", and "int const volatile restrict *" to the set of
8690/// pointer types. Returns true if the add of @p Ty itself succeeded,
8691/// false otherwise.
8692///
8693/// FIXME: what to do about extended qualifiers?
8694bool
8695BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8696 QualType Ty) {
8697 // Insert this type.
8698 if (!MemberPointerTypes.insert(X: Ty))
8699 return false;
8700
8701 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8702 assert(PointerTy && "type was not a member pointer type!");
8703
8704 QualType PointeeTy = PointerTy->getPointeeType();
8705 // Don't add qualified variants of arrays. For one, they're not allowed
8706 // (the qualifier would sink to the element type), and for another, the
8707 // only overload situation where it matters is subscript or pointer +- int,
8708 // and those shouldn't have qualifier variants anyway.
8709 if (PointeeTy->isArrayType())
8710 return true;
8711 const Type *ClassTy = PointerTy->getClass();
8712
8713 // Iterate through all strict supersets of the pointee type's CVR
8714 // qualifiers.
8715 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8716 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8717 if ((CVR | BaseCVR) != CVR) continue;
8718
8719 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8720 MemberPointerTypes.insert(
8721 X: Context.getMemberPointerType(T: QPointeeTy, Cls: ClassTy));
8722 }
8723
8724 return true;
8725}
8726
8727/// AddTypesConvertedFrom - Add each of the types to which the type @p
8728/// Ty can be implicit converted to the given set of @p Types. We're
8729/// primarily interested in pointer types and enumeration types. We also
8730/// take member pointer types, for the conditional operator.
8731/// AllowUserConversions is true if we should look at the conversion
8732/// functions of a class type, and AllowExplicitConversions if we
8733/// should also include the explicit conversion functions of a class
8734/// type.
8735void
8736BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8737 SourceLocation Loc,
8738 bool AllowUserConversions,
8739 bool AllowExplicitConversions,
8740 const Qualifiers &VisibleQuals) {
8741 // Only deal with canonical types.
8742 Ty = Context.getCanonicalType(T: Ty);
8743
8744 // Look through reference types; they aren't part of the type of an
8745 // expression for the purposes of conversions.
8746 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8747 Ty = RefTy->getPointeeType();
8748
8749 // If we're dealing with an array type, decay to the pointer.
8750 if (Ty->isArrayType())
8751 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
8752
8753 // Otherwise, we don't care about qualifiers on the type.
8754 Ty = Ty.getLocalUnqualifiedType();
8755
8756 // Flag if we ever add a non-record type.
8757 const RecordType *TyRec = Ty->getAs<RecordType>();
8758 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8759
8760 // Flag if we encounter an arithmetic type.
8761 HasArithmeticOrEnumeralTypes =
8762 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8763
8764 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8765 PointerTypes.insert(X: Ty);
8766 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8767 // Insert our type, and its more-qualified variants, into the set
8768 // of types.
8769 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8770 return;
8771 } else if (Ty->isMemberPointerType()) {
8772 // Member pointers are far easier, since the pointee can't be converted.
8773 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8774 return;
8775 } else if (Ty->isEnumeralType()) {
8776 HasArithmeticOrEnumeralTypes = true;
8777 EnumerationTypes.insert(X: Ty);
8778 } else if (Ty->isBitIntType()) {
8779 HasArithmeticOrEnumeralTypes = true;
8780 BitIntTypes.insert(X: Ty);
8781 } else if (Ty->isVectorType()) {
8782 // We treat vector types as arithmetic types in many contexts as an
8783 // extension.
8784 HasArithmeticOrEnumeralTypes = true;
8785 VectorTypes.insert(X: Ty);
8786 } else if (Ty->isMatrixType()) {
8787 // Similar to vector types, we treat vector types as arithmetic types in
8788 // many contexts as an extension.
8789 HasArithmeticOrEnumeralTypes = true;
8790 MatrixTypes.insert(X: Ty);
8791 } else if (Ty->isNullPtrType()) {
8792 HasNullPtrType = true;
8793 } else if (AllowUserConversions && TyRec) {
8794 // No conversion functions in incomplete types.
8795 if (!SemaRef.isCompleteType(Loc, T: Ty))
8796 return;
8797
8798 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl());
8799 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8800 if (isa<UsingShadowDecl>(Val: D))
8801 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
8802
8803 // Skip conversion function templates; they don't tell us anything
8804 // about which builtin types we can convert to.
8805 if (isa<FunctionTemplateDecl>(Val: D))
8806 continue;
8807
8808 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
8809 if (AllowExplicitConversions || !Conv->isExplicit()) {
8810 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
8811 VisibleQuals);
8812 }
8813 }
8814 }
8815}
8816/// Helper function for adjusting address spaces for the pointer or reference
8817/// operands of builtin operators depending on the argument.
8818static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8819 Expr *Arg) {
8820 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
8821}
8822
8823/// Helper function for AddBuiltinOperatorCandidates() that adds
8824/// the volatile- and non-volatile-qualified assignment operators for the
8825/// given type to the candidate set.
8826static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8827 QualType T,
8828 ArrayRef<Expr *> Args,
8829 OverloadCandidateSet &CandidateSet) {
8830 QualType ParamTypes[2];
8831
8832 // T& operator=(T&, T)
8833 ParamTypes[0] = S.Context.getLValueReferenceType(
8834 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
8835 ParamTypes[1] = T;
8836 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
8837 /*IsAssignmentOperator=*/true);
8838
8839 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8840 // volatile T& operator=(volatile T&, T)
8841 ParamTypes[0] = S.Context.getLValueReferenceType(
8842 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
8843 Arg: Args[0]));
8844 ParamTypes[1] = T;
8845 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
8846 /*IsAssignmentOperator=*/true);
8847 }
8848}
8849
8850/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8851/// if any, found in visible type conversion functions found in ArgExpr's type.
8852static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8853 Qualifiers VRQuals;
8854 const RecordType *TyRec;
8855 if (const MemberPointerType *RHSMPType =
8856 ArgExpr->getType()->getAs<MemberPointerType>())
8857 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8858 else
8859 TyRec = ArgExpr->getType()->getAs<RecordType>();
8860 if (!TyRec) {
8861 // Just to be safe, assume the worst case.
8862 VRQuals.addVolatile();
8863 VRQuals.addRestrict();
8864 return VRQuals;
8865 }
8866
8867 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl());
8868 if (!ClassDecl->hasDefinition())
8869 return VRQuals;
8870
8871 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8872 if (isa<UsingShadowDecl>(Val: D))
8873 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
8874 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
8875 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
8876 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8877 CanTy = ResTypeRef->getPointeeType();
8878 // Need to go down the pointer/mempointer chain and add qualifiers
8879 // as see them.
8880 bool done = false;
8881 while (!done) {
8882 if (CanTy.isRestrictQualified())
8883 VRQuals.addRestrict();
8884 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8885 CanTy = ResTypePtr->getPointeeType();
8886 else if (const MemberPointerType *ResTypeMPtr =
8887 CanTy->getAs<MemberPointerType>())
8888 CanTy = ResTypeMPtr->getPointeeType();
8889 else
8890 done = true;
8891 if (CanTy.isVolatileQualified())
8892 VRQuals.addVolatile();
8893 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8894 return VRQuals;
8895 }
8896 }
8897 }
8898 return VRQuals;
8899}
8900
8901// Note: We're currently only handling qualifiers that are meaningful for the
8902// LHS of compound assignment overloading.
8903static void forAllQualifierCombinationsImpl(
8904 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8905 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8906 // _Atomic
8907 if (Available.hasAtomic()) {
8908 Available.removeAtomic();
8909 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
8910 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8911 return;
8912 }
8913
8914 // volatile
8915 if (Available.hasVolatile()) {
8916 Available.removeVolatile();
8917 assert(!Applied.hasVolatile());
8918 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
8919 Callback);
8920 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8921 return;
8922 }
8923
8924 Callback(Applied);
8925}
8926
8927static void forAllQualifierCombinations(
8928 QualifiersAndAtomic Quals,
8929 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8930 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
8931 Callback);
8932}
8933
8934static QualType makeQualifiedLValueReferenceType(QualType Base,
8935 QualifiersAndAtomic Quals,
8936 Sema &S) {
8937 if (Quals.hasAtomic())
8938 Base = S.Context.getAtomicType(T: Base);
8939 if (Quals.hasVolatile())
8940 Base = S.Context.getVolatileType(T: Base);
8941 return S.Context.getLValueReferenceType(T: Base);
8942}
8943
8944namespace {
8945
8946/// Helper class to manage the addition of builtin operator overload
8947/// candidates. It provides shared state and utility methods used throughout
8948/// the process, as well as a helper method to add each group of builtin
8949/// operator overloads from the standard to a candidate set.
8950class BuiltinOperatorOverloadBuilder {
8951 // Common instance state available to all overload candidate addition methods.
8952 Sema &S;
8953 ArrayRef<Expr *> Args;
8954 QualifiersAndAtomic VisibleTypeConversionsQuals;
8955 bool HasArithmeticOrEnumeralCandidateType;
8956 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8957 OverloadCandidateSet &CandidateSet;
8958
8959 static constexpr int ArithmeticTypesCap = 26;
8960 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8961
8962 // Define some indices used to iterate over the arithmetic types in
8963 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8964 // types are that preserved by promotion (C++ [over.built]p2).
8965 unsigned FirstIntegralType,
8966 LastIntegralType;
8967 unsigned FirstPromotedIntegralType,
8968 LastPromotedIntegralType;
8969 unsigned FirstPromotedArithmeticType,
8970 LastPromotedArithmeticType;
8971 unsigned NumArithmeticTypes;
8972
8973 void InitArithmeticTypes() {
8974 // Start of promoted types.
8975 FirstPromotedArithmeticType = 0;
8976 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
8977 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
8978 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
8979 if (S.Context.getTargetInfo().hasFloat128Type())
8980 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
8981 if (S.Context.getTargetInfo().hasIbm128Type())
8982 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
8983
8984 // Start of integral types.
8985 FirstIntegralType = ArithmeticTypes.size();
8986 FirstPromotedIntegralType = ArithmeticTypes.size();
8987 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
8988 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
8989 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
8990 if (S.Context.getTargetInfo().hasInt128Type() ||
8991 (S.Context.getAuxTargetInfo() &&
8992 S.Context.getAuxTargetInfo()->hasInt128Type()))
8993 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
8994 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
8995 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
8996 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
8997 if (S.Context.getTargetInfo().hasInt128Type() ||
8998 (S.Context.getAuxTargetInfo() &&
8999 S.Context.getAuxTargetInfo()->hasInt128Type()))
9000 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9001
9002 /// We add candidates for the unique, unqualified _BitInt types present in
9003 /// the candidate type set. The candidate set already handled ensuring the
9004 /// type is unqualified and canonical, but because we're adding from N
9005 /// different sets, we need to do some extra work to unique things. Insert
9006 /// the candidates into a unique set, then move from that set into the list
9007 /// of arithmetic types.
9008 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9009 llvm::for_each(Range&: CandidateTypes, F: [&BitIntCandidates](
9010 BuiltinCandidateTypeSet &Candidate) {
9011 for (QualType BitTy : Candidate.bitint_types())
9012 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9013 });
9014 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9015 LastPromotedIntegralType = ArithmeticTypes.size();
9016 LastPromotedArithmeticType = ArithmeticTypes.size();
9017 // End of promoted types.
9018
9019 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9020 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9021 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9022 if (S.Context.getLangOpts().Char8)
9023 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9024 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9025 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9026 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9027 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9028 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9029 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9030 LastIntegralType = ArithmeticTypes.size();
9031 NumArithmeticTypes = ArithmeticTypes.size();
9032 // End of integral types.
9033 // FIXME: What about complex? What about half?
9034
9035 // We don't know for sure how many bit-precise candidates were involved, so
9036 // we subtract those from the total when testing whether we're under the
9037 // cap or not.
9038 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9039 ArithmeticTypesCap &&
9040 "Enough inline storage for all arithmetic types.");
9041 }
9042
9043 /// Helper method to factor out the common pattern of adding overloads
9044 /// for '++' and '--' builtin operators.
9045 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9046 bool HasVolatile,
9047 bool HasRestrict) {
9048 QualType ParamTypes[2] = {
9049 S.Context.getLValueReferenceType(T: CandidateTy),
9050 S.Context.IntTy
9051 };
9052
9053 // Non-volatile version.
9054 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9055
9056 // Use a heuristic to reduce number of builtin candidates in the set:
9057 // add volatile version only if there are conversions to a volatile type.
9058 if (HasVolatile) {
9059 ParamTypes[0] =
9060 S.Context.getLValueReferenceType(
9061 T: S.Context.getVolatileType(T: CandidateTy));
9062 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9063 }
9064
9065 // Add restrict version only if there are conversions to a restrict type
9066 // and our candidate type is a non-restrict-qualified pointer.
9067 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9068 !CandidateTy.isRestrictQualified()) {
9069 ParamTypes[0]
9070 = S.Context.getLValueReferenceType(
9071 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9072 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9073
9074 if (HasVolatile) {
9075 ParamTypes[0]
9076 = S.Context.getLValueReferenceType(
9077 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9078 CVR: (Qualifiers::Volatile |
9079 Qualifiers::Restrict)));
9080 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9081 }
9082 }
9083
9084 }
9085
9086 /// Helper to add an overload candidate for a binary builtin with types \p L
9087 /// and \p R.
9088 void AddCandidate(QualType L, QualType R) {
9089 QualType LandR[2] = {L, R};
9090 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9091 }
9092
9093public:
9094 BuiltinOperatorOverloadBuilder(
9095 Sema &S, ArrayRef<Expr *> Args,
9096 QualifiersAndAtomic VisibleTypeConversionsQuals,
9097 bool HasArithmeticOrEnumeralCandidateType,
9098 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9099 OverloadCandidateSet &CandidateSet)
9100 : S(S), Args(Args),
9101 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9102 HasArithmeticOrEnumeralCandidateType(
9103 HasArithmeticOrEnumeralCandidateType),
9104 CandidateTypes(CandidateTypes),
9105 CandidateSet(CandidateSet) {
9106
9107 InitArithmeticTypes();
9108 }
9109
9110 // Increment is deprecated for bool since C++17.
9111 //
9112 // C++ [over.built]p3:
9113 //
9114 // For every pair (T, VQ), where T is an arithmetic type other
9115 // than bool, and VQ is either volatile or empty, there exist
9116 // candidate operator functions of the form
9117 //
9118 // VQ T& operator++(VQ T&);
9119 // T operator++(VQ T&, int);
9120 //
9121 // C++ [over.built]p4:
9122 //
9123 // For every pair (T, VQ), where T is an arithmetic type other
9124 // than bool, and VQ is either volatile or empty, there exist
9125 // candidate operator functions of the form
9126 //
9127 // VQ T& operator--(VQ T&);
9128 // T operator--(VQ T&, int);
9129 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9130 if (!HasArithmeticOrEnumeralCandidateType)
9131 return;
9132
9133 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9134 const auto TypeOfT = ArithmeticTypes[Arith];
9135 if (TypeOfT == S.Context.BoolTy) {
9136 if (Op == OO_MinusMinus)
9137 continue;
9138 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9139 continue;
9140 }
9141 addPlusPlusMinusMinusStyleOverloads(
9142 CandidateTy: TypeOfT,
9143 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9144 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9145 }
9146 }
9147
9148 // C++ [over.built]p5:
9149 //
9150 // For every pair (T, VQ), where T is a cv-qualified or
9151 // cv-unqualified object type, and VQ is either volatile or
9152 // empty, there exist candidate operator functions of the form
9153 //
9154 // T*VQ& operator++(T*VQ&);
9155 // T*VQ& operator--(T*VQ&);
9156 // T* operator++(T*VQ&, int);
9157 // T* operator--(T*VQ&, int);
9158 void addPlusPlusMinusMinusPointerOverloads() {
9159 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9160 // Skip pointer types that aren't pointers to object types.
9161 if (!PtrTy->getPointeeType()->isObjectType())
9162 continue;
9163
9164 addPlusPlusMinusMinusStyleOverloads(
9165 CandidateTy: PtrTy,
9166 HasVolatile: (!PtrTy.isVolatileQualified() &&
9167 VisibleTypeConversionsQuals.hasVolatile()),
9168 HasRestrict: (!PtrTy.isRestrictQualified() &&
9169 VisibleTypeConversionsQuals.hasRestrict()));
9170 }
9171 }
9172
9173 // C++ [over.built]p6:
9174 // For every cv-qualified or cv-unqualified object type T, there
9175 // exist candidate operator functions of the form
9176 //
9177 // T& operator*(T*);
9178 //
9179 // C++ [over.built]p7:
9180 // For every function type T that does not have cv-qualifiers or a
9181 // ref-qualifier, there exist candidate operator functions of the form
9182 // T& operator*(T*);
9183 void addUnaryStarPointerOverloads() {
9184 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9185 QualType PointeeTy = ParamTy->getPointeeType();
9186 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9187 continue;
9188
9189 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9190 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9191 continue;
9192
9193 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9194 }
9195 }
9196
9197 // C++ [over.built]p9:
9198 // For every promoted arithmetic type T, there exist candidate
9199 // operator functions of the form
9200 //
9201 // T operator+(T);
9202 // T operator-(T);
9203 void addUnaryPlusOrMinusArithmeticOverloads() {
9204 if (!HasArithmeticOrEnumeralCandidateType)
9205 return;
9206
9207 for (unsigned Arith = FirstPromotedArithmeticType;
9208 Arith < LastPromotedArithmeticType; ++Arith) {
9209 QualType ArithTy = ArithmeticTypes[Arith];
9210 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9211 }
9212
9213 // Extension: We also add these operators for vector types.
9214 for (QualType VecTy : CandidateTypes[0].vector_types())
9215 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9216 }
9217
9218 // C++ [over.built]p8:
9219 // For every type T, there exist candidate operator functions of
9220 // the form
9221 //
9222 // T* operator+(T*);
9223 void addUnaryPlusPointerOverloads() {
9224 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9225 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9226 }
9227
9228 // C++ [over.built]p10:
9229 // For every promoted integral type T, there exist candidate
9230 // operator functions of the form
9231 //
9232 // T operator~(T);
9233 void addUnaryTildePromotedIntegralOverloads() {
9234 if (!HasArithmeticOrEnumeralCandidateType)
9235 return;
9236
9237 for (unsigned Int = FirstPromotedIntegralType;
9238 Int < LastPromotedIntegralType; ++Int) {
9239 QualType IntTy = ArithmeticTypes[Int];
9240 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9241 }
9242
9243 // Extension: We also add this operator for vector types.
9244 for (QualType VecTy : CandidateTypes[0].vector_types())
9245 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9246 }
9247
9248 // C++ [over.match.oper]p16:
9249 // For every pointer to member type T or type std::nullptr_t, there
9250 // exist candidate operator functions of the form
9251 //
9252 // bool operator==(T,T);
9253 // bool operator!=(T,T);
9254 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9255 /// Set of (canonical) types that we've already handled.
9256 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9257
9258 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9259 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9260 // Don't add the same builtin candidate twice.
9261 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9262 continue;
9263
9264 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9265 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9266 }
9267
9268 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9269 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9270 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9271 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9272 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9273 }
9274 }
9275 }
9276 }
9277
9278 // C++ [over.built]p15:
9279 //
9280 // For every T, where T is an enumeration type or a pointer type,
9281 // there exist candidate operator functions of the form
9282 //
9283 // bool operator<(T, T);
9284 // bool operator>(T, T);
9285 // bool operator<=(T, T);
9286 // bool operator>=(T, T);
9287 // bool operator==(T, T);
9288 // bool operator!=(T, T);
9289 // R operator<=>(T, T)
9290 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9291 // C++ [over.match.oper]p3:
9292 // [...]the built-in candidates include all of the candidate operator
9293 // functions defined in 13.6 that, compared to the given operator, [...]
9294 // do not have the same parameter-type-list as any non-template non-member
9295 // candidate.
9296 //
9297 // Note that in practice, this only affects enumeration types because there
9298 // aren't any built-in candidates of record type, and a user-defined operator
9299 // must have an operand of record or enumeration type. Also, the only other
9300 // overloaded operator with enumeration arguments, operator=,
9301 // cannot be overloaded for enumeration types, so this is the only place
9302 // where we must suppress candidates like this.
9303 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9304 UserDefinedBinaryOperators;
9305
9306 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9307 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9308 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9309 CEnd = CandidateSet.end();
9310 C != CEnd; ++C) {
9311 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9312 continue;
9313
9314 if (C->Function->isFunctionTemplateSpecialization())
9315 continue;
9316
9317 // We interpret "same parameter-type-list" as applying to the
9318 // "synthesized candidate, with the order of the two parameters
9319 // reversed", not to the original function.
9320 bool Reversed = C->isReversed();
9321 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9322 ->getType()
9323 .getUnqualifiedType();
9324 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9325 ->getType()
9326 .getUnqualifiedType();
9327
9328 // Skip if either parameter isn't of enumeral type.
9329 if (!FirstParamType->isEnumeralType() ||
9330 !SecondParamType->isEnumeralType())
9331 continue;
9332
9333 // Add this operator to the set of known user-defined operators.
9334 UserDefinedBinaryOperators.insert(
9335 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9336 y: S.Context.getCanonicalType(T: SecondParamType)));
9337 }
9338 }
9339 }
9340
9341 /// Set of (canonical) types that we've already handled.
9342 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9343
9344 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9345 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9346 // Don't add the same builtin candidate twice.
9347 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9348 continue;
9349 if (IsSpaceship && PtrTy->isFunctionPointerType())
9350 continue;
9351
9352 QualType ParamTypes[2] = {PtrTy, PtrTy};
9353 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9354 }
9355 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9356 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9357
9358 // Don't add the same builtin candidate twice, or if a user defined
9359 // candidate exists.
9360 if (!AddedTypes.insert(Ptr: CanonType).second ||
9361 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9362 y&: CanonType)))
9363 continue;
9364 QualType ParamTypes[2] = {EnumTy, EnumTy};
9365 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9366 }
9367 }
9368 }
9369
9370 // C++ [over.built]p13:
9371 //
9372 // For every cv-qualified or cv-unqualified object type T
9373 // there exist candidate operator functions of the form
9374 //
9375 // T* operator+(T*, ptrdiff_t);
9376 // T& operator[](T*, ptrdiff_t); [BELOW]
9377 // T* operator-(T*, ptrdiff_t);
9378 // T* operator+(ptrdiff_t, T*);
9379 // T& operator[](ptrdiff_t, T*); [BELOW]
9380 //
9381 // C++ [over.built]p14:
9382 //
9383 // For every T, where T is a pointer to object type, there
9384 // exist candidate operator functions of the form
9385 //
9386 // ptrdiff_t operator-(T, T);
9387 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9388 /// Set of (canonical) types that we've already handled.
9389 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9390
9391 for (int Arg = 0; Arg < 2; ++Arg) {
9392 QualType AsymmetricParamTypes[2] = {
9393 S.Context.getPointerDiffType(),
9394 S.Context.getPointerDiffType(),
9395 };
9396 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9397 QualType PointeeTy = PtrTy->getPointeeType();
9398 if (!PointeeTy->isObjectType())
9399 continue;
9400
9401 AsymmetricParamTypes[Arg] = PtrTy;
9402 if (Arg == 0 || Op == OO_Plus) {
9403 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9404 // T* operator+(ptrdiff_t, T*);
9405 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9406 }
9407 if (Op == OO_Minus) {
9408 // ptrdiff_t operator-(T, T);
9409 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9410 continue;
9411
9412 QualType ParamTypes[2] = {PtrTy, PtrTy};
9413 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9414 }
9415 }
9416 }
9417 }
9418
9419 // C++ [over.built]p12:
9420 //
9421 // For every pair of promoted arithmetic types L and R, there
9422 // exist candidate operator functions of the form
9423 //
9424 // LR operator*(L, R);
9425 // LR operator/(L, R);
9426 // LR operator+(L, R);
9427 // LR operator-(L, R);
9428 // bool operator<(L, R);
9429 // bool operator>(L, R);
9430 // bool operator<=(L, R);
9431 // bool operator>=(L, R);
9432 // bool operator==(L, R);
9433 // bool operator!=(L, R);
9434 //
9435 // where LR is the result of the usual arithmetic conversions
9436 // between types L and R.
9437 //
9438 // C++ [over.built]p24:
9439 //
9440 // For every pair of promoted arithmetic types L and R, there exist
9441 // candidate operator functions of the form
9442 //
9443 // LR operator?(bool, L, R);
9444 //
9445 // where LR is the result of the usual arithmetic conversions
9446 // between types L and R.
9447 // Our candidates ignore the first parameter.
9448 void addGenericBinaryArithmeticOverloads() {
9449 if (!HasArithmeticOrEnumeralCandidateType)
9450 return;
9451
9452 for (unsigned Left = FirstPromotedArithmeticType;
9453 Left < LastPromotedArithmeticType; ++Left) {
9454 for (unsigned Right = FirstPromotedArithmeticType;
9455 Right < LastPromotedArithmeticType; ++Right) {
9456 QualType LandR[2] = { ArithmeticTypes[Left],
9457 ArithmeticTypes[Right] };
9458 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9459 }
9460 }
9461
9462 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9463 // conditional operator for vector types.
9464 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9465 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9466 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9467 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9468 }
9469 }
9470
9471 /// Add binary operator overloads for each candidate matrix type M1, M2:
9472 /// * (M1, M1) -> M1
9473 /// * (M1, M1.getElementType()) -> M1
9474 /// * (M2.getElementType(), M2) -> M2
9475 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9476 void addMatrixBinaryArithmeticOverloads() {
9477 if (!HasArithmeticOrEnumeralCandidateType)
9478 return;
9479
9480 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9481 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9482 AddCandidate(L: M1, R: M1);
9483 }
9484
9485 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9486 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9487 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9488 AddCandidate(L: M2, R: M2);
9489 }
9490 }
9491
9492 // C++2a [over.built]p14:
9493 //
9494 // For every integral type T there exists a candidate operator function
9495 // of the form
9496 //
9497 // std::strong_ordering operator<=>(T, T)
9498 //
9499 // C++2a [over.built]p15:
9500 //
9501 // For every pair of floating-point types L and R, there exists a candidate
9502 // operator function of the form
9503 //
9504 // std::partial_ordering operator<=>(L, R);
9505 //
9506 // FIXME: The current specification for integral types doesn't play nice with
9507 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9508 // comparisons. Under the current spec this can lead to ambiguity during
9509 // overload resolution. For example:
9510 //
9511 // enum A : int {a};
9512 // auto x = (a <=> (long)42);
9513 //
9514 // error: call is ambiguous for arguments 'A' and 'long'.
9515 // note: candidate operator<=>(int, int)
9516 // note: candidate operator<=>(long, long)
9517 //
9518 // To avoid this error, this function deviates from the specification and adds
9519 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9520 // arithmetic types (the same as the generic relational overloads).
9521 //
9522 // For now this function acts as a placeholder.
9523 void addThreeWayArithmeticOverloads() {
9524 addGenericBinaryArithmeticOverloads();
9525 }
9526
9527 // C++ [over.built]p17:
9528 //
9529 // For every pair of promoted integral types L and R, there
9530 // exist candidate operator functions of the form
9531 //
9532 // LR operator%(L, R);
9533 // LR operator&(L, R);
9534 // LR operator^(L, R);
9535 // LR operator|(L, R);
9536 // L operator<<(L, R);
9537 // L operator>>(L, R);
9538 //
9539 // where LR is the result of the usual arithmetic conversions
9540 // between types L and R.
9541 void addBinaryBitwiseArithmeticOverloads() {
9542 if (!HasArithmeticOrEnumeralCandidateType)
9543 return;
9544
9545 for (unsigned Left = FirstPromotedIntegralType;
9546 Left < LastPromotedIntegralType; ++Left) {
9547 for (unsigned Right = FirstPromotedIntegralType;
9548 Right < LastPromotedIntegralType; ++Right) {
9549 QualType LandR[2] = { ArithmeticTypes[Left],
9550 ArithmeticTypes[Right] };
9551 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9552 }
9553 }
9554 }
9555
9556 // C++ [over.built]p20:
9557 //
9558 // For every pair (T, VQ), where T is an enumeration or
9559 // pointer to member type and VQ is either volatile or
9560 // empty, there exist candidate operator functions of the form
9561 //
9562 // VQ T& operator=(VQ T&, T);
9563 void addAssignmentMemberPointerOrEnumeralOverloads() {
9564 /// Set of (canonical) types that we've already handled.
9565 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9566
9567 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9568 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9569 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9570 continue;
9571
9572 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
9573 }
9574
9575 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9576 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9577 continue;
9578
9579 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
9580 }
9581 }
9582 }
9583
9584 // C++ [over.built]p19:
9585 //
9586 // For every pair (T, VQ), where T is any type and VQ is either
9587 // volatile or empty, there exist candidate operator functions
9588 // of the form
9589 //
9590 // T*VQ& operator=(T*VQ&, T*);
9591 //
9592 // C++ [over.built]p21:
9593 //
9594 // For every pair (T, VQ), where T is a cv-qualified or
9595 // cv-unqualified object type and VQ is either volatile or
9596 // empty, there exist candidate operator functions of the form
9597 //
9598 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9599 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9600 void addAssignmentPointerOverloads(bool isEqualOp) {
9601 /// Set of (canonical) types that we've already handled.
9602 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9603
9604 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9605 // If this is operator=, keep track of the builtin candidates we added.
9606 if (isEqualOp)
9607 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
9608 else if (!PtrTy->getPointeeType()->isObjectType())
9609 continue;
9610
9611 // non-volatile version
9612 QualType ParamTypes[2] = {
9613 S.Context.getLValueReferenceType(T: PtrTy),
9614 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9615 };
9616 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9617 /*IsAssignmentOperator=*/ isEqualOp);
9618
9619 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9620 VisibleTypeConversionsQuals.hasVolatile();
9621 if (NeedVolatile) {
9622 // volatile version
9623 ParamTypes[0] =
9624 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
9625 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9626 /*IsAssignmentOperator=*/isEqualOp);
9627 }
9628
9629 if (!PtrTy.isRestrictQualified() &&
9630 VisibleTypeConversionsQuals.hasRestrict()) {
9631 // restrict version
9632 ParamTypes[0] =
9633 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
9634 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9635 /*IsAssignmentOperator=*/isEqualOp);
9636
9637 if (NeedVolatile) {
9638 // volatile restrict version
9639 ParamTypes[0] =
9640 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9641 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9642 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9643 /*IsAssignmentOperator=*/isEqualOp);
9644 }
9645 }
9646 }
9647
9648 if (isEqualOp) {
9649 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9650 // Make sure we don't add the same candidate twice.
9651 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9652 continue;
9653
9654 QualType ParamTypes[2] = {
9655 S.Context.getLValueReferenceType(T: PtrTy),
9656 PtrTy,
9657 };
9658
9659 // non-volatile version
9660 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9661 /*IsAssignmentOperator=*/true);
9662
9663 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9664 VisibleTypeConversionsQuals.hasVolatile();
9665 if (NeedVolatile) {
9666 // volatile version
9667 ParamTypes[0] = S.Context.getLValueReferenceType(
9668 T: S.Context.getVolatileType(T: PtrTy));
9669 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9670 /*IsAssignmentOperator=*/true);
9671 }
9672
9673 if (!PtrTy.isRestrictQualified() &&
9674 VisibleTypeConversionsQuals.hasRestrict()) {
9675 // restrict version
9676 ParamTypes[0] = S.Context.getLValueReferenceType(
9677 T: S.Context.getRestrictType(T: PtrTy));
9678 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9679 /*IsAssignmentOperator=*/true);
9680
9681 if (NeedVolatile) {
9682 // volatile restrict version
9683 ParamTypes[0] =
9684 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9685 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9686 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9687 /*IsAssignmentOperator=*/true);
9688 }
9689 }
9690 }
9691 }
9692 }
9693
9694 // C++ [over.built]p18:
9695 //
9696 // For every triple (L, VQ, R), where L is an arithmetic type,
9697 // VQ is either volatile or empty, and R is a promoted
9698 // arithmetic type, there exist candidate operator functions of
9699 // the form
9700 //
9701 // VQ L& operator=(VQ L&, R);
9702 // VQ L& operator*=(VQ L&, R);
9703 // VQ L& operator/=(VQ L&, R);
9704 // VQ L& operator+=(VQ L&, R);
9705 // VQ L& operator-=(VQ L&, R);
9706 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9707 if (!HasArithmeticOrEnumeralCandidateType)
9708 return;
9709
9710 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9711 for (unsigned Right = FirstPromotedArithmeticType;
9712 Right < LastPromotedArithmeticType; ++Right) {
9713 QualType ParamTypes[2];
9714 ParamTypes[1] = ArithmeticTypes[Right];
9715 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9716 S, T: ArithmeticTypes[Left], Arg: Args[0]);
9717
9718 forAllQualifierCombinations(
9719 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
9720 ParamTypes[0] =
9721 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
9722 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9723 /*IsAssignmentOperator=*/isEqualOp);
9724 });
9725 }
9726 }
9727
9728 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9729 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9730 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9731 QualType ParamTypes[2];
9732 ParamTypes[1] = Vec2Ty;
9733 // Add this built-in operator as a candidate (VQ is empty).
9734 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
9735 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9736 /*IsAssignmentOperator=*/isEqualOp);
9737
9738 // Add this built-in operator as a candidate (VQ is 'volatile').
9739 if (VisibleTypeConversionsQuals.hasVolatile()) {
9740 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
9741 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
9742 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9743 /*IsAssignmentOperator=*/isEqualOp);
9744 }
9745 }
9746 }
9747
9748 // C++ [over.built]p22:
9749 //
9750 // For every triple (L, VQ, R), where L is an integral type, VQ
9751 // is either volatile or empty, and R is a promoted integral
9752 // type, there exist candidate operator functions of the form
9753 //
9754 // VQ L& operator%=(VQ L&, R);
9755 // VQ L& operator<<=(VQ L&, R);
9756 // VQ L& operator>>=(VQ L&, R);
9757 // VQ L& operator&=(VQ L&, R);
9758 // VQ L& operator^=(VQ L&, R);
9759 // VQ L& operator|=(VQ L&, R);
9760 void addAssignmentIntegralOverloads() {
9761 if (!HasArithmeticOrEnumeralCandidateType)
9762 return;
9763
9764 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9765 for (unsigned Right = FirstPromotedIntegralType;
9766 Right < LastPromotedIntegralType; ++Right) {
9767 QualType ParamTypes[2];
9768 ParamTypes[1] = ArithmeticTypes[Right];
9769 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9770 S, T: ArithmeticTypes[Left], Arg: Args[0]);
9771
9772 forAllQualifierCombinations(
9773 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
9774 ParamTypes[0] =
9775 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
9776 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9777 });
9778 }
9779 }
9780 }
9781
9782 // C++ [over.operator]p23:
9783 //
9784 // There also exist candidate operator functions of the form
9785 //
9786 // bool operator!(bool);
9787 // bool operator&&(bool, bool);
9788 // bool operator||(bool, bool);
9789 void addExclaimOverload() {
9790 QualType ParamTy = S.Context.BoolTy;
9791 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
9792 /*IsAssignmentOperator=*/false,
9793 /*NumContextualBoolArguments=*/1);
9794 }
9795 void addAmpAmpOrPipePipeOverload() {
9796 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9797 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9798 /*IsAssignmentOperator=*/false,
9799 /*NumContextualBoolArguments=*/2);
9800 }
9801
9802 // C++ [over.built]p13:
9803 //
9804 // For every cv-qualified or cv-unqualified object type T there
9805 // exist candidate operator functions of the form
9806 //
9807 // T* operator+(T*, ptrdiff_t); [ABOVE]
9808 // T& operator[](T*, ptrdiff_t);
9809 // T* operator-(T*, ptrdiff_t); [ABOVE]
9810 // T* operator+(ptrdiff_t, T*); [ABOVE]
9811 // T& operator[](ptrdiff_t, T*);
9812 void addSubscriptOverloads() {
9813 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9814 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9815 QualType PointeeType = PtrTy->getPointeeType();
9816 if (!PointeeType->isObjectType())
9817 continue;
9818
9819 // T& operator[](T*, ptrdiff_t)
9820 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9821 }
9822
9823 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9824 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9825 QualType PointeeType = PtrTy->getPointeeType();
9826 if (!PointeeType->isObjectType())
9827 continue;
9828
9829 // T& operator[](ptrdiff_t, T*)
9830 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9831 }
9832 }
9833
9834 // C++ [over.built]p11:
9835 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9836 // C1 is the same type as C2 or is a derived class of C2, T is an object
9837 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9838 // there exist candidate operator functions of the form
9839 //
9840 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9841 //
9842 // where CV12 is the union of CV1 and CV2.
9843 void addArrowStarOverloads() {
9844 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9845 QualType C1Ty = PtrTy;
9846 QualType C1;
9847 QualifierCollector Q1;
9848 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
9849 if (!isa<RecordType>(Val: C1))
9850 continue;
9851 // heuristic to reduce number of builtin candidates in the set.
9852 // Add volatile/restrict version only if there are conversions to a
9853 // volatile/restrict type.
9854 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9855 continue;
9856 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9857 continue;
9858 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9859 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
9860 QualType C2 = QualType(mptr->getClass(), 0);
9861 C2 = C2.getUnqualifiedType();
9862 if (C1 != C2 && !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: C1, Base: C2))
9863 break;
9864 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9865 // build CV12 T&
9866 QualType T = mptr->getPointeeType();
9867 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9868 T.isVolatileQualified())
9869 continue;
9870 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9871 T.isRestrictQualified())
9872 continue;
9873 T = Q1.apply(Context: S.Context, QT: T);
9874 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9875 }
9876 }
9877 }
9878
9879 // Note that we don't consider the first argument, since it has been
9880 // contextually converted to bool long ago. The candidates below are
9881 // therefore added as binary.
9882 //
9883 // C++ [over.built]p25:
9884 // For every type T, where T is a pointer, pointer-to-member, or scoped
9885 // enumeration type, there exist candidate operator functions of the form
9886 //
9887 // T operator?(bool, T, T);
9888 //
9889 void addConditionalOperatorOverloads() {
9890 /// Set of (canonical) types that we've already handled.
9891 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9892
9893 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9894 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9895 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9896 continue;
9897
9898 QualType ParamTypes[2] = {PtrTy, PtrTy};
9899 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9900 }
9901
9902 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9903 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9904 continue;
9905
9906 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9907 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9908 }
9909
9910 if (S.getLangOpts().CPlusPlus11) {
9911 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9912 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9913 continue;
9914
9915 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9916 continue;
9917
9918 QualType ParamTypes[2] = {EnumTy, EnumTy};
9919 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9920 }
9921 }
9922 }
9923 }
9924};
9925
9926} // end anonymous namespace
9927
9928/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9929/// operator overloads to the candidate set (C++ [over.built]), based
9930/// on the operator @p Op and the arguments given. For example, if the
9931/// operator is a binary '+', this routine might add "int
9932/// operator+(int, int)" to cover integer addition.
9933void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9934 SourceLocation OpLoc,
9935 ArrayRef<Expr *> Args,
9936 OverloadCandidateSet &CandidateSet) {
9937 // Find all of the types that the arguments can convert to, but only
9938 // if the operator we're looking at has built-in operator candidates
9939 // that make use of these types. Also record whether we encounter non-record
9940 // candidate types or either arithmetic or enumeral candidate types.
9941 QualifiersAndAtomic VisibleTypeConversionsQuals;
9942 VisibleTypeConversionsQuals.addConst();
9943 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9944 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
9945 if (Args[ArgIdx]->getType()->isAtomicType())
9946 VisibleTypeConversionsQuals.addAtomic();
9947 }
9948
9949 bool HasNonRecordCandidateType = false;
9950 bool HasArithmeticOrEnumeralCandidateType = false;
9951 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9952 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9953 CandidateTypes.emplace_back(Args&: *this);
9954 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
9955 Loc: OpLoc,
9956 AllowUserConversions: true,
9957 AllowExplicitConversions: (Op == OO_Exclaim ||
9958 Op == OO_AmpAmp ||
9959 Op == OO_PipePipe),
9960 VisibleQuals: VisibleTypeConversionsQuals);
9961 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9962 CandidateTypes[ArgIdx].hasNonRecordTypes();
9963 HasArithmeticOrEnumeralCandidateType =
9964 HasArithmeticOrEnumeralCandidateType ||
9965 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9966 }
9967
9968 // Exit early when no non-record types have been added to the candidate set
9969 // for any of the arguments to the operator.
9970 //
9971 // We can't exit early for !, ||, or &&, since there we have always have
9972 // 'bool' overloads.
9973 if (!HasNonRecordCandidateType &&
9974 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9975 return;
9976
9977 // Setup an object to manage the common state for building overloads.
9978 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9979 VisibleTypeConversionsQuals,
9980 HasArithmeticOrEnumeralCandidateType,
9981 CandidateTypes, CandidateSet);
9982
9983 // Dispatch over the operation to add in only those overloads which apply.
9984 switch (Op) {
9985 case OO_None:
9986 case NUM_OVERLOADED_OPERATORS:
9987 llvm_unreachable("Expected an overloaded operator");
9988
9989 case OO_New:
9990 case OO_Delete:
9991 case OO_Array_New:
9992 case OO_Array_Delete:
9993 case OO_Call:
9994 llvm_unreachable(
9995 "Special operators don't use AddBuiltinOperatorCandidates");
9996
9997 case OO_Comma:
9998 case OO_Arrow:
9999 case OO_Coawait:
10000 // C++ [over.match.oper]p3:
10001 // -- For the operator ',', the unary operator '&', the
10002 // operator '->', or the operator 'co_await', the
10003 // built-in candidates set is empty.
10004 break;
10005
10006 case OO_Plus: // '+' is either unary or binary
10007 if (Args.size() == 1)
10008 OpBuilder.addUnaryPlusPointerOverloads();
10009 [[fallthrough]];
10010
10011 case OO_Minus: // '-' is either unary or binary
10012 if (Args.size() == 1) {
10013 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10014 } else {
10015 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10016 OpBuilder.addGenericBinaryArithmeticOverloads();
10017 OpBuilder.addMatrixBinaryArithmeticOverloads();
10018 }
10019 break;
10020
10021 case OO_Star: // '*' is either unary or binary
10022 if (Args.size() == 1)
10023 OpBuilder.addUnaryStarPointerOverloads();
10024 else {
10025 OpBuilder.addGenericBinaryArithmeticOverloads();
10026 OpBuilder.addMatrixBinaryArithmeticOverloads();
10027 }
10028 break;
10029
10030 case OO_Slash:
10031 OpBuilder.addGenericBinaryArithmeticOverloads();
10032 break;
10033
10034 case OO_PlusPlus:
10035 case OO_MinusMinus:
10036 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10037 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10038 break;
10039
10040 case OO_EqualEqual:
10041 case OO_ExclaimEqual:
10042 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10043 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10044 OpBuilder.addGenericBinaryArithmeticOverloads();
10045 break;
10046
10047 case OO_Less:
10048 case OO_Greater:
10049 case OO_LessEqual:
10050 case OO_GreaterEqual:
10051 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10052 OpBuilder.addGenericBinaryArithmeticOverloads();
10053 break;
10054
10055 case OO_Spaceship:
10056 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10057 OpBuilder.addThreeWayArithmeticOverloads();
10058 break;
10059
10060 case OO_Percent:
10061 case OO_Caret:
10062 case OO_Pipe:
10063 case OO_LessLess:
10064 case OO_GreaterGreater:
10065 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10066 break;
10067
10068 case OO_Amp: // '&' is either unary or binary
10069 if (Args.size() == 1)
10070 // C++ [over.match.oper]p3:
10071 // -- For the operator ',', the unary operator '&', or the
10072 // operator '->', the built-in candidates set is empty.
10073 break;
10074
10075 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10076 break;
10077
10078 case OO_Tilde:
10079 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10080 break;
10081
10082 case OO_Equal:
10083 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10084 [[fallthrough]];
10085
10086 case OO_PlusEqual:
10087 case OO_MinusEqual:
10088 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10089 [[fallthrough]];
10090
10091 case OO_StarEqual:
10092 case OO_SlashEqual:
10093 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10094 break;
10095
10096 case OO_PercentEqual:
10097 case OO_LessLessEqual:
10098 case OO_GreaterGreaterEqual:
10099 case OO_AmpEqual:
10100 case OO_CaretEqual:
10101 case OO_PipeEqual:
10102 OpBuilder.addAssignmentIntegralOverloads();
10103 break;
10104
10105 case OO_Exclaim:
10106 OpBuilder.addExclaimOverload();
10107 break;
10108
10109 case OO_AmpAmp:
10110 case OO_PipePipe:
10111 OpBuilder.addAmpAmpOrPipePipeOverload();
10112 break;
10113
10114 case OO_Subscript:
10115 if (Args.size() == 2)
10116 OpBuilder.addSubscriptOverloads();
10117 break;
10118
10119 case OO_ArrowStar:
10120 OpBuilder.addArrowStarOverloads();
10121 break;
10122
10123 case OO_Conditional:
10124 OpBuilder.addConditionalOperatorOverloads();
10125 OpBuilder.addGenericBinaryArithmeticOverloads();
10126 break;
10127 }
10128}
10129
10130/// Add function candidates found via argument-dependent lookup
10131/// to the set of overloading candidates.
10132///
10133/// This routine performs argument-dependent name lookup based on the
10134/// given function name (which may also be an operator name) and adds
10135/// all of the overload candidates found by ADL to the overload
10136/// candidate set (C++ [basic.lookup.argdep]).
10137void
10138Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10139 SourceLocation Loc,
10140 ArrayRef<Expr *> Args,
10141 TemplateArgumentListInfo *ExplicitTemplateArgs,
10142 OverloadCandidateSet& CandidateSet,
10143 bool PartialOverloading) {
10144 ADLResult Fns;
10145
10146 // FIXME: This approach for uniquing ADL results (and removing
10147 // redundant candidates from the set) relies on pointer-equality,
10148 // which means we need to key off the canonical decl. However,
10149 // always going back to the canonical decl might not get us the
10150 // right set of default arguments. What default arguments are
10151 // we supposed to consider on ADL candidates, anyway?
10152
10153 // FIXME: Pass in the explicit template arguments?
10154 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10155
10156 // Erase all of the candidates we already knew about.
10157 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10158 CandEnd = CandidateSet.end();
10159 Cand != CandEnd; ++Cand)
10160 if (Cand->Function) {
10161 Fns.erase(Cand->Function);
10162 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
10163 Fns.erase(FunTmpl);
10164 }
10165
10166 // For each of the ADL candidates we found, add it to the overload
10167 // set.
10168 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10169 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10170
10171 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10172 if (ExplicitTemplateArgs)
10173 continue;
10174
10175 AddOverloadCandidate(
10176 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10177 PartialOverloading, /*AllowExplicit=*/true,
10178 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10179 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10180 AddOverloadCandidate(
10181 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10182 /*SuppressUserConversions=*/false, PartialOverloading,
10183 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10184 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: std::nullopt,
10185 PO: OverloadCandidateParamOrder::Reversed);
10186 }
10187 } else {
10188 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10189 AddTemplateOverloadCandidate(
10190 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10191 /*SuppressUserConversions=*/false, PartialOverloading,
10192 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10193 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10194 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10195 AddTemplateOverloadCandidate(
10196 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: {Args[1], Args[0]},
10197 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10198 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10199 PO: OverloadCandidateParamOrder::Reversed);
10200 }
10201 }
10202 }
10203}
10204
10205namespace {
10206enum class Comparison { Equal, Better, Worse };
10207}
10208
10209/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10210/// overload resolution.
10211///
10212/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10213/// Cand1's first N enable_if attributes have precisely the same conditions as
10214/// Cand2's first N enable_if attributes (where N = the number of enable_if
10215/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10216///
10217/// Note that you can have a pair of candidates such that Cand1's enable_if
10218/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10219/// worse than Cand1's.
10220static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10221 const FunctionDecl *Cand2) {
10222 // Common case: One (or both) decls don't have enable_if attrs.
10223 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10224 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10225 if (!Cand1Attr || !Cand2Attr) {
10226 if (Cand1Attr == Cand2Attr)
10227 return Comparison::Equal;
10228 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10229 }
10230
10231 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10232 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10233
10234 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10235 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10236 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10237 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10238
10239 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10240 // has fewer enable_if attributes than Cand2, and vice versa.
10241 if (!Cand1A)
10242 return Comparison::Worse;
10243 if (!Cand2A)
10244 return Comparison::Better;
10245
10246 Cand1ID.clear();
10247 Cand2ID.clear();
10248
10249 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10250 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10251 if (Cand1ID != Cand2ID)
10252 return Comparison::Worse;
10253 }
10254
10255 return Comparison::Equal;
10256}
10257
10258static Comparison
10259isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10260 const OverloadCandidate &Cand2) {
10261 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10262 !Cand2.Function->isMultiVersion())
10263 return Comparison::Equal;
10264
10265 // If both are invalid, they are equal. If one of them is invalid, the other
10266 // is better.
10267 if (Cand1.Function->isInvalidDecl()) {
10268 if (Cand2.Function->isInvalidDecl())
10269 return Comparison::Equal;
10270 return Comparison::Worse;
10271 }
10272 if (Cand2.Function->isInvalidDecl())
10273 return Comparison::Better;
10274
10275 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10276 // cpu_dispatch, else arbitrarily based on the identifiers.
10277 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10278 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10279 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10280 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10281
10282 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10283 return Comparison::Equal;
10284
10285 if (Cand1CPUDisp && !Cand2CPUDisp)
10286 return Comparison::Better;
10287 if (Cand2CPUDisp && !Cand1CPUDisp)
10288 return Comparison::Worse;
10289
10290 if (Cand1CPUSpec && Cand2CPUSpec) {
10291 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10292 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10293 ? Comparison::Better
10294 : Comparison::Worse;
10295
10296 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10297 FirstDiff = std::mismatch(
10298 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10299 Cand2CPUSpec->cpus_begin(),
10300 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10301 return LHS->getName() == RHS->getName();
10302 });
10303
10304 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10305 "Two different cpu-specific versions should not have the same "
10306 "identifier list, otherwise they'd be the same decl!");
10307 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10308 ? Comparison::Better
10309 : Comparison::Worse;
10310 }
10311 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10312}
10313
10314/// Compute the type of the implicit object parameter for the given function,
10315/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10316/// null QualType if there is a 'matches anything' implicit object parameter.
10317static std::optional<QualType>
10318getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10319 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10320 return std::nullopt;
10321
10322 auto *M = cast<CXXMethodDecl>(Val: F);
10323 // Static member functions' object parameters match all types.
10324 if (M->isStatic())
10325 return QualType();
10326 return M->getFunctionObjectParameterReferenceType();
10327}
10328
10329// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10330// represent the same entity.
10331static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10332 const FunctionDecl *F2) {
10333 if (declaresSameEntity(F1, F2))
10334 return true;
10335 auto PT1 = F1->getPrimaryTemplate();
10336 auto PT2 = F2->getPrimaryTemplate();
10337 if (PT1 && PT2) {
10338 if (declaresSameEntity(PT1, PT2) ||
10339 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10340 PT2->getInstantiatedFromMemberTemplate()))
10341 return true;
10342 }
10343 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10344 // different functions with same params). Consider removing this (as no test
10345 // fail w/o it).
10346 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10347 if (First) {
10348 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10349 return *T;
10350 }
10351 assert(I < F->getNumParams());
10352 return F->getParamDecl(I++)->getType();
10353 };
10354
10355 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10356 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10357
10358 if (F1NumParams != F2NumParams)
10359 return false;
10360
10361 unsigned I1 = 0, I2 = 0;
10362 for (unsigned I = 0; I != F1NumParams; ++I) {
10363 QualType T1 = NextParam(F1, I1, I == 0);
10364 QualType T2 = NextParam(F2, I2, I == 0);
10365 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10366 if (!Context.hasSameUnqualifiedType(T1, T2))
10367 return false;
10368 }
10369 return true;
10370}
10371
10372/// We're allowed to use constraints partial ordering only if the candidates
10373/// have the same parameter types:
10374/// [over.match.best.general]p2.6
10375/// F1 and F2 are non-template functions with the same
10376/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10377static bool sameFunctionParameterTypeLists(Sema &S,
10378 const OverloadCandidate &Cand1,
10379 const OverloadCandidate &Cand2) {
10380 if (!Cand1.Function || !Cand2.Function)
10381 return false;
10382
10383 FunctionDecl *Fn1 = Cand1.Function;
10384 FunctionDecl *Fn2 = Cand2.Function;
10385
10386 if (Fn1->isVariadic() != Fn1->isVariadic())
10387 return false;
10388
10389 if (!S.FunctionNonObjectParamTypesAreEqual(
10390 OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr, Reversed: Cand1.isReversed() ^ Cand2.isReversed()))
10391 return false;
10392
10393 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10394 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10395 if (Mem1 && Mem2) {
10396 // if they are member functions, both are direct members of the same class,
10397 // and
10398 if (Mem1->getParent() != Mem2->getParent())
10399 return false;
10400 // if both are non-static member functions, they have the same types for
10401 // their object parameters
10402 if (Mem1->isInstance() && Mem2->isInstance() &&
10403 !S.getASTContext().hasSameType(
10404 T1: Mem1->getFunctionObjectParameterReferenceType(),
10405 T2: Mem1->getFunctionObjectParameterReferenceType()))
10406 return false;
10407 }
10408 return true;
10409}
10410
10411/// isBetterOverloadCandidate - Determines whether the first overload
10412/// candidate is a better candidate than the second (C++ 13.3.3p1).
10413bool clang::isBetterOverloadCandidate(
10414 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10415 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
10416 // Define viable functions to be better candidates than non-viable
10417 // functions.
10418 if (!Cand2.Viable)
10419 return Cand1.Viable;
10420 else if (!Cand1.Viable)
10421 return false;
10422
10423 // [CUDA] A function with 'never' preference is marked not viable, therefore
10424 // is never shown up here. The worst preference shown up here is 'wrong side',
10425 // e.g. an H function called by a HD function in device compilation. This is
10426 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10427 // function which is called only by an H function. A deferred diagnostic will
10428 // be triggered if it is emitted. However a wrong-sided function is still
10429 // a viable candidate here.
10430 //
10431 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10432 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10433 // can be emitted, Cand1 is not better than Cand2. This rule should have
10434 // precedence over other rules.
10435 //
10436 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10437 // other rules should be used to determine which is better. This is because
10438 // host/device based overloading resolution is mostly for determining
10439 // viability of a function. If two functions are both viable, other factors
10440 // should take precedence in preference, e.g. the standard-defined preferences
10441 // like argument conversion ranks or enable_if partial-ordering. The
10442 // preference for pass-object-size parameters is probably most similar to a
10443 // type-based-overloading decision and so should take priority.
10444 //
10445 // If other rules cannot determine which is better, CUDA preference will be
10446 // used again to determine which is better.
10447 //
10448 // TODO: Currently IdentifyPreference does not return correct values
10449 // for functions called in global variable initializers due to missing
10450 // correct context about device/host. Therefore we can only enforce this
10451 // rule when there is a caller. We should enforce this rule for functions
10452 // in global variable initializers once proper context is added.
10453 //
10454 // TODO: We can only enable the hostness based overloading resolution when
10455 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10456 // overloading resolution diagnostics.
10457 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10458 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10459 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10460 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10461 bool IsCand1ImplicitHD =
10462 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10463 bool IsCand2ImplicitHD =
10464 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10465 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10466 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10467 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10468 // The implicit HD function may be a function in a system header which
10469 // is forced by pragma. In device compilation, if we prefer HD candidates
10470 // over wrong-sided candidates, overloading resolution may change, which
10471 // may result in non-deferrable diagnostics. As a workaround, we let
10472 // implicit HD candidates take equal preference as wrong-sided candidates.
10473 // This will preserve the overloading resolution.
10474 // TODO: We still need special handling of implicit HD functions since
10475 // they may incur other diagnostics to be deferred. We should make all
10476 // host/device related diagnostics deferrable and remove special handling
10477 // of implicit HD functions.
10478 auto EmitThreshold =
10479 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10480 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10481 ? SemaCUDA::CFP_Never
10482 : SemaCUDA::CFP_WrongSide;
10483 auto Cand1Emittable = P1 > EmitThreshold;
10484 auto Cand2Emittable = P2 > EmitThreshold;
10485 if (Cand1Emittable && !Cand2Emittable)
10486 return true;
10487 if (!Cand1Emittable && Cand2Emittable)
10488 return false;
10489 }
10490 }
10491
10492 // C++ [over.match.best]p1: (Changed in C++23)
10493 //
10494 // -- if F is a static member function, ICS1(F) is defined such
10495 // that ICS1(F) is neither better nor worse than ICS1(G) for
10496 // any function G, and, symmetrically, ICS1(G) is neither
10497 // better nor worse than ICS1(F).
10498 unsigned StartArg = 0;
10499 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10500 StartArg = 1;
10501
10502 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10503 // We don't allow incompatible pointer conversions in C++.
10504 if (!S.getLangOpts().CPlusPlus)
10505 return ICS.isStandard() &&
10506 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10507
10508 // The only ill-formed conversion we allow in C++ is the string literal to
10509 // char* conversion, which is only considered ill-formed after C++11.
10510 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10511 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10512 };
10513
10514 // Define functions that don't require ill-formed conversions for a given
10515 // argument to be better candidates than functions that do.
10516 unsigned NumArgs = Cand1.Conversions.size();
10517 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10518 bool HasBetterConversion = false;
10519 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10520 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10521 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10522 if (Cand1Bad != Cand2Bad) {
10523 if (Cand1Bad)
10524 return false;
10525 HasBetterConversion = true;
10526 }
10527 }
10528
10529 if (HasBetterConversion)
10530 return true;
10531
10532 // C++ [over.match.best]p1:
10533 // A viable function F1 is defined to be a better function than another
10534 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10535 // conversion sequence than ICSi(F2), and then...
10536 bool HasWorseConversion = false;
10537 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10538 switch (CompareImplicitConversionSequences(S, Loc,
10539 ICS1: Cand1.Conversions[ArgIdx],
10540 ICS2: Cand2.Conversions[ArgIdx])) {
10541 case ImplicitConversionSequence::Better:
10542 // Cand1 has a better conversion sequence.
10543 HasBetterConversion = true;
10544 break;
10545
10546 case ImplicitConversionSequence::Worse:
10547 if (Cand1.Function && Cand2.Function &&
10548 Cand1.isReversed() != Cand2.isReversed() &&
10549 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
10550 // Work around large-scale breakage caused by considering reversed
10551 // forms of operator== in C++20:
10552 //
10553 // When comparing a function against a reversed function, if we have a
10554 // better conversion for one argument and a worse conversion for the
10555 // other, the implicit conversion sequences are treated as being equally
10556 // good.
10557 //
10558 // This prevents a comparison function from being considered ambiguous
10559 // with a reversed form that is written in the same way.
10560 //
10561 // We diagnose this as an extension from CreateOverloadedBinOp.
10562 HasWorseConversion = true;
10563 break;
10564 }
10565
10566 // Cand1 can't be better than Cand2.
10567 return false;
10568
10569 case ImplicitConversionSequence::Indistinguishable:
10570 // Do nothing.
10571 break;
10572 }
10573 }
10574
10575 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10576 // ICSj(F2), or, if not that,
10577 if (HasBetterConversion && !HasWorseConversion)
10578 return true;
10579
10580 // -- the context is an initialization by user-defined conversion
10581 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10582 // from the return type of F1 to the destination type (i.e.,
10583 // the type of the entity being initialized) is a better
10584 // conversion sequence than the standard conversion sequence
10585 // from the return type of F2 to the destination type.
10586 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10587 Cand1.Function && Cand2.Function &&
10588 isa<CXXConversionDecl>(Val: Cand1.Function) &&
10589 isa<CXXConversionDecl>(Val: Cand2.Function)) {
10590 // First check whether we prefer one of the conversion functions over the
10591 // other. This only distinguishes the results in non-standard, extension
10592 // cases such as the conversion from a lambda closure type to a function
10593 // pointer or block.
10594 ImplicitConversionSequence::CompareKind Result =
10595 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
10596 if (Result == ImplicitConversionSequence::Indistinguishable)
10597 Result = CompareStandardConversionSequences(S, Loc,
10598 SCS1: Cand1.FinalConversion,
10599 SCS2: Cand2.FinalConversion);
10600
10601 if (Result != ImplicitConversionSequence::Indistinguishable)
10602 return Result == ImplicitConversionSequence::Better;
10603
10604 // FIXME: Compare kind of reference binding if conversion functions
10605 // convert to a reference type used in direct reference binding, per
10606 // C++14 [over.match.best]p1 section 2 bullet 3.
10607 }
10608
10609 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10610 // as combined with the resolution to CWG issue 243.
10611 //
10612 // When the context is initialization by constructor ([over.match.ctor] or
10613 // either phase of [over.match.list]), a constructor is preferred over
10614 // a conversion function.
10615 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10616 Cand1.Function && Cand2.Function &&
10617 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
10618 isa<CXXConstructorDecl>(Val: Cand2.Function))
10619 return isa<CXXConstructorDecl>(Val: Cand1.Function);
10620
10621 // -- F1 is a non-template function and F2 is a function template
10622 // specialization, or, if not that,
10623 bool Cand1IsSpecialization = Cand1.Function &&
10624 Cand1.Function->getPrimaryTemplate();
10625 bool Cand2IsSpecialization = Cand2.Function &&
10626 Cand2.Function->getPrimaryTemplate();
10627 if (Cand1IsSpecialization != Cand2IsSpecialization)
10628 return Cand2IsSpecialization;
10629
10630 // -- F1 and F2 are function template specializations, and the function
10631 // template for F1 is more specialized than the template for F2
10632 // according to the partial ordering rules described in 14.5.5.2, or,
10633 // if not that,
10634 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10635 const auto *Obj1Context =
10636 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10637 const auto *Obj2Context =
10638 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10639 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10640 FT1: Cand1.Function->getPrimaryTemplate(),
10641 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
10642 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
10643 : TPOC_Call,
10644 NumCallArguments1: Cand1.ExplicitCallArguments,
10645 RawObj1Ty: Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10646 : QualType{},
10647 RawObj2Ty: Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10648 : QualType{},
10649 Reversed: Cand1.isReversed() ^ Cand2.isReversed())) {
10650 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10651 }
10652 }
10653
10654 // -— F1 and F2 are non-template functions with the same
10655 // parameter-type-lists, and F1 is more constrained than F2 [...],
10656 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10657 sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10658 FunctionDecl *Function1 = Cand1.Function;
10659 FunctionDecl *Function2 = Cand2.Function;
10660 if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10661 Function1 = MF;
10662 if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10663 Function2 = MF;
10664
10665 const Expr *RC1 = Function1->getTrailingRequiresClause();
10666 const Expr *RC2 = Function2->getTrailingRequiresClause();
10667 if (RC1 && RC2) {
10668 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10669 if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10670 AtLeastAsConstrained1) ||
10671 S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10672 AtLeastAsConstrained2))
10673 return false;
10674 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10675 return AtLeastAsConstrained1;
10676 } else if (RC1 || RC2) {
10677 return RC1 != nullptr;
10678 }
10679 }
10680
10681 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10682 // class B of D, and for all arguments the corresponding parameters of
10683 // F1 and F2 have the same type.
10684 // FIXME: Implement the "all parameters have the same type" check.
10685 bool Cand1IsInherited =
10686 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
10687 bool Cand2IsInherited =
10688 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
10689 if (Cand1IsInherited != Cand2IsInherited)
10690 return Cand2IsInherited;
10691 else if (Cand1IsInherited) {
10692 assert(Cand2IsInherited);
10693 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10694 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10695 if (Cand1Class->isDerivedFrom(Cand2Class))
10696 return true;
10697 if (Cand2Class->isDerivedFrom(Cand1Class))
10698 return false;
10699 // Inherited from sibling base classes: still ambiguous.
10700 }
10701
10702 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10703 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10704 // with reversed order of parameters and F1 is not
10705 //
10706 // We rank reversed + different operator as worse than just reversed, but
10707 // that comparison can never happen, because we only consider reversing for
10708 // the maximally-rewritten operator (== or <=>).
10709 if (Cand1.RewriteKind != Cand2.RewriteKind)
10710 return Cand1.RewriteKind < Cand2.RewriteKind;
10711
10712 // Check C++17 tie-breakers for deduction guides.
10713 {
10714 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
10715 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
10716 if (Guide1 && Guide2) {
10717 // -- F1 is generated from a deduction-guide and F2 is not
10718 if (Guide1->isImplicit() != Guide2->isImplicit())
10719 return Guide2->isImplicit();
10720
10721 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10722 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10723 return true;
10724 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10725 return false;
10726
10727 // --F1 is generated from a non-template constructor and F2 is generated
10728 // from a constructor template
10729 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10730 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10731 if (Constructor1 && Constructor2) {
10732 bool isC1Templated = Constructor1->getTemplatedKind() !=
10733 FunctionDecl::TemplatedKind::TK_NonTemplate;
10734 bool isC2Templated = Constructor2->getTemplatedKind() !=
10735 FunctionDecl::TemplatedKind::TK_NonTemplate;
10736 if (isC1Templated != isC2Templated)
10737 return isC2Templated;
10738 }
10739 }
10740 }
10741
10742 // Check for enable_if value-based overload resolution.
10743 if (Cand1.Function && Cand2.Function) {
10744 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
10745 if (Cmp != Comparison::Equal)
10746 return Cmp == Comparison::Better;
10747 }
10748
10749 bool HasPS1 = Cand1.Function != nullptr &&
10750 functionHasPassObjectSizeParams(FD: Cand1.Function);
10751 bool HasPS2 = Cand2.Function != nullptr &&
10752 functionHasPassObjectSizeParams(FD: Cand2.Function);
10753 if (HasPS1 != HasPS2 && HasPS1)
10754 return true;
10755
10756 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10757 if (MV == Comparison::Better)
10758 return true;
10759 if (MV == Comparison::Worse)
10760 return false;
10761
10762 // If other rules cannot determine which is better, CUDA preference is used
10763 // to determine which is better.
10764 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10765 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10766 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
10767 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10768 }
10769
10770 // General member function overloading is handled above, so this only handles
10771 // constructors with address spaces.
10772 // This only handles address spaces since C++ has no other
10773 // qualifier that can be used with constructors.
10774 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
10775 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
10776 if (CD1 && CD2) {
10777 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10778 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10779 if (AS1 != AS2) {
10780 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1))
10781 return true;
10782 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2))
10783 return false;
10784 }
10785 }
10786
10787 return false;
10788}
10789
10790/// Determine whether two declarations are "equivalent" for the purposes of
10791/// name lookup and overload resolution. This applies when the same internal/no
10792/// linkage entity is defined by two modules (probably by textually including
10793/// the same header). In such a case, we don't consider the declarations to
10794/// declare the same entity, but we also don't want lookups with both
10795/// declarations visible to be ambiguous in some cases (this happens when using
10796/// a modularized libstdc++).
10797bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10798 const NamedDecl *B) {
10799 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
10800 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
10801 if (!VA || !VB)
10802 return false;
10803
10804 // The declarations must be declaring the same name as an internal linkage
10805 // entity in different modules.
10806 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10807 VB->getDeclContext()->getRedeclContext()) ||
10808 getOwningModule(VA) == getOwningModule(VB) ||
10809 VA->isExternallyVisible() || VB->isExternallyVisible())
10810 return false;
10811
10812 // Check that the declarations appear to be equivalent.
10813 //
10814 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10815 // For constants and functions, we should check the initializer or body is
10816 // the same. For non-constant variables, we shouldn't allow it at all.
10817 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
10818 return true;
10819
10820 // Enum constants within unnamed enumerations will have different types, but
10821 // may still be similar enough to be interchangeable for our purposes.
10822 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
10823 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
10824 // Only handle anonymous enums. If the enumerations were named and
10825 // equivalent, they would have been merged to the same type.
10826 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10827 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10828 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10829 !Context.hasSameType(EnumA->getIntegerType(),
10830 EnumB->getIntegerType()))
10831 return false;
10832 // Allow this only if the value is the same for both enumerators.
10833 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
10834 }
10835 }
10836
10837 // Nothing else is sufficiently similar.
10838 return false;
10839}
10840
10841void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10842 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10843 assert(D && "Unknown declaration");
10844 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10845
10846 Module *M = getOwningModule(D);
10847 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10848 << !M << (M ? M->getFullModuleName() : "");
10849
10850 for (auto *E : Equiv) {
10851 Module *M = getOwningModule(E);
10852 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10853 << !M << (M ? M->getFullModuleName() : "");
10854 }
10855}
10856
10857bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10858 return FailureKind == ovl_fail_bad_deduction &&
10859 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10860 TemplateDeductionResult::ConstraintsNotSatisfied &&
10861 static_cast<CNSInfo *>(DeductionFailure.Data)
10862 ->Satisfaction.ContainsErrors;
10863}
10864
10865/// Computes the best viable function (C++ 13.3.3)
10866/// within an overload candidate set.
10867///
10868/// \param Loc The location of the function name (or operator symbol) for
10869/// which overload resolution occurs.
10870///
10871/// \param Best If overload resolution was successful or found a deleted
10872/// function, \p Best points to the candidate function found.
10873///
10874/// \returns The result of overload resolution.
10875OverloadingResult
10876OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10877 iterator &Best) {
10878 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10879 std::transform(first: begin(), last: end(), result: std::back_inserter(x&: Candidates),
10880 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
10881
10882 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10883 // are accepted by both clang and NVCC. However, during a particular
10884 // compilation mode only one call variant is viable. We need to
10885 // exclude non-viable overload candidates from consideration based
10886 // only on their host/device attributes. Specifically, if one
10887 // candidate call is WrongSide and the other is SameSide, we ignore
10888 // the WrongSide candidate.
10889 // We only need to remove wrong-sided candidates here if
10890 // -fgpu-exclude-wrong-side-overloads is off. When
10891 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10892 // uniformly in isBetterOverloadCandidate.
10893 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10894 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10895 bool ContainsSameSideCandidate =
10896 llvm::any_of(Range&: Candidates, P: [&](OverloadCandidate *Cand) {
10897 // Check viable function only.
10898 return Cand->Viable && Cand->Function &&
10899 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
10900 SemaCUDA::CFP_SameSide;
10901 });
10902 if (ContainsSameSideCandidate) {
10903 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10904 // Check viable function only to avoid unnecessary data copying/moving.
10905 return Cand->Viable && Cand->Function &&
10906 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
10907 SemaCUDA::CFP_WrongSide;
10908 };
10909 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
10910 }
10911 }
10912
10913 // Find the best viable function.
10914 Best = end();
10915 for (auto *Cand : Candidates) {
10916 Cand->Best = false;
10917 if (Cand->Viable) {
10918 if (Best == end() ||
10919 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
10920 Best = Cand;
10921 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10922 // This candidate has constraint that we were unable to evaluate because
10923 // it referenced an expression that contained an error. Rather than fall
10924 // back onto a potentially unintended candidate (made worse by
10925 // subsuming constraints), treat this as 'no viable candidate'.
10926 Best = end();
10927 return OR_No_Viable_Function;
10928 }
10929 }
10930
10931 // If we didn't find any viable functions, abort.
10932 if (Best == end())
10933 return OR_No_Viable_Function;
10934
10935 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10936
10937 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10938 PendingBest.push_back(Elt: &*Best);
10939 Best->Best = true;
10940
10941 // Make sure that this function is better than every other viable
10942 // function. If not, we have an ambiguity.
10943 while (!PendingBest.empty()) {
10944 auto *Curr = PendingBest.pop_back_val();
10945 for (auto *Cand : Candidates) {
10946 if (Cand->Viable && !Cand->Best &&
10947 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
10948 PendingBest.push_back(Elt: Cand);
10949 Cand->Best = true;
10950
10951 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10952 Curr->Function))
10953 EquivalentCands.push_back(Cand->Function);
10954 else
10955 Best = end();
10956 }
10957 }
10958 }
10959
10960 // If we found more than one best candidate, this is ambiguous.
10961 if (Best == end())
10962 return OR_Ambiguous;
10963
10964 // Best is the best viable function.
10965 if (Best->Function && Best->Function->isDeleted())
10966 return OR_Deleted;
10967
10968 if (!EquivalentCands.empty())
10969 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10970 EquivalentCands);
10971
10972 return OR_Success;
10973}
10974
10975namespace {
10976
10977enum OverloadCandidateKind {
10978 oc_function,
10979 oc_method,
10980 oc_reversed_binary_operator,
10981 oc_constructor,
10982 oc_implicit_default_constructor,
10983 oc_implicit_copy_constructor,
10984 oc_implicit_move_constructor,
10985 oc_implicit_copy_assignment,
10986 oc_implicit_move_assignment,
10987 oc_implicit_equality_comparison,
10988 oc_inherited_constructor
10989};
10990
10991enum OverloadCandidateSelect {
10992 ocs_non_template,
10993 ocs_template,
10994 ocs_described_template,
10995};
10996
10997static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10998ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10999 const FunctionDecl *Fn,
11000 OverloadCandidateRewriteKind CRK,
11001 std::string &Description) {
11002
11003 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11004 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11005 isTemplate = true;
11006 Description = S.getTemplateArgumentBindingsText(
11007 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11008 }
11009
11010 OverloadCandidateSelect Select = [&]() {
11011 if (!Description.empty())
11012 return ocs_described_template;
11013 return isTemplate ? ocs_template : ocs_non_template;
11014 }();
11015
11016 OverloadCandidateKind Kind = [&]() {
11017 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11018 return oc_implicit_equality_comparison;
11019
11020 if (CRK & CRK_Reversed)
11021 return oc_reversed_binary_operator;
11022
11023 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11024 if (!Ctor->isImplicit()) {
11025 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11026 return oc_inherited_constructor;
11027 else
11028 return oc_constructor;
11029 }
11030
11031 if (Ctor->isDefaultConstructor())
11032 return oc_implicit_default_constructor;
11033
11034 if (Ctor->isMoveConstructor())
11035 return oc_implicit_move_constructor;
11036
11037 assert(Ctor->isCopyConstructor() &&
11038 "unexpected sort of implicit constructor");
11039 return oc_implicit_copy_constructor;
11040 }
11041
11042 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11043 // This actually gets spelled 'candidate function' for now, but
11044 // it doesn't hurt to split it out.
11045 if (!Meth->isImplicit())
11046 return oc_method;
11047
11048 if (Meth->isMoveAssignmentOperator())
11049 return oc_implicit_move_assignment;
11050
11051 if (Meth->isCopyAssignmentOperator())
11052 return oc_implicit_copy_assignment;
11053
11054 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11055 return oc_method;
11056 }
11057
11058 return oc_function;
11059 }();
11060
11061 return std::make_pair(x&: Kind, y&: Select);
11062}
11063
11064void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11065 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11066 // set.
11067 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11068 S.Diag(FoundDecl->getLocation(),
11069 diag::note_ovl_candidate_inherited_constructor)
11070 << Shadow->getNominatedBaseClass();
11071}
11072
11073} // end anonymous namespace
11074
11075static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11076 const FunctionDecl *FD) {
11077 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11078 bool AlwaysTrue;
11079 if (EnableIf->getCond()->isValueDependent() ||
11080 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11081 return false;
11082 if (!AlwaysTrue)
11083 return false;
11084 }
11085 return true;
11086}
11087
11088/// Returns true if we can take the address of the function.
11089///
11090/// \param Complain - If true, we'll emit a diagnostic
11091/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11092/// we in overload resolution?
11093/// \param Loc - The location of the statement we're complaining about. Ignored
11094/// if we're not complaining, or if we're in overload resolution.
11095static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11096 bool Complain,
11097 bool InOverloadResolution,
11098 SourceLocation Loc) {
11099 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11100 if (Complain) {
11101 if (InOverloadResolution)
11102 S.Diag(FD->getBeginLoc(),
11103 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11104 else
11105 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11106 }
11107 return false;
11108 }
11109
11110 if (FD->getTrailingRequiresClause()) {
11111 ConstraintSatisfaction Satisfaction;
11112 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11113 return false;
11114 if (!Satisfaction.IsSatisfied) {
11115 if (Complain) {
11116 if (InOverloadResolution) {
11117 SmallString<128> TemplateArgString;
11118 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11119 TemplateArgString += " ";
11120 TemplateArgString += S.getTemplateArgumentBindingsText(
11121 FunTmpl->getTemplateParameters(),
11122 *FD->getTemplateSpecializationArgs());
11123 }
11124
11125 S.Diag(FD->getBeginLoc(),
11126 diag::note_ovl_candidate_unsatisfied_constraints)
11127 << TemplateArgString;
11128 } else
11129 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11130 << FD;
11131 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11132 }
11133 return false;
11134 }
11135 }
11136
11137 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11138 return P->hasAttr<PassObjectSizeAttr>();
11139 });
11140 if (I == FD->param_end())
11141 return true;
11142
11143 if (Complain) {
11144 // Add one to ParamNo because it's user-facing
11145 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11146 if (InOverloadResolution)
11147 S.Diag(FD->getLocation(),
11148 diag::note_ovl_candidate_has_pass_object_size_params)
11149 << ParamNo;
11150 else
11151 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11152 << FD << ParamNo;
11153 }
11154 return false;
11155}
11156
11157static bool checkAddressOfCandidateIsAvailable(Sema &S,
11158 const FunctionDecl *FD) {
11159 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11160 /*InOverloadResolution=*/true,
11161 /*Loc=*/SourceLocation());
11162}
11163
11164bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11165 bool Complain,
11166 SourceLocation Loc) {
11167 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11168 /*InOverloadResolution=*/false,
11169 Loc);
11170}
11171
11172// Don't print candidates other than the one that matches the calling
11173// convention of the call operator, since that is guaranteed to exist.
11174static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11175 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11176
11177 if (!ConvD)
11178 return false;
11179 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11180 if (!RD->isLambda())
11181 return false;
11182
11183 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11184 CallingConv CallOpCC =
11185 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11186 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11187 CallingConv ConvToCC =
11188 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11189
11190 return ConvToCC != CallOpCC;
11191}
11192
11193// Notes the location of an overload candidate.
11194void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11195 OverloadCandidateRewriteKind RewriteKind,
11196 QualType DestType, bool TakingAddress) {
11197 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11198 return;
11199 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11200 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11201 return;
11202 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11203 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11204 return;
11205 if (shouldSkipNotingLambdaConversionDecl(Fn))
11206 return;
11207
11208 std::string FnDesc;
11209 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11210 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11211 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11212 << (unsigned)KSPair.first << (unsigned)KSPair.second
11213 << Fn << FnDesc;
11214
11215 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11216 Diag(Fn->getLocation(), PD);
11217 MaybeEmitInheritedConstructorNote(*this, Found);
11218}
11219
11220static void
11221MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11222 // Perhaps the ambiguity was caused by two atomic constraints that are
11223 // 'identical' but not equivalent:
11224 //
11225 // void foo() requires (sizeof(T) > 4) { } // #1
11226 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11227 //
11228 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11229 // #2 to subsume #1, but these constraint are not considered equivalent
11230 // according to the subsumption rules because they are not the same
11231 // source-level construct. This behavior is quite confusing and we should try
11232 // to help the user figure out what happened.
11233
11234 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11235 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11236 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11237 if (!I->Function)
11238 continue;
11239 SmallVector<const Expr *, 3> AC;
11240 if (auto *Template = I->Function->getPrimaryTemplate())
11241 Template->getAssociatedConstraints(AC);
11242 else
11243 I->Function->getAssociatedConstraints(AC);
11244 if (AC.empty())
11245 continue;
11246 if (FirstCand == nullptr) {
11247 FirstCand = I->Function;
11248 FirstAC = AC;
11249 } else if (SecondCand == nullptr) {
11250 SecondCand = I->Function;
11251 SecondAC = AC;
11252 } else {
11253 // We have more than one pair of constrained functions - this check is
11254 // expensive and we'd rather not try to diagnose it.
11255 return;
11256 }
11257 }
11258 if (!SecondCand)
11259 return;
11260 // The diagnostic can only happen if there are associated constraints on
11261 // both sides (there needs to be some identical atomic constraint).
11262 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11263 SecondCand, SecondAC))
11264 // Just show the user one diagnostic, they'll probably figure it out
11265 // from here.
11266 return;
11267}
11268
11269// Notes the location of all overload candidates designated through
11270// OverloadedExpr
11271void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11272 bool TakingAddress) {
11273 assert(OverloadedExpr->getType() == Context.OverloadTy);
11274
11275 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11276 OverloadExpr *OvlExpr = Ovl.Expression;
11277
11278 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11279 IEnd = OvlExpr->decls_end();
11280 I != IEnd; ++I) {
11281 if (FunctionTemplateDecl *FunTmpl =
11282 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11283 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11284 TakingAddress);
11285 } else if (FunctionDecl *Fun
11286 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11287 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11288 }
11289 }
11290}
11291
11292/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11293/// "lead" diagnostic; it will be given two arguments, the source and
11294/// target types of the conversion.
11295void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11296 Sema &S,
11297 SourceLocation CaretLoc,
11298 const PartialDiagnostic &PDiag) const {
11299 S.Diag(CaretLoc, PDiag)
11300 << Ambiguous.getFromType() << Ambiguous.getToType();
11301 unsigned CandsShown = 0;
11302 AmbiguousConversionSequence::const_iterator I, E;
11303 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11304 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11305 break;
11306 ++CandsShown;
11307 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11308 }
11309 S.Diags.overloadCandidatesShown(N: CandsShown);
11310 if (I != E)
11311 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11312}
11313
11314static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11315 unsigned I, bool TakingCandidateAddress) {
11316 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11317 assert(Conv.isBad());
11318 assert(Cand->Function && "for now, candidate must be a function");
11319 FunctionDecl *Fn = Cand->Function;
11320
11321 // There's a conversion slot for the object argument if this is a
11322 // non-constructor method. Note that 'I' corresponds the
11323 // conversion-slot index.
11324 bool isObjectArgument = false;
11325 if (isa<CXXMethodDecl>(Val: Fn) && !isa<CXXConstructorDecl>(Val: Fn)) {
11326 if (I == 0)
11327 isObjectArgument = true;
11328 else
11329 I--;
11330 }
11331
11332 std::string FnDesc;
11333 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11334 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
11335 Description&: FnDesc);
11336
11337 Expr *FromExpr = Conv.Bad.FromExpr;
11338 QualType FromTy = Conv.Bad.getFromType();
11339 QualType ToTy = Conv.Bad.getToType();
11340 SourceRange ToParamRange =
11341 !isObjectArgument ? Fn->getParamDecl(i: I)->getSourceRange() : SourceRange();
11342
11343 if (FromTy == S.Context.OverloadTy) {
11344 assert(FromExpr && "overload set argument came from implicit argument?");
11345 Expr *E = FromExpr->IgnoreParens();
11346 if (isa<UnaryOperator>(Val: E))
11347 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
11348 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
11349
11350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11351 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11352 << ToParamRange << ToTy << Name << I + 1;
11353 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11354 return;
11355 }
11356
11357 // Do some hand-waving analysis to see if the non-viability is due
11358 // to a qualifier mismatch.
11359 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
11360 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
11361 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11362 CToTy = RT->getPointeeType();
11363 else {
11364 // TODO: detect and diagnose the full richness of const mismatches.
11365 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11366 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11367 CFromTy = FromPT->getPointeeType();
11368 CToTy = ToPT->getPointeeType();
11369 }
11370 }
11371
11372 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11373 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy)) {
11374 Qualifiers FromQs = CFromTy.getQualifiers();
11375 Qualifiers ToQs = CToTy.getQualifiers();
11376
11377 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11378 if (isObjectArgument)
11379 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11380 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11381 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11382 else
11383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11384 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11385 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11386 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11387 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11388 return;
11389 }
11390
11391 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11393 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11394 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11395 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11396 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11397 return;
11398 }
11399
11400 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11402 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11403 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11404 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11405 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11406 return;
11407 }
11408
11409 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11410 assert(CVR && "expected qualifiers mismatch");
11411
11412 if (isObjectArgument) {
11413 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11414 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11415 << FromTy << (CVR - 1);
11416 } else {
11417 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11418 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11419 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11420 }
11421 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11422 return;
11423 }
11424
11425 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11426 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11428 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11429 << (unsigned)isObjectArgument << I + 1
11430 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11431 << ToParamRange;
11432 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11433 return;
11434 }
11435
11436 // Special diagnostic for failure to convert an initializer list, since
11437 // telling the user that it has type void is not useful.
11438 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
11439 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11440 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11441 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11442 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11443 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11444 ? 2
11445 : 0);
11446 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11447 return;
11448 }
11449
11450 // Diagnose references or pointers to incomplete types differently,
11451 // since it's far from impossible that the incompleteness triggered
11452 // the failure.
11453 QualType TempFromTy = FromTy.getNonReferenceType();
11454 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11455 TempFromTy = PTy->getPointeeType();
11456 if (TempFromTy->isIncompleteType()) {
11457 // Emit the generic diagnostic and, optionally, add the hints to it.
11458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11459 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11460 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11461 << (unsigned)(Cand->Fix.Kind);
11462
11463 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11464 return;
11465 }
11466
11467 // Diagnose base -> derived pointer conversions.
11468 unsigned BaseToDerivedConversion = 0;
11469 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11470 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11471 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11472 other: FromPtrTy->getPointeeType()) &&
11473 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11474 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11475 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
11476 Base: FromPtrTy->getPointeeType()))
11477 BaseToDerivedConversion = 1;
11478 }
11479 } else if (const ObjCObjectPointerType *FromPtrTy
11480 = FromTy->getAs<ObjCObjectPointerType>()) {
11481 if (const ObjCObjectPointerType *ToPtrTy
11482 = ToTy->getAs<ObjCObjectPointerType>())
11483 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11484 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11485 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11486 other: FromPtrTy->getPointeeType()) &&
11487 FromIface->isSuperClassOf(I: ToIface))
11488 BaseToDerivedConversion = 2;
11489 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11490 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy) &&
11491 !FromTy->isIncompleteType() &&
11492 !ToRefTy->getPointeeType()->isIncompleteType() &&
11493 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
11494 BaseToDerivedConversion = 3;
11495 }
11496 }
11497
11498 if (BaseToDerivedConversion) {
11499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11500 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11501 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11502 << I + 1;
11503 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11504 return;
11505 }
11506
11507 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
11508 isa<PointerType>(Val: CToTy)) {
11509 Qualifiers FromQs = CFromTy.getQualifiers();
11510 Qualifiers ToQs = CToTy.getQualifiers();
11511 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11513 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11514 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11515 << I + 1;
11516 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11517 return;
11518 }
11519 }
11520
11521 if (TakingCandidateAddress &&
11522 !checkAddressOfCandidateIsAvailable(S, FD: Cand->Function))
11523 return;
11524
11525 // Emit the generic diagnostic and, optionally, add the hints to it.
11526 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11527 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11528 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11529 << (unsigned)(Cand->Fix.Kind);
11530
11531 // Check that location of Fn is not in system header.
11532 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
11533 // If we can fix the conversion, suggest the FixIts.
11534 for (const FixItHint &HI : Cand->Fix.Hints)
11535 FDiag << HI;
11536 }
11537
11538 S.Diag(Fn->getLocation(), FDiag);
11539
11540 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11541}
11542
11543/// Additional arity mismatch diagnosis specific to a function overload
11544/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11545/// over a candidate in any candidate set.
11546static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11547 unsigned NumArgs) {
11548 FunctionDecl *Fn = Cand->Function;
11549 unsigned MinParams = Fn->getMinRequiredArguments();
11550
11551 // With invalid overloaded operators, it's possible that we think we
11552 // have an arity mismatch when in fact it looks like we have the
11553 // right number of arguments, because only overloaded operators have
11554 // the weird behavior of overloading member and non-member functions.
11555 // Just don't report anything.
11556 if (Fn->isInvalidDecl() &&
11557 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11558 return true;
11559
11560 if (NumArgs < MinParams) {
11561 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11562 (Cand->FailureKind == ovl_fail_bad_deduction &&
11563 Cand->DeductionFailure.getResult() ==
11564 TemplateDeductionResult::TooFewArguments));
11565 } else {
11566 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11567 (Cand->FailureKind == ovl_fail_bad_deduction &&
11568 Cand->DeductionFailure.getResult() ==
11569 TemplateDeductionResult::TooManyArguments));
11570 }
11571
11572 return false;
11573}
11574
11575/// General arity mismatch diagnosis over a candidate in a candidate set.
11576static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11577 unsigned NumFormalArgs) {
11578 assert(isa<FunctionDecl>(D) &&
11579 "The templated declaration should at least be a function"
11580 " when diagnosing bad template argument deduction due to too many"
11581 " or too few arguments");
11582
11583 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
11584
11585 // TODO: treat calls to a missing default constructor as a special case
11586 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11587 unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11588
11589 // at least / at most / exactly
11590 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11591 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11592 unsigned mode, modeCount;
11593 if (NumFormalArgs < MinParams) {
11594 if (MinParams != ParamCount || FnTy->isVariadic() ||
11595 FnTy->isTemplateVariadic())
11596 mode = 0; // "at least"
11597 else
11598 mode = 2; // "exactly"
11599 modeCount = MinParams;
11600 } else {
11601 if (MinParams != ParamCount)
11602 mode = 1; // "at most"
11603 else
11604 mode = 2; // "exactly"
11605 modeCount = ParamCount;
11606 }
11607
11608 std::string Description;
11609 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11610 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
11611
11612 if (modeCount == 1 &&
11613 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11614 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11615 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11616 << Description << mode
11617 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11618 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11619 else
11620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11621 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11622 << Description << mode << modeCount << NumFormalArgs
11623 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11624
11625 MaybeEmitInheritedConstructorNote(S, Found);
11626}
11627
11628/// Arity mismatch diagnosis specific to a function overload candidate.
11629static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11630 unsigned NumFormalArgs) {
11631 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs))
11632 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11633}
11634
11635static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11636 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11637 return TD;
11638 llvm_unreachable("Unsupported: Getting the described template declaration"
11639 " for bad deduction diagnosis");
11640}
11641
11642/// Diagnose a failed template-argument deduction.
11643static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11644 DeductionFailureInfo &DeductionFailure,
11645 unsigned NumArgs,
11646 bool TakingCandidateAddress) {
11647 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11648 NamedDecl *ParamD;
11649 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11650 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11651 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11652 switch (DeductionFailure.getResult()) {
11653 case TemplateDeductionResult::Success:
11654 llvm_unreachable(
11655 "TemplateDeductionResult::Success while diagnosing bad deduction");
11656 case TemplateDeductionResult::NonDependentConversionFailure:
11657 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11658 "while diagnosing bad deduction");
11659 case TemplateDeductionResult::Invalid:
11660 case TemplateDeductionResult::AlreadyDiagnosed:
11661 return;
11662
11663 case TemplateDeductionResult::Incomplete: {
11664 assert(ParamD && "no parameter found for incomplete deduction result");
11665 S.Diag(Templated->getLocation(),
11666 diag::note_ovl_candidate_incomplete_deduction)
11667 << ParamD->getDeclName();
11668 MaybeEmitInheritedConstructorNote(S, Found);
11669 return;
11670 }
11671
11672 case TemplateDeductionResult::IncompletePack: {
11673 assert(ParamD && "no parameter found for incomplete deduction result");
11674 S.Diag(Templated->getLocation(),
11675 diag::note_ovl_candidate_incomplete_deduction_pack)
11676 << ParamD->getDeclName()
11677 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11678 << *DeductionFailure.getFirstArg();
11679 MaybeEmitInheritedConstructorNote(S, Found);
11680 return;
11681 }
11682
11683 case TemplateDeductionResult::Underqualified: {
11684 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11685 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
11686
11687 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11688
11689 // Param will have been canonicalized, but it should just be a
11690 // qualified version of ParamD, so move the qualifiers to that.
11691 QualifierCollector Qs;
11692 Qs.strip(type: Param);
11693 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11694 assert(S.Context.hasSameType(Param, NonCanonParam));
11695
11696 // Arg has also been canonicalized, but there's nothing we can do
11697 // about that. It also doesn't matter as much, because it won't
11698 // have any template parameters in it (because deduction isn't
11699 // done on dependent types).
11700 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11701
11702 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11703 << ParamD->getDeclName() << Arg << NonCanonParam;
11704 MaybeEmitInheritedConstructorNote(S, Found);
11705 return;
11706 }
11707
11708 case TemplateDeductionResult::Inconsistent: {
11709 assert(ParamD && "no parameter found for inconsistent deduction result");
11710 int which = 0;
11711 if (isa<TemplateTypeParmDecl>(Val: ParamD))
11712 which = 0;
11713 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
11714 // Deduction might have failed because we deduced arguments of two
11715 // different types for a non-type template parameter.
11716 // FIXME: Use a different TDK value for this.
11717 QualType T1 =
11718 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11719 QualType T2 =
11720 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11721 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11722 S.Diag(Templated->getLocation(),
11723 diag::note_ovl_candidate_inconsistent_deduction_types)
11724 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11725 << *DeductionFailure.getSecondArg() << T2;
11726 MaybeEmitInheritedConstructorNote(S, Found);
11727 return;
11728 }
11729
11730 which = 1;
11731 } else {
11732 which = 2;
11733 }
11734
11735 // Tweak the diagnostic if the problem is that we deduced packs of
11736 // different arities. We'll print the actual packs anyway in case that
11737 // includes additional useful information.
11738 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11739 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11740 DeductionFailure.getFirstArg()->pack_size() !=
11741 DeductionFailure.getSecondArg()->pack_size()) {
11742 which = 3;
11743 }
11744
11745 S.Diag(Templated->getLocation(),
11746 diag::note_ovl_candidate_inconsistent_deduction)
11747 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11748 << *DeductionFailure.getSecondArg();
11749 MaybeEmitInheritedConstructorNote(S, Found);
11750 return;
11751 }
11752
11753 case TemplateDeductionResult::InvalidExplicitArguments:
11754 assert(ParamD && "no parameter found for invalid explicit arguments");
11755 if (ParamD->getDeclName())
11756 S.Diag(Templated->getLocation(),
11757 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11758 << ParamD->getDeclName();
11759 else {
11760 int index = 0;
11761 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
11762 index = TTP->getIndex();
11763 else if (NonTypeTemplateParmDecl *NTTP
11764 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
11765 index = NTTP->getIndex();
11766 else
11767 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
11768 S.Diag(Templated->getLocation(),
11769 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11770 << (index + 1);
11771 }
11772 MaybeEmitInheritedConstructorNote(S, Found);
11773 return;
11774
11775 case TemplateDeductionResult::ConstraintsNotSatisfied: {
11776 // Format the template argument list into the argument string.
11777 SmallString<128> TemplateArgString;
11778 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11779 TemplateArgString = " ";
11780 TemplateArgString += S.getTemplateArgumentBindingsText(
11781 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
11782 if (TemplateArgString.size() == 1)
11783 TemplateArgString.clear();
11784 S.Diag(Templated->getLocation(),
11785 diag::note_ovl_candidate_unsatisfied_constraints)
11786 << TemplateArgString;
11787
11788 S.DiagnoseUnsatisfiedConstraint(
11789 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11790 return;
11791 }
11792 case TemplateDeductionResult::TooManyArguments:
11793 case TemplateDeductionResult::TooFewArguments:
11794 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs);
11795 return;
11796
11797 case TemplateDeductionResult::InstantiationDepth:
11798 S.Diag(Templated->getLocation(),
11799 diag::note_ovl_candidate_instantiation_depth);
11800 MaybeEmitInheritedConstructorNote(S, Found);
11801 return;
11802
11803 case TemplateDeductionResult::SubstitutionFailure: {
11804 // Format the template argument list into the argument string.
11805 SmallString<128> TemplateArgString;
11806 if (TemplateArgumentList *Args =
11807 DeductionFailure.getTemplateArgumentList()) {
11808 TemplateArgString = " ";
11809 TemplateArgString += S.getTemplateArgumentBindingsText(
11810 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
11811 if (TemplateArgString.size() == 1)
11812 TemplateArgString.clear();
11813 }
11814
11815 // If this candidate was disabled by enable_if, say so.
11816 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11817 if (PDiag && PDiag->second.getDiagID() ==
11818 diag::err_typename_nested_not_found_enable_if) {
11819 // FIXME: Use the source range of the condition, and the fully-qualified
11820 // name of the enable_if template. These are both present in PDiag.
11821 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11822 << "'enable_if'" << TemplateArgString;
11823 return;
11824 }
11825
11826 // We found a specific requirement that disabled the enable_if.
11827 if (PDiag && PDiag->second.getDiagID() ==
11828 diag::err_typename_nested_not_found_requirement) {
11829 S.Diag(Templated->getLocation(),
11830 diag::note_ovl_candidate_disabled_by_requirement)
11831 << PDiag->second.getStringArg(0) << TemplateArgString;
11832 return;
11833 }
11834
11835 // Format the SFINAE diagnostic into the argument string.
11836 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11837 // formatted message in another diagnostic.
11838 SmallString<128> SFINAEArgString;
11839 SourceRange R;
11840 if (PDiag) {
11841 SFINAEArgString = ": ";
11842 R = SourceRange(PDiag->first, PDiag->first);
11843 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
11844 }
11845
11846 S.Diag(Templated->getLocation(),
11847 diag::note_ovl_candidate_substitution_failure)
11848 << TemplateArgString << SFINAEArgString << R;
11849 MaybeEmitInheritedConstructorNote(S, Found);
11850 return;
11851 }
11852
11853 case TemplateDeductionResult::DeducedMismatch:
11854 case TemplateDeductionResult::DeducedMismatchNested: {
11855 // Format the template argument list into the argument string.
11856 SmallString<128> TemplateArgString;
11857 if (TemplateArgumentList *Args =
11858 DeductionFailure.getTemplateArgumentList()) {
11859 TemplateArgString = " ";
11860 TemplateArgString += S.getTemplateArgumentBindingsText(
11861 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
11862 if (TemplateArgString.size() == 1)
11863 TemplateArgString.clear();
11864 }
11865
11866 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11867 << (*DeductionFailure.getCallArgIndex() + 1)
11868 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11869 << TemplateArgString
11870 << (DeductionFailure.getResult() ==
11871 TemplateDeductionResult::DeducedMismatchNested);
11872 break;
11873 }
11874
11875 case TemplateDeductionResult::NonDeducedMismatch: {
11876 // FIXME: Provide a source location to indicate what we couldn't match.
11877 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11878 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11879 if (FirstTA.getKind() == TemplateArgument::Template &&
11880 SecondTA.getKind() == TemplateArgument::Template) {
11881 TemplateName FirstTN = FirstTA.getAsTemplate();
11882 TemplateName SecondTN = SecondTA.getAsTemplate();
11883 if (FirstTN.getKind() == TemplateName::Template &&
11884 SecondTN.getKind() == TemplateName::Template) {
11885 if (FirstTN.getAsTemplateDecl()->getName() ==
11886 SecondTN.getAsTemplateDecl()->getName()) {
11887 // FIXME: This fixes a bad diagnostic where both templates are named
11888 // the same. This particular case is a bit difficult since:
11889 // 1) It is passed as a string to the diagnostic printer.
11890 // 2) The diagnostic printer only attempts to find a better
11891 // name for types, not decls.
11892 // Ideally, this should folded into the diagnostic printer.
11893 S.Diag(Templated->getLocation(),
11894 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11895 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11896 return;
11897 }
11898 }
11899 }
11900
11901 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
11902 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
11903 return;
11904
11905 // FIXME: For generic lambda parameters, check if the function is a lambda
11906 // call operator, and if so, emit a prettier and more informative
11907 // diagnostic that mentions 'auto' and lambda in addition to
11908 // (or instead of?) the canonical template type parameters.
11909 S.Diag(Templated->getLocation(),
11910 diag::note_ovl_candidate_non_deduced_mismatch)
11911 << FirstTA << SecondTA;
11912 return;
11913 }
11914 // TODO: diagnose these individually, then kill off
11915 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11916 case TemplateDeductionResult::MiscellaneousDeductionFailure:
11917 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11918 MaybeEmitInheritedConstructorNote(S, Found);
11919 return;
11920 case TemplateDeductionResult::CUDATargetMismatch:
11921 S.Diag(Templated->getLocation(),
11922 diag::note_cuda_ovl_candidate_target_mismatch);
11923 return;
11924 }
11925}
11926
11927/// Diagnose a failed template-argument deduction, for function calls.
11928static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11929 unsigned NumArgs,
11930 bool TakingCandidateAddress) {
11931 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
11932 if (TDK == TemplateDeductionResult::TooFewArguments ||
11933 TDK == TemplateDeductionResult::TooManyArguments) {
11934 if (CheckArityMismatch(S, Cand, NumArgs))
11935 return;
11936 }
11937 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11938 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11939}
11940
11941/// CUDA: diagnose an invalid call across targets.
11942static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11943 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11944 FunctionDecl *Callee = Cand->Function;
11945
11946 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
11947 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
11948
11949 std::string FnDesc;
11950 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11951 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
11952 CRK: Cand->getRewriteKind(), Description&: FnDesc);
11953
11954 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11955 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11956 << FnDesc /* Ignored */
11957 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11958
11959 // This could be an implicit constructor for which we could not infer the
11960 // target due to a collsion. Diagnose that case.
11961 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
11962 if (Meth != nullptr && Meth->isImplicit()) {
11963 CXXRecordDecl *ParentClass = Meth->getParent();
11964 CXXSpecialMemberKind CSM;
11965
11966 switch (FnKindPair.first) {
11967 default:
11968 return;
11969 case oc_implicit_default_constructor:
11970 CSM = CXXSpecialMemberKind::DefaultConstructor;
11971 break;
11972 case oc_implicit_copy_constructor:
11973 CSM = CXXSpecialMemberKind::CopyConstructor;
11974 break;
11975 case oc_implicit_move_constructor:
11976 CSM = CXXSpecialMemberKind::MoveConstructor;
11977 break;
11978 case oc_implicit_copy_assignment:
11979 CSM = CXXSpecialMemberKind::CopyAssignment;
11980 break;
11981 case oc_implicit_move_assignment:
11982 CSM = CXXSpecialMemberKind::MoveAssignment;
11983 break;
11984 };
11985
11986 bool ConstRHS = false;
11987 if (Meth->getNumParams()) {
11988 if (const ReferenceType *RT =
11989 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11990 ConstRHS = RT->getPointeeType().isConstQualified();
11991 }
11992 }
11993
11994 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
11995 /* ConstRHS */ ConstRHS,
11996 /* Diagnose */ true);
11997 }
11998}
11999
12000static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12001 FunctionDecl *Callee = Cand->Function;
12002 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12003
12004 S.Diag(Callee->getLocation(),
12005 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12006 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12007}
12008
12009static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12010 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Cand->Function);
12011 assert(ES.isExplicit() && "not an explicit candidate");
12012
12013 unsigned Kind;
12014 switch (Cand->Function->getDeclKind()) {
12015 case Decl::Kind::CXXConstructor:
12016 Kind = 0;
12017 break;
12018 case Decl::Kind::CXXConversion:
12019 Kind = 1;
12020 break;
12021 case Decl::Kind::CXXDeductionGuide:
12022 Kind = Cand->Function->isImplicit() ? 0 : 2;
12023 break;
12024 default:
12025 llvm_unreachable("invalid Decl");
12026 }
12027
12028 // Note the location of the first (in-class) declaration; a redeclaration
12029 // (particularly an out-of-class definition) will typically lack the
12030 // 'explicit' specifier.
12031 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12032 FunctionDecl *First = Cand->Function->getFirstDecl();
12033 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12034 First = Pattern->getFirstDecl();
12035
12036 S.Diag(First->getLocation(),
12037 diag::note_ovl_candidate_explicit)
12038 << Kind << (ES.getExpr() ? 1 : 0)
12039 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12040}
12041
12042/// Generates a 'note' diagnostic for an overload candidate. We've
12043/// already generated a primary error at the call site.
12044///
12045/// It really does need to be a single diagnostic with its caret
12046/// pointed at the candidate declaration. Yes, this creates some
12047/// major challenges of technical writing. Yes, this makes pointing
12048/// out problems with specific arguments quite awkward. It's still
12049/// better than generating twenty screens of text for every failed
12050/// overload.
12051///
12052/// It would be great to be able to express per-candidate problems
12053/// more richly for those diagnostic clients that cared, but we'd
12054/// still have to be just as careful with the default diagnostics.
12055/// \param CtorDestAS Addr space of object being constructed (for ctor
12056/// candidates only).
12057static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12058 unsigned NumArgs,
12059 bool TakingCandidateAddress,
12060 LangAS CtorDestAS = LangAS::Default) {
12061 FunctionDecl *Fn = Cand->Function;
12062 if (shouldSkipNotingLambdaConversionDecl(Fn))
12063 return;
12064
12065 // There is no physical candidate declaration to point to for OpenCL builtins.
12066 // Except for failed conversions, the notes are identical for each candidate,
12067 // so do not generate such notes.
12068 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12069 Cand->FailureKind != ovl_fail_bad_conversion)
12070 return;
12071
12072 // Note deleted candidates, but only if they're viable.
12073 if (Cand->Viable) {
12074 if (Fn->isDeleted()) {
12075 std::string FnDesc;
12076 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12077 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12078 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12079
12080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12081 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12082 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12083 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12084 return;
12085 }
12086
12087 // We don't really have anything else to say about viable candidates.
12088 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12089 return;
12090 }
12091
12092 switch (Cand->FailureKind) {
12093 case ovl_fail_too_many_arguments:
12094 case ovl_fail_too_few_arguments:
12095 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12096
12097 case ovl_fail_bad_deduction:
12098 return DiagnoseBadDeduction(S, Cand, NumArgs,
12099 TakingCandidateAddress);
12100
12101 case ovl_fail_illegal_constructor: {
12102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12103 << (Fn->getPrimaryTemplate() ? 1 : 0);
12104 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12105 return;
12106 }
12107
12108 case ovl_fail_object_addrspace_mismatch: {
12109 Qualifiers QualsForPrinting;
12110 QualsForPrinting.setAddressSpace(CtorDestAS);
12111 S.Diag(Fn->getLocation(),
12112 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12113 << QualsForPrinting;
12114 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12115 return;
12116 }
12117
12118 case ovl_fail_trivial_conversion:
12119 case ovl_fail_bad_final_conversion:
12120 case ovl_fail_final_conversion_not_exact:
12121 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12122
12123 case ovl_fail_bad_conversion: {
12124 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12125 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12126 if (Cand->Conversions[I].isBad())
12127 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12128
12129 // FIXME: this currently happens when we're called from SemaInit
12130 // when user-conversion overload fails. Figure out how to handle
12131 // those conditions and diagnose them well.
12132 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12133 }
12134
12135 case ovl_fail_bad_target:
12136 return DiagnoseBadTarget(S, Cand);
12137
12138 case ovl_fail_enable_if:
12139 return DiagnoseFailedEnableIfAttr(S, Cand);
12140
12141 case ovl_fail_explicit:
12142 return DiagnoseFailedExplicitSpec(S, Cand);
12143
12144 case ovl_fail_inhctor_slice:
12145 // It's generally not interesting to note copy/move constructors here.
12146 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12147 return;
12148 S.Diag(Fn->getLocation(),
12149 diag::note_ovl_candidate_inherited_constructor_slice)
12150 << (Fn->getPrimaryTemplate() ? 1 : 0)
12151 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12152 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12153 return;
12154
12155 case ovl_fail_addr_not_available: {
12156 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Cand->Function);
12157 (void)Available;
12158 assert(!Available);
12159 break;
12160 }
12161 case ovl_non_default_multiversion_function:
12162 // Do nothing, these should simply be ignored.
12163 break;
12164
12165 case ovl_fail_constraints_not_satisfied: {
12166 std::string FnDesc;
12167 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12168 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12169 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12170
12171 S.Diag(Fn->getLocation(),
12172 diag::note_ovl_candidate_constraints_not_satisfied)
12173 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12174 << FnDesc /* Ignored */;
12175 ConstraintSatisfaction Satisfaction;
12176 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction))
12177 break;
12178 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12179 }
12180 }
12181}
12182
12183static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12184 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
12185 return;
12186
12187 // Desugar the type of the surrogate down to a function type,
12188 // retaining as many typedefs as possible while still showing
12189 // the function type (and, therefore, its parameter types).
12190 QualType FnType = Cand->Surrogate->getConversionType();
12191 bool isLValueReference = false;
12192 bool isRValueReference = false;
12193 bool isPointer = false;
12194 if (const LValueReferenceType *FnTypeRef =
12195 FnType->getAs<LValueReferenceType>()) {
12196 FnType = FnTypeRef->getPointeeType();
12197 isLValueReference = true;
12198 } else if (const RValueReferenceType *FnTypeRef =
12199 FnType->getAs<RValueReferenceType>()) {
12200 FnType = FnTypeRef->getPointeeType();
12201 isRValueReference = true;
12202 }
12203 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12204 FnType = FnTypePtr->getPointeeType();
12205 isPointer = true;
12206 }
12207 // Desugar down to a function type.
12208 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12209 // Reconstruct the pointer/reference as appropriate.
12210 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12211 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12212 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12213
12214 if (!Cand->Viable &&
12215 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12216 S.Diag(Cand->Surrogate->getLocation(),
12217 diag::note_ovl_surrogate_constraints_not_satisfied)
12218 << Cand->Surrogate;
12219 ConstraintSatisfaction Satisfaction;
12220 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12221 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12222 } else {
12223 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12224 << FnType;
12225 }
12226}
12227
12228static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12229 SourceLocation OpLoc,
12230 OverloadCandidate *Cand) {
12231 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12232 std::string TypeStr("operator");
12233 TypeStr += Opc;
12234 TypeStr += "(";
12235 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12236 if (Cand->Conversions.size() == 1) {
12237 TypeStr += ")";
12238 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12239 } else {
12240 TypeStr += ", ";
12241 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12242 TypeStr += ")";
12243 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12244 }
12245}
12246
12247static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12248 OverloadCandidate *Cand) {
12249 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12250 if (ICS.isBad()) break; // all meaningless after first invalid
12251 if (!ICS.isAmbiguous()) continue;
12252
12253 ICS.DiagnoseAmbiguousConversion(
12254 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12255 }
12256}
12257
12258static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12259 if (Cand->Function)
12260 return Cand->Function->getLocation();
12261 if (Cand->IsSurrogate)
12262 return Cand->Surrogate->getLocation();
12263 return SourceLocation();
12264}
12265
12266static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12267 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12268 case TemplateDeductionResult::Success:
12269 case TemplateDeductionResult::NonDependentConversionFailure:
12270 case TemplateDeductionResult::AlreadyDiagnosed:
12271 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12272
12273 case TemplateDeductionResult::Invalid:
12274 case TemplateDeductionResult::Incomplete:
12275 case TemplateDeductionResult::IncompletePack:
12276 return 1;
12277
12278 case TemplateDeductionResult::Underqualified:
12279 case TemplateDeductionResult::Inconsistent:
12280 return 2;
12281
12282 case TemplateDeductionResult::SubstitutionFailure:
12283 case TemplateDeductionResult::DeducedMismatch:
12284 case TemplateDeductionResult::ConstraintsNotSatisfied:
12285 case TemplateDeductionResult::DeducedMismatchNested:
12286 case TemplateDeductionResult::NonDeducedMismatch:
12287 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12288 case TemplateDeductionResult::CUDATargetMismatch:
12289 return 3;
12290
12291 case TemplateDeductionResult::InstantiationDepth:
12292 return 4;
12293
12294 case TemplateDeductionResult::InvalidExplicitArguments:
12295 return 5;
12296
12297 case TemplateDeductionResult::TooManyArguments:
12298 case TemplateDeductionResult::TooFewArguments:
12299 return 6;
12300 }
12301 llvm_unreachable("Unhandled deduction result");
12302}
12303
12304namespace {
12305
12306struct CompareOverloadCandidatesForDisplay {
12307 Sema &S;
12308 SourceLocation Loc;
12309 size_t NumArgs;
12310 OverloadCandidateSet::CandidateSetKind CSK;
12311
12312 CompareOverloadCandidatesForDisplay(
12313 Sema &S, SourceLocation Loc, size_t NArgs,
12314 OverloadCandidateSet::CandidateSetKind CSK)
12315 : S(S), NumArgs(NArgs), CSK(CSK) {}
12316
12317 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12318 // If there are too many or too few arguments, that's the high-order bit we
12319 // want to sort by, even if the immediate failure kind was something else.
12320 if (C->FailureKind == ovl_fail_too_many_arguments ||
12321 C->FailureKind == ovl_fail_too_few_arguments)
12322 return static_cast<OverloadFailureKind>(C->FailureKind);
12323
12324 if (C->Function) {
12325 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12326 return ovl_fail_too_many_arguments;
12327 if (NumArgs < C->Function->getMinRequiredArguments())
12328 return ovl_fail_too_few_arguments;
12329 }
12330
12331 return static_cast<OverloadFailureKind>(C->FailureKind);
12332 }
12333
12334 bool operator()(const OverloadCandidate *L,
12335 const OverloadCandidate *R) {
12336 // Fast-path this check.
12337 if (L == R) return false;
12338
12339 // Order first by viability.
12340 if (L->Viable) {
12341 if (!R->Viable) return true;
12342
12343 if (int Ord = CompareConversions(L: *L, R: *R))
12344 return Ord < 0;
12345 // Use other tie breakers.
12346 } else if (R->Viable)
12347 return false;
12348
12349 assert(L->Viable == R->Viable);
12350
12351 // Criteria by which we can sort non-viable candidates:
12352 if (!L->Viable) {
12353 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
12354 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
12355
12356 // 1. Arity mismatches come after other candidates.
12357 if (LFailureKind == ovl_fail_too_many_arguments ||
12358 LFailureKind == ovl_fail_too_few_arguments) {
12359 if (RFailureKind == ovl_fail_too_many_arguments ||
12360 RFailureKind == ovl_fail_too_few_arguments) {
12361 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
12362 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
12363 if (LDist == RDist) {
12364 if (LFailureKind == RFailureKind)
12365 // Sort non-surrogates before surrogates.
12366 return !L->IsSurrogate && R->IsSurrogate;
12367 // Sort candidates requiring fewer parameters than there were
12368 // arguments given after candidates requiring more parameters
12369 // than there were arguments given.
12370 return LFailureKind == ovl_fail_too_many_arguments;
12371 }
12372 return LDist < RDist;
12373 }
12374 return false;
12375 }
12376 if (RFailureKind == ovl_fail_too_many_arguments ||
12377 RFailureKind == ovl_fail_too_few_arguments)
12378 return true;
12379
12380 // 2. Bad conversions come first and are ordered by the number
12381 // of bad conversions and quality of good conversions.
12382 if (LFailureKind == ovl_fail_bad_conversion) {
12383 if (RFailureKind != ovl_fail_bad_conversion)
12384 return true;
12385
12386 // The conversion that can be fixed with a smaller number of changes,
12387 // comes first.
12388 unsigned numLFixes = L->Fix.NumConversionsFixed;
12389 unsigned numRFixes = R->Fix.NumConversionsFixed;
12390 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12391 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12392 if (numLFixes != numRFixes) {
12393 return numLFixes < numRFixes;
12394 }
12395
12396 // If there's any ordering between the defined conversions...
12397 if (int Ord = CompareConversions(L: *L, R: *R))
12398 return Ord < 0;
12399 } else if (RFailureKind == ovl_fail_bad_conversion)
12400 return false;
12401
12402 if (LFailureKind == ovl_fail_bad_deduction) {
12403 if (RFailureKind != ovl_fail_bad_deduction)
12404 return true;
12405
12406 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12407 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
12408 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
12409 if (LRank != RRank)
12410 return LRank < RRank;
12411 }
12412 } else if (RFailureKind == ovl_fail_bad_deduction)
12413 return false;
12414
12415 // TODO: others?
12416 }
12417
12418 // Sort everything else by location.
12419 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
12420 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
12421
12422 // Put candidates without locations (e.g. builtins) at the end.
12423 if (LLoc.isValid() && RLoc.isValid())
12424 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
12425 if (LLoc.isValid() && !RLoc.isValid())
12426 return true;
12427 if (RLoc.isValid() && !LLoc.isValid())
12428 return false;
12429 assert(!LLoc.isValid() && !RLoc.isValid());
12430 // For builtins and other functions without locations, fallback to the order
12431 // in which they were added into the candidate set.
12432 return L < R;
12433 }
12434
12435private:
12436 struct ConversionSignals {
12437 unsigned KindRank = 0;
12438 ImplicitConversionRank Rank = ICR_Exact_Match;
12439
12440 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12441 ConversionSignals Sig;
12442 Sig.KindRank = Seq.getKindRank();
12443 if (Seq.isStandard())
12444 Sig.Rank = Seq.Standard.getRank();
12445 else if (Seq.isUserDefined())
12446 Sig.Rank = Seq.UserDefined.After.getRank();
12447 // We intend StaticObjectArgumentConversion to compare the same as
12448 // StandardConversion with ICR_ExactMatch rank.
12449 return Sig;
12450 }
12451
12452 static ConversionSignals ForObjectArgument() {
12453 // We intend StaticObjectArgumentConversion to compare the same as
12454 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12455 return {};
12456 }
12457 };
12458
12459 // Returns -1 if conversions in L are considered better.
12460 // 0 if they are considered indistinguishable.
12461 // 1 if conversions in R are better.
12462 int CompareConversions(const OverloadCandidate &L,
12463 const OverloadCandidate &R) {
12464 // We cannot use `isBetterOverloadCandidate` because it is defined
12465 // according to the C++ standard and provides a partial order, but we need
12466 // a total order as this function is used in sort.
12467 assert(L.Conversions.size() == R.Conversions.size());
12468 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12469 auto LS = L.IgnoreObjectArgument && I == 0
12470 ? ConversionSignals::ForObjectArgument()
12471 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
12472 auto RS = R.IgnoreObjectArgument
12473 ? ConversionSignals::ForObjectArgument()
12474 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
12475 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
12476 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
12477 ? -1
12478 : 1;
12479 }
12480 // FIXME: find a way to compare templates for being more or less
12481 // specialized that provides a strict weak ordering.
12482 return 0;
12483 }
12484};
12485}
12486
12487/// CompleteNonViableCandidate - Normally, overload resolution only
12488/// computes up to the first bad conversion. Produces the FixIt set if
12489/// possible.
12490static void
12491CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
12492 ArrayRef<Expr *> Args,
12493 OverloadCandidateSet::CandidateSetKind CSK) {
12494 assert(!Cand->Viable);
12495
12496 // Don't do anything on failures other than bad conversion.
12497 if (Cand->FailureKind != ovl_fail_bad_conversion)
12498 return;
12499
12500 // We only want the FixIts if all the arguments can be corrected.
12501 bool Unfixable = false;
12502 // Use a implicit copy initialization to check conversion fixes.
12503 Cand->Fix.setConversionChecker(TryCopyInitialization);
12504
12505 // Attempt to fix the bad conversion.
12506 unsigned ConvCount = Cand->Conversions.size();
12507 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12508 ++ConvIdx) {
12509 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12510 if (Cand->Conversions[ConvIdx].isInitialized() &&
12511 Cand->Conversions[ConvIdx].isBad()) {
12512 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
12513 break;
12514 }
12515 }
12516
12517 // FIXME: this should probably be preserved from the overload
12518 // operation somehow.
12519 bool SuppressUserConversions = false;
12520
12521 unsigned ConvIdx = 0;
12522 unsigned ArgIdx = 0;
12523 ArrayRef<QualType> ParamTypes;
12524 bool Reversed = Cand->isReversed();
12525
12526 if (Cand->IsSurrogate) {
12527 QualType ConvType
12528 = Cand->Surrogate->getConversionType().getNonReferenceType();
12529 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12530 ConvType = ConvPtrType->getPointeeType();
12531 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12532 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12533 ConvIdx = 1;
12534 } else if (Cand->Function) {
12535 ParamTypes =
12536 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12537 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
12538 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed) {
12539 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12540 ConvIdx = 1;
12541 if (CSK == OverloadCandidateSet::CSK_Operator &&
12542 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12543 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
12544 OO_Subscript)
12545 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12546 ArgIdx = 1;
12547 }
12548 } else {
12549 // Builtin operator.
12550 assert(ConvCount <= 3);
12551 ParamTypes = Cand->BuiltinParamTypes;
12552 }
12553
12554 // Fill in the rest of the conversions.
12555 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12556 ConvIdx != ConvCount;
12557 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12558 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12559 if (Cand->Conversions[ConvIdx].isInitialized()) {
12560 // We've already checked this conversion.
12561 } else if (ParamIdx < ParamTypes.size()) {
12562 if (ParamTypes[ParamIdx]->isDependentType())
12563 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12564 Args[ArgIdx]->getType());
12565 else {
12566 Cand->Conversions[ConvIdx] =
12567 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
12568 SuppressUserConversions,
12569 /*InOverloadResolution=*/true,
12570 /*AllowObjCWritebackConversion=*/
12571 S.getLangOpts().ObjCAutoRefCount);
12572 // Store the FixIt in the candidate if it exists.
12573 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12574 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
12575 }
12576 } else
12577 Cand->Conversions[ConvIdx].setEllipsis();
12578 }
12579}
12580
12581SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
12582 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
12583 SourceLocation OpLoc,
12584 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12585 // Sort the candidates by viability and position. Sorting directly would
12586 // be prohibitive, so we make a set of pointers and sort those.
12587 SmallVector<OverloadCandidate*, 32> Cands;
12588 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
12589 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12590 if (!Filter(*Cand))
12591 continue;
12592 switch (OCD) {
12593 case OCD_AllCandidates:
12594 if (!Cand->Viable) {
12595 if (!Cand->Function && !Cand->IsSurrogate) {
12596 // This a non-viable builtin candidate. We do not, in general,
12597 // want to list every possible builtin candidate.
12598 continue;
12599 }
12600 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
12601 }
12602 break;
12603
12604 case OCD_ViableCandidates:
12605 if (!Cand->Viable)
12606 continue;
12607 break;
12608
12609 case OCD_AmbiguousCandidates:
12610 if (!Cand->Best)
12611 continue;
12612 break;
12613 }
12614
12615 Cands.push_back(Elt: Cand);
12616 }
12617
12618 llvm::stable_sort(
12619 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12620
12621 return Cands;
12622}
12623
12624bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12625 SourceLocation OpLoc) {
12626 bool DeferHint = false;
12627 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12628 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12629 // host device candidates.
12630 auto WrongSidedCands =
12631 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12632 return (Cand.Viable == false &&
12633 Cand.FailureKind == ovl_fail_bad_target) ||
12634 (Cand.Function &&
12635 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12636 Cand.Function->template hasAttr<CUDADeviceAttr>());
12637 });
12638 DeferHint = !WrongSidedCands.empty();
12639 }
12640 return DeferHint;
12641}
12642
12643/// When overload resolution fails, prints diagnostic messages containing the
12644/// candidates in the candidate set.
12645void OverloadCandidateSet::NoteCandidates(
12646 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12647 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12648 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12649
12650 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12651
12652 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12653
12654 // In WebAssembly we don't want to emit further diagnostics if a table is
12655 // passed as an argument to a function.
12656 bool NoteCands = true;
12657 for (const Expr *Arg : Args) {
12658 if (Arg->getType()->isWebAssemblyTableType())
12659 NoteCands = false;
12660 }
12661
12662 if (NoteCands)
12663 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12664
12665 if (OCD == OCD_AmbiguousCandidates)
12666 MaybeDiagnoseAmbiguousConstraints(S, Cands: {begin(), end()});
12667}
12668
12669void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12670 ArrayRef<OverloadCandidate *> Cands,
12671 StringRef Opc, SourceLocation OpLoc) {
12672 bool ReportedAmbiguousConversions = false;
12673
12674 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12675 unsigned CandsShown = 0;
12676 auto I = Cands.begin(), E = Cands.end();
12677 for (; I != E; ++I) {
12678 OverloadCandidate *Cand = *I;
12679
12680 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12681 ShowOverloads == Ovl_Best) {
12682 break;
12683 }
12684 ++CandsShown;
12685
12686 if (Cand->Function)
12687 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
12688 /*TakingCandidateAddress=*/false, CtorDestAS: DestAS);
12689 else if (Cand->IsSurrogate)
12690 NoteSurrogateCandidate(S, Cand);
12691 else {
12692 assert(Cand->Viable &&
12693 "Non-viable built-in candidates are not added to Cands.");
12694 // Generally we only see ambiguities including viable builtin
12695 // operators if overload resolution got screwed up by an
12696 // ambiguous user-defined conversion.
12697 //
12698 // FIXME: It's quite possible for different conversions to see
12699 // different ambiguities, though.
12700 if (!ReportedAmbiguousConversions) {
12701 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12702 ReportedAmbiguousConversions = true;
12703 }
12704
12705 // If this is a viable builtin, print it.
12706 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12707 }
12708 }
12709
12710 // Inform S.Diags that we've shown an overload set with N elements. This may
12711 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12712 S.Diags.overloadCandidatesShown(N: CandsShown);
12713
12714 if (I != E)
12715 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12716 shouldDeferDiags(S, Args, OpLoc))
12717 << int(E - I);
12718}
12719
12720static SourceLocation
12721GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12722 return Cand->Specialization ? Cand->Specialization->getLocation()
12723 : SourceLocation();
12724}
12725
12726namespace {
12727struct CompareTemplateSpecCandidatesForDisplay {
12728 Sema &S;
12729 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12730
12731 bool operator()(const TemplateSpecCandidate *L,
12732 const TemplateSpecCandidate *R) {
12733 // Fast-path this check.
12734 if (L == R)
12735 return false;
12736
12737 // Assuming that both candidates are not matches...
12738
12739 // Sort by the ranking of deduction failures.
12740 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12741 return RankDeductionFailure(DFI: L->DeductionFailure) <
12742 RankDeductionFailure(DFI: R->DeductionFailure);
12743
12744 // Sort everything else by location.
12745 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
12746 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
12747
12748 // Put candidates without locations (e.g. builtins) at the end.
12749 if (LLoc.isInvalid())
12750 return false;
12751 if (RLoc.isInvalid())
12752 return true;
12753
12754 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
12755 }
12756};
12757}
12758
12759/// Diagnose a template argument deduction failure.
12760/// We are treating these failures as overload failures due to bad
12761/// deductions.
12762void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12763 bool ForTakingAddress) {
12764 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
12765 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
12766}
12767
12768void TemplateSpecCandidateSet::destroyCandidates() {
12769 for (iterator i = begin(), e = end(); i != e; ++i) {
12770 i->DeductionFailure.Destroy();
12771 }
12772}
12773
12774void TemplateSpecCandidateSet::clear() {
12775 destroyCandidates();
12776 Candidates.clear();
12777}
12778
12779/// NoteCandidates - When no template specialization match is found, prints
12780/// diagnostic messages containing the non-matching specializations that form
12781/// the candidate set.
12782/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12783/// OCD == OCD_AllCandidates and Cand->Viable == false.
12784void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12785 // Sort the candidates by position (assuming no candidate is a match).
12786 // Sorting directly would be prohibitive, so we make a set of pointers
12787 // and sort those.
12788 SmallVector<TemplateSpecCandidate *, 32> Cands;
12789 Cands.reserve(N: size());
12790 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12791 if (Cand->Specialization)
12792 Cands.push_back(Elt: Cand);
12793 // Otherwise, this is a non-matching builtin candidate. We do not,
12794 // in general, want to list every possible builtin candidate.
12795 }
12796
12797 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
12798
12799 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12800 // for generalization purposes (?).
12801 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12802
12803 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12804 unsigned CandsShown = 0;
12805 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12806 TemplateSpecCandidate *Cand = *I;
12807
12808 // Set an arbitrary limit on the number of candidates we'll spam
12809 // the user with. FIXME: This limit should depend on details of the
12810 // candidate list.
12811 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12812 break;
12813 ++CandsShown;
12814
12815 assert(Cand->Specialization &&
12816 "Non-matching built-in candidates are not added to Cands.");
12817 Cand->NoteDeductionFailure(S, ForTakingAddress);
12818 }
12819
12820 if (I != E)
12821 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12822}
12823
12824// [PossiblyAFunctionType] --> [Return]
12825// NonFunctionType --> NonFunctionType
12826// R (A) --> R(A)
12827// R (*)(A) --> R (A)
12828// R (&)(A) --> R (A)
12829// R (S::*)(A) --> R (A)
12830QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12831 QualType Ret = PossiblyAFunctionType;
12832 if (const PointerType *ToTypePtr =
12833 PossiblyAFunctionType->getAs<PointerType>())
12834 Ret = ToTypePtr->getPointeeType();
12835 else if (const ReferenceType *ToTypeRef =
12836 PossiblyAFunctionType->getAs<ReferenceType>())
12837 Ret = ToTypeRef->getPointeeType();
12838 else if (const MemberPointerType *MemTypePtr =
12839 PossiblyAFunctionType->getAs<MemberPointerType>())
12840 Ret = MemTypePtr->getPointeeType();
12841 Ret =
12842 Context.getCanonicalType(T: Ret).getUnqualifiedType();
12843 return Ret;
12844}
12845
12846static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12847 bool Complain = true) {
12848 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12849 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
12850 return true;
12851
12852 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12853 if (S.getLangOpts().CPlusPlus17 &&
12854 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12855 !S.ResolveExceptionSpec(Loc, FPT: FPT))
12856 return true;
12857
12858 return false;
12859}
12860
12861namespace {
12862// A helper class to help with address of function resolution
12863// - allows us to avoid passing around all those ugly parameters
12864class AddressOfFunctionResolver {
12865 Sema& S;
12866 Expr* SourceExpr;
12867 const QualType& TargetType;
12868 QualType TargetFunctionType; // Extracted function type from target type
12869
12870 bool Complain;
12871 //DeclAccessPair& ResultFunctionAccessPair;
12872 ASTContext& Context;
12873
12874 bool TargetTypeIsNonStaticMemberFunction;
12875 bool FoundNonTemplateFunction;
12876 bool StaticMemberFunctionFromBoundPointer;
12877 bool HasComplained;
12878
12879 OverloadExpr::FindResult OvlExprInfo;
12880 OverloadExpr *OvlExpr;
12881 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12882 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12883 TemplateSpecCandidateSet FailedCandidates;
12884
12885public:
12886 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12887 const QualType &TargetType, bool Complain)
12888 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12889 Complain(Complain), Context(S.getASTContext()),
12890 TargetTypeIsNonStaticMemberFunction(
12891 !!TargetType->getAs<MemberPointerType>()),
12892 FoundNonTemplateFunction(false),
12893 StaticMemberFunctionFromBoundPointer(false),
12894 HasComplained(false),
12895 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
12896 OvlExpr(OvlExprInfo.Expression),
12897 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12898 ExtractUnqualifiedFunctionTypeFromTargetType();
12899
12900 if (TargetFunctionType->isFunctionType()) {
12901 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
12902 if (!UME->isImplicitAccess() &&
12903 !S.ResolveSingleFunctionTemplateSpecialization(UME))
12904 StaticMemberFunctionFromBoundPointer = true;
12905 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12906 DeclAccessPair dap;
12907 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12908 ovl: OvlExpr, Complain: false, Found: &dap)) {
12909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
12910 if (!Method->isStatic()) {
12911 // If the target type is a non-function type and the function found
12912 // is a non-static member function, pretend as if that was the
12913 // target, it's the only possible type to end up with.
12914 TargetTypeIsNonStaticMemberFunction = true;
12915
12916 // And skip adding the function if its not in the proper form.
12917 // We'll diagnose this due to an empty set of functions.
12918 if (!OvlExprInfo.HasFormOfMemberPointer)
12919 return;
12920 }
12921
12922 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
12923 }
12924 return;
12925 }
12926
12927 if (OvlExpr->hasExplicitTemplateArgs())
12928 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
12929
12930 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12931 // C++ [over.over]p4:
12932 // If more than one function is selected, [...]
12933 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12934 if (FoundNonTemplateFunction)
12935 EliminateAllTemplateMatches();
12936 else
12937 EliminateAllExceptMostSpecializedTemplate();
12938 }
12939 }
12940
12941 if (S.getLangOpts().CUDA && Matches.size() > 1)
12942 EliminateSuboptimalCudaMatches();
12943 }
12944
12945 bool hasComplained() const { return HasComplained; }
12946
12947private:
12948 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12949 QualType Discard;
12950 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12951 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12952 }
12953
12954 /// \return true if A is considered a better overload candidate for the
12955 /// desired type than B.
12956 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12957 // If A doesn't have exactly the correct type, we don't want to classify it
12958 // as "better" than anything else. This way, the user is required to
12959 // disambiguate for us if there are multiple candidates and no exact match.
12960 return candidateHasExactlyCorrectType(FD: A) &&
12961 (!candidateHasExactlyCorrectType(FD: B) ||
12962 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
12963 }
12964
12965 /// \return true if we were able to eliminate all but one overload candidate,
12966 /// false otherwise.
12967 bool eliminiateSuboptimalOverloadCandidates() {
12968 // Same algorithm as overload resolution -- one pass to pick the "best",
12969 // another pass to be sure that nothing is better than the best.
12970 auto Best = Matches.begin();
12971 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12972 if (isBetterCandidate(A: I->second, B: Best->second))
12973 Best = I;
12974
12975 const FunctionDecl *BestFn = Best->second;
12976 auto IsBestOrInferiorToBest = [this, BestFn](
12977 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12978 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
12979 };
12980
12981 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12982 // option, so we can potentially give the user a better error
12983 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
12984 return false;
12985 Matches[0] = *Best;
12986 Matches.resize(N: 1);
12987 return true;
12988 }
12989
12990 bool isTargetTypeAFunction() const {
12991 return TargetFunctionType->isFunctionType();
12992 }
12993
12994 // [ToType] [Return]
12995
12996 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12997 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12998 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12999 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13000 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13001 }
13002
13003 // return true if any matching specializations were found
13004 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13005 const DeclAccessPair& CurAccessFunPair) {
13006 if (CXXMethodDecl *Method
13007 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13008 // Skip non-static function templates when converting to pointer, and
13009 // static when converting to member pointer.
13010 bool CanConvertToFunctionPointer =
13011 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13012 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13013 return false;
13014 }
13015 else if (TargetTypeIsNonStaticMemberFunction)
13016 return false;
13017
13018 // C++ [over.over]p2:
13019 // If the name is a function template, template argument deduction is
13020 // done (14.8.2.2), and if the argument deduction succeeds, the
13021 // resulting template argument list is used to generate a single
13022 // function template specialization, which is added to the set of
13023 // overloaded functions considered.
13024 FunctionDecl *Specialization = nullptr;
13025 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13026 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13027 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13028 Specialization, Info, /*IsAddressOfFunction*/ true);
13029 Result != TemplateDeductionResult::Success) {
13030 // Make a note of the failed deduction for diagnostics.
13031 FailedCandidates.addCandidate()
13032 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13033 MakeDeductionFailureInfo(Context, TDK: Result, Info));
13034 return false;
13035 }
13036
13037 // Template argument deduction ensures that we have an exact match or
13038 // compatible pointer-to-function arguments that would be adjusted by ICS.
13039 // This function template specicalization works.
13040 assert(S.isSameOrCompatibleFunctionType(
13041 Context.getCanonicalType(Specialization->getType()),
13042 Context.getCanonicalType(TargetFunctionType)));
13043
13044 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13045 return false;
13046
13047 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13048 return true;
13049 }
13050
13051 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13052 const DeclAccessPair& CurAccessFunPair) {
13053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13054 // Skip non-static functions when converting to pointer, and static
13055 // when converting to member pointer.
13056 bool CanConvertToFunctionPointer =
13057 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13058 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13059 return false;
13060 }
13061 else if (TargetTypeIsNonStaticMemberFunction)
13062 return false;
13063
13064 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13065 if (S.getLangOpts().CUDA) {
13066 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13067 if (!(Caller && Caller->isImplicit()) &&
13068 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13069 return false;
13070 }
13071 if (FunDecl->isMultiVersion()) {
13072 const auto *TA = FunDecl->getAttr<TargetAttr>();
13073 if (TA && !TA->isDefaultVersion())
13074 return false;
13075 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13076 if (TVA && !TVA->isDefaultVersion())
13077 return false;
13078 }
13079
13080 // If any candidate has a placeholder return type, trigger its deduction
13081 // now.
13082 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13083 Complain)) {
13084 HasComplained |= Complain;
13085 return false;
13086 }
13087
13088 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13089 return false;
13090
13091 // If we're in C, we need to support types that aren't exactly identical.
13092 if (!S.getLangOpts().CPlusPlus ||
13093 candidateHasExactlyCorrectType(FD: FunDecl)) {
13094 Matches.push_back(Elt: std::make_pair(
13095 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13096 FoundNonTemplateFunction = true;
13097 return true;
13098 }
13099 }
13100
13101 return false;
13102 }
13103
13104 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13105 bool Ret = false;
13106
13107 // If the overload expression doesn't have the form of a pointer to
13108 // member, don't try to convert it to a pointer-to-member type.
13109 if (IsInvalidFormOfPointerToMemberFunction())
13110 return false;
13111
13112 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13113 E = OvlExpr->decls_end();
13114 I != E; ++I) {
13115 // Look through any using declarations to find the underlying function.
13116 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13117
13118 // C++ [over.over]p3:
13119 // Non-member functions and static member functions match
13120 // targets of type "pointer-to-function" or "reference-to-function."
13121 // Nonstatic member functions match targets of
13122 // type "pointer-to-member-function."
13123 // Note that according to DR 247, the containing class does not matter.
13124 if (FunctionTemplateDecl *FunctionTemplate
13125 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13126 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13127 Ret = true;
13128 }
13129 // If we have explicit template arguments supplied, skip non-templates.
13130 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13131 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13132 Ret = true;
13133 }
13134 assert(Ret || Matches.empty());
13135 return Ret;
13136 }
13137
13138 void EliminateAllExceptMostSpecializedTemplate() {
13139 // [...] and any given function template specialization F1 is
13140 // eliminated if the set contains a second function template
13141 // specialization whose function template is more specialized
13142 // than the function template of F1 according to the partial
13143 // ordering rules of 14.5.5.2.
13144
13145 // The algorithm specified above is quadratic. We instead use a
13146 // two-pass algorithm (similar to the one used to identify the
13147 // best viable function in an overload set) that identifies the
13148 // best function template (if it exists).
13149
13150 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13151 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13152 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13153
13154 // TODO: It looks like FailedCandidates does not serve much purpose
13155 // here, since the no_viable diagnostic has index 0.
13156 UnresolvedSetIterator Result = S.getMostSpecialized(
13157 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13158 SourceExpr->getBeginLoc(), S.PDiag(),
13159 S.PDiag(diag::err_addr_ovl_ambiguous)
13160 << Matches[0].second->getDeclName(),
13161 S.PDiag(diag::note_ovl_candidate)
13162 << (unsigned)oc_function << (unsigned)ocs_described_template,
13163 Complain, TargetFunctionType);
13164
13165 if (Result != MatchesCopy.end()) {
13166 // Make it the first and only element
13167 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13168 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13169 Matches.resize(N: 1);
13170 } else
13171 HasComplained |= Complain;
13172 }
13173
13174 void EliminateAllTemplateMatches() {
13175 // [...] any function template specializations in the set are
13176 // eliminated if the set also contains a non-template function, [...]
13177 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13178 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13179 ++I;
13180 else {
13181 Matches[I] = Matches[--N];
13182 Matches.resize(N);
13183 }
13184 }
13185 }
13186
13187 void EliminateSuboptimalCudaMatches() {
13188 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
13189 Matches);
13190 }
13191
13192public:
13193 void ComplainNoMatchesFound() const {
13194 assert(Matches.empty());
13195 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13196 << OvlExpr->getName() << TargetFunctionType
13197 << OvlExpr->getSourceRange();
13198 if (FailedCandidates.empty())
13199 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13200 /*TakingAddress=*/true);
13201 else {
13202 // We have some deduction failure messages. Use them to diagnose
13203 // the function templates, and diagnose the non-template candidates
13204 // normally.
13205 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13206 IEnd = OvlExpr->decls_end();
13207 I != IEnd; ++I)
13208 if (FunctionDecl *Fun =
13209 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13210 if (!functionHasPassObjectSizeParams(Fun))
13211 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13212 /*TakingAddress=*/true);
13213 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13214 }
13215 }
13216
13217 bool IsInvalidFormOfPointerToMemberFunction() const {
13218 return TargetTypeIsNonStaticMemberFunction &&
13219 !OvlExprInfo.HasFormOfMemberPointer;
13220 }
13221
13222 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13223 // TODO: Should we condition this on whether any functions might
13224 // have matched, or is it more appropriate to do that in callers?
13225 // TODO: a fixit wouldn't hurt.
13226 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13227 << TargetType << OvlExpr->getSourceRange();
13228 }
13229
13230 bool IsStaticMemberFunctionFromBoundPointer() const {
13231 return StaticMemberFunctionFromBoundPointer;
13232 }
13233
13234 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13235 S.Diag(OvlExpr->getBeginLoc(),
13236 diag::err_invalid_form_pointer_member_function)
13237 << OvlExpr->getSourceRange();
13238 }
13239
13240 void ComplainOfInvalidConversion() const {
13241 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13242 << OvlExpr->getName() << TargetType;
13243 }
13244
13245 void ComplainMultipleMatchesFound() const {
13246 assert(Matches.size() > 1);
13247 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13248 << OvlExpr->getName() << OvlExpr->getSourceRange();
13249 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13250 /*TakingAddress=*/true);
13251 }
13252
13253 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13254
13255 int getNumMatches() const { return Matches.size(); }
13256
13257 FunctionDecl* getMatchingFunctionDecl() const {
13258 if (Matches.size() != 1) return nullptr;
13259 return Matches[0].second;
13260 }
13261
13262 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13263 if (Matches.size() != 1) return nullptr;
13264 return &Matches[0].first;
13265 }
13266};
13267}
13268
13269/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13270/// an overloaded function (C++ [over.over]), where @p From is an
13271/// expression with overloaded function type and @p ToType is the type
13272/// we're trying to resolve to. For example:
13273///
13274/// @code
13275/// int f(double);
13276/// int f(int);
13277///
13278/// int (*pfd)(double) = f; // selects f(double)
13279/// @endcode
13280///
13281/// This routine returns the resulting FunctionDecl if it could be
13282/// resolved, and NULL otherwise. When @p Complain is true, this
13283/// routine will emit diagnostics if there is an error.
13284FunctionDecl *
13285Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13286 QualType TargetType,
13287 bool Complain,
13288 DeclAccessPair &FoundResult,
13289 bool *pHadMultipleCandidates) {
13290 assert(AddressOfExpr->getType() == Context.OverloadTy);
13291
13292 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13293 Complain);
13294 int NumMatches = Resolver.getNumMatches();
13295 FunctionDecl *Fn = nullptr;
13296 bool ShouldComplain = Complain && !Resolver.hasComplained();
13297 if (NumMatches == 0 && ShouldComplain) {
13298 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13299 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13300 else
13301 Resolver.ComplainNoMatchesFound();
13302 }
13303 else if (NumMatches > 1 && ShouldComplain)
13304 Resolver.ComplainMultipleMatchesFound();
13305 else if (NumMatches == 1) {
13306 Fn = Resolver.getMatchingFunctionDecl();
13307 assert(Fn);
13308 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13309 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT: FPT);
13310 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13311 if (Complain) {
13312 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13313 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13314 else
13315 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
13316 }
13317 }
13318
13319 if (pHadMultipleCandidates)
13320 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13321 return Fn;
13322}
13323
13324/// Given an expression that refers to an overloaded function, try to
13325/// resolve that function to a single function that can have its address taken.
13326/// This will modify `Pair` iff it returns non-null.
13327///
13328/// This routine can only succeed if from all of the candidates in the overload
13329/// set for SrcExpr that can have their addresses taken, there is one candidate
13330/// that is more constrained than the rest.
13331FunctionDecl *
13332Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13333 OverloadExpr::FindResult R = OverloadExpr::find(E);
13334 OverloadExpr *Ovl = R.Expression;
13335 bool IsResultAmbiguous = false;
13336 FunctionDecl *Result = nullptr;
13337 DeclAccessPair DAP;
13338 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13339
13340 // Return positive for better, negative for worse, 0 for equal preference.
13341 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13342 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13343 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
13344 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
13345 };
13346
13347 auto CheckMoreConstrained = [&](FunctionDecl *FD1,
13348 FunctionDecl *FD2) -> std::optional<bool> {
13349 if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
13350 FD1 = MF;
13351 if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
13352 FD2 = MF;
13353 SmallVector<const Expr *, 1> AC1, AC2;
13354 FD1->getAssociatedConstraints(AC&: AC1);
13355 FD2->getAssociatedConstraints(AC&: AC2);
13356 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
13357 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
13358 return std::nullopt;
13359 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
13360 return std::nullopt;
13361 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
13362 return std::nullopt;
13363 return AtLeastAsConstrained1;
13364 };
13365
13366 // Don't use the AddressOfResolver because we're specifically looking for
13367 // cases where we have one overload candidate that lacks
13368 // enable_if/pass_object_size/...
13369 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13370 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
13371 if (!FD)
13372 return nullptr;
13373
13374 if (!checkAddressOfFunctionIsAvailable(Function: FD))
13375 continue;
13376
13377 // If we found a better result, update Result.
13378 auto FoundBetter = [&]() {
13379 IsResultAmbiguous = false;
13380 DAP = I.getPair();
13381 Result = FD;
13382 };
13383
13384 // We have more than one result - see if it is more constrained than the
13385 // previous one.
13386 if (Result) {
13387 // Check CUDA preference first. If the candidates have differennt CUDA
13388 // preference, choose the one with higher CUDA preference. Otherwise,
13389 // choose the one with more constraints.
13390 if (getLangOpts().CUDA) {
13391 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13392 // FD has different preference than Result.
13393 if (PreferenceByCUDA != 0) {
13394 // FD is more preferable than Result.
13395 if (PreferenceByCUDA > 0)
13396 FoundBetter();
13397 continue;
13398 }
13399 }
13400 // FD has the same CUDA prefernece than Result. Continue check
13401 // constraints.
13402 std::optional<bool> MoreConstrainedThanPrevious =
13403 CheckMoreConstrained(FD, Result);
13404 if (!MoreConstrainedThanPrevious) {
13405 IsResultAmbiguous = true;
13406 AmbiguousDecls.push_back(Elt: FD);
13407 continue;
13408 }
13409 if (!*MoreConstrainedThanPrevious)
13410 continue;
13411 // FD is more constrained - replace Result with it.
13412 }
13413 FoundBetter();
13414 }
13415
13416 if (IsResultAmbiguous)
13417 return nullptr;
13418
13419 if (Result) {
13420 SmallVector<const Expr *, 1> ResultAC;
13421 // We skipped over some ambiguous declarations which might be ambiguous with
13422 // the selected result.
13423 for (FunctionDecl *Skipped : AmbiguousDecls) {
13424 // If skipped candidate has different CUDA preference than the result,
13425 // there is no ambiguity. Otherwise check whether they have different
13426 // constraints.
13427 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13428 continue;
13429 if (!CheckMoreConstrained(Skipped, Result))
13430 return nullptr;
13431 }
13432 Pair = DAP;
13433 }
13434 return Result;
13435}
13436
13437/// Given an overloaded function, tries to turn it into a non-overloaded
13438/// function reference using resolveAddressOfSingleOverloadCandidate. This
13439/// will perform access checks, diagnose the use of the resultant decl, and, if
13440/// requested, potentially perform a function-to-pointer decay.
13441///
13442/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13443/// Otherwise, returns true. This may emit diagnostics and return true.
13444bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13445 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13446 Expr *E = SrcExpr.get();
13447 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13448
13449 DeclAccessPair DAP;
13450 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
13451 if (!Found || Found->isCPUDispatchMultiVersion() ||
13452 Found->isCPUSpecificMultiVersion())
13453 return false;
13454
13455 // Emitting multiple diagnostics for a function that is both inaccessible and
13456 // unavailable is consistent with our behavior elsewhere. So, always check
13457 // for both.
13458 DiagnoseUseOfDecl(Found, E->getExprLoc());
13459 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
13460 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
13461 if (Res.isInvalid())
13462 return false;
13463 Expr *Fixed = Res.get();
13464 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13465 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
13466 else
13467 SrcExpr = Fixed;
13468 return true;
13469}
13470
13471/// Given an expression that refers to an overloaded function, try to
13472/// resolve that overloaded function expression down to a single function.
13473///
13474/// This routine can only resolve template-ids that refer to a single function
13475/// template, where that template-id refers to a single template whose template
13476/// arguments are either provided by the template-id or have defaults,
13477/// as described in C++0x [temp.arg.explicit]p3.
13478///
13479/// If no template-ids are found, no diagnostics are emitted and NULL is
13480/// returned.
13481FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
13482 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13483 TemplateSpecCandidateSet *FailedTSC) {
13484 // C++ [over.over]p1:
13485 // [...] [Note: any redundant set of parentheses surrounding the
13486 // overloaded function name is ignored (5.1). ]
13487 // C++ [over.over]p1:
13488 // [...] The overloaded function name can be preceded by the &
13489 // operator.
13490
13491 // If we didn't actually find any template-ids, we're done.
13492 if (!ovl->hasExplicitTemplateArgs())
13493 return nullptr;
13494
13495 TemplateArgumentListInfo ExplicitTemplateArgs;
13496 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
13497
13498 // Look through all of the overloaded functions, searching for one
13499 // whose type matches exactly.
13500 FunctionDecl *Matched = nullptr;
13501 for (UnresolvedSetIterator I = ovl->decls_begin(),
13502 E = ovl->decls_end(); I != E; ++I) {
13503 // C++0x [temp.arg.explicit]p3:
13504 // [...] In contexts where deduction is done and fails, or in contexts
13505 // where deduction is not done, if a template argument list is
13506 // specified and it, along with any default template arguments,
13507 // identifies a single function template specialization, then the
13508 // template-id is an lvalue for the function template specialization.
13509 FunctionTemplateDecl *FunctionTemplate
13510 = cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
13511
13512 // C++ [over.over]p2:
13513 // If the name is a function template, template argument deduction is
13514 // done (14.8.2.2), and if the argument deduction succeeds, the
13515 // resulting template argument list is used to generate a single
13516 // function template specialization, which is added to the set of
13517 // overloaded functions considered.
13518 FunctionDecl *Specialization = nullptr;
13519 TemplateDeductionInfo Info(ovl->getNameLoc());
13520 if (TemplateDeductionResult Result = DeduceTemplateArguments(
13521 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
13522 /*IsAddressOfFunction*/ true);
13523 Result != TemplateDeductionResult::Success) {
13524 // Make a note of the failed deduction for diagnostics.
13525 if (FailedTSC)
13526 FailedTSC->addCandidate().set(
13527 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13528 MakeDeductionFailureInfo(Context, TDK: Result, Info));
13529 continue;
13530 }
13531
13532 assert(Specialization && "no specialization and no error?");
13533
13534 // Multiple matches; we can't resolve to a single declaration.
13535 if (Matched) {
13536 if (Complain) {
13537 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13538 << ovl->getName();
13539 NoteAllOverloadCandidates(ovl);
13540 }
13541 return nullptr;
13542 }
13543
13544 Matched = Specialization;
13545 if (FoundResult) *FoundResult = I.getPair();
13546 }
13547
13548 if (Matched &&
13549 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13550 return nullptr;
13551
13552 return Matched;
13553}
13554
13555// Resolve and fix an overloaded expression that can be resolved
13556// because it identifies a single function template specialization.
13557//
13558// Last three arguments should only be supplied if Complain = true
13559//
13560// Return true if it was logically possible to so resolve the
13561// expression, regardless of whether or not it succeeded. Always
13562// returns true if 'complain' is set.
13563bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13564 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13565 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13566 unsigned DiagIDForComplaining) {
13567 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13568
13569 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
13570
13571 DeclAccessPair found;
13572 ExprResult SingleFunctionExpression;
13573 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13574 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
13575 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
13576 SrcExpr = ExprError();
13577 return true;
13578 }
13579
13580 // It is only correct to resolve to an instance method if we're
13581 // resolving a form that's permitted to be a pointer to member.
13582 // Otherwise we'll end up making a bound member expression, which
13583 // is illegal in all the contexts we resolve like this.
13584 if (!ovl.HasFormOfMemberPointer &&
13585 isa<CXXMethodDecl>(Val: fn) &&
13586 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
13587 if (!complain) return false;
13588
13589 Diag(ovl.Expression->getExprLoc(),
13590 diag::err_bound_member_function)
13591 << 0 << ovl.Expression->getSourceRange();
13592
13593 // TODO: I believe we only end up here if there's a mix of
13594 // static and non-static candidates (otherwise the expression
13595 // would have 'bound member' type, not 'overload' type).
13596 // Ideally we would note which candidate was chosen and why
13597 // the static candidates were rejected.
13598 SrcExpr = ExprError();
13599 return true;
13600 }
13601
13602 // Fix the expression to refer to 'fn'.
13603 SingleFunctionExpression =
13604 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
13605
13606 // If desired, do function-to-pointer decay.
13607 if (doFunctionPointerConversion) {
13608 SingleFunctionExpression =
13609 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
13610 if (SingleFunctionExpression.isInvalid()) {
13611 SrcExpr = ExprError();
13612 return true;
13613 }
13614 }
13615 }
13616
13617 if (!SingleFunctionExpression.isUsable()) {
13618 if (complain) {
13619 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13620 << ovl.Expression->getName()
13621 << DestTypeForComplaining
13622 << OpRangeForComplaining
13623 << ovl.Expression->getQualifierLoc().getSourceRange();
13624 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
13625
13626 SrcExpr = ExprError();
13627 return true;
13628 }
13629
13630 return false;
13631 }
13632
13633 SrcExpr = SingleFunctionExpression;
13634 return true;
13635}
13636
13637/// Add a single candidate to the overload set.
13638static void AddOverloadedCallCandidate(Sema &S,
13639 DeclAccessPair FoundDecl,
13640 TemplateArgumentListInfo *ExplicitTemplateArgs,
13641 ArrayRef<Expr *> Args,
13642 OverloadCandidateSet &CandidateSet,
13643 bool PartialOverloading,
13644 bool KnownValid) {
13645 NamedDecl *Callee = FoundDecl.getDecl();
13646 if (isa<UsingShadowDecl>(Val: Callee))
13647 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
13648
13649 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
13650 if (ExplicitTemplateArgs) {
13651 assert(!KnownValid && "Explicit template arguments?");
13652 return;
13653 }
13654 // Prevent ill-formed function decls to be added as overload candidates.
13655 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13656 return;
13657
13658 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
13659 /*SuppressUserConversions=*/false,
13660 PartialOverloading);
13661 return;
13662 }
13663
13664 if (FunctionTemplateDecl *FuncTemplate
13665 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
13666 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
13667 ExplicitTemplateArgs, Args, CandidateSet,
13668 /*SuppressUserConversions=*/false,
13669 PartialOverloading);
13670 return;
13671 }
13672
13673 assert(!KnownValid && "unhandled case in overloaded call candidate");
13674}
13675
13676/// Add the overload candidates named by callee and/or found by argument
13677/// dependent lookup to the given overload set.
13678void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13679 ArrayRef<Expr *> Args,
13680 OverloadCandidateSet &CandidateSet,
13681 bool PartialOverloading) {
13682
13683#ifndef NDEBUG
13684 // Verify that ArgumentDependentLookup is consistent with the rules
13685 // in C++0x [basic.lookup.argdep]p3:
13686 //
13687 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13688 // and let Y be the lookup set produced by argument dependent
13689 // lookup (defined as follows). If X contains
13690 //
13691 // -- a declaration of a class member, or
13692 //
13693 // -- a block-scope function declaration that is not a
13694 // using-declaration, or
13695 //
13696 // -- a declaration that is neither a function or a function
13697 // template
13698 //
13699 // then Y is empty.
13700
13701 if (ULE->requiresADL()) {
13702 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13703 E = ULE->decls_end(); I != E; ++I) {
13704 assert(!(*I)->getDeclContext()->isRecord());
13705 assert(isa<UsingShadowDecl>(*I) ||
13706 !(*I)->getDeclContext()->isFunctionOrMethod());
13707 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13708 }
13709 }
13710#endif
13711
13712 // It would be nice to avoid this copy.
13713 TemplateArgumentListInfo TABuffer;
13714 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13715 if (ULE->hasExplicitTemplateArgs()) {
13716 ULE->copyTemplateArgumentsInto(TABuffer);
13717 ExplicitTemplateArgs = &TABuffer;
13718 }
13719
13720 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13721 E = ULE->decls_end(); I != E; ++I)
13722 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
13723 CandidateSet, PartialOverloading,
13724 /*KnownValid*/ true);
13725
13726 if (ULE->requiresADL())
13727 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
13728 Args, ExplicitTemplateArgs,
13729 CandidateSet, PartialOverloading);
13730}
13731
13732/// Add the call candidates from the given set of lookup results to the given
13733/// overload set. Non-function lookup results are ignored.
13734void Sema::AddOverloadedCallCandidates(
13735 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13736 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13737 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13738 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
13739 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
13740}
13741
13742/// Determine whether a declaration with the specified name could be moved into
13743/// a different namespace.
13744static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13745 switch (Name.getCXXOverloadedOperator()) {
13746 case OO_New: case OO_Array_New:
13747 case OO_Delete: case OO_Array_Delete:
13748 return false;
13749
13750 default:
13751 return true;
13752 }
13753}
13754
13755/// Attempt to recover from an ill-formed use of a non-dependent name in a
13756/// template, where the non-dependent name was declared after the template
13757/// was defined. This is common in code written for a compilers which do not
13758/// correctly implement two-stage name lookup.
13759///
13760/// Returns true if a viable candidate was found and a diagnostic was issued.
13761static bool DiagnoseTwoPhaseLookup(
13762 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13763 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13764 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13765 CXXRecordDecl **FoundInClass = nullptr) {
13766 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13767 return false;
13768
13769 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13770 if (DC->isTransparentContext())
13771 continue;
13772
13773 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
13774
13775 if (!R.empty()) {
13776 R.suppressDiagnostics();
13777
13778 OverloadCandidateSet Candidates(FnLoc, CSK);
13779 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13780 CandidateSet&: Candidates);
13781
13782 OverloadCandidateSet::iterator Best;
13783 OverloadingResult OR =
13784 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
13785
13786 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
13787 // We either found non-function declarations or a best viable function
13788 // at class scope. A class-scope lookup result disables ADL. Don't
13789 // look past this, but let the caller know that we found something that
13790 // either is, or might be, usable in this class.
13791 if (FoundInClass) {
13792 *FoundInClass = RD;
13793 if (OR == OR_Success) {
13794 R.clear();
13795 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
13796 R.resolveKind();
13797 }
13798 }
13799 return false;
13800 }
13801
13802 if (OR != OR_Success) {
13803 // There wasn't a unique best function or function template.
13804 return false;
13805 }
13806
13807 // Find the namespaces where ADL would have looked, and suggest
13808 // declaring the function there instead.
13809 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13810 Sema::AssociatedClassSet AssociatedClasses;
13811 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
13812 AssociatedNamespaces,
13813 AssociatedClasses);
13814 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13815 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
13816 DeclContext *Std = SemaRef.getStdNamespace();
13817 for (Sema::AssociatedNamespaceSet::iterator
13818 it = AssociatedNamespaces.begin(),
13819 end = AssociatedNamespaces.end(); it != end; ++it) {
13820 // Never suggest declaring a function within namespace 'std'.
13821 if (Std && Std->Encloses(DC: *it))
13822 continue;
13823
13824 // Never suggest declaring a function within a namespace with a
13825 // reserved name, like __gnu_cxx.
13826 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
13827 if (NS &&
13828 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13829 continue;
13830
13831 SuggestedNamespaces.insert(X: *it);
13832 }
13833 }
13834
13835 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13836 << R.getLookupName();
13837 if (SuggestedNamespaces.empty()) {
13838 SemaRef.Diag(Best->Function->getLocation(),
13839 diag::note_not_found_by_two_phase_lookup)
13840 << R.getLookupName() << 0;
13841 } else if (SuggestedNamespaces.size() == 1) {
13842 SemaRef.Diag(Best->Function->getLocation(),
13843 diag::note_not_found_by_two_phase_lookup)
13844 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13845 } else {
13846 // FIXME: It would be useful to list the associated namespaces here,
13847 // but the diagnostics infrastructure doesn't provide a way to produce
13848 // a localized representation of a list of items.
13849 SemaRef.Diag(Best->Function->getLocation(),
13850 diag::note_not_found_by_two_phase_lookup)
13851 << R.getLookupName() << 2;
13852 }
13853
13854 // Try to recover by calling this function.
13855 return true;
13856 }
13857
13858 R.clear();
13859 }
13860
13861 return false;
13862}
13863
13864/// Attempt to recover from ill-formed use of a non-dependent operator in a
13865/// template, where the non-dependent operator was declared after the template
13866/// was defined.
13867///
13868/// Returns true if a viable candidate was found and a diagnostic was issued.
13869static bool
13870DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13871 SourceLocation OpLoc,
13872 ArrayRef<Expr *> Args) {
13873 DeclarationName OpName =
13874 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13875 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13876 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
13877 CSK: OverloadCandidateSet::CSK_Operator,
13878 /*ExplicitTemplateArgs=*/nullptr, Args);
13879}
13880
13881namespace {
13882class BuildRecoveryCallExprRAII {
13883 Sema &SemaRef;
13884 Sema::SatisfactionStackResetRAII SatStack;
13885
13886public:
13887 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13888 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13889 SemaRef.IsBuildingRecoveryCallExpr = true;
13890 }
13891
13892 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13893};
13894}
13895
13896/// Attempts to recover from a call where no functions were found.
13897///
13898/// This function will do one of three things:
13899/// * Diagnose, recover, and return a recovery expression.
13900/// * Diagnose, fail to recover, and return ExprError().
13901/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13902/// expected to diagnose as appropriate.
13903static ExprResult
13904BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13905 UnresolvedLookupExpr *ULE,
13906 SourceLocation LParenLoc,
13907 MutableArrayRef<Expr *> Args,
13908 SourceLocation RParenLoc,
13909 bool EmptyLookup, bool AllowTypoCorrection) {
13910 // Do not try to recover if it is already building a recovery call.
13911 // This stops infinite loops for template instantiations like
13912 //
13913 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13914 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13915 if (SemaRef.IsBuildingRecoveryCallExpr)
13916 return ExprResult();
13917 BuildRecoveryCallExprRAII RCE(SemaRef);
13918
13919 CXXScopeSpec SS;
13920 SS.Adopt(Other: ULE->getQualifierLoc());
13921 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13922
13923 TemplateArgumentListInfo TABuffer;
13924 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13925 if (ULE->hasExplicitTemplateArgs()) {
13926 ULE->copyTemplateArgumentsInto(TABuffer);
13927 ExplicitTemplateArgs = &TABuffer;
13928 }
13929
13930 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13931 Sema::LookupOrdinaryName);
13932 CXXRecordDecl *FoundInClass = nullptr;
13933 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
13934 CSK: OverloadCandidateSet::CSK_Normal,
13935 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
13936 // OK, diagnosed a two-phase lookup issue.
13937 } else if (EmptyLookup) {
13938 // Try to recover from an empty lookup with typo correction.
13939 R.clear();
13940 NoTypoCorrectionCCC NoTypoValidator{};
13941 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13942 ExplicitTemplateArgs != nullptr,
13943 dyn_cast<MemberExpr>(Val: Fn));
13944 CorrectionCandidateCallback &Validator =
13945 AllowTypoCorrection
13946 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13947 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13948 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
13949 Args))
13950 return ExprError();
13951 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13952 // We found a usable declaration of the name in a dependent base of some
13953 // enclosing class.
13954 // FIXME: We should also explain why the candidates found by name lookup
13955 // were not viable.
13956 if (SemaRef.DiagnoseDependentMemberLookup(R))
13957 return ExprError();
13958 } else {
13959 // We had viable candidates and couldn't recover; let the caller diagnose
13960 // this.
13961 return ExprResult();
13962 }
13963
13964 // If we get here, we should have issued a diagnostic and formed a recovery
13965 // lookup result.
13966 assert(!R.empty() && "lookup results empty despite recovery");
13967
13968 // If recovery created an ambiguity, just bail out.
13969 if (R.isAmbiguous()) {
13970 R.suppressDiagnostics();
13971 return ExprError();
13972 }
13973
13974 // Build an implicit member call if appropriate. Just drop the
13975 // casts and such from the call, we don't really care.
13976 ExprResult NewFn = ExprError();
13977 if ((*R.begin())->isCXXClassMember())
13978 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13979 TemplateArgs: ExplicitTemplateArgs, S);
13980 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13981 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
13982 TemplateArgs: ExplicitTemplateArgs);
13983 else
13984 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
13985
13986 if (NewFn.isInvalid())
13987 return ExprError();
13988
13989 // This shouldn't cause an infinite loop because we're giving it
13990 // an expression with viable lookup results, which should never
13991 // end up here.
13992 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
13993 ArgExprs: MultiExprArg(Args.data(), Args.size()),
13994 RParenLoc);
13995}
13996
13997/// Constructs and populates an OverloadedCandidateSet from
13998/// the given function.
13999/// \returns true when an the ExprResult output parameter has been set.
14000bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14001 UnresolvedLookupExpr *ULE,
14002 MultiExprArg Args,
14003 SourceLocation RParenLoc,
14004 OverloadCandidateSet *CandidateSet,
14005 ExprResult *Result) {
14006#ifndef NDEBUG
14007 if (ULE->requiresADL()) {
14008 // To do ADL, we must have found an unqualified name.
14009 assert(!ULE->getQualifier() && "qualified name with ADL");
14010
14011 // We don't perform ADL for implicit declarations of builtins.
14012 // Verify that this was correctly set up.
14013 FunctionDecl *F;
14014 if (ULE->decls_begin() != ULE->decls_end() &&
14015 ULE->decls_begin() + 1 == ULE->decls_end() &&
14016 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14017 F->getBuiltinID() && F->isImplicit())
14018 llvm_unreachable("performing ADL for builtin");
14019
14020 // We don't perform ADL in C.
14021 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14022 }
14023#endif
14024
14025 UnbridgedCastsSet UnbridgedCasts;
14026 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14027 *Result = ExprError();
14028 return true;
14029 }
14030
14031 // Add the functions denoted by the callee to the set of candidate
14032 // functions, including those from argument-dependent lookup.
14033 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14034
14035 if (getLangOpts().MSVCCompat &&
14036 CurContext->isDependentContext() && !isSFINAEContext() &&
14037 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14038
14039 OverloadCandidateSet::iterator Best;
14040 if (CandidateSet->empty() ||
14041 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14042 OR_No_Viable_Function) {
14043 // In Microsoft mode, if we are inside a template class member function
14044 // then create a type dependent CallExpr. The goal is to postpone name
14045 // lookup to instantiation time to be able to search into type dependent
14046 // base classes.
14047 CallExpr *CE =
14048 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14049 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14050 CE->markDependentForPostponedNameLookup();
14051 *Result = CE;
14052 return true;
14053 }
14054 }
14055
14056 if (CandidateSet->empty())
14057 return false;
14058
14059 UnbridgedCasts.restore();
14060 return false;
14061}
14062
14063// Guess at what the return type for an unresolvable overload should be.
14064static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14065 OverloadCandidateSet::iterator *Best) {
14066 std::optional<QualType> Result;
14067 // Adjust Type after seeing a candidate.
14068 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14069 if (!Candidate.Function)
14070 return;
14071 if (Candidate.Function->isInvalidDecl())
14072 return;
14073 QualType T = Candidate.Function->getReturnType();
14074 if (T.isNull())
14075 return;
14076 if (!Result)
14077 Result = T;
14078 else if (Result != T)
14079 Result = QualType();
14080 };
14081
14082 // Look for an unambiguous type from a progressively larger subset.
14083 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14084 //
14085 // First, consider only the best candidate.
14086 if (Best && *Best != CS.end())
14087 ConsiderCandidate(**Best);
14088 // Next, consider only viable candidates.
14089 if (!Result)
14090 for (const auto &C : CS)
14091 if (C.Viable)
14092 ConsiderCandidate(C);
14093 // Finally, consider all candidates.
14094 if (!Result)
14095 for (const auto &C : CS)
14096 ConsiderCandidate(C);
14097
14098 if (!Result)
14099 return QualType();
14100 auto Value = *Result;
14101 if (Value.isNull() || Value->isUndeducedType())
14102 return QualType();
14103 return Value;
14104}
14105
14106/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14107/// the completed call expression. If overload resolution fails, emits
14108/// diagnostics and returns ExprError()
14109static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14110 UnresolvedLookupExpr *ULE,
14111 SourceLocation LParenLoc,
14112 MultiExprArg Args,
14113 SourceLocation RParenLoc,
14114 Expr *ExecConfig,
14115 OverloadCandidateSet *CandidateSet,
14116 OverloadCandidateSet::iterator *Best,
14117 OverloadingResult OverloadResult,
14118 bool AllowTypoCorrection) {
14119 switch (OverloadResult) {
14120 case OR_Success: {
14121 FunctionDecl *FDecl = (*Best)->Function;
14122 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14123 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14124 return ExprError();
14125 ExprResult Res =
14126 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14127 if (Res.isInvalid())
14128 return ExprError();
14129 return SemaRef.BuildResolvedCallExpr(
14130 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14131 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14132 }
14133
14134 case OR_No_Viable_Function: {
14135 // Try to recover by looking for viable functions which the user might
14136 // have meant to call.
14137 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14138 Args, RParenLoc,
14139 EmptyLookup: CandidateSet->empty(),
14140 AllowTypoCorrection);
14141 if (Recovery.isInvalid() || Recovery.isUsable())
14142 return Recovery;
14143
14144 // If the user passes in a function that we can't take the address of, we
14145 // generally end up emitting really bad error messages. Here, we attempt to
14146 // emit better ones.
14147 for (const Expr *Arg : Args) {
14148 if (!Arg->getType()->isFunctionType())
14149 continue;
14150 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14151 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14152 if (FD &&
14153 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14154 Loc: Arg->getExprLoc()))
14155 return ExprError();
14156 }
14157 }
14158
14159 CandidateSet->NoteCandidates(
14160 PartialDiagnosticAt(
14161 Fn->getBeginLoc(),
14162 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14163 << ULE->getName() << Fn->getSourceRange()),
14164 SemaRef, OCD_AllCandidates, Args);
14165 break;
14166 }
14167
14168 case OR_Ambiguous:
14169 CandidateSet->NoteCandidates(
14170 PartialDiagnosticAt(Fn->getBeginLoc(),
14171 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14172 << ULE->getName() << Fn->getSourceRange()),
14173 SemaRef, OCD_AmbiguousCandidates, Args);
14174 break;
14175
14176 case OR_Deleted: {
14177 FunctionDecl *FDecl = (*Best)->Function;
14178 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14179 Range: Fn->getSourceRange(), Name: ULE->getName(),
14180 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14181
14182 // We emitted an error for the unavailable/deleted function call but keep
14183 // the call in the AST.
14184 ExprResult Res =
14185 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14186 if (Res.isInvalid())
14187 return ExprError();
14188 return SemaRef.BuildResolvedCallExpr(
14189 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14190 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14191 }
14192 }
14193
14194 // Overload resolution failed, try to recover.
14195 SmallVector<Expr *, 8> SubExprs = {Fn};
14196 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14197 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14198 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14199}
14200
14201static void markUnaddressableCandidatesUnviable(Sema &S,
14202 OverloadCandidateSet &CS) {
14203 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14204 if (I->Viable &&
14205 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14206 I->Viable = false;
14207 I->FailureKind = ovl_fail_addr_not_available;
14208 }
14209 }
14210}
14211
14212/// BuildOverloadedCallExpr - Given the call expression that calls Fn
14213/// (which eventually refers to the declaration Func) and the call
14214/// arguments Args/NumArgs, attempt to resolve the function call down
14215/// to a specific function. If overload resolution succeeds, returns
14216/// the call expression produced by overload resolution.
14217/// Otherwise, emits diagnostics and returns ExprError.
14218ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14219 UnresolvedLookupExpr *ULE,
14220 SourceLocation LParenLoc,
14221 MultiExprArg Args,
14222 SourceLocation RParenLoc,
14223 Expr *ExecConfig,
14224 bool AllowTypoCorrection,
14225 bool CalleesAddressIsTaken) {
14226 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14227 OverloadCandidateSet::CSK_Normal);
14228 ExprResult result;
14229
14230 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
14231 Result: &result))
14232 return result;
14233
14234 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14235 // functions that aren't addressible are considered unviable.
14236 if (CalleesAddressIsTaken)
14237 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
14238
14239 OverloadCandidateSet::iterator Best;
14240 OverloadingResult OverloadResult =
14241 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
14242
14243 // Model the case with a call to a templated function whose definition
14244 // encloses the call and whose return type contains a placeholder type as if
14245 // the UnresolvedLookupExpr was type-dependent.
14246 if (OverloadResult == OR_Success) {
14247 const FunctionDecl *FDecl = Best->Function;
14248 if (FDecl && FDecl->isTemplateInstantiation() &&
14249 FDecl->getReturnType()->isUndeducedType()) {
14250 if (const auto *TP =
14251 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14252 TP && TP->willHaveBody()) {
14253 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
14254 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
14255 }
14256 }
14257 }
14258
14259 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14260 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
14261 OverloadResult, AllowTypoCorrection);
14262}
14263
14264ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14265 NestedNameSpecifierLoc NNSLoc,
14266 DeclarationNameInfo DNI,
14267 const UnresolvedSetImpl &Fns,
14268 bool PerformADL) {
14269 return UnresolvedLookupExpr::Create(Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI,
14270 RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
14271 /*KnownDependent=*/false);
14272}
14273
14274ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14275 CXXConversionDecl *Method,
14276 bool HadMultipleCandidates) {
14277 // Convert the expression to match the conversion function's implicit object
14278 // parameter.
14279 ExprResult Exp;
14280 if (Method->isExplicitObjectMemberFunction())
14281 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14282 else
14283 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14284 FoundDecl, Method);
14285 if (Exp.isInvalid())
14286 return true;
14287
14288 if (Method->getParent()->isLambda() &&
14289 Method->getConversionType()->isBlockPointerType()) {
14290 // This is a lambda conversion to block pointer; check if the argument
14291 // was a LambdaExpr.
14292 Expr *SubE = E;
14293 auto *CE = dyn_cast<CastExpr>(Val: SubE);
14294 if (CE && CE->getCastKind() == CK_NoOp)
14295 SubE = CE->getSubExpr();
14296 SubE = SubE->IgnoreParens();
14297 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
14298 SubE = BE->getSubExpr();
14299 if (isa<LambdaExpr>(Val: SubE)) {
14300 // For the conversion to block pointer on a lambda expression, we
14301 // construct a special BlockLiteral instead; this doesn't really make
14302 // a difference in ARC, but outside of ARC the resulting block literal
14303 // follows the normal lifetime rules for block literals instead of being
14304 // autoreleased.
14305 PushExpressionEvaluationContext(
14306 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
14307 ExprResult BlockExp = BuildBlockForLambdaConversion(
14308 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
14309 PopExpressionEvaluationContext();
14310
14311 // FIXME: This note should be produced by a CodeSynthesisContext.
14312 if (BlockExp.isInvalid())
14313 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14314 return BlockExp;
14315 }
14316 }
14317 CallExpr *CE;
14318 QualType ResultType = Method->getReturnType();
14319 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
14320 ResultType = ResultType.getNonLValueExprType(Context);
14321 if (Method->isExplicitObjectMemberFunction()) {
14322 ExprResult FnExpr =
14323 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14324 HadMultipleCandidates, E->getBeginLoc());
14325 if (FnExpr.isInvalid())
14326 return ExprError();
14327 Expr *ObjectParam = Exp.get();
14328 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
14329 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
14330 FPFeatures: CurFPFeatureOverrides());
14331 } else {
14332 MemberExpr *ME =
14333 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14334 NestedNameSpecifierLoc(), SourceLocation(), Method,
14335 DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
14336 HadMultipleCandidates, DeclarationNameInfo(),
14337 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14338
14339 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
14340 RP: Exp.get()->getEndLoc(),
14341 FPFeatures: CurFPFeatureOverrides());
14342 }
14343
14344 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
14345 Proto: Method->getType()->castAs<FunctionProtoType>()))
14346 return ExprError();
14347
14348 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14349}
14350
14351/// Create a unary operation that may resolve to an overloaded
14352/// operator.
14353///
14354/// \param OpLoc The location of the operator itself (e.g., '*').
14355///
14356/// \param Opc The UnaryOperatorKind that describes this operator.
14357///
14358/// \param Fns The set of non-member functions that will be
14359/// considered by overload resolution. The caller needs to build this
14360/// set based on the context using, e.g.,
14361/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14362/// set should not contain any member functions; those will be added
14363/// by CreateOverloadedUnaryOp().
14364///
14365/// \param Input The input argument.
14366ExprResult
14367Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14368 const UnresolvedSetImpl &Fns,
14369 Expr *Input, bool PerformADL) {
14370 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14371 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14372 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14373 // TODO: provide better source location info.
14374 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14375
14376 if (checkPlaceholderForOverload(S&: *this, E&: Input))
14377 return ExprError();
14378
14379 Expr *Args[2] = { Input, nullptr };
14380 unsigned NumArgs = 1;
14381
14382 // For post-increment and post-decrement, add the implicit '0' as
14383 // the second argument, so that we know this is a post-increment or
14384 // post-decrement.
14385 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14386 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14387 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14388 SourceLocation());
14389 NumArgs = 2;
14390 }
14391
14392 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14393
14394 if (Input->isTypeDependent()) {
14395 ExprValueKind VK = ExprValueKind::VK_PRValue;
14396 // [C++26][expr.unary.op][expr.pre.incr]
14397 // The * operator yields an lvalue of type
14398 // The pre/post increment operators yied an lvalue.
14399 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14400 VK = VK_LValue;
14401
14402 if (Fns.empty())
14403 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
14404 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
14405 FPFeatures: CurFPFeatureOverrides());
14406
14407 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14408 ExprResult Fn = CreateUnresolvedLookupExpr(
14409 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
14410 if (Fn.isInvalid())
14411 return ExprError();
14412 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
14413 Ty: Context.DependentTy, VK, OperatorLoc: OpLoc,
14414 FPFeatures: CurFPFeatureOverrides());
14415 }
14416
14417 // Build an empty overload set.
14418 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14419
14420 // Add the candidates from the given function set.
14421 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
14422
14423 // Add operator candidates that are member functions.
14424 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
14425
14426 // Add candidates from ADL.
14427 if (PerformADL) {
14428 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
14429 /*ExplicitTemplateArgs*/nullptr,
14430 CandidateSet);
14431 }
14432
14433 // Add builtin operator candidates.
14434 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
14435
14436 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14437
14438 // Perform overload resolution.
14439 OverloadCandidateSet::iterator Best;
14440 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
14441 case OR_Success: {
14442 // We found a built-in operator or an overloaded operator.
14443 FunctionDecl *FnDecl = Best->Function;
14444
14445 if (FnDecl) {
14446 Expr *Base = nullptr;
14447 // We matched an overloaded operator. Build a call to that
14448 // operator.
14449
14450 // Convert the arguments.
14451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
14452 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
14453
14454 ExprResult InputInit;
14455 if (Method->isExplicitObjectMemberFunction())
14456 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14457 else
14458 InputInit = PerformImplicitObjectArgumentInitialization(
14459 From: Input, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
14460 if (InputInit.isInvalid())
14461 return ExprError();
14462 Base = Input = InputInit.get();
14463 } else {
14464 // Convert the arguments.
14465 ExprResult InputInit
14466 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
14467 Context,
14468 Parm: FnDecl->getParamDecl(i: 0)),
14469 EqualLoc: SourceLocation(),
14470 Init: Input);
14471 if (InputInit.isInvalid())
14472 return ExprError();
14473 Input = InputInit.get();
14474 }
14475
14476 // Build the actual expression node.
14477 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
14478 Base, HadMultipleCandidates,
14479 Loc: OpLoc);
14480 if (FnExpr.isInvalid())
14481 return ExprError();
14482
14483 // Determine the result type.
14484 QualType ResultTy = FnDecl->getReturnType();
14485 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
14486 ResultTy = ResultTy.getNonLValueExprType(Context);
14487
14488 Args[0] = Input;
14489 CallExpr *TheCall = CXXOperatorCallExpr::Create(
14490 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
14491 FPFeatures: CurFPFeatureOverrides(), UsesADL: Best->IsADLCandidate);
14492
14493 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
14494 return ExprError();
14495
14496 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
14497 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
14498 return ExprError();
14499 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), Decl: FnDecl);
14500 } else {
14501 // We matched a built-in operator. Convert the arguments, then
14502 // break out so that we will build the appropriate built-in
14503 // operator node.
14504 ExprResult InputRes = PerformImplicitConversion(
14505 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14506 CheckedConversionKind::ForBuiltinOverloadedOp);
14507 if (InputRes.isInvalid())
14508 return ExprError();
14509 Input = InputRes.get();
14510 break;
14511 }
14512 }
14513
14514 case OR_No_Viable_Function:
14515 // This is an erroneous use of an operator which can be overloaded by
14516 // a non-member function. Check for non-member operators which were
14517 // defined too late to be candidates.
14518 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
14519 // FIXME: Recover by calling the found function.
14520 return ExprError();
14521
14522 // No viable function; fall through to handling this as a
14523 // built-in operator, which will produce an error message for us.
14524 break;
14525
14526 case OR_Ambiguous:
14527 CandidateSet.NoteCandidates(
14528 PartialDiagnosticAt(OpLoc,
14529 PDiag(diag::err_ovl_ambiguous_oper_unary)
14530 << UnaryOperator::getOpcodeStr(Opc)
14531 << Input->getType() << Input->getSourceRange()),
14532 *this, OCD_AmbiguousCandidates, ArgsArray,
14533 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14534 return ExprError();
14535
14536 case OR_Deleted: {
14537 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14538 // object whose method was called. Later in NoteCandidates size of ArgsArray
14539 // is passed further and it eventually ends up compared to number of
14540 // function candidate parameters which never includes the object parameter,
14541 // so slice ArgsArray to make sure apples are compared to apples.
14542 StringLiteral *Msg = Best->Function->getDeletedMessage();
14543 CandidateSet.NoteCandidates(
14544 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14545 << UnaryOperator::getOpcodeStr(Opc)
14546 << (Msg != nullptr)
14547 << (Msg ? Msg->getString() : StringRef())
14548 << Input->getSourceRange()),
14549 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14550 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14551 return ExprError();
14552 }
14553 }
14554
14555 // Either we found no viable overloaded operator or we matched a
14556 // built-in operator. In either case, fall through to trying to
14557 // build a built-in operation.
14558 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
14559}
14560
14561/// Perform lookup for an overloaded binary operator.
14562void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
14563 OverloadedOperatorKind Op,
14564 const UnresolvedSetImpl &Fns,
14565 ArrayRef<Expr *> Args, bool PerformADL) {
14566 SourceLocation OpLoc = CandidateSet.getLocation();
14567
14568 OverloadedOperatorKind ExtraOp =
14569 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
14570 ? getRewrittenOverloadedOperator(Kind: Op)
14571 : OO_None;
14572
14573 // Add the candidates from the given function set. This also adds the
14574 // rewritten candidates using these functions if necessary.
14575 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14576
14577 // Add operator candidates that are member functions.
14578 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14579 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14580 AddMemberOperatorCandidates(Op, OpLoc, Args: {Args[1], Args[0]}, CandidateSet,
14581 PO: OverloadCandidateParamOrder::Reversed);
14582
14583 // In C++20, also add any rewritten member candidates.
14584 if (ExtraOp) {
14585 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
14586 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
14587 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: {Args[1], Args[0]},
14588 CandidateSet,
14589 PO: OverloadCandidateParamOrder::Reversed);
14590 }
14591
14592 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14593 // performed for an assignment operator (nor for operator[] nor operator->,
14594 // which don't get here).
14595 if (Op != OO_Equal && PerformADL) {
14596 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14597 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
14598 /*ExplicitTemplateArgs*/ nullptr,
14599 CandidateSet);
14600 if (ExtraOp) {
14601 DeclarationName ExtraOpName =
14602 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
14603 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
14604 /*ExplicitTemplateArgs*/ nullptr,
14605 CandidateSet);
14606 }
14607 }
14608
14609 // Add builtin operator candidates.
14610 //
14611 // FIXME: We don't add any rewritten candidates here. This is strictly
14612 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14613 // resulting in our selecting a rewritten builtin candidate. For example:
14614 //
14615 // enum class E { e };
14616 // bool operator!=(E, E) requires false;
14617 // bool k = E::e != E::e;
14618 //
14619 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14620 // it seems unreasonable to consider rewritten builtin candidates. A core
14621 // issue has been filed proposing to removed this requirement.
14622 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14623}
14624
14625/// Create a binary operation that may resolve to an overloaded
14626/// operator.
14627///
14628/// \param OpLoc The location of the operator itself (e.g., '+').
14629///
14630/// \param Opc The BinaryOperatorKind that describes this operator.
14631///
14632/// \param Fns The set of non-member functions that will be
14633/// considered by overload resolution. The caller needs to build this
14634/// set based on the context using, e.g.,
14635/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14636/// set should not contain any member functions; those will be added
14637/// by CreateOverloadedBinOp().
14638///
14639/// \param LHS Left-hand argument.
14640/// \param RHS Right-hand argument.
14641/// \param PerformADL Whether to consider operator candidates found by ADL.
14642/// \param AllowRewrittenCandidates Whether to consider candidates found by
14643/// C++20 operator rewrites.
14644/// \param DefaultedFn If we are synthesizing a defaulted operator function,
14645/// the function in question. Such a function is never a candidate in
14646/// our overload resolution. This also enables synthesizing a three-way
14647/// comparison from < and == as described in C++20 [class.spaceship]p1.
14648ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
14649 BinaryOperatorKind Opc,
14650 const UnresolvedSetImpl &Fns, Expr *LHS,
14651 Expr *RHS, bool PerformADL,
14652 bool AllowRewrittenCandidates,
14653 FunctionDecl *DefaultedFn) {
14654 Expr *Args[2] = { LHS, RHS };
14655 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14656
14657 if (!getLangOpts().CPlusPlus20)
14658 AllowRewrittenCandidates = false;
14659
14660 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
14661
14662 // If either side is type-dependent, create an appropriate dependent
14663 // expression.
14664 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14665 if (Fns.empty()) {
14666 // If there are no functions to store, just build a dependent
14667 // BinaryOperator or CompoundAssignment.
14668 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14669 return CompoundAssignOperator::Create(
14670 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
14671 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
14672 CompResultType: Context.DependentTy);
14673 return BinaryOperator::Create(
14674 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
14675 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
14676 }
14677
14678 // FIXME: save results of ADL from here?
14679 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14680 // TODO: provide better source location info in DNLoc component.
14681 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14682 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14683 ExprResult Fn = CreateUnresolvedLookupExpr(
14684 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
14685 if (Fn.isInvalid())
14686 return ExprError();
14687 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
14688 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
14689 FPFeatures: CurFPFeatureOverrides());
14690 }
14691
14692 // If this is the .* operator, which is not overloadable, just
14693 // create a built-in binary operator.
14694 if (Opc == BO_PtrMemD) {
14695 auto CheckPlaceholder = [&](Expr *&Arg) {
14696 ExprResult Res = CheckPlaceholderExpr(E: Arg);
14697 if (Res.isUsable())
14698 Arg = Res.get();
14699 return !Res.isUsable();
14700 };
14701
14702 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14703 // expression that contains placeholders (in either the LHS or RHS).
14704 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14705 return ExprError();
14706 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
14707 }
14708
14709 // Always do placeholder-like conversions on the RHS.
14710 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
14711 return ExprError();
14712
14713 // Do placeholder-like conversion on the LHS; note that we should
14714 // not get here with a PseudoObject LHS.
14715 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14716 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
14717 return ExprError();
14718
14719 // If this is the assignment operator, we only perform overload resolution
14720 // if the left-hand side is a class or enumeration type. This is actually
14721 // a hack. The standard requires that we do overload resolution between the
14722 // various built-in candidates, but as DR507 points out, this can lead to
14723 // problems. So we do it this way, which pretty much follows what GCC does.
14724 // Note that we go the traditional code path for compound assignment forms.
14725 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14726 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
14727
14728 // Build the overload set.
14729 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
14730 OverloadCandidateSet::OperatorRewriteInfo(
14731 Op, OpLoc, AllowRewrittenCandidates));
14732 if (DefaultedFn)
14733 CandidateSet.exclude(DefaultedFn);
14734 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14735
14736 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14737
14738 // Perform overload resolution.
14739 OverloadCandidateSet::iterator Best;
14740 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
14741 case OR_Success: {
14742 // We found a built-in operator or an overloaded operator.
14743 FunctionDecl *FnDecl = Best->Function;
14744
14745 bool IsReversed = Best->isReversed();
14746 if (IsReversed)
14747 std::swap(a&: Args[0], b&: Args[1]);
14748
14749 if (FnDecl) {
14750
14751 if (FnDecl->isInvalidDecl())
14752 return ExprError();
14753
14754 Expr *Base = nullptr;
14755 // We matched an overloaded operator. Build a call to that
14756 // operator.
14757
14758 OverloadedOperatorKind ChosenOp =
14759 FnDecl->getDeclName().getCXXOverloadedOperator();
14760
14761 // C++2a [over.match.oper]p9:
14762 // If a rewritten operator== candidate is selected by overload
14763 // resolution for an operator@, its return type shall be cv bool
14764 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14765 !FnDecl->getReturnType()->isBooleanType()) {
14766 bool IsExtension =
14767 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14768 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14769 : diag::err_ovl_rewrite_equalequal_not_bool)
14770 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14771 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14772 Diag(FnDecl->getLocation(), diag::note_declared_at);
14773 if (!IsExtension)
14774 return ExprError();
14775 }
14776
14777 if (AllowRewrittenCandidates && !IsReversed &&
14778 CandidateSet.getRewriteInfo().isReversible()) {
14779 // We could have reversed this operator, but didn't. Check if some
14780 // reversed form was a viable candidate, and if so, if it had a
14781 // better conversion for either parameter. If so, this call is
14782 // formally ambiguous, and allowing it is an extension.
14783 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14784 for (OverloadCandidate &Cand : CandidateSet) {
14785 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14786 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
14787 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14788 if (CompareImplicitConversionSequences(
14789 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
14790 ICS2: Best->Conversions[ArgIdx]) ==
14791 ImplicitConversionSequence::Better) {
14792 AmbiguousWith.push_back(Elt: Cand.Function);
14793 break;
14794 }
14795 }
14796 }
14797 }
14798
14799 if (!AmbiguousWith.empty()) {
14800 bool AmbiguousWithSelf =
14801 AmbiguousWith.size() == 1 &&
14802 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14803 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14804 << BinaryOperator::getOpcodeStr(Opc)
14805 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14806 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14807 if (AmbiguousWithSelf) {
14808 Diag(FnDecl->getLocation(),
14809 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14810 // Mark member== const or provide matching != to disallow reversed
14811 // args. Eg.
14812 // struct S { bool operator==(const S&); };
14813 // S()==S();
14814 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14815 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14816 !MD->isConst() &&
14817 !MD->hasCXXExplicitFunctionObjectParameter() &&
14818 Context.hasSameUnqualifiedType(
14819 MD->getFunctionObjectParameterType(),
14820 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14821 Context.hasSameUnqualifiedType(
14822 MD->getFunctionObjectParameterType(),
14823 Args[0]->getType()) &&
14824 Context.hasSameUnqualifiedType(
14825 MD->getFunctionObjectParameterType(),
14826 Args[1]->getType()))
14827 Diag(FnDecl->getLocation(),
14828 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14829 } else {
14830 Diag(FnDecl->getLocation(),
14831 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14832 for (auto *F : AmbiguousWith)
14833 Diag(F->getLocation(),
14834 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14835 }
14836 }
14837 }
14838
14839 // Check for nonnull = nullable.
14840 // This won't be caught in the arg's initialization: the parameter to
14841 // the assignment operator is not marked nonnull.
14842 if (Op == OO_Equal)
14843 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
14844 SrcType: Args[1]->getType(), Loc: OpLoc);
14845
14846 // Convert the arguments.
14847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
14848 // Best->Access is only meaningful for class members.
14849 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
14850
14851 ExprResult Arg0, Arg1;
14852 unsigned ParamIdx = 0;
14853 if (Method->isExplicitObjectMemberFunction()) {
14854 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
14855 ParamIdx = 1;
14856 } else {
14857 Arg0 = PerformImplicitObjectArgumentInitialization(
14858 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
14859 }
14860 Arg1 = PerformCopyInitialization(
14861 Entity: InitializedEntity::InitializeParameter(
14862 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
14863 EqualLoc: SourceLocation(), Init: Args[1]);
14864 if (Arg0.isInvalid() || Arg1.isInvalid())
14865 return ExprError();
14866
14867 Base = Args[0] = Arg0.getAs<Expr>();
14868 Args[1] = RHS = Arg1.getAs<Expr>();
14869 } else {
14870 // Convert the arguments.
14871 ExprResult Arg0 = PerformCopyInitialization(
14872 Entity: InitializedEntity::InitializeParameter(Context,
14873 Parm: FnDecl->getParamDecl(i: 0)),
14874 EqualLoc: SourceLocation(), Init: Args[0]);
14875 if (Arg0.isInvalid())
14876 return ExprError();
14877
14878 ExprResult Arg1 =
14879 PerformCopyInitialization(
14880 Entity: InitializedEntity::InitializeParameter(Context,
14881 Parm: FnDecl->getParamDecl(i: 1)),
14882 EqualLoc: SourceLocation(), Init: Args[1]);
14883 if (Arg1.isInvalid())
14884 return ExprError();
14885 Args[0] = LHS = Arg0.getAs<Expr>();
14886 Args[1] = RHS = Arg1.getAs<Expr>();
14887 }
14888
14889 // Build the actual expression node.
14890 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
14891 FoundDecl: Best->FoundDecl, Base,
14892 HadMultipleCandidates, Loc: OpLoc);
14893 if (FnExpr.isInvalid())
14894 return ExprError();
14895
14896 // Determine the result type.
14897 QualType ResultTy = FnDecl->getReturnType();
14898 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
14899 ResultTy = ResultTy.getNonLValueExprType(Context);
14900
14901 CallExpr *TheCall;
14902 ArrayRef<const Expr *> ArgsArray(Args, 2);
14903 const Expr *ImplicitThis = nullptr;
14904
14905 // We always create a CXXOperatorCallExpr, even for explicit object
14906 // members; CodeGen should take care not to emit the this pointer.
14907 TheCall = CXXOperatorCallExpr::Create(
14908 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
14909 FPFeatures: CurFPFeatureOverrides(), UsesADL: Best->IsADLCandidate);
14910
14911 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
14912 Method && Method->isImplicitObjectMemberFunction()) {
14913 // Cut off the implicit 'this'.
14914 ImplicitThis = ArgsArray[0];
14915 ArgsArray = ArgsArray.slice(N: 1);
14916 }
14917
14918 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
14919 FD: FnDecl))
14920 return ExprError();
14921
14922 // Check for a self move.
14923 if (Op == OO_Equal)
14924 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
14925
14926 if (ImplicitThis) {
14927 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
14928 QualType ThisTypeFromDecl = Context.getPointerType(
14929 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
14930
14931 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14932 ThisTypeFromDecl);
14933 }
14934
14935 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
14936 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
14937 CallType: VariadicDoesNotApply);
14938
14939 ExprResult R = MaybeBindToTemporary(TheCall);
14940 if (R.isInvalid())
14941 return ExprError();
14942
14943 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
14944 if (R.isInvalid())
14945 return ExprError();
14946
14947 // For a rewritten candidate, we've already reversed the arguments
14948 // if needed. Perform the rest of the rewrite now.
14949 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14950 (Op == OO_Spaceship && IsReversed)) {
14951 if (Op == OO_ExclaimEqual) {
14952 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14953 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
14954 } else {
14955 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14956 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14957 Expr *ZeroLiteral =
14958 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14959
14960 Sema::CodeSynthesisContext Ctx;
14961 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14962 Ctx.Entity = FnDecl;
14963 pushCodeSynthesisContext(Ctx);
14964
14965 R = CreateOverloadedBinOp(
14966 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
14967 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14968 /*AllowRewrittenCandidates=*/false);
14969
14970 popCodeSynthesisContext();
14971 }
14972 if (R.isInvalid())
14973 return ExprError();
14974 } else {
14975 assert(ChosenOp == Op && "unexpected operator name");
14976 }
14977
14978 // Make a note in the AST if we did any rewriting.
14979 if (Best->RewriteKind != CRK_None)
14980 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14981
14982 return R;
14983 } else {
14984 // We matched a built-in operator. Convert the arguments, then
14985 // break out so that we will build the appropriate built-in
14986 // operator node.
14987 ExprResult ArgsRes0 = PerformImplicitConversion(
14988 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14989 AA_Passing, CheckedConversionKind::ForBuiltinOverloadedOp);
14990 if (ArgsRes0.isInvalid())
14991 return ExprError();
14992 Args[0] = ArgsRes0.get();
14993
14994 ExprResult ArgsRes1 = PerformImplicitConversion(
14995 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14996 AA_Passing, CheckedConversionKind::ForBuiltinOverloadedOp);
14997 if (ArgsRes1.isInvalid())
14998 return ExprError();
14999 Args[1] = ArgsRes1.get();
15000 break;
15001 }
15002 }
15003
15004 case OR_No_Viable_Function: {
15005 // C++ [over.match.oper]p9:
15006 // If the operator is the operator , [...] and there are no
15007 // viable functions, then the operator is assumed to be the
15008 // built-in operator and interpreted according to clause 5.
15009 if (Opc == BO_Comma)
15010 break;
15011
15012 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15013 // compare result using '==' and '<'.
15014 if (DefaultedFn && Opc == BO_Cmp) {
15015 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15016 RHS: Args[1], DefaultedFn);
15017 if (E.isInvalid() || E.isUsable())
15018 return E;
15019 }
15020
15021 // For class as left operand for assignment or compound assignment
15022 // operator do not fall through to handling in built-in, but report that
15023 // no overloaded assignment operator found
15024 ExprResult Result = ExprError();
15025 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15026 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15027 Args, OpLoc);
15028 DeferDiagsRAII DDR(*this,
15029 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15030 if (Args[0]->getType()->isRecordType() &&
15031 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15032 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15033 << BinaryOperator::getOpcodeStr(Opc)
15034 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15035 if (Args[0]->getType()->isIncompleteType()) {
15036 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15037 << Args[0]->getType()
15038 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15039 }
15040 } else {
15041 // This is an erroneous use of an operator which can be overloaded by
15042 // a non-member function. Check for non-member operators which were
15043 // defined too late to be candidates.
15044 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15045 // FIXME: Recover by calling the found function.
15046 return ExprError();
15047
15048 // No viable function; try to create a built-in operation, which will
15049 // produce an error. Then, show the non-viable candidates.
15050 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15051 }
15052 assert(Result.isInvalid() &&
15053 "C++ binary operator overloading is missing candidates!");
15054 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15055 return Result;
15056 }
15057
15058 case OR_Ambiguous:
15059 CandidateSet.NoteCandidates(
15060 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15061 << BinaryOperator::getOpcodeStr(Opc)
15062 << Args[0]->getType()
15063 << Args[1]->getType()
15064 << Args[0]->getSourceRange()
15065 << Args[1]->getSourceRange()),
15066 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15067 OpLoc);
15068 return ExprError();
15069
15070 case OR_Deleted: {
15071 if (isImplicitlyDeleted(FD: Best->Function)) {
15072 FunctionDecl *DeletedFD = Best->Function;
15073 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15074 if (DFK.isSpecialMember()) {
15075 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15076 << Args[0]->getType()
15077 << llvm::to_underlying(DFK.asSpecialMember());
15078 } else {
15079 assert(DFK.isComparison());
15080 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15081 << Args[0]->getType() << DeletedFD;
15082 }
15083
15084 // The user probably meant to call this special member. Just
15085 // explain why it's deleted.
15086 NoteDeletedFunction(FD: DeletedFD);
15087 return ExprError();
15088 }
15089
15090 StringLiteral *Msg = Best->Function->getDeletedMessage();
15091 CandidateSet.NoteCandidates(
15092 PartialDiagnosticAt(
15093 OpLoc,
15094 PDiag(diag::err_ovl_deleted_oper)
15095 << getOperatorSpelling(Best->Function->getDeclName()
15096 .getCXXOverloadedOperator())
15097 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15098 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15099 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15100 OpLoc);
15101 return ExprError();
15102 }
15103 }
15104
15105 // We matched a built-in operator; build it.
15106 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15107}
15108
15109ExprResult Sema::BuildSynthesizedThreeWayComparison(
15110 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15111 FunctionDecl *DefaultedFn) {
15112 const ComparisonCategoryInfo *Info =
15113 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15114 // If we're not producing a known comparison category type, we can't
15115 // synthesize a three-way comparison. Let the caller diagnose this.
15116 if (!Info)
15117 return ExprResult((Expr*)nullptr);
15118
15119 // If we ever want to perform this synthesis more generally, we will need to
15120 // apply the temporary materialization conversion to the operands.
15121 assert(LHS->isGLValue() && RHS->isGLValue() &&
15122 "cannot use prvalue expressions more than once");
15123 Expr *OrigLHS = LHS;
15124 Expr *OrigRHS = RHS;
15125
15126 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15127 // each of them multiple times below.
15128 LHS = new (Context)
15129 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15130 LHS->getObjectKind(), LHS);
15131 RHS = new (Context)
15132 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15133 RHS->getObjectKind(), RHS);
15134
15135 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15136 DefaultedFn);
15137 if (Eq.isInvalid())
15138 return ExprError();
15139
15140 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15141 AllowRewrittenCandidates: true, DefaultedFn);
15142 if (Less.isInvalid())
15143 return ExprError();
15144
15145 ExprResult Greater;
15146 if (Info->isPartial()) {
15147 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15148 DefaultedFn);
15149 if (Greater.isInvalid())
15150 return ExprError();
15151 }
15152
15153 // Form the list of comparisons we're going to perform.
15154 struct Comparison {
15155 ExprResult Cmp;
15156 ComparisonCategoryResult Result;
15157 } Comparisons[4] =
15158 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15159 : ComparisonCategoryResult::Equivalent},
15160 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15161 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15162 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15163 };
15164
15165 int I = Info->isPartial() ? 3 : 2;
15166
15167 // Combine the comparisons with suitable conditional expressions.
15168 ExprResult Result;
15169 for (; I >= 0; --I) {
15170 // Build a reference to the comparison category constant.
15171 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15172 // FIXME: Missing a constant for a comparison category. Diagnose this?
15173 if (!VI)
15174 return ExprResult((Expr*)nullptr);
15175 ExprResult ThisResult =
15176 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15177 if (ThisResult.isInvalid())
15178 return ExprError();
15179
15180 // Build a conditional unless this is the final case.
15181 if (Result.get()) {
15182 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15183 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15184 if (Result.isInvalid())
15185 return ExprError();
15186 } else {
15187 Result = ThisResult;
15188 }
15189 }
15190
15191 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15192 // bind the OpaqueValueExprs before they're (repeatedly) used.
15193 Expr *SyntacticForm = BinaryOperator::Create(
15194 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15195 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15196 FPFeatures: CurFPFeatureOverrides());
15197 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15198 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15199}
15200
15201static bool PrepareArgumentsForCallToObjectOfClassType(
15202 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15203 MultiExprArg Args, SourceLocation LParenLoc) {
15204
15205 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15206 unsigned NumParams = Proto->getNumParams();
15207 unsigned NumArgsSlots =
15208 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
15209 // Build the full argument list for the method call (the implicit object
15210 // parameter is placed at the beginning of the list).
15211 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
15212 bool IsError = false;
15213 // Initialize the implicit object parameter.
15214 // Check the argument types.
15215 for (unsigned i = 0; i != NumParams; i++) {
15216 Expr *Arg;
15217 if (i < Args.size()) {
15218 Arg = Args[i];
15219 ExprResult InputInit =
15220 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15221 S.Context, Method->getParamDecl(i)),
15222 EqualLoc: SourceLocation(), Init: Arg);
15223 IsError |= InputInit.isInvalid();
15224 Arg = InputInit.getAs<Expr>();
15225 } else {
15226 ExprResult DefArg =
15227 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
15228 if (DefArg.isInvalid()) {
15229 IsError = true;
15230 break;
15231 }
15232 Arg = DefArg.getAs<Expr>();
15233 }
15234
15235 MethodArgs.push_back(Elt: Arg);
15236 }
15237 return IsError;
15238}
15239
15240ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15241 SourceLocation RLoc,
15242 Expr *Base,
15243 MultiExprArg ArgExpr) {
15244 SmallVector<Expr *, 2> Args;
15245 Args.push_back(Elt: Base);
15246 for (auto *e : ArgExpr) {
15247 Args.push_back(Elt: e);
15248 }
15249 DeclarationName OpName =
15250 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
15251
15252 SourceRange Range = ArgExpr.empty()
15253 ? SourceRange{}
15254 : SourceRange(ArgExpr.front()->getBeginLoc(),
15255 ArgExpr.back()->getEndLoc());
15256
15257 // If either side is type-dependent, create an appropriate dependent
15258 // expression.
15259 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
15260
15261 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15262 // CHECKME: no 'operator' keyword?
15263 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15264 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15265 ExprResult Fn = CreateUnresolvedLookupExpr(
15266 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
15267 if (Fn.isInvalid())
15268 return ExprError();
15269 // Can't add any actual overloads yet
15270
15271 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
15272 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
15273 FPFeatures: CurFPFeatureOverrides());
15274 }
15275
15276 // Handle placeholders
15277 UnbridgedCastsSet UnbridgedCasts;
15278 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
15279 return ExprError();
15280 }
15281 // Build an empty overload set.
15282 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15283
15284 // Subscript can only be overloaded as a member function.
15285
15286 // Add operator candidates that are member functions.
15287 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15288
15289 // Add builtin operator candidates.
15290 if (Args.size() == 2)
15291 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15292
15293 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15294
15295 // Perform overload resolution.
15296 OverloadCandidateSet::iterator Best;
15297 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
15298 case OR_Success: {
15299 // We found a built-in operator or an overloaded operator.
15300 FunctionDecl *FnDecl = Best->Function;
15301
15302 if (FnDecl) {
15303 // We matched an overloaded operator. Build a call to that
15304 // operator.
15305
15306 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
15307
15308 // Convert the arguments.
15309 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
15310 SmallVector<Expr *, 2> MethodArgs;
15311
15312 // Initialize the object parameter.
15313 if (Method->isExplicitObjectMemberFunction()) {
15314 ExprResult Res =
15315 InitializeExplicitObjectArgument(*this, Args[0], Method);
15316 if (Res.isInvalid())
15317 return ExprError();
15318 Args[0] = Res.get();
15319 ArgExpr = Args;
15320 } else {
15321 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15322 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15323 if (Arg0.isInvalid())
15324 return ExprError();
15325
15326 MethodArgs.push_back(Elt: Arg0.get());
15327 }
15328
15329 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15330 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
15331 if (IsError)
15332 return ExprError();
15333
15334 // Build the actual expression node.
15335 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15336 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15337 ExprResult FnExpr = CreateFunctionRefExpr(
15338 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
15339 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
15340 if (FnExpr.isInvalid())
15341 return ExprError();
15342
15343 // Determine the result type
15344 QualType ResultTy = FnDecl->getReturnType();
15345 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15346 ResultTy = ResultTy.getNonLValueExprType(Context);
15347
15348 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15349 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
15350 FPFeatures: CurFPFeatureOverrides());
15351
15352 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
15353 return ExprError();
15354
15355 if (CheckFunctionCall(FDecl: Method, TheCall,
15356 Proto: Method->getType()->castAs<FunctionProtoType>()))
15357 return ExprError();
15358
15359 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall),
15360 Decl: FnDecl);
15361 } else {
15362 // We matched a built-in operator. Convert the arguments, then
15363 // break out so that we will build the appropriate built-in
15364 // operator node.
15365 ExprResult ArgsRes0 = PerformImplicitConversion(
15366 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15367 AA_Passing, CheckedConversionKind::ForBuiltinOverloadedOp);
15368 if (ArgsRes0.isInvalid())
15369 return ExprError();
15370 Args[0] = ArgsRes0.get();
15371
15372 ExprResult ArgsRes1 = PerformImplicitConversion(
15373 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15374 AA_Passing, CheckedConversionKind::ForBuiltinOverloadedOp);
15375 if (ArgsRes1.isInvalid())
15376 return ExprError();
15377 Args[1] = ArgsRes1.get();
15378
15379 break;
15380 }
15381 }
15382
15383 case OR_No_Viable_Function: {
15384 PartialDiagnostic PD =
15385 CandidateSet.empty()
15386 ? (PDiag(diag::err_ovl_no_oper)
15387 << Args[0]->getType() << /*subscript*/ 0
15388 << Args[0]->getSourceRange() << Range)
15389 : (PDiag(diag::err_ovl_no_viable_subscript)
15390 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15391 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
15392 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
15393 return ExprError();
15394 }
15395
15396 case OR_Ambiguous:
15397 if (Args.size() == 2) {
15398 CandidateSet.NoteCandidates(
15399 PartialDiagnosticAt(
15400 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15401 << "[]" << Args[0]->getType() << Args[1]->getType()
15402 << Args[0]->getSourceRange() << Range),
15403 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15404 } else {
15405 CandidateSet.NoteCandidates(
15406 PartialDiagnosticAt(LLoc,
15407 PDiag(diag::err_ovl_ambiguous_subscript_call)
15408 << Args[0]->getType()
15409 << Args[0]->getSourceRange() << Range),
15410 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15411 }
15412 return ExprError();
15413
15414 case OR_Deleted: {
15415 StringLiteral *Msg = Best->Function->getDeletedMessage();
15416 CandidateSet.NoteCandidates(
15417 PartialDiagnosticAt(LLoc,
15418 PDiag(diag::err_ovl_deleted_oper)
15419 << "[]" << (Msg != nullptr)
15420 << (Msg ? Msg->getString() : StringRef())
15421 << Args[0]->getSourceRange() << Range),
15422 *this, OCD_AllCandidates, Args, "[]", LLoc);
15423 return ExprError();
15424 }
15425 }
15426
15427 // We matched a built-in operator; build it.
15428 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
15429}
15430
15431/// BuildCallToMemberFunction - Build a call to a member
15432/// function. MemExpr is the expression that refers to the member
15433/// function (and includes the object parameter), Args/NumArgs are the
15434/// arguments to the function call (not including the object
15435/// parameter). The caller needs to validate that the member
15436/// expression refers to a non-static member function or an overloaded
15437/// member function.
15438ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
15439 SourceLocation LParenLoc,
15440 MultiExprArg Args,
15441 SourceLocation RParenLoc,
15442 Expr *ExecConfig, bool IsExecConfig,
15443 bool AllowRecovery) {
15444 assert(MemExprE->getType() == Context.BoundMemberTy ||
15445 MemExprE->getType() == Context.OverloadTy);
15446
15447 // Dig out the member expression. This holds both the object
15448 // argument and the member function we're referring to.
15449 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15450
15451 // Determine whether this is a call to a pointer-to-member function.
15452 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
15453 assert(op->getType() == Context.BoundMemberTy);
15454 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15455
15456 QualType fnType =
15457 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15458
15459 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15460 QualType resultType = proto->getCallResultType(Context);
15461 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
15462
15463 // Check that the object type isn't more qualified than the
15464 // member function we're calling.
15465 Qualifiers funcQuals = proto->getMethodQuals();
15466
15467 QualType objectType = op->getLHS()->getType();
15468 if (op->getOpcode() == BO_PtrMemI)
15469 objectType = objectType->castAs<PointerType>()->getPointeeType();
15470 Qualifiers objectQuals = objectType.getQualifiers();
15471
15472 Qualifiers difference = objectQuals - funcQuals;
15473 difference.removeObjCGCAttr();
15474 difference.removeAddressSpace();
15475 if (difference) {
15476 std::string qualsString = difference.getAsString();
15477 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15478 << fnType.getUnqualifiedType()
15479 << qualsString
15480 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15481 }
15482
15483 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
15484 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
15485 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
15486
15487 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
15488 CE: call, FD: nullptr))
15489 return ExprError();
15490
15491 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15492 return ExprError();
15493
15494 if (CheckOtherCall(call, proto))
15495 return ExprError();
15496
15497 return MaybeBindToTemporary(call);
15498 }
15499
15500 // We only try to build a recovery expr at this level if we can preserve
15501 // the return type, otherwise we return ExprError() and let the caller
15502 // recover.
15503 auto BuildRecoveryExpr = [&](QualType Type) {
15504 if (!AllowRecovery)
15505 return ExprError();
15506 std::vector<Expr *> SubExprs = {MemExprE};
15507 llvm::append_range(C&: SubExprs, R&: Args);
15508 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15509 Type);
15510 };
15511 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
15512 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
15513 RParenLoc, FPFeatures: CurFPFeatureOverrides());
15514
15515 UnbridgedCastsSet UnbridgedCasts;
15516 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
15517 return ExprError();
15518
15519 MemberExpr *MemExpr;
15520 CXXMethodDecl *Method = nullptr;
15521 bool HadMultipleCandidates = false;
15522 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
15523 NestedNameSpecifier *Qualifier = nullptr;
15524 if (isa<MemberExpr>(Val: NakedMemExpr)) {
15525 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
15526 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
15527 FoundDecl = MemExpr->getFoundDecl();
15528 Qualifier = MemExpr->getQualifier();
15529 UnbridgedCasts.restore();
15530 } else {
15531 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
15532 Qualifier = UnresExpr->getQualifier();
15533
15534 QualType ObjectType = UnresExpr->getBaseType();
15535 Expr::Classification ObjectClassification
15536 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
15537 : UnresExpr->getBase()->Classify(Ctx&: Context);
15538
15539 // Add overload candidates
15540 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15541 OverloadCandidateSet::CSK_Normal);
15542
15543 // FIXME: avoid copy.
15544 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15545 if (UnresExpr->hasExplicitTemplateArgs()) {
15546 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15547 TemplateArgs = &TemplateArgsBuffer;
15548 }
15549
15550 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
15551 E = UnresExpr->decls_end(); I != E; ++I) {
15552
15553 QualType ExplicitObjectType = ObjectType;
15554
15555 NamedDecl *Func = *I;
15556 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15557 if (isa<UsingShadowDecl>(Val: Func))
15558 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
15559
15560 bool HasExplicitParameter = false;
15561 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
15562 M && M->hasCXXExplicitFunctionObjectParameter())
15563 HasExplicitParameter = true;
15564 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
15565 M &&
15566 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15567 HasExplicitParameter = true;
15568
15569 if (HasExplicitParameter)
15570 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15571
15572 // Microsoft supports direct constructor calls.
15573 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
15574 AddOverloadCandidate(cast<CXXConstructorDecl>(Val: Func), I.getPair(), Args,
15575 CandidateSet,
15576 /*SuppressUserConversions*/ false);
15577 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
15578 // If explicit template arguments were provided, we can't call a
15579 // non-template member function.
15580 if (TemplateArgs)
15581 continue;
15582
15583 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
15584 ObjectClassification, Args, CandidateSet,
15585 /*SuppressUserConversions=*/false);
15586 } else {
15587 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
15588 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
15589 ObjectType: ExplicitObjectType, ObjectClassification,
15590 Args, CandidateSet,
15591 /*SuppressUserConversions=*/false);
15592 }
15593 }
15594
15595 HadMultipleCandidates = (CandidateSet.size() > 1);
15596
15597 DeclarationName DeclName = UnresExpr->getMemberName();
15598
15599 UnbridgedCasts.restore();
15600
15601 OverloadCandidateSet::iterator Best;
15602 bool Succeeded = false;
15603 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
15604 Best)) {
15605 case OR_Success:
15606 Method = cast<CXXMethodDecl>(Val: Best->Function);
15607 FoundDecl = Best->FoundDecl;
15608 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
15609 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
15610 break;
15611 // If FoundDecl is different from Method (such as if one is a template
15612 // and the other a specialization), make sure DiagnoseUseOfDecl is
15613 // called on both.
15614 // FIXME: This would be more comprehensively addressed by modifying
15615 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15616 // being used.
15617 if (Method != FoundDecl.getDecl() &&
15618 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
15619 break;
15620 Succeeded = true;
15621 break;
15622
15623 case OR_No_Viable_Function:
15624 CandidateSet.NoteCandidates(
15625 PartialDiagnosticAt(
15626 UnresExpr->getMemberLoc(),
15627 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15628 << DeclName << MemExprE->getSourceRange()),
15629 *this, OCD_AllCandidates, Args);
15630 break;
15631 case OR_Ambiguous:
15632 CandidateSet.NoteCandidates(
15633 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15634 PDiag(diag::err_ovl_ambiguous_member_call)
15635 << DeclName << MemExprE->getSourceRange()),
15636 *this, OCD_AmbiguousCandidates, Args);
15637 break;
15638 case OR_Deleted:
15639 DiagnoseUseOfDeletedFunction(
15640 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
15641 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
15642 break;
15643 }
15644 // Overload resolution fails, try to recover.
15645 if (!Succeeded)
15646 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
15647
15648 ExprResult Res =
15649 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15650 if (Res.isInvalid())
15651 return ExprError();
15652 MemExprE = Res.get();
15653
15654 // If overload resolution picked a static member
15655 // build a non-member call based on that function.
15656 if (Method->isStatic()) {
15657 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15658 ExecConfig, IsExecConfig);
15659 }
15660
15661 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
15662 }
15663
15664 QualType ResultType = Method->getReturnType();
15665 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15666 ResultType = ResultType.getNonLValueExprType(Context);
15667
15668 assert(Method && "Member call to something that isn't a method?");
15669 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15670
15671 CallExpr *TheCall = nullptr;
15672 llvm::SmallVector<Expr *, 8> NewArgs;
15673 if (Method->isExplicitObjectMemberFunction()) {
15674 PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
15675 NewArgs);
15676 // Build the actual expression node.
15677 ExprResult FnExpr =
15678 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15679 HadMultipleCandidates, MemExpr->getExprLoc());
15680 if (FnExpr.isInvalid())
15681 return ExprError();
15682
15683 TheCall =
15684 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
15685 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
15686 } else {
15687 // Convert the object argument (for a non-static member function call).
15688 // We only need to do this if there was actually an overload; otherwise
15689 // it was done at lookup.
15690 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15691 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
15692 if (ObjectArg.isInvalid())
15693 return ExprError();
15694 MemExpr->setBase(ObjectArg.get());
15695 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
15696 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
15697 MinNumArgs: Proto->getNumParams());
15698 }
15699
15700 // Check for a valid return type.
15701 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
15702 CE: TheCall, FD: Method))
15703 return BuildRecoveryExpr(ResultType);
15704
15705 // Convert the rest of the arguments
15706 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto: Proto, Args,
15707 RParenLoc))
15708 return BuildRecoveryExpr(ResultType);
15709
15710 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15711
15712 if (CheckFunctionCall(FDecl: Method, TheCall, Proto: Proto))
15713 return ExprError();
15714
15715 // In the case the method to call was not selected by the overloading
15716 // resolution process, we still need to handle the enable_if attribute. Do
15717 // that here, so it will not hide previous -- and more relevant -- errors.
15718 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
15719 if (const EnableIfAttr *Attr =
15720 CheckEnableIf(Method, LParenLoc, Args, true)) {
15721 Diag(MemE->getMemberLoc(),
15722 diag::err_ovl_no_viable_member_function_in_call)
15723 << Method << Method->getSourceRange();
15724 Diag(Method->getLocation(),
15725 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15726 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15727 return ExprError();
15728 }
15729 }
15730
15731 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
15732 TheCall->getDirectCallee()->isPureVirtual()) {
15733 const FunctionDecl *MD = TheCall->getDirectCallee();
15734
15735 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
15736 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
15737 Diag(MemExpr->getBeginLoc(),
15738 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15739 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15740 << MD->getParent();
15741
15742 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15743 if (getLangOpts().AppleKext)
15744 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15745 << MD->getParent() << MD->getDeclName();
15746 }
15747 }
15748
15749 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
15750 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15751 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15752 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
15753 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15754 DtorLoc: MemExpr->getMemberLoc());
15755 }
15756
15757 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall),
15758 Decl: TheCall->getDirectCallee());
15759}
15760
15761/// BuildCallToObjectOfClassType - Build a call to an object of class
15762/// type (C++ [over.call.object]), which can end up invoking an
15763/// overloaded function call operator (@c operator()) or performing a
15764/// user-defined conversion on the object argument.
15765ExprResult
15766Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
15767 SourceLocation LParenLoc,
15768 MultiExprArg Args,
15769 SourceLocation RParenLoc) {
15770 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
15771 return ExprError();
15772 ExprResult Object = Obj;
15773
15774 UnbridgedCastsSet UnbridgedCasts;
15775 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
15776 return ExprError();
15777
15778 assert(Object.get()->getType()->isRecordType() &&
15779 "Requires object type argument");
15780
15781 // C++ [over.call.object]p1:
15782 // If the primary-expression E in the function call syntax
15783 // evaluates to a class object of type "cv T", then the set of
15784 // candidate functions includes at least the function call
15785 // operators of T. The function call operators of T are obtained by
15786 // ordinary lookup of the name operator() in the context of
15787 // (E).operator().
15788 OverloadCandidateSet CandidateSet(LParenLoc,
15789 OverloadCandidateSet::CSK_Operator);
15790 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
15791
15792 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15793 diag::err_incomplete_object_call, Object.get()))
15794 return true;
15795
15796 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15797 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15798 LookupQualifiedName(R, Record->getDecl());
15799 R.suppressAccessDiagnostics();
15800
15801 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15802 Oper != OperEnd; ++Oper) {
15803 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
15804 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
15805 /*SuppressUserConversion=*/SuppressUserConversions: false);
15806 }
15807
15808 // When calling a lambda, both the call operator, and
15809 // the conversion operator to function pointer
15810 // are considered. But when constraint checking
15811 // on the call operator fails, it will also fail on the
15812 // conversion operator as the constraints are always the same.
15813 // As the user probably does not intend to perform a surrogate call,
15814 // we filter them out to produce better error diagnostics, ie to avoid
15815 // showing 2 failed overloads instead of one.
15816 bool IgnoreSurrogateFunctions = false;
15817 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15818 const OverloadCandidate &Candidate = *CandidateSet.begin();
15819 if (!Candidate.Viable &&
15820 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15821 IgnoreSurrogateFunctions = true;
15822 }
15823
15824 // C++ [over.call.object]p2:
15825 // In addition, for each (non-explicit in C++0x) conversion function
15826 // declared in T of the form
15827 //
15828 // operator conversion-type-id () cv-qualifier;
15829 //
15830 // where cv-qualifier is the same cv-qualification as, or a
15831 // greater cv-qualification than, cv, and where conversion-type-id
15832 // denotes the type "pointer to function of (P1,...,Pn) returning
15833 // R", or the type "reference to pointer to function of
15834 // (P1,...,Pn) returning R", or the type "reference to function
15835 // of (P1,...,Pn) returning R", a surrogate call function [...]
15836 // is also considered as a candidate function. Similarly,
15837 // surrogate call functions are added to the set of candidate
15838 // functions for each conversion function declared in an
15839 // accessible base class provided the function is not hidden
15840 // within T by another intervening declaration.
15841 const auto &Conversions =
15842 cast<CXXRecordDecl>(Val: Record->getDecl())->getVisibleConversionFunctions();
15843 for (auto I = Conversions.begin(), E = Conversions.end();
15844 !IgnoreSurrogateFunctions && I != E; ++I) {
15845 NamedDecl *D = *I;
15846 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15847 if (isa<UsingShadowDecl>(Val: D))
15848 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
15849
15850 // Skip over templated conversion functions; they aren't
15851 // surrogates.
15852 if (isa<FunctionTemplateDecl>(Val: D))
15853 continue;
15854
15855 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
15856 if (!Conv->isExplicit()) {
15857 // Strip the reference type (if any) and then the pointer type (if
15858 // any) to get down to what might be a function type.
15859 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15860 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15861 ConvType = ConvPtrType->getPointeeType();
15862
15863 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15864 {
15865 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
15866 Object: Object.get(), Args, CandidateSet);
15867 }
15868 }
15869 }
15870
15871 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15872
15873 // Perform overload resolution.
15874 OverloadCandidateSet::iterator Best;
15875 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
15876 Best)) {
15877 case OR_Success:
15878 // Overload resolution succeeded; we'll build the appropriate call
15879 // below.
15880 break;
15881
15882 case OR_No_Viable_Function: {
15883 PartialDiagnostic PD =
15884 CandidateSet.empty()
15885 ? (PDiag(diag::err_ovl_no_oper)
15886 << Object.get()->getType() << /*call*/ 1
15887 << Object.get()->getSourceRange())
15888 : (PDiag(diag::err_ovl_no_viable_object_call)
15889 << Object.get()->getType() << Object.get()->getSourceRange());
15890 CandidateSet.NoteCandidates(
15891 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
15892 OCD: OCD_AllCandidates, Args);
15893 break;
15894 }
15895 case OR_Ambiguous:
15896 if (!R.isAmbiguous())
15897 CandidateSet.NoteCandidates(
15898 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15899 PDiag(diag::err_ovl_ambiguous_object_call)
15900 << Object.get()->getType()
15901 << Object.get()->getSourceRange()),
15902 *this, OCD_AmbiguousCandidates, Args);
15903 break;
15904
15905 case OR_Deleted: {
15906 // FIXME: Is this diagnostic here really necessary? It seems that
15907 // 1. we don't have any tests for this diagnostic, and
15908 // 2. we already issue err_deleted_function_use for this later on anyway.
15909 StringLiteral *Msg = Best->Function->getDeletedMessage();
15910 CandidateSet.NoteCandidates(
15911 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15912 PDiag(diag::err_ovl_deleted_object_call)
15913 << Object.get()->getType() << (Msg != nullptr)
15914 << (Msg ? Msg->getString() : StringRef())
15915 << Object.get()->getSourceRange()),
15916 *this, OCD_AllCandidates, Args);
15917 break;
15918 }
15919 }
15920
15921 if (Best == CandidateSet.end())
15922 return true;
15923
15924 UnbridgedCasts.restore();
15925
15926 if (Best->Function == nullptr) {
15927 // Since there is no function declaration, this is one of the
15928 // surrogate candidates. Dig out the conversion function.
15929 CXXConversionDecl *Conv
15930 = cast<CXXConversionDecl>(
15931 Val: Best->Conversions[0].UserDefined.ConversionFunction);
15932
15933 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
15934 FoundDecl: Best->FoundDecl);
15935 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
15936 return ExprError();
15937 assert(Conv == Best->FoundDecl.getDecl() &&
15938 "Found Decl & conversion-to-functionptr should be same, right?!");
15939 // We selected one of the surrogate functions that converts the
15940 // object parameter to a function pointer. Perform the conversion
15941 // on the object argument, then let BuildCallExpr finish the job.
15942
15943 // Create an implicit member expr to refer to the conversion operator.
15944 // and then call it.
15945 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
15946 Method: Conv, HadMultipleCandidates);
15947 if (Call.isInvalid())
15948 return ExprError();
15949 // Record usage of conversion in an implicit cast.
15950 Call = ImplicitCastExpr::Create(
15951 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
15952 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
15953
15954 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
15955 }
15956
15957 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15958
15959 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15960 // that calls this method, using Object for the implicit object
15961 // parameter and passing along the remaining arguments.
15962 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
15963
15964 // An error diagnostic has already been printed when parsing the declaration.
15965 if (Method->isInvalidDecl())
15966 return ExprError();
15967
15968 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15969 unsigned NumParams = Proto->getNumParams();
15970
15971 DeclarationNameInfo OpLocInfo(
15972 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
15973 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15974 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15975 Obj, HadMultipleCandidates,
15976 OpLocInfo.getLoc(),
15977 OpLocInfo.getInfo());
15978 if (NewFn.isInvalid())
15979 return true;
15980
15981 SmallVector<Expr *, 8> MethodArgs;
15982 MethodArgs.reserve(N: NumParams + 1);
15983
15984 bool IsError = false;
15985
15986 // Initialize the object parameter.
15987 llvm::SmallVector<Expr *, 8> NewArgs;
15988 if (Method->isExplicitObjectMemberFunction()) {
15989 // FIXME: we should do that during the definition of the lambda when we can.
15990 DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15991 PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
15992 } else {
15993 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15994 From: Object.get(), /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15995 if (ObjRes.isInvalid())
15996 IsError = true;
15997 else
15998 Object = ObjRes;
15999 MethodArgs.push_back(Elt: Object.get());
16000 }
16001
16002 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16003 S&: *this, MethodArgs, Method, Args, LParenLoc);
16004
16005 // If this is a variadic call, handle args passed through "...".
16006 if (Proto->isVariadic()) {
16007 // Promote the arguments (C99 6.5.2.2p7).
16008 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16009 ExprResult Arg = DefaultVariadicArgumentPromotion(E: Args[i], CT: VariadicMethod,
16010 FDecl: nullptr);
16011 IsError |= Arg.isInvalid();
16012 MethodArgs.push_back(Elt: Arg.get());
16013 }
16014 }
16015
16016 if (IsError)
16017 return true;
16018
16019 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16020
16021 // Once we've built TheCall, all of the expressions are properly owned.
16022 QualType ResultTy = Method->getReturnType();
16023 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16024 ResultTy = ResultTy.getNonLValueExprType(Context);
16025
16026 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16027 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16028 FPFeatures: CurFPFeatureOverrides());
16029
16030 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16031 return true;
16032
16033 if (CheckFunctionCall(FDecl: Method, TheCall, Proto: Proto))
16034 return true;
16035
16036 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16037}
16038
16039/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
16040/// (if one exists), where @c Base is an expression of class type and
16041/// @c Member is the name of the member we're trying to find.
16042ExprResult
16043Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
16044 bool *NoArrowOperatorFound) {
16045 assert(Base->getType()->isRecordType() &&
16046 "left-hand side must have class type");
16047
16048 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16049 return ExprError();
16050
16051 SourceLocation Loc = Base->getExprLoc();
16052
16053 // C++ [over.ref]p1:
16054 //
16055 // [...] An expression x->m is interpreted as (x.operator->())->m
16056 // for a class object x of type T if T::operator->() exists and if
16057 // the operator is selected as the best match function by the
16058 // overload resolution mechanism (13.3).
16059 DeclarationName OpName =
16060 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16061 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16062
16063 if (RequireCompleteType(Loc, Base->getType(),
16064 diag::err_typecheck_incomplete_tag, Base))
16065 return ExprError();
16066
16067 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16068 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16069 R.suppressAccessDiagnostics();
16070
16071 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16072 Oper != OperEnd; ++Oper) {
16073 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16074 Args: std::nullopt, CandidateSet,
16075 /*SuppressUserConversion=*/SuppressUserConversions: false);
16076 }
16077
16078 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16079
16080 // Perform overload resolution.
16081 OverloadCandidateSet::iterator Best;
16082 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16083 case OR_Success:
16084 // Overload resolution succeeded; we'll build the call below.
16085 break;
16086
16087 case OR_No_Viable_Function: {
16088 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16089 if (CandidateSet.empty()) {
16090 QualType BaseType = Base->getType();
16091 if (NoArrowOperatorFound) {
16092 // Report this specific error to the caller instead of emitting a
16093 // diagnostic, as requested.
16094 *NoArrowOperatorFound = true;
16095 return ExprError();
16096 }
16097 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16098 << BaseType << Base->getSourceRange();
16099 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16100 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16101 << FixItHint::CreateReplacement(OpLoc, ".");
16102 }
16103 } else
16104 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16105 << "operator->" << Base->getSourceRange();
16106 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16107 return ExprError();
16108 }
16109 case OR_Ambiguous:
16110 if (!R.isAmbiguous())
16111 CandidateSet.NoteCandidates(
16112 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16113 << "->" << Base->getType()
16114 << Base->getSourceRange()),
16115 *this, OCD_AmbiguousCandidates, Base);
16116 return ExprError();
16117
16118 case OR_Deleted: {
16119 StringLiteral *Msg = Best->Function->getDeletedMessage();
16120 CandidateSet.NoteCandidates(
16121 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16122 << "->" << (Msg != nullptr)
16123 << (Msg ? Msg->getString() : StringRef())
16124 << Base->getSourceRange()),
16125 *this, OCD_AllCandidates, Base);
16126 return ExprError();
16127 }
16128 }
16129
16130 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16131
16132 // Convert the object parameter.
16133 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16134
16135 if (Method->isExplicitObjectMemberFunction()) {
16136 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16137 if (R.isInvalid())
16138 return ExprError();
16139 Base = R.get();
16140 } else {
16141 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16142 From: Base, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
16143 if (BaseResult.isInvalid())
16144 return ExprError();
16145 Base = BaseResult.get();
16146 }
16147
16148 // Build the operator call.
16149 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16150 Base, HadMultipleCandidates, OpLoc);
16151 if (FnExpr.isInvalid())
16152 return ExprError();
16153
16154 QualType ResultTy = Method->getReturnType();
16155 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16156 ResultTy = ResultTy.getNonLValueExprType(Context);
16157
16158 CallExpr *TheCall =
16159 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16160 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16161
16162 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16163 return ExprError();
16164
16165 if (CheckFunctionCall(FDecl: Method, TheCall,
16166 Proto: Method->getType()->castAs<FunctionProtoType>()))
16167 return ExprError();
16168
16169 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16170}
16171
16172/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
16173/// a literal operator described by the provided lookup results.
16174ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16175 DeclarationNameInfo &SuffixInfo,
16176 ArrayRef<Expr*> Args,
16177 SourceLocation LitEndLoc,
16178 TemplateArgumentListInfo *TemplateArgs) {
16179 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16180
16181 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16182 OverloadCandidateSet::CSK_Normal);
16183 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16184 ExplicitTemplateArgs: TemplateArgs);
16185
16186 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16187
16188 // Perform overload resolution. This will usually be trivial, but might need
16189 // to perform substitutions for a literal operator template.
16190 OverloadCandidateSet::iterator Best;
16191 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16192 case OR_Success:
16193 case OR_Deleted:
16194 break;
16195
16196 case OR_No_Viable_Function:
16197 CandidateSet.NoteCandidates(
16198 PartialDiagnosticAt(UDSuffixLoc,
16199 PDiag(diag::err_ovl_no_viable_function_in_call)
16200 << R.getLookupName()),
16201 *this, OCD_AllCandidates, Args);
16202 return ExprError();
16203
16204 case OR_Ambiguous:
16205 CandidateSet.NoteCandidates(
16206 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16207 << R.getLookupName()),
16208 *this, OCD_AmbiguousCandidates, Args);
16209 return ExprError();
16210 }
16211
16212 FunctionDecl *FD = Best->Function;
16213 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16214 Base: nullptr, HadMultipleCandidates,
16215 Loc: SuffixInfo.getLoc(),
16216 LocInfo: SuffixInfo.getInfo());
16217 if (Fn.isInvalid())
16218 return true;
16219
16220 // Check the argument types. This should almost always be a no-op, except
16221 // that array-to-pointer decay is applied to string literals.
16222 Expr *ConvArgs[2];
16223 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16224 ExprResult InputInit = PerformCopyInitialization(
16225 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
16226 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
16227 if (InputInit.isInvalid())
16228 return true;
16229 ConvArgs[ArgIdx] = InputInit.get();
16230 }
16231
16232 QualType ResultTy = FD->getReturnType();
16233 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16234 ResultTy = ResultTy.getNonLValueExprType(Context);
16235
16236 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16237 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
16238 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
16239
16240 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16241 return ExprError();
16242
16243 if (CheckFunctionCall(FD, UDL, nullptr))
16244 return ExprError();
16245
16246 return CheckForImmediateInvocation(E: MaybeBindToTemporary(UDL), Decl: FD);
16247}
16248
16249/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16250/// given LookupResult is non-empty, it is assumed to describe a member which
16251/// will be invoked. Otherwise, the function will be found via argument
16252/// dependent lookup.
16253/// CallExpr is set to a valid expression and FRS_Success returned on success,
16254/// otherwise CallExpr is set to ExprError() and some non-success value
16255/// is returned.
16256Sema::ForRangeStatus
16257Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16258 SourceLocation RangeLoc,
16259 const DeclarationNameInfo &NameInfo,
16260 LookupResult &MemberLookup,
16261 OverloadCandidateSet *CandidateSet,
16262 Expr *Range, ExprResult *CallExpr) {
16263 Scope *S = nullptr;
16264
16265 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
16266 if (!MemberLookup.empty()) {
16267 ExprResult MemberRef =
16268 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
16269 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
16270 /*TemplateKWLoc=*/SourceLocation(),
16271 /*FirstQualifierInScope=*/nullptr,
16272 R&: MemberLookup,
16273 /*TemplateArgs=*/nullptr, S);
16274 if (MemberRef.isInvalid()) {
16275 *CallExpr = ExprError();
16276 return FRS_DiagnosticIssued;
16277 }
16278 *CallExpr =
16279 BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc, ExecConfig: nullptr);
16280 if (CallExpr->isInvalid()) {
16281 *CallExpr = ExprError();
16282 return FRS_DiagnosticIssued;
16283 }
16284 } else {
16285 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16286 NNSLoc: NestedNameSpecifierLoc(),
16287 DNI: NameInfo, Fns: UnresolvedSet<0>());
16288 if (FnR.isInvalid())
16289 return FRS_DiagnosticIssued;
16290 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
16291
16292 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16293 CandidateSet, CallExpr);
16294 if (CandidateSet->empty() || CandidateSetError) {
16295 *CallExpr = ExprError();
16296 return FRS_NoViableFunction;
16297 }
16298 OverloadCandidateSet::iterator Best;
16299 OverloadingResult OverloadResult =
16300 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
16301
16302 if (OverloadResult == OR_No_Viable_Function) {
16303 *CallExpr = ExprError();
16304 return FRS_NoViableFunction;
16305 }
16306 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16307 Loc, nullptr, CandidateSet, &Best,
16308 OverloadResult,
16309 /*AllowTypoCorrection=*/false);
16310 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16311 *CallExpr = ExprError();
16312 return FRS_DiagnosticIssued;
16313 }
16314 }
16315 return FRS_Success;
16316}
16317
16318
16319/// FixOverloadedFunctionReference - E is an expression that refers to
16320/// a C++ overloaded function (possibly with some parentheses and
16321/// perhaps a '&' around it). We have resolved the overloaded function
16322/// to the function declaration Fn, so patch up the expression E to
16323/// refer (possibly indirectly) to Fn. Returns the new expr.
16324ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16325 FunctionDecl *Fn) {
16326 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
16327 ExprResult SubExpr =
16328 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
16329 if (SubExpr.isInvalid())
16330 return ExprError();
16331 if (SubExpr.get() == PE->getSubExpr())
16332 return PE;
16333
16334 return new (Context)
16335 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16336 }
16337
16338 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
16339 ExprResult SubExpr =
16340 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16341 if (SubExpr.isInvalid())
16342 return ExprError();
16343 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16344 SubExpr.get()->getType()) &&
16345 "Implicit cast type cannot be determined from overload");
16346 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16347 if (SubExpr.get() == ICE->getSubExpr())
16348 return ICE;
16349
16350 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
16351 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
16352 FPO: CurFPFeatureOverrides());
16353 }
16354
16355 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
16356 if (!GSE->isResultDependent()) {
16357 ExprResult SubExpr =
16358 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
16359 if (SubExpr.isInvalid())
16360 return ExprError();
16361 if (SubExpr.get() == GSE->getResultExpr())
16362 return GSE;
16363
16364 // Replace the resulting type information before rebuilding the generic
16365 // selection expression.
16366 ArrayRef<Expr *> A = GSE->getAssocExprs();
16367 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16368 unsigned ResultIdx = GSE->getResultIndex();
16369 AssocExprs[ResultIdx] = SubExpr.get();
16370
16371 if (GSE->isExprPredicate())
16372 return GenericSelectionExpr::Create(
16373 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16374 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16375 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16376 ResultIdx);
16377 return GenericSelectionExpr::Create(
16378 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16379 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16380 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16381 ResultIdx);
16382 }
16383 // Rather than fall through to the unreachable, return the original generic
16384 // selection expression.
16385 return GSE;
16386 }
16387
16388 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
16389 assert(UnOp->getOpcode() == UO_AddrOf &&
16390 "Can only take the address of an overloaded function");
16391 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
16392 if (Method->isStatic()) {
16393 // Do nothing: static member functions aren't any different
16394 // from non-member functions.
16395 } else {
16396 // Fix the subexpression, which really has to be an
16397 // UnresolvedLookupExpr holding an overloaded member function
16398 // or template.
16399 ExprResult SubExpr =
16400 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16401 if (SubExpr.isInvalid())
16402 return ExprError();
16403 if (SubExpr.get() == UnOp->getSubExpr())
16404 return UnOp;
16405
16406 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
16407 Op: SubExpr.get(), MD: Method))
16408 return ExprError();
16409
16410 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16411 "fixed to something other than a decl ref");
16412 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16413 "fixed to a member ref with no nested name qualifier");
16414
16415 // We have taken the address of a pointer to member
16416 // function. Perform the computation here so that we get the
16417 // appropriate pointer to member type.
16418 QualType ClassType
16419 = Context.getTypeDeclType(Decl: cast<RecordDecl>(Method->getDeclContext()));
16420 QualType MemPtrType
16421 = Context.getMemberPointerType(T: Fn->getType(), Cls: ClassType.getTypePtr());
16422 // Under the MS ABI, lock down the inheritance model now.
16423 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16424 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
16425
16426 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
16427 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
16428 l: UnOp->getOperatorLoc(), CanOverflow: false,
16429 FPFeatures: CurFPFeatureOverrides());
16430 }
16431 }
16432 ExprResult SubExpr =
16433 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16434 if (SubExpr.isInvalid())
16435 return ExprError();
16436 if (SubExpr.get() == UnOp->getSubExpr())
16437 return UnOp;
16438
16439 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
16440 InputExpr: SubExpr.get());
16441 }
16442
16443 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16444 // FIXME: avoid copy.
16445 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16446 if (ULE->hasExplicitTemplateArgs()) {
16447 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16448 TemplateArgs = &TemplateArgsBuffer;
16449 }
16450
16451 QualType Type = Fn->getType();
16452 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16453
16454 // FIXME: Duplicated from BuildDeclarationNameExpr.
16455 if (unsigned BID = Fn->getBuiltinID()) {
16456 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
16457 Type = Context.BuiltinFnTy;
16458 ValueKind = VK_PRValue;
16459 }
16460 }
16461
16462 DeclRefExpr *DRE = BuildDeclRefExpr(
16463 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16464 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16465 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16466 return DRE;
16467 }
16468
16469 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
16470 // FIXME: avoid copy.
16471 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16472 if (MemExpr->hasExplicitTemplateArgs()) {
16473 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16474 TemplateArgs = &TemplateArgsBuffer;
16475 }
16476
16477 Expr *Base;
16478
16479 // If we're filling in a static method where we used to have an
16480 // implicit member access, rewrite to a simple decl ref.
16481 if (MemExpr->isImplicitAccess()) {
16482 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
16483 DeclRefExpr *DRE = BuildDeclRefExpr(
16484 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16485 MemExpr->getQualifierLoc(), Found.getDecl(),
16486 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16487 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16488 return DRE;
16489 } else {
16490 SourceLocation Loc = MemExpr->getMemberLoc();
16491 if (MemExpr->getQualifier())
16492 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16493 Base =
16494 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
16495 }
16496 } else
16497 Base = MemExpr->getBase();
16498
16499 ExprValueKind valueKind;
16500 QualType type;
16501 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
16502 valueKind = VK_LValue;
16503 type = Fn->getType();
16504 } else {
16505 valueKind = VK_PRValue;
16506 type = Context.BoundMemberTy;
16507 }
16508
16509 return BuildMemberExpr(
16510 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16511 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16512 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16513 type, valueKind, OK_Ordinary, TemplateArgs);
16514 }
16515
16516 llvm_unreachable("Invalid reference to overloaded function");
16517}
16518
16519ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
16520 DeclAccessPair Found,
16521 FunctionDecl *Fn) {
16522 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
16523}
16524
16525bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16526 FunctionDecl *Function) {
16527 if (!PartialOverloading || !Function)
16528 return true;
16529 if (Function->isVariadic())
16530 return false;
16531 if (const auto *Proto =
16532 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16533 if (Proto->isTemplateVariadic())
16534 return false;
16535 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16536 if (const auto *Proto =
16537 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16538 if (Proto->isTemplateVariadic())
16539 return false;
16540 return true;
16541}
16542
16543void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
16544 DeclarationName Name,
16545 OverloadCandidateSet &CandidateSet,
16546 FunctionDecl *Fn, MultiExprArg Args,
16547 bool IsMember) {
16548 StringLiteral *Msg = Fn->getDeletedMessage();
16549 CandidateSet.NoteCandidates(
16550 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16551 << IsMember << Name << (Msg != nullptr)
16552 << (Msg ? Msg->getString() : StringRef())
16553 << Range),
16554 *this, OCD_AllCandidates, Args);
16555}
16556

source code of clang/lib/Sema/SemaOverload.cpp