1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/DiagnosticOptions.h"
25#include "clang/Basic/OperatorKinds.h"
26#include "clang/Basic/PartialDiagnostic.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.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/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
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(D: Fn, Locs: 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(ESpecType: FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: 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_HLSL_Dimension_Reduction,
165 ICR_Conversion,
166 ICR_HLSL_Scalar_Widening,
167 };
168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169 return Rank[(int)Kind];
170}
171
172ImplicitConversionRank
173clang::GetDimensionConversionRank(ImplicitConversionRank Base,
174 ImplicitConversionKind Dimension) {
175 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
176 if (Rank == ICR_HLSL_Scalar_Widening) {
177 if (Base == ICR_Promotion)
178 return ICR_HLSL_Scalar_Widening_Promotion;
179 if (Base == ICR_Conversion)
180 return ICR_HLSL_Scalar_Widening_Conversion;
181 }
182 if (Rank == ICR_HLSL_Dimension_Reduction) {
183 if (Base == ICR_Promotion)
184 return ICR_HLSL_Dimension_Reduction_Promotion;
185 if (Base == ICR_Conversion)
186 return ICR_HLSL_Dimension_Reduction_Conversion;
187 }
188 return Rank;
189}
190
191/// GetImplicitConversionName - Return the name of this kind of
192/// implicit conversion.
193static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
194 static const char *const Name[] = {
195 "No conversion",
196 "Lvalue-to-rvalue",
197 "Array-to-pointer",
198 "Function-to-pointer",
199 "Function pointer conversion",
200 "Qualification",
201 "Integral promotion",
202 "Floating point promotion",
203 "Complex promotion",
204 "Integral conversion",
205 "Floating conversion",
206 "Complex conversion",
207 "Floating-integral conversion",
208 "Pointer conversion",
209 "Pointer-to-member conversion",
210 "Boolean conversion",
211 "Compatible-types conversion",
212 "Derived-to-base conversion",
213 "Vector conversion",
214 "SVE Vector conversion",
215 "RVV Vector conversion",
216 "Vector splat",
217 "Complex-real conversion",
218 "Block Pointer conversion",
219 "Transparent Union Conversion",
220 "Writeback conversion",
221 "OpenCL Zero Event Conversion",
222 "OpenCL Zero Queue Conversion",
223 "C specific type conversion",
224 "Incompatible pointer conversion",
225 "Fixed point conversion",
226 "HLSL vector truncation",
227 "Non-decaying array conversion",
228 "HLSL vector splat",
229 };
230 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
231 return Name[Kind];
232}
233
234/// StandardConversionSequence - Set the standard conversion
235/// sequence to the identity conversion.
236void StandardConversionSequence::setAsIdentityConversion() {
237 First = ICK_Identity;
238 Second = ICK_Identity;
239 Dimension = ICK_Identity;
240 Third = ICK_Identity;
241 DeprecatedStringLiteralToCharPtr = false;
242 QualificationIncludesObjCLifetime = false;
243 ReferenceBinding = false;
244 DirectBinding = false;
245 IsLvalueReference = true;
246 BindsToFunctionLvalue = false;
247 BindsToRvalue = false;
248 BindsImplicitObjectArgumentWithoutRefQualifier = false;
249 ObjCLifetimeConversionBinding = false;
250 FromBracedInitList = false;
251 CopyConstructor = nullptr;
252}
253
254/// getRank - Retrieve the rank of this standard conversion sequence
255/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
256/// implicit conversions.
257ImplicitConversionRank StandardConversionSequence::getRank() const {
258 ImplicitConversionRank Rank = ICR_Exact_Match;
259 if (GetConversionRank(Kind: First) > Rank)
260 Rank = GetConversionRank(Kind: First);
261 if (GetConversionRank(Kind: Second) > Rank)
262 Rank = GetConversionRank(Kind: Second);
263 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
264 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
265 if (GetConversionRank(Kind: Third) > Rank)
266 Rank = GetConversionRank(Kind: Third);
267 return Rank;
268}
269
270/// isPointerConversionToBool - Determines whether this conversion is
271/// a conversion of a pointer or pointer-to-member to bool. This is
272/// used as part of the ranking of standard conversion sequences
273/// (C++ 13.3.3.2p4).
274bool StandardConversionSequence::isPointerConversionToBool() const {
275 // Note that FromType has not necessarily been transformed by the
276 // array-to-pointer or function-to-pointer implicit conversions, so
277 // check for their presence as well as checking whether FromType is
278 // a pointer.
279 if (getToType(Idx: 1)->isBooleanType() &&
280 (getFromType()->isPointerType() ||
281 getFromType()->isMemberPointerType() ||
282 getFromType()->isObjCObjectPointerType() ||
283 getFromType()->isBlockPointerType() ||
284 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
285 return true;
286
287 return false;
288}
289
290/// isPointerConversionToVoidPointer - Determines whether this
291/// conversion is a conversion of a pointer to a void pointer. This is
292/// used as part of the ranking of standard conversion sequences (C++
293/// 13.3.3.2p4).
294bool
295StandardConversionSequence::
296isPointerConversionToVoidPointer(ASTContext& Context) const {
297 QualType FromType = getFromType();
298 QualType ToType = getToType(Idx: 1);
299
300 // Note that FromType has not necessarily been transformed by the
301 // array-to-pointer implicit conversion, so check for its presence
302 // and redo the conversion to get a pointer.
303 if (First == ICK_Array_To_Pointer)
304 FromType = Context.getArrayDecayedType(T: FromType);
305
306 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
307 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
308 return ToPtrType->getPointeeType()->isVoidType();
309
310 return false;
311}
312
313/// Skip any implicit casts which could be either part of a narrowing conversion
314/// or after one in an implicit conversion.
315static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
316 const Expr *Converted) {
317 // We can have cleanups wrapping the converted expression; these need to be
318 // preserved so that destructors run if necessary.
319 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
320 Expr *Inner =
321 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
322 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
323 objects: EWC->getObjects());
324 }
325
326 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
327 switch (ICE->getCastKind()) {
328 case CK_NoOp:
329 case CK_IntegralCast:
330 case CK_IntegralToBoolean:
331 case CK_IntegralToFloating:
332 case CK_BooleanToSignedIntegral:
333 case CK_FloatingToIntegral:
334 case CK_FloatingToBoolean:
335 case CK_FloatingCast:
336 Converted = ICE->getSubExpr();
337 continue;
338
339 default:
340 return Converted;
341 }
342 }
343
344 return Converted;
345}
346
347/// Check if this standard conversion sequence represents a narrowing
348/// conversion, according to C++11 [dcl.init.list]p7.
349///
350/// \param Ctx The AST context.
351/// \param Converted The result of applying this standard conversion sequence.
352/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
353/// value of the expression prior to the narrowing conversion.
354/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
355/// type of the expression prior to the narrowing conversion.
356/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
357/// from floating point types to integral types should be ignored.
358NarrowingKind StandardConversionSequence::getNarrowingKind(
359 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
360 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
361 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
362 "narrowing check outside C++");
363
364 // C++11 [dcl.init.list]p7:
365 // A narrowing conversion is an implicit conversion ...
366 QualType FromType = getToType(Idx: 0);
367 QualType ToType = getToType(Idx: 1);
368
369 // A conversion to an enumeration type is narrowing if the conversion to
370 // the underlying type is narrowing. This only arises for expressions of
371 // the form 'Enum{init}'.
372 if (auto *ET = ToType->getAs<EnumType>())
373 ToType = ET->getDecl()->getIntegerType();
374
375 switch (Second) {
376 // 'bool' is an integral type; dispatch to the right place to handle it.
377 case ICK_Boolean_Conversion:
378 if (FromType->isRealFloatingType())
379 goto FloatingIntegralConversion;
380 if (FromType->isIntegralOrUnscopedEnumerationType())
381 goto IntegralConversion;
382 // -- from a pointer type or pointer-to-member type to bool, or
383 return NK_Type_Narrowing;
384
385 // -- from a floating-point type to an integer type, or
386 //
387 // -- from an integer type or unscoped enumeration type to a floating-point
388 // type, except where the source is a constant expression and the actual
389 // value after conversion will fit into the target type and will produce
390 // the original value when converted back to the original type, or
391 case ICK_Floating_Integral:
392 FloatingIntegralConversion:
393 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
394 return NK_Type_Narrowing;
395 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
396 ToType->isRealFloatingType()) {
397 if (IgnoreFloatToIntegralConversion)
398 return NK_Not_Narrowing;
399 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
400 assert(Initializer && "Unknown conversion expression");
401
402 // If it's value-dependent, we can't tell whether it's narrowing.
403 if (Initializer->isValueDependent())
404 return NK_Dependent_Narrowing;
405
406 if (std::optional<llvm::APSInt> IntConstantValue =
407 Initializer->getIntegerConstantExpr(Ctx)) {
408 // Convert the integer to the floating type.
409 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
410 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
411 RM: llvm::APFloat::rmNearestTiesToEven);
412 // And back.
413 llvm::APSInt ConvertedValue = *IntConstantValue;
414 bool ignored;
415 Result.convertToInteger(Result&: ConvertedValue,
416 RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
417 // If the resulting value is different, this was a narrowing conversion.
418 if (*IntConstantValue != ConvertedValue) {
419 ConstantValue = APValue(*IntConstantValue);
420 ConstantType = Initializer->getType();
421 return NK_Constant_Narrowing;
422 }
423 } else {
424 // Variables are always narrowings.
425 return NK_Variable_Narrowing;
426 }
427 }
428 return NK_Not_Narrowing;
429
430 // -- from long double to double or float, or from double to float, except
431 // where the source is a constant expression and the actual value after
432 // conversion is within the range of values that can be represented (even
433 // if it cannot be represented exactly), or
434 case ICK_Floating_Conversion:
435 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
436 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
437 // FromType is larger than ToType.
438 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439
440 // If it's value-dependent, we can't tell whether it's narrowing.
441 if (Initializer->isValueDependent())
442 return NK_Dependent_Narrowing;
443
444 Expr::EvalResult R;
445 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
446 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)) {
447 // Constant!
448 if (Ctx.getLangOpts().C23)
449 ConstantValue = R.Val;
450 assert(ConstantValue.isFloat());
451 llvm::APFloat FloatVal = ConstantValue.getFloat();
452 // Convert the source value into the target type.
453 bool ignored;
454 llvm::APFloat Converted = FloatVal;
455 llvm::APFloat::opStatus ConvertStatus =
456 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
457 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
458 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
459 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
460 if (Ctx.getLangOpts().C23) {
461 if (FloatVal.isNaN() && Converted.isNaN() &&
462 !FloatVal.isSignaling() && !Converted.isSignaling()) {
463 // Quiet NaNs are considered the same value, regardless of
464 // payloads.
465 return NK_Not_Narrowing;
466 }
467 // For normal values, check exact equality.
468 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
469 ConstantType = Initializer->getType();
470 return NK_Constant_Narrowing;
471 }
472 } else {
473 // If there was no overflow, the source value is within the range of
474 // values that can be represented.
475 if (ConvertStatus & llvm::APFloat::opOverflow) {
476 ConstantType = Initializer->getType();
477 return NK_Constant_Narrowing;
478 }
479 }
480 } else {
481 return NK_Variable_Narrowing;
482 }
483 }
484 return NK_Not_Narrowing;
485
486 // -- from an integer type or unscoped enumeration type to an integer type
487 // that cannot represent all the values of the original type, except where
488 // (CWG2627) -- the source is a bit-field whose width w is less than that
489 // of its type (or, for an enumeration type, its underlying type) and the
490 // target type can represent all the values of a hypothetical extended
491 // integer type with width w and with the same signedness as the original
492 // type or
493 // -- the source is a constant expression and the actual value after
494 // conversion will fit into the target type and will produce the original
495 // value when converted back to the original type.
496 case ICK_Integral_Conversion:
497 IntegralConversion: {
498 assert(FromType->isIntegralOrUnscopedEnumerationType());
499 assert(ToType->isIntegralOrUnscopedEnumerationType());
500 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
501 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
502 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
503 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
504
505 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
506 bool ToSigned, unsigned ToWidth) {
507 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
508 !(FromSigned && !ToSigned);
509 };
510
511 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
512 return NK_Not_Narrowing;
513
514 // Not all values of FromType can be represented in ToType.
515 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
516
517 bool DependentBitField = false;
518 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
519 if (BitField->getBitWidth()->isValueDependent())
520 DependentBitField = true;
521 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
522 BitFieldWidth < FromWidth) {
523 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
524 return NK_Not_Narrowing;
525
526 // The initializer will be truncated to the bit-field width
527 FromWidth = BitFieldWidth;
528 }
529 }
530
531 // If it's value-dependent, we can't tell whether it's narrowing.
532 if (Initializer->isValueDependent())
533 return NK_Dependent_Narrowing;
534
535 std::optional<llvm::APSInt> OptInitializerValue =
536 Initializer->getIntegerConstantExpr(Ctx);
537 if (!OptInitializerValue) {
538 // If the bit-field width was dependent, it might end up being small
539 // enough to fit in the target type (unless the target type is unsigned
540 // and the source type is signed, in which case it will never fit)
541 if (DependentBitField && !(FromSigned && !ToSigned))
542 return NK_Dependent_Narrowing;
543
544 // Otherwise, such a conversion is always narrowing
545 return NK_Variable_Narrowing;
546 }
547 llvm::APSInt &InitializerValue = *OptInitializerValue;
548 bool Narrowing = false;
549 if (FromWidth < ToWidth) {
550 // Negative -> unsigned is narrowing. Otherwise, more bits is never
551 // narrowing.
552 if (InitializerValue.isSigned() && InitializerValue.isNegative())
553 Narrowing = true;
554 } else {
555 // Add a bit to the InitializerValue so we don't have to worry about
556 // signed vs. unsigned comparisons.
557 InitializerValue =
558 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
559 // Convert the initializer to and from the target width and signed-ness.
560 llvm::APSInt ConvertedValue = InitializerValue;
561 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
562 ConvertedValue.setIsSigned(ToSigned);
563 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
564 ConvertedValue.setIsSigned(InitializerValue.isSigned());
565 // If the result is different, this was a narrowing conversion.
566 if (ConvertedValue != InitializerValue)
567 Narrowing = true;
568 }
569 if (Narrowing) {
570 ConstantType = Initializer->getType();
571 ConstantValue = APValue(InitializerValue);
572 return NK_Constant_Narrowing;
573 }
574
575 return NK_Not_Narrowing;
576 }
577 case ICK_Complex_Real:
578 if (FromType->isComplexType() && !ToType->isComplexType())
579 return NK_Type_Narrowing;
580 return NK_Not_Narrowing;
581
582 case ICK_Floating_Promotion:
583 if (Ctx.getLangOpts().C23) {
584 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
585 Expr::EvalResult R;
586 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
587 ConstantValue = R.Val;
588 assert(ConstantValue.isFloat());
589 llvm::APFloat FloatVal = ConstantValue.getFloat();
590 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
591 // value, the unqualified versions of the type of the initializer and
592 // the corresponding real type of the object declared shall be
593 // compatible.
594 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
595 ConstantType = Initializer->getType();
596 return NK_Constant_Narrowing;
597 }
598 }
599 }
600 return NK_Not_Narrowing;
601 default:
602 // Other kinds of conversions are not narrowings.
603 return NK_Not_Narrowing;
604 }
605}
606
607/// dump - Print this standard conversion sequence to standard
608/// error. Useful for debugging overloading issues.
609LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
610 raw_ostream &OS = llvm::errs();
611 bool PrintedSomething = false;
612 if (First != ICK_Identity) {
613 OS << GetImplicitConversionName(Kind: First);
614 PrintedSomething = true;
615 }
616
617 if (Second != ICK_Identity) {
618 if (PrintedSomething) {
619 OS << " -> ";
620 }
621 OS << GetImplicitConversionName(Kind: Second);
622
623 if (CopyConstructor) {
624 OS << " (by copy constructor)";
625 } else if (DirectBinding) {
626 OS << " (direct reference binding)";
627 } else if (ReferenceBinding) {
628 OS << " (reference binding)";
629 }
630 PrintedSomething = true;
631 }
632
633 if (Third != ICK_Identity) {
634 if (PrintedSomething) {
635 OS << " -> ";
636 }
637 OS << GetImplicitConversionName(Kind: Third);
638 PrintedSomething = true;
639 }
640
641 if (!PrintedSomething) {
642 OS << "No conversions required";
643 }
644}
645
646/// dump - Print this user-defined conversion sequence to standard
647/// error. Useful for debugging overloading issues.
648void UserDefinedConversionSequence::dump() const {
649 raw_ostream &OS = llvm::errs();
650 if (Before.First || Before.Second || Before.Third) {
651 Before.dump();
652 OS << " -> ";
653 }
654 if (ConversionFunction)
655 OS << '\'' << *ConversionFunction << '\'';
656 else
657 OS << "aggregate initialization";
658 if (After.First || After.Second || After.Third) {
659 OS << " -> ";
660 After.dump();
661 }
662}
663
664/// dump - Print this implicit conversion sequence to standard
665/// error. Useful for debugging overloading issues.
666void ImplicitConversionSequence::dump() const {
667 raw_ostream &OS = llvm::errs();
668 if (hasInitializerListContainerType())
669 OS << "Worst list element conversion: ";
670 switch (ConversionKind) {
671 case StandardConversion:
672 OS << "Standard conversion: ";
673 Standard.dump();
674 break;
675 case UserDefinedConversion:
676 OS << "User-defined conversion: ";
677 UserDefined.dump();
678 break;
679 case EllipsisConversion:
680 OS << "Ellipsis conversion";
681 break;
682 case AmbiguousConversion:
683 OS << "Ambiguous conversion";
684 break;
685 case BadConversion:
686 OS << "Bad conversion";
687 break;
688 }
689
690 OS << "\n";
691}
692
693void AmbiguousConversionSequence::construct() {
694 new (&conversions()) ConversionSet();
695}
696
697void AmbiguousConversionSequence::destruct() {
698 conversions().~ConversionSet();
699}
700
701void
702AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
703 FromTypePtr = O.FromTypePtr;
704 ToTypePtr = O.ToTypePtr;
705 new (&conversions()) ConversionSet(O.conversions());
706}
707
708namespace {
709 // Structure used by DeductionFailureInfo to store
710 // template argument information.
711 struct DFIArguments {
712 TemplateArgument FirstArg;
713 TemplateArgument SecondArg;
714 };
715 // Structure used by DeductionFailureInfo to store
716 // template parameter and template argument information.
717 struct DFIParamWithArguments : DFIArguments {
718 TemplateParameter Param;
719 };
720 // Structure used by DeductionFailureInfo to store template argument
721 // information and the index of the problematic call argument.
722 struct DFIDeducedMismatchArgs : DFIArguments {
723 TemplateArgumentList *TemplateArgs;
724 unsigned CallArgIndex;
725 };
726 // Structure used by DeductionFailureInfo to store information about
727 // unsatisfied constraints.
728 struct CNSInfo {
729 TemplateArgumentList *TemplateArgs;
730 ConstraintSatisfaction Satisfaction;
731 };
732}
733
734/// Convert from Sema's representation of template deduction information
735/// to the form used in overload-candidate information.
736DeductionFailureInfo
737clang::MakeDeductionFailureInfo(ASTContext &Context,
738 TemplateDeductionResult TDK,
739 TemplateDeductionInfo &Info) {
740 DeductionFailureInfo Result;
741 Result.Result = static_cast<unsigned>(TDK);
742 Result.HasDiagnostic = false;
743 switch (TDK) {
744 case TemplateDeductionResult::Invalid:
745 case TemplateDeductionResult::InstantiationDepth:
746 case TemplateDeductionResult::TooManyArguments:
747 case TemplateDeductionResult::TooFewArguments:
748 case TemplateDeductionResult::MiscellaneousDeductionFailure:
749 case TemplateDeductionResult::CUDATargetMismatch:
750 Result.Data = nullptr;
751 break;
752
753 case TemplateDeductionResult::Incomplete:
754 case TemplateDeductionResult::InvalidExplicitArguments:
755 Result.Data = Info.Param.getOpaqueValue();
756 break;
757
758 case TemplateDeductionResult::DeducedMismatch:
759 case TemplateDeductionResult::DeducedMismatchNested: {
760 // FIXME: Should allocate from normal heap so that we can free this later.
761 auto *Saved = new (Context) DFIDeducedMismatchArgs;
762 Saved->FirstArg = Info.FirstArg;
763 Saved->SecondArg = Info.SecondArg;
764 Saved->TemplateArgs = Info.takeSugared();
765 Saved->CallArgIndex = Info.CallArgIndex;
766 Result.Data = Saved;
767 break;
768 }
769
770 case TemplateDeductionResult::NonDeducedMismatch: {
771 // FIXME: Should allocate from normal heap so that we can free this later.
772 DFIArguments *Saved = new (Context) DFIArguments;
773 Saved->FirstArg = Info.FirstArg;
774 Saved->SecondArg = Info.SecondArg;
775 Result.Data = Saved;
776 break;
777 }
778
779 case TemplateDeductionResult::IncompletePack:
780 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
781 case TemplateDeductionResult::Inconsistent:
782 case TemplateDeductionResult::Underqualified: {
783 // FIXME: Should allocate from normal heap so that we can free this later.
784 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
785 Saved->Param = Info.Param;
786 Saved->FirstArg = Info.FirstArg;
787 Saved->SecondArg = Info.SecondArg;
788 Result.Data = Saved;
789 break;
790 }
791
792 case TemplateDeductionResult::SubstitutionFailure:
793 Result.Data = Info.takeSugared();
794 if (Info.hasSFINAEDiagnostic()) {
795 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
796 SourceLocation(), PartialDiagnostic::NullDiagnostic());
797 Info.takeSFINAEDiagnostic(PD&: *Diag);
798 Result.HasDiagnostic = true;
799 }
800 break;
801
802 case TemplateDeductionResult::ConstraintsNotSatisfied: {
803 CNSInfo *Saved = new (Context) CNSInfo;
804 Saved->TemplateArgs = Info.takeSugared();
805 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
806 Result.Data = Saved;
807 break;
808 }
809
810 case TemplateDeductionResult::Success:
811 case TemplateDeductionResult::NonDependentConversionFailure:
812 case TemplateDeductionResult::AlreadyDiagnosed:
813 llvm_unreachable("not a deduction failure");
814 }
815
816 return Result;
817}
818
819void DeductionFailureInfo::Destroy() {
820 switch (static_cast<TemplateDeductionResult>(Result)) {
821 case TemplateDeductionResult::Success:
822 case TemplateDeductionResult::Invalid:
823 case TemplateDeductionResult::InstantiationDepth:
824 case TemplateDeductionResult::Incomplete:
825 case TemplateDeductionResult::TooManyArguments:
826 case TemplateDeductionResult::TooFewArguments:
827 case TemplateDeductionResult::InvalidExplicitArguments:
828 case TemplateDeductionResult::CUDATargetMismatch:
829 case TemplateDeductionResult::NonDependentConversionFailure:
830 break;
831
832 case TemplateDeductionResult::IncompletePack:
833 case TemplateDeductionResult::Inconsistent:
834 case TemplateDeductionResult::Underqualified:
835 case TemplateDeductionResult::DeducedMismatch:
836 case TemplateDeductionResult::DeducedMismatchNested:
837 case TemplateDeductionResult::NonDeducedMismatch:
838 // FIXME: Destroy the data?
839 Data = nullptr;
840 break;
841
842 case TemplateDeductionResult::SubstitutionFailure:
843 // FIXME: Destroy the template argument list?
844 Data = nullptr;
845 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
846 Diag->~PartialDiagnosticAt();
847 HasDiagnostic = false;
848 }
849 break;
850
851 case TemplateDeductionResult::ConstraintsNotSatisfied:
852 // FIXME: Destroy the template argument list?
853 Data = nullptr;
854 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
855 Diag->~PartialDiagnosticAt();
856 HasDiagnostic = false;
857 }
858 break;
859
860 // Unhandled
861 case TemplateDeductionResult::MiscellaneousDeductionFailure:
862 case TemplateDeductionResult::AlreadyDiagnosed:
863 break;
864 }
865}
866
867PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
868 if (HasDiagnostic)
869 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
870 return nullptr;
871}
872
873TemplateParameter DeductionFailureInfo::getTemplateParameter() {
874 switch (static_cast<TemplateDeductionResult>(Result)) {
875 case TemplateDeductionResult::Success:
876 case TemplateDeductionResult::Invalid:
877 case TemplateDeductionResult::InstantiationDepth:
878 case TemplateDeductionResult::TooManyArguments:
879 case TemplateDeductionResult::TooFewArguments:
880 case TemplateDeductionResult::SubstitutionFailure:
881 case TemplateDeductionResult::DeducedMismatch:
882 case TemplateDeductionResult::DeducedMismatchNested:
883 case TemplateDeductionResult::NonDeducedMismatch:
884 case TemplateDeductionResult::CUDATargetMismatch:
885 case TemplateDeductionResult::NonDependentConversionFailure:
886 case TemplateDeductionResult::ConstraintsNotSatisfied:
887 return TemplateParameter();
888
889 case TemplateDeductionResult::Incomplete:
890 case TemplateDeductionResult::InvalidExplicitArguments:
891 return TemplateParameter::getFromOpaqueValue(VP: Data);
892
893 case TemplateDeductionResult::IncompletePack:
894 case TemplateDeductionResult::Inconsistent:
895 case TemplateDeductionResult::Underqualified:
896 return static_cast<DFIParamWithArguments*>(Data)->Param;
897
898 // Unhandled
899 case TemplateDeductionResult::MiscellaneousDeductionFailure:
900 case TemplateDeductionResult::AlreadyDiagnosed:
901 break;
902 }
903
904 return TemplateParameter();
905}
906
907TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
908 switch (static_cast<TemplateDeductionResult>(Result)) {
909 case TemplateDeductionResult::Success:
910 case TemplateDeductionResult::Invalid:
911 case TemplateDeductionResult::InstantiationDepth:
912 case TemplateDeductionResult::TooManyArguments:
913 case TemplateDeductionResult::TooFewArguments:
914 case TemplateDeductionResult::Incomplete:
915 case TemplateDeductionResult::IncompletePack:
916 case TemplateDeductionResult::InvalidExplicitArguments:
917 case TemplateDeductionResult::Inconsistent:
918 case TemplateDeductionResult::Underqualified:
919 case TemplateDeductionResult::NonDeducedMismatch:
920 case TemplateDeductionResult::CUDATargetMismatch:
921 case TemplateDeductionResult::NonDependentConversionFailure:
922 return nullptr;
923
924 case TemplateDeductionResult::DeducedMismatch:
925 case TemplateDeductionResult::DeducedMismatchNested:
926 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
927
928 case TemplateDeductionResult::SubstitutionFailure:
929 return static_cast<TemplateArgumentList*>(Data);
930
931 case TemplateDeductionResult::ConstraintsNotSatisfied:
932 return static_cast<CNSInfo*>(Data)->TemplateArgs;
933
934 // Unhandled
935 case TemplateDeductionResult::MiscellaneousDeductionFailure:
936 case TemplateDeductionResult::AlreadyDiagnosed:
937 break;
938 }
939
940 return nullptr;
941}
942
943const TemplateArgument *DeductionFailureInfo::getFirstArg() {
944 switch (static_cast<TemplateDeductionResult>(Result)) {
945 case TemplateDeductionResult::Success:
946 case TemplateDeductionResult::Invalid:
947 case TemplateDeductionResult::InstantiationDepth:
948 case TemplateDeductionResult::Incomplete:
949 case TemplateDeductionResult::TooManyArguments:
950 case TemplateDeductionResult::TooFewArguments:
951 case TemplateDeductionResult::InvalidExplicitArguments:
952 case TemplateDeductionResult::SubstitutionFailure:
953 case TemplateDeductionResult::CUDATargetMismatch:
954 case TemplateDeductionResult::NonDependentConversionFailure:
955 case TemplateDeductionResult::ConstraintsNotSatisfied:
956 return nullptr;
957
958 case TemplateDeductionResult::IncompletePack:
959 case TemplateDeductionResult::Inconsistent:
960 case TemplateDeductionResult::Underqualified:
961 case TemplateDeductionResult::DeducedMismatch:
962 case TemplateDeductionResult::DeducedMismatchNested:
963 case TemplateDeductionResult::NonDeducedMismatch:
964 return &static_cast<DFIArguments*>(Data)->FirstArg;
965
966 // Unhandled
967 case TemplateDeductionResult::MiscellaneousDeductionFailure:
968 case TemplateDeductionResult::AlreadyDiagnosed:
969 break;
970 }
971
972 return nullptr;
973}
974
975const TemplateArgument *DeductionFailureInfo::getSecondArg() {
976 switch (static_cast<TemplateDeductionResult>(Result)) {
977 case TemplateDeductionResult::Success:
978 case TemplateDeductionResult::Invalid:
979 case TemplateDeductionResult::InstantiationDepth:
980 case TemplateDeductionResult::Incomplete:
981 case TemplateDeductionResult::IncompletePack:
982 case TemplateDeductionResult::TooManyArguments:
983 case TemplateDeductionResult::TooFewArguments:
984 case TemplateDeductionResult::InvalidExplicitArguments:
985 case TemplateDeductionResult::SubstitutionFailure:
986 case TemplateDeductionResult::CUDATargetMismatch:
987 case TemplateDeductionResult::NonDependentConversionFailure:
988 case TemplateDeductionResult::ConstraintsNotSatisfied:
989 return nullptr;
990
991 case TemplateDeductionResult::Inconsistent:
992 case TemplateDeductionResult::Underqualified:
993 case TemplateDeductionResult::DeducedMismatch:
994 case TemplateDeductionResult::DeducedMismatchNested:
995 case TemplateDeductionResult::NonDeducedMismatch:
996 return &static_cast<DFIArguments*>(Data)->SecondArg;
997
998 // Unhandled
999 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1000 case TemplateDeductionResult::AlreadyDiagnosed:
1001 break;
1002 }
1003
1004 return nullptr;
1005}
1006
1007UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1008 switch (static_cast<TemplateDeductionResult>(Result)) {
1009 case TemplateDeductionResult::DeducedMismatch:
1010 case TemplateDeductionResult::DeducedMismatchNested:
1011 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1012
1013 default:
1014 return std::nullopt;
1015 }
1016}
1017
1018static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1019 const FunctionDecl *Y) {
1020 if (!X || !Y)
1021 return false;
1022 if (X->getNumParams() != Y->getNumParams())
1023 return false;
1024 // FIXME: when do rewritten comparison operators
1025 // with explicit object parameters correspond?
1026 // https://cplusplus.github.io/CWG/issues/2797.html
1027 for (unsigned I = 0; I < X->getNumParams(); ++I)
1028 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1029 T2: Y->getParamDecl(i: I)->getType()))
1030 return false;
1031 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1032 auto *FTY = Y->getDescribedFunctionTemplate();
1033 if (!FTY)
1034 return false;
1035 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1036 Y: FTY->getTemplateParameters()))
1037 return false;
1038 }
1039 return true;
1040}
1041
1042static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1043 Expr *FirstOperand, FunctionDecl *EqFD) {
1044 assert(EqFD->getOverloadedOperator() ==
1045 OverloadedOperatorKind::OO_EqualEqual);
1046 // C++2a [over.match.oper]p4:
1047 // A non-template function or function template F named operator== is a
1048 // rewrite target with first operand o unless a search for the name operator!=
1049 // in the scope S from the instantiation context of the operator expression
1050 // finds a function or function template that would correspond
1051 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1052 // scope of the class type of o if F is a class member, and the namespace
1053 // scope of which F is a member otherwise. A function template specialization
1054 // named operator== is a rewrite target if its function template is a rewrite
1055 // target.
1056 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1057 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1058 if (isa<CXXMethodDecl>(Val: EqFD)) {
1059 // If F is a class member, search scope is class type of first operand.
1060 QualType RHS = FirstOperand->getType();
1061 auto *RHSRec = RHS->getAs<RecordType>();
1062 if (!RHSRec)
1063 return true;
1064 LookupResult Members(S, NotEqOp, OpLoc,
1065 Sema::LookupNameKind::LookupMemberName);
1066 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec->getDecl());
1067 Members.suppressAccessDiagnostics();
1068 for (NamedDecl *Op : Members)
1069 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1070 return false;
1071 return true;
1072 }
1073 // Otherwise the search scope is the namespace scope of which F is a member.
1074 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1075 auto *NotEqFD = Op->getAsFunction();
1076 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1077 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1078 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1079 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1080 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1081 return false;
1082 }
1083 return true;
1084}
1085
1086bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1087 OverloadedOperatorKind Op) {
1088 if (!AllowRewrittenCandidates)
1089 return false;
1090 return Op == OO_EqualEqual || Op == OO_Spaceship;
1091}
1092
1093bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1094 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1095 auto Op = FD->getOverloadedOperator();
1096 if (!allowsReversed(Op))
1097 return false;
1098 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1099 assert(OriginalArgs.size() == 2);
1100 if (!shouldAddReversedEqEq(
1101 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1102 return false;
1103 }
1104 // Don't bother adding a reversed candidate that can never be a better
1105 // match than the non-reversed version.
1106 return FD->getNumNonObjectParams() != 2 ||
1107 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1108 T2: FD->getParamDecl(i: 1)->getType()) ||
1109 FD->hasAttr<EnableIfAttr>();
1110}
1111
1112void OverloadCandidateSet::destroyCandidates() {
1113 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1114 for (auto &C : i->Conversions)
1115 C.~ImplicitConversionSequence();
1116 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1117 i->DeductionFailure.Destroy();
1118 }
1119}
1120
1121void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1122 destroyCandidates();
1123 SlabAllocator.Reset();
1124 NumInlineBytesUsed = 0;
1125 Candidates.clear();
1126 Functions.clear();
1127 Kind = CSK;
1128 FirstDeferredCandidate = nullptr;
1129 DeferredCandidatesCount = 0;
1130 HasDeferredTemplateConstructors = false;
1131 ResolutionByPerfectCandidateIsDisabled = false;
1132}
1133
1134namespace {
1135 class UnbridgedCastsSet {
1136 struct Entry {
1137 Expr **Addr;
1138 Expr *Saved;
1139 };
1140 SmallVector<Entry, 2> Entries;
1141
1142 public:
1143 void save(Sema &S, Expr *&E) {
1144 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1145 Entry entry = { .Addr: &E, .Saved: E };
1146 Entries.push_back(Elt: entry);
1147 E = S.ObjC().stripARCUnbridgedCast(e: E);
1148 }
1149
1150 void restore() {
1151 for (SmallVectorImpl<Entry>::iterator
1152 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1153 *i->Addr = i->Saved;
1154 }
1155 };
1156}
1157
1158/// checkPlaceholderForOverload - Do any interesting placeholder-like
1159/// preprocessing on the given expression.
1160///
1161/// \param unbridgedCasts a collection to which to add unbridged casts;
1162/// without this, they will be immediately diagnosed as errors
1163///
1164/// Return true on unrecoverable error.
1165static bool
1166checkPlaceholderForOverload(Sema &S, Expr *&E,
1167 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1168 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1169 // We can't handle overloaded expressions here because overload
1170 // resolution might reasonably tweak them.
1171 if (placeholder->getKind() == BuiltinType::Overload) return false;
1172
1173 // If the context potentially accepts unbridged ARC casts, strip
1174 // the unbridged cast and add it to the collection for later restoration.
1175 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1176 unbridgedCasts) {
1177 unbridgedCasts->save(S, E);
1178 return false;
1179 }
1180
1181 // Go ahead and check everything else.
1182 ExprResult result = S.CheckPlaceholderExpr(E);
1183 if (result.isInvalid())
1184 return true;
1185
1186 E = result.get();
1187 return false;
1188 }
1189
1190 // Nothing to do.
1191 return false;
1192}
1193
1194/// checkArgPlaceholdersForOverload - Check a set of call operands for
1195/// placeholders.
1196static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1197 UnbridgedCastsSet &unbridged) {
1198 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1199 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1200 return true;
1201
1202 return false;
1203}
1204
1205OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1206 const LookupResult &Old, NamedDecl *&Match,
1207 bool NewIsUsingDecl) {
1208 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1209 I != E; ++I) {
1210 NamedDecl *OldD = *I;
1211
1212 bool OldIsUsingDecl = false;
1213 if (isa<UsingShadowDecl>(Val: OldD)) {
1214 OldIsUsingDecl = true;
1215
1216 // We can always introduce two using declarations into the same
1217 // context, even if they have identical signatures.
1218 if (NewIsUsingDecl) continue;
1219
1220 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1221 }
1222
1223 // A using-declaration does not conflict with another declaration
1224 // if one of them is hidden.
1225 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1226 continue;
1227
1228 // If either declaration was introduced by a using declaration,
1229 // we'll need to use slightly different rules for matching.
1230 // Essentially, these rules are the normal rules, except that
1231 // function templates hide function templates with different
1232 // return types or template parameter lists.
1233 bool UseMemberUsingDeclRules =
1234 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1235 !New->getFriendObjectKind();
1236
1237 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1238 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1239 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1240 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1241 continue;
1242 }
1243
1244 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1245 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1246 continue;
1247
1248 Match = *I;
1249 return OverloadKind::Match;
1250 }
1251
1252 // Builtins that have custom typechecking or have a reference should
1253 // not be overloadable or redeclarable.
1254 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1255 Match = *I;
1256 return OverloadKind::NonFunction;
1257 }
1258 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1259 // We can overload with these, which can show up when doing
1260 // redeclaration checks for UsingDecls.
1261 assert(Old.getLookupKind() == LookupUsingDeclName);
1262 } else if (isa<TagDecl>(Val: OldD)) {
1263 // We can always overload with tags by hiding them.
1264 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1265 // Optimistically assume that an unresolved using decl will
1266 // overload; if it doesn't, we'll have to diagnose during
1267 // template instantiation.
1268 //
1269 // Exception: if the scope is dependent and this is not a class
1270 // member, the using declaration can only introduce an enumerator.
1271 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1272 Match = *I;
1273 return OverloadKind::NonFunction;
1274 }
1275 } else {
1276 // (C++ 13p1):
1277 // Only function declarations can be overloaded; object and type
1278 // declarations cannot be overloaded.
1279 Match = *I;
1280 return OverloadKind::NonFunction;
1281 }
1282 }
1283
1284 // C++ [temp.friend]p1:
1285 // For a friend function declaration that is not a template declaration:
1286 // -- if the name of the friend is a qualified or unqualified template-id,
1287 // [...], otherwise
1288 // -- if the name of the friend is a qualified-id and a matching
1289 // non-template function is found in the specified class or namespace,
1290 // the friend declaration refers to that function, otherwise,
1291 // -- if the name of the friend is a qualified-id and a matching function
1292 // template is found in the specified class or namespace, the friend
1293 // declaration refers to the deduced specialization of that function
1294 // template, otherwise
1295 // -- the name shall be an unqualified-id [...]
1296 // If we get here for a qualified friend declaration, we've just reached the
1297 // third bullet. If the type of the friend is dependent, skip this lookup
1298 // until instantiation.
1299 if (New->getFriendObjectKind() && New->getQualifier() &&
1300 !New->getDescribedFunctionTemplate() &&
1301 !New->getDependentSpecializationInfo() &&
1302 !New->getType()->isDependentType()) {
1303 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1304 TemplateSpecResult.addAllDecls(Other: Old);
1305 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1306 /*QualifiedFriend*/true)) {
1307 New->setInvalidDecl();
1308 return OverloadKind::Overload;
1309 }
1310
1311 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1312 return OverloadKind::Match;
1313 }
1314
1315 return OverloadKind::Overload;
1316}
1317
1318template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1319 assert(D && "function decl should not be null");
1320 if (auto *A = D->getAttr<AttrT>())
1321 return !A->isImplicit();
1322 return false;
1323}
1324
1325static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1326 FunctionDecl *Old,
1327 bool UseMemberUsingDeclRules,
1328 bool ConsiderCudaAttrs,
1329 bool UseOverrideRules = false) {
1330 // C++ [basic.start.main]p2: This function shall not be overloaded.
1331 if (New->isMain())
1332 return false;
1333
1334 // MSVCRT user defined entry points cannot be overloaded.
1335 if (New->isMSVCRTEntryPoint())
1336 return false;
1337
1338 NamedDecl *OldDecl = Old;
1339 NamedDecl *NewDecl = New;
1340 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1341 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1342
1343 // C++ [temp.fct]p2:
1344 // A function template can be overloaded with other function templates
1345 // and with normal (non-template) functions.
1346 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1347 return true;
1348
1349 // Is the function New an overload of the function Old?
1350 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1351 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1352
1353 // Compare the signatures (C++ 1.3.10) of the two functions to
1354 // determine whether they are overloads. If we find any mismatch
1355 // in the signature, they are overloads.
1356
1357 // If either of these functions is a K&R-style function (no
1358 // prototype), then we consider them to have matching signatures.
1359 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1360 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1361 return false;
1362
1363 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1364 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1365
1366 // The signature of a function includes the types of its
1367 // parameters (C++ 1.3.10), which includes the presence or absence
1368 // of the ellipsis; see C++ DR 357).
1369 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1370 return true;
1371
1372 // For member-like friends, the enclosing class is part of the signature.
1373 if ((New->isMemberLikeConstrainedFriend() ||
1374 Old->isMemberLikeConstrainedFriend()) &&
1375 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1376 return true;
1377
1378 // Compare the parameter lists.
1379 // This can only be done once we have establish that friend functions
1380 // inhabit the same context, otherwise we might tried to instantiate
1381 // references to non-instantiated entities during constraint substitution.
1382 // GH78101.
1383 if (NewTemplate) {
1384 OldDecl = OldTemplate;
1385 NewDecl = NewTemplate;
1386 // C++ [temp.over.link]p4:
1387 // The signature of a function template consists of its function
1388 // signature, its return type and its template parameter list. The names
1389 // of the template parameters are significant only for establishing the
1390 // relationship between the template parameters and the rest of the
1391 // signature.
1392 //
1393 // We check the return type and template parameter lists for function
1394 // templates first; the remaining checks follow.
1395 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1396 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1397 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1398 bool SameReturnType = SemaRef.Context.hasSameType(
1399 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1400 // FIXME(GH58571): Match template parameter list even for non-constrained
1401 // template heads. This currently ensures that the code prior to C++20 is
1402 // not newly broken.
1403 bool ConstraintsInTemplateHead =
1404 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1405 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1406 // C++ [namespace.udecl]p11:
1407 // The set of declarations named by a using-declarator that inhabits a
1408 // class C does not include member functions and member function
1409 // templates of a base class that "correspond" to (and thus would
1410 // conflict with) a declaration of a function or function template in
1411 // C.
1412 // Comparing return types is not required for the "correspond" check to
1413 // decide whether a member introduced by a shadow declaration is hidden.
1414 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1415 !SameTemplateParameterList)
1416 return true;
1417 if (!UseMemberUsingDeclRules &&
1418 (!SameTemplateParameterList || !SameReturnType))
1419 return true;
1420 }
1421
1422 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1423 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1424
1425 int OldParamsOffset = 0;
1426 int NewParamsOffset = 0;
1427
1428 // When determining if a method is an overload from a base class, act as if
1429 // the implicit object parameter are of the same type.
1430
1431 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1432 if (M->isExplicitObjectMemberFunction()) {
1433 auto ThisType = M->getFunctionObjectParameterReferenceType();
1434 if (ThisType.isConstQualified())
1435 Q.removeConst();
1436 return Q;
1437 }
1438
1439 // We do not allow overloading based off of '__restrict'.
1440 Q.removeRestrict();
1441
1442 // We may not have applied the implicit const for a constexpr member
1443 // function yet (because we haven't yet resolved whether this is a static
1444 // or non-static member function). Add it now, on the assumption that this
1445 // is a redeclaration of OldMethod.
1446 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1447 (M->isConstexpr() || M->isConsteval()) &&
1448 !isa<CXXConstructorDecl>(Val: NewMethod))
1449 Q.addConst();
1450 return Q;
1451 };
1452
1453 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1454 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1455 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1456
1457 if (OldMethod->isExplicitObjectMemberFunction()) {
1458 BS.Quals.removeVolatile();
1459 DS.Quals.removeVolatile();
1460 }
1461
1462 return BS.Quals == DS.Quals;
1463 };
1464
1465 auto CompareType = [&](QualType Base, QualType D) {
1466 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1467 auto DS = D.getNonReferenceType().getCanonicalType().split();
1468
1469 if (!AreQualifiersEqual(BS, DS))
1470 return false;
1471
1472 if (OldMethod->isImplicitObjectMemberFunction() &&
1473 OldMethod->getParent() != NewMethod->getParent()) {
1474 QualType ParentType =
1475 SemaRef.Context.getTypeDeclType(Decl: OldMethod->getParent())
1476 .getCanonicalType();
1477 if (ParentType.getTypePtr() != BS.Ty)
1478 return false;
1479 BS.Ty = DS.Ty;
1480 }
1481
1482 // FIXME: should we ignore some type attributes here?
1483 if (BS.Ty != DS.Ty)
1484 return false;
1485
1486 if (Base->isLValueReferenceType())
1487 return D->isLValueReferenceType();
1488 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1489 };
1490
1491 // If the function is a class member, its signature includes the
1492 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1493 auto DiagnoseInconsistentRefQualifiers = [&]() {
1494 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1495 return false;
1496 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1497 return false;
1498 if (OldMethod->isExplicitObjectMemberFunction() ||
1499 NewMethod->isExplicitObjectMemberFunction())
1500 return false;
1501 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1502 NewMethod->getRefQualifier() == RQ_None)) {
1503 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1504 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1505 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1506 return true;
1507 }
1508 return false;
1509 };
1510
1511 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1512 OldParamsOffset++;
1513 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1514 NewParamsOffset++;
1515
1516 if (OldType->getNumParams() - OldParamsOffset !=
1517 NewType->getNumParams() - NewParamsOffset ||
1518 !SemaRef.FunctionParamTypesAreEqual(
1519 Old: {OldType->param_type_begin() + OldParamsOffset,
1520 OldType->param_type_end()},
1521 New: {NewType->param_type_begin() + NewParamsOffset,
1522 NewType->param_type_end()},
1523 ArgPos: nullptr)) {
1524 return true;
1525 }
1526
1527 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1528 !NewMethod->isStatic()) {
1529 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1530 const CXXMethodDecl *New) {
1531 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1532 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1533
1534 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1535 return F->getRefQualifier() == RQ_None &&
1536 !F->isExplicitObjectMemberFunction();
1537 };
1538
1539 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1540 CompareType(OldObjectType.getNonReferenceType(),
1541 NewObjectType.getNonReferenceType()))
1542 return true;
1543 return CompareType(OldObjectType, NewObjectType);
1544 }(OldMethod, NewMethod);
1545
1546 if (!HaveCorrespondingObjectParameters) {
1547 if (DiagnoseInconsistentRefQualifiers())
1548 return true;
1549 // CWG2554
1550 // and, if at least one is an explicit object member function, ignoring
1551 // object parameters
1552 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1553 !OldMethod->isExplicitObjectMemberFunction()))
1554 return true;
1555 }
1556 }
1557
1558 if (!UseOverrideRules &&
1559 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1560 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1561 OldRC = Old->getTrailingRequiresClause();
1562 if (!NewRC != !OldRC)
1563 return true;
1564 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1565 return true;
1566 if (NewRC &&
1567 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1568 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1569 return true;
1570 }
1571
1572 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1573 NewMethod->isImplicitObjectMemberFunction()) {
1574 if (DiagnoseInconsistentRefQualifiers())
1575 return true;
1576 }
1577
1578 // Though pass_object_size is placed on parameters and takes an argument, we
1579 // consider it to be a function-level modifier for the sake of function
1580 // identity. Either the function has one or more parameters with
1581 // pass_object_size or it doesn't.
1582 if (functionHasPassObjectSizeParams(FD: New) !=
1583 functionHasPassObjectSizeParams(FD: Old))
1584 return true;
1585
1586 // enable_if attributes are an order-sensitive part of the signature.
1587 for (specific_attr_iterator<EnableIfAttr>
1588 NewI = New->specific_attr_begin<EnableIfAttr>(),
1589 NewE = New->specific_attr_end<EnableIfAttr>(),
1590 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1591 OldE = Old->specific_attr_end<EnableIfAttr>();
1592 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1593 if (NewI == NewE || OldI == OldE)
1594 return true;
1595 llvm::FoldingSetNodeID NewID, OldID;
1596 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1597 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1598 if (NewID != OldID)
1599 return true;
1600 }
1601
1602 // At this point, it is known that the two functions have the same signature.
1603 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1604 // Don't allow overloading of destructors. (In theory we could, but it
1605 // would be a giant change to clang.)
1606 if (!isa<CXXDestructorDecl>(Val: New)) {
1607 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1608 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1609 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1610 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1611 "Unexpected invalid target.");
1612
1613 // Allow overloading of functions with same signature and different CUDA
1614 // target attributes.
1615 if (NewTarget != OldTarget) {
1616 // Special case: non-constexpr function is allowed to override
1617 // constexpr virtual function
1618 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1619 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1620 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1621 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1622 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1623 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1624 return false;
1625 }
1626 return true;
1627 }
1628 }
1629 }
1630 }
1631
1632 // The signatures match; this is not an overload.
1633 return false;
1634}
1635
1636bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1637 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1638 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1639 ConsiderCudaAttrs);
1640}
1641
1642bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1643 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1644 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1645 /*UseMemberUsingDeclRules=*/false,
1646 /*ConsiderCudaAttrs=*/true,
1647 /*UseOverrideRules=*/true);
1648}
1649
1650/// Tries a user-defined conversion from From to ToType.
1651///
1652/// Produces an implicit conversion sequence for when a standard conversion
1653/// is not an option. See TryImplicitConversion for more information.
1654static ImplicitConversionSequence
1655TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1656 bool SuppressUserConversions,
1657 AllowedExplicit AllowExplicit,
1658 bool InOverloadResolution,
1659 bool CStyle,
1660 bool AllowObjCWritebackConversion,
1661 bool AllowObjCConversionOnExplicit) {
1662 ImplicitConversionSequence ICS;
1663
1664 if (SuppressUserConversions) {
1665 // We're not in the case above, so there is no conversion that
1666 // we can perform.
1667 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1668 return ICS;
1669 }
1670
1671 // Attempt user-defined conversion.
1672 OverloadCandidateSet Conversions(From->getExprLoc(),
1673 OverloadCandidateSet::CSK_Normal);
1674 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1675 Conversions, AllowExplicit,
1676 AllowObjCConversionOnExplicit)) {
1677 case OR_Success:
1678 case OR_Deleted:
1679 ICS.setUserDefined();
1680 // C++ [over.ics.user]p4:
1681 // A conversion of an expression of class type to the same class
1682 // type is given Exact Match rank, and a conversion of an
1683 // expression of class type to a base class of that type is
1684 // given Conversion rank, in spite of the fact that a copy
1685 // constructor (i.e., a user-defined conversion function) is
1686 // called for those cases.
1687 if (CXXConstructorDecl *Constructor
1688 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1689 QualType FromType;
1690 SourceLocation FromLoc;
1691 // C++11 [over.ics.list]p6, per DR2137:
1692 // C++17 [over.ics.list]p6:
1693 // If C is not an initializer-list constructor and the initializer list
1694 // has a single element of type cv U, where U is X or a class derived
1695 // from X, the implicit conversion sequence has Exact Match rank if U is
1696 // X, or Conversion rank if U is derived from X.
1697 bool FromListInit = false;
1698 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1699 InitList && InitList->getNumInits() == 1 &&
1700 !S.isInitListConstructor(Ctor: Constructor)) {
1701 const Expr *SingleInit = InitList->getInit(Init: 0);
1702 FromType = SingleInit->getType();
1703 FromLoc = SingleInit->getBeginLoc();
1704 FromListInit = true;
1705 } else {
1706 FromType = From->getType();
1707 FromLoc = From->getBeginLoc();
1708 }
1709 QualType FromCanon =
1710 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1711 QualType ToCanon
1712 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1713 if ((FromCanon == ToCanon ||
1714 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1715 // Turn this into a "standard" conversion sequence, so that it
1716 // gets ranked with standard conversion sequences.
1717 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1718 ICS.setStandard();
1719 ICS.Standard.setAsIdentityConversion();
1720 ICS.Standard.setFromType(FromType);
1721 ICS.Standard.setAllToTypes(ToType);
1722 ICS.Standard.FromBracedInitList = FromListInit;
1723 ICS.Standard.CopyConstructor = Constructor;
1724 ICS.Standard.FoundCopyConstructor = Found;
1725 if (ToCanon != FromCanon)
1726 ICS.Standard.Second = ICK_Derived_To_Base;
1727 }
1728 }
1729 break;
1730
1731 case OR_Ambiguous:
1732 ICS.setAmbiguous();
1733 ICS.Ambiguous.setFromType(From->getType());
1734 ICS.Ambiguous.setToType(ToType);
1735 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1736 Cand != Conversions.end(); ++Cand)
1737 if (Cand->Best)
1738 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1739 break;
1740
1741 // Fall through.
1742 case OR_No_Viable_Function:
1743 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1744 break;
1745 }
1746
1747 return ICS;
1748}
1749
1750/// TryImplicitConversion - Attempt to perform an implicit conversion
1751/// from the given expression (Expr) to the given type (ToType). This
1752/// function returns an implicit conversion sequence that can be used
1753/// to perform the initialization. Given
1754///
1755/// void f(float f);
1756/// void g(int i) { f(i); }
1757///
1758/// this routine would produce an implicit conversion sequence to
1759/// describe the initialization of f from i, which will be a standard
1760/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1761/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1762//
1763/// Note that this routine only determines how the conversion can be
1764/// performed; it does not actually perform the conversion. As such,
1765/// it will not produce any diagnostics if no conversion is available,
1766/// but will instead return an implicit conversion sequence of kind
1767/// "BadConversion".
1768///
1769/// If @p SuppressUserConversions, then user-defined conversions are
1770/// not permitted.
1771/// If @p AllowExplicit, then explicit user-defined conversions are
1772/// permitted.
1773///
1774/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1775/// writeback conversion, which allows __autoreleasing id* parameters to
1776/// be initialized with __strong id* or __weak id* arguments.
1777static ImplicitConversionSequence
1778TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1779 bool SuppressUserConversions,
1780 AllowedExplicit AllowExplicit,
1781 bool InOverloadResolution,
1782 bool CStyle,
1783 bool AllowObjCWritebackConversion,
1784 bool AllowObjCConversionOnExplicit) {
1785 ImplicitConversionSequence ICS;
1786 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1787 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1788 ICS.setStandard();
1789 return ICS;
1790 }
1791
1792 if (!S.getLangOpts().CPlusPlus) {
1793 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1794 return ICS;
1795 }
1796
1797 // C++ [over.ics.user]p4:
1798 // A conversion of an expression of class type to the same class
1799 // type is given Exact Match rank, and a conversion of an
1800 // expression of class type to a base class of that type is
1801 // given Conversion rank, in spite of the fact that a copy/move
1802 // constructor (i.e., a user-defined conversion function) is
1803 // called for those cases.
1804 QualType FromType = From->getType();
1805 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1806 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1807 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1808 ICS.setStandard();
1809 ICS.Standard.setAsIdentityConversion();
1810 ICS.Standard.setFromType(FromType);
1811 ICS.Standard.setAllToTypes(ToType);
1812
1813 // We don't actually check at this point whether there is a valid
1814 // copy/move constructor, since overloading just assumes that it
1815 // exists. When we actually perform initialization, we'll find the
1816 // appropriate constructor to copy the returned object, if needed.
1817 ICS.Standard.CopyConstructor = nullptr;
1818
1819 // Determine whether this is considered a derived-to-base conversion.
1820 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1821 ICS.Standard.Second = ICK_Derived_To_Base;
1822
1823 return ICS;
1824 }
1825
1826 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1827 FromType->isHLSLAttributedResourceType()) {
1828 auto *ToResType = cast<HLSLAttributedResourceType>(Val&: ToType);
1829 auto *FromResType = cast<HLSLAttributedResourceType>(Val&: FromType);
1830 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1831 T2: FromResType->getWrappedType()) &&
1832 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1833 T2: FromResType->getContainedType()) &&
1834 ToResType->getAttrs() == FromResType->getAttrs()) {
1835 ICS.setStandard();
1836 ICS.Standard.setAsIdentityConversion();
1837 ICS.Standard.setFromType(FromType);
1838 ICS.Standard.setAllToTypes(ToType);
1839 return ICS;
1840 }
1841 }
1842
1843 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1844 AllowExplicit, InOverloadResolution, CStyle,
1845 AllowObjCWritebackConversion,
1846 AllowObjCConversionOnExplicit);
1847}
1848
1849ImplicitConversionSequence
1850Sema::TryImplicitConversion(Expr *From, QualType ToType,
1851 bool SuppressUserConversions,
1852 AllowedExplicit AllowExplicit,
1853 bool InOverloadResolution,
1854 bool CStyle,
1855 bool AllowObjCWritebackConversion) {
1856 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1857 AllowExplicit, InOverloadResolution, CStyle,
1858 AllowObjCWritebackConversion,
1859 /*AllowObjCConversionOnExplicit=*/false);
1860}
1861
1862ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1863 AssignmentAction Action,
1864 bool AllowExplicit) {
1865 if (checkPlaceholderForOverload(S&: *this, E&: From))
1866 return ExprError();
1867
1868 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1869 bool AllowObjCWritebackConversion =
1870 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1871 Action == AssignmentAction::Sending);
1872 if (getLangOpts().ObjC)
1873 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1874 SrcType: From->getType(), SrcExpr&: From);
1875 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1876 S&: *this, From, ToType,
1877 /*SuppressUserConversions=*/false,
1878 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1879 /*InOverloadResolution=*/false,
1880 /*CStyle=*/false, AllowObjCWritebackConversion,
1881 /*AllowObjCConversionOnExplicit=*/false);
1882 return PerformImplicitConversion(From, ToType, ICS, Action);
1883}
1884
1885bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1886 QualType &ResultTy) const {
1887 bool Changed = IsFunctionConversion(FromType, ToType);
1888 if (Changed)
1889 ResultTy = ToType;
1890 return Changed;
1891}
1892
1893bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1894 bool *DiscardingCFIUncheckedCallee,
1895 bool *AddingCFIUncheckedCallee) const {
1896 if (DiscardingCFIUncheckedCallee)
1897 *DiscardingCFIUncheckedCallee = false;
1898 if (AddingCFIUncheckedCallee)
1899 *AddingCFIUncheckedCallee = false;
1900
1901 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1902 return false;
1903
1904 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1905 // or F(t noexcept) -> F(t)
1906 // where F adds one of the following at most once:
1907 // - a pointer
1908 // - a member pointer
1909 // - a block pointer
1910 // Changes here need matching changes in FindCompositePointerType.
1911 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1912 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1913 Type::TypeClass TyClass = CanTo->getTypeClass();
1914 if (TyClass != CanFrom->getTypeClass()) return false;
1915 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1916 if (TyClass == Type::Pointer) {
1917 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1918 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1919 } else if (TyClass == Type::BlockPointer) {
1920 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1921 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1922 } else if (TyClass == Type::MemberPointer) {
1923 auto ToMPT = CanTo.castAs<MemberPointerType>();
1924 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1925 // A function pointer conversion cannot change the class of the function.
1926 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1927 D2: FromMPT->getMostRecentCXXRecordDecl()))
1928 return false;
1929 CanTo = ToMPT->getPointeeType();
1930 CanFrom = FromMPT->getPointeeType();
1931 } else {
1932 return false;
1933 }
1934
1935 TyClass = CanTo->getTypeClass();
1936 if (TyClass != CanFrom->getTypeClass()) return false;
1937 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1938 return false;
1939 }
1940
1941 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1942 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1943
1944 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1945 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1946
1947 bool Changed = false;
1948
1949 // Drop 'noreturn' if not present in target type.
1950 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1951 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1952 Changed = true;
1953 }
1954
1955 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1956 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1957
1958 if (FromFPT && ToFPT) {
1959 if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1960 QualType NewTy = Context.getFunctionType(
1961 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1962 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(CFIUncheckedCallee: false));
1963 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1964 FromFn = FromFPT;
1965 Changed = true;
1966 if (DiscardingCFIUncheckedCallee)
1967 *DiscardingCFIUncheckedCallee = true;
1968 } else if (!FromFPT->hasCFIUncheckedCallee() &&
1969 ToFPT->hasCFIUncheckedCallee()) {
1970 QualType NewTy = Context.getFunctionType(
1971 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1972 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(CFIUncheckedCallee: true));
1973 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1974 FromFn = FromFPT;
1975 Changed = true;
1976 if (AddingCFIUncheckedCallee)
1977 *AddingCFIUncheckedCallee = true;
1978 }
1979 }
1980
1981 // Drop 'noexcept' if not present in target type.
1982 if (FromFPT) {
1983 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1984 FromFn = cast<FunctionType>(
1985 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1986 ESI: EST_None)
1987 .getTypePtr());
1988 Changed = true;
1989 }
1990
1991 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1992 // only if the ExtParameterInfo lists of the two function prototypes can be
1993 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1994 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1995 bool CanUseToFPT, CanUseFromFPT;
1996 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
1997 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
1998 CanUseToFPT && !CanUseFromFPT) {
1999 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2000 ExtInfo.ExtParameterInfos =
2001 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2002 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2003 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2004 FromFn = QT->getAs<FunctionType>();
2005 Changed = true;
2006 }
2007
2008 // For C, when called from checkPointerTypesForAssignment,
2009 // we need to not alter FromFn, or else even an innocuous cast
2010 // like dropping effects will fail. In C++ however we do want to
2011 // alter FromFn (because of the way PerformImplicitConversion works).
2012 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2013 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2014
2015 // Transparently add/drop effects; here we are concerned with
2016 // language rules/canonicalization. Adding/dropping effects is a warning.
2017 const auto FromFX = FromFPT->getFunctionEffects();
2018 const auto ToFX = ToFPT->getFunctionEffects();
2019 if (FromFX != ToFX) {
2020 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2021 ExtInfo.FunctionEffects = ToFX;
2022 QualType QT = Context.getFunctionType(
2023 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2024 FromFn = QT->getAs<FunctionType>();
2025 Changed = true;
2026 }
2027 }
2028 }
2029
2030 if (!Changed)
2031 return false;
2032
2033 assert(QualType(FromFn, 0).isCanonical());
2034 if (QualType(FromFn, 0) != CanTo) return false;
2035
2036 return true;
2037}
2038
2039/// Determine whether the conversion from FromType to ToType is a valid
2040/// floating point conversion.
2041///
2042static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2043 QualType ToType) {
2044 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2045 return false;
2046 // FIXME: disable conversions between long double, __ibm128 and __float128
2047 // if their representation is different until there is back end support
2048 // We of course allow this conversion if long double is really double.
2049
2050 // Conversions between bfloat16 and float16 are currently not supported.
2051 if ((FromType->isBFloat16Type() &&
2052 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2053 (ToType->isBFloat16Type() &&
2054 (FromType->isFloat16Type() || FromType->isHalfType())))
2055 return false;
2056
2057 // Conversions between IEEE-quad and IBM-extended semantics are not
2058 // permitted.
2059 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2060 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2061 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2062 &ToSem == &llvm::APFloat::IEEEquad()) ||
2063 (&FromSem == &llvm::APFloat::IEEEquad() &&
2064 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2065 return false;
2066 return true;
2067}
2068
2069static bool IsVectorElementConversion(Sema &S, QualType FromType,
2070 QualType ToType,
2071 ImplicitConversionKind &ICK, Expr *From) {
2072 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2073 return true;
2074
2075 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2076 ICK = ICK_Floating_Promotion;
2077 return true;
2078 }
2079
2080 if (IsFloatingPointConversion(S, FromType, ToType)) {
2081 ICK = ICK_Floating_Conversion;
2082 return true;
2083 }
2084
2085 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2086 ICK = ICK_Boolean_Conversion;
2087 return true;
2088 }
2089
2090 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2091 (FromType->isIntegralOrUnscopedEnumerationType() &&
2092 ToType->isRealFloatingType())) {
2093 ICK = ICK_Floating_Integral;
2094 return true;
2095 }
2096
2097 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2098 ICK = ICK_Integral_Promotion;
2099 return true;
2100 }
2101
2102 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2103 ToType->isIntegralType(Ctx: S.Context)) {
2104 ICK = ICK_Integral_Conversion;
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
2111/// Determine whether the conversion from FromType to ToType is a valid
2112/// vector conversion.
2113///
2114/// \param ICK Will be set to the vector conversion kind, if this is a vector
2115/// conversion.
2116static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2117 ImplicitConversionKind &ICK,
2118 ImplicitConversionKind &ElConv, Expr *From,
2119 bool InOverloadResolution, bool CStyle) {
2120 // We need at least one of these types to be a vector type to have a vector
2121 // conversion.
2122 if (!ToType->isVectorType() && !FromType->isVectorType())
2123 return false;
2124
2125 // Identical types require no conversions.
2126 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2127 return false;
2128
2129 // HLSL allows implicit truncation of vector types.
2130 if (S.getLangOpts().HLSL) {
2131 auto *ToExtType = ToType->getAs<ExtVectorType>();
2132 auto *FromExtType = FromType->getAs<ExtVectorType>();
2133
2134 // If both arguments are vectors, handle possible vector truncation and
2135 // element conversion.
2136 if (ToExtType && FromExtType) {
2137 unsigned FromElts = FromExtType->getNumElements();
2138 unsigned ToElts = ToExtType->getNumElements();
2139 if (FromElts < ToElts)
2140 return false;
2141 if (FromElts == ToElts)
2142 ElConv = ICK_Identity;
2143 else
2144 ElConv = ICK_HLSL_Vector_Truncation;
2145
2146 QualType FromElTy = FromExtType->getElementType();
2147 QualType ToElTy = ToExtType->getElementType();
2148 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2149 return true;
2150 return IsVectorElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2151 }
2152 if (FromExtType && !ToExtType) {
2153 ElConv = ICK_HLSL_Vector_Truncation;
2154 QualType FromElTy = FromExtType->getElementType();
2155 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2156 return true;
2157 return IsVectorElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2158 }
2159 // Fallthrough for the case where ToType is a vector and FromType is not.
2160 }
2161
2162 // There are no conversions between extended vector types, only identity.
2163 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2164 if (FromType->getAs<ExtVectorType>()) {
2165 // There are no conversions between extended vector types other than the
2166 // identity conversion.
2167 return false;
2168 }
2169
2170 // Vector splat from any arithmetic type to a vector.
2171 if (FromType->isArithmeticType()) {
2172 if (S.getLangOpts().HLSL) {
2173 ElConv = ICK_HLSL_Vector_Splat;
2174 QualType ToElTy = ToExtType->getElementType();
2175 return IsVectorElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2176 }
2177 ICK = ICK_Vector_Splat;
2178 return true;
2179 }
2180 }
2181
2182 if (ToType->isSVESizelessBuiltinType() ||
2183 FromType->isSVESizelessBuiltinType())
2184 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2185 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2186 ICK = ICK_SVE_Vector_Conversion;
2187 return true;
2188 }
2189
2190 if (ToType->isRVVSizelessBuiltinType() ||
2191 FromType->isRVVSizelessBuiltinType())
2192 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2193 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2194 ICK = ICK_RVV_Vector_Conversion;
2195 return true;
2196 }
2197
2198 // We can perform the conversion between vector types in the following cases:
2199 // 1)vector types are equivalent AltiVec and GCC vector types
2200 // 2)lax vector conversions are permitted and the vector types are of the
2201 // same size
2202 // 3)the destination type does not have the ARM MVE strict-polymorphism
2203 // attribute, which inhibits lax vector conversion for overload resolution
2204 // only
2205 if (ToType->isVectorType() && FromType->isVectorType()) {
2206 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2207 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2208 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2209 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2210 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2211 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2212 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2213 !InOverloadResolution && !CStyle) {
2214 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2215 << FromType << ToType;
2216 }
2217 ICK = ICK_Vector_Conversion;
2218 return true;
2219 }
2220 }
2221
2222 return false;
2223}
2224
2225static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2226 bool InOverloadResolution,
2227 StandardConversionSequence &SCS,
2228 bool CStyle);
2229
2230/// IsStandardConversion - Determines whether there is a standard
2231/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2232/// expression From to the type ToType. Standard conversion sequences
2233/// only consider non-class types; for conversions that involve class
2234/// types, use TryImplicitConversion. If a conversion exists, SCS will
2235/// contain the standard conversion sequence required to perform this
2236/// conversion and this routine will return true. Otherwise, this
2237/// routine will return false and the value of SCS is unspecified.
2238static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2239 bool InOverloadResolution,
2240 StandardConversionSequence &SCS,
2241 bool CStyle,
2242 bool AllowObjCWritebackConversion) {
2243 QualType FromType = From->getType();
2244
2245 // Standard conversions (C++ [conv])
2246 SCS.setAsIdentityConversion();
2247 SCS.IncompatibleObjC = false;
2248 SCS.setFromType(FromType);
2249 SCS.CopyConstructor = nullptr;
2250
2251 // There are no standard conversions for class types in C++, so
2252 // abort early. When overloading in C, however, we do permit them.
2253 if (S.getLangOpts().CPlusPlus &&
2254 (FromType->isRecordType() || ToType->isRecordType()))
2255 return false;
2256
2257 // The first conversion can be an lvalue-to-rvalue conversion,
2258 // array-to-pointer conversion, or function-to-pointer conversion
2259 // (C++ 4p1).
2260
2261 if (FromType == S.Context.OverloadTy) {
2262 DeclAccessPair AccessPair;
2263 if (FunctionDecl *Fn
2264 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2265 Found&: AccessPair)) {
2266 // We were able to resolve the address of the overloaded function,
2267 // so we can convert to the type of that function.
2268 FromType = Fn->getType();
2269 SCS.setFromType(FromType);
2270
2271 // we can sometimes resolve &foo<int> regardless of ToType, so check
2272 // if the type matches (identity) or we are converting to bool
2273 if (!S.Context.hasSameUnqualifiedType(
2274 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2275 // if the function type matches except for [[noreturn]], it's ok
2276 if (!S.IsFunctionConversion(FromType,
2277 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2278 // otherwise, only a boolean conversion is standard
2279 if (!ToType->isBooleanType())
2280 return false;
2281 }
2282
2283 // Check if the "from" expression is taking the address of an overloaded
2284 // function and recompute the FromType accordingly. Take advantage of the
2285 // fact that non-static member functions *must* have such an address-of
2286 // expression.
2287 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2288 if (Method && !Method->isStatic() &&
2289 !Method->isExplicitObjectMemberFunction()) {
2290 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2291 "Non-unary operator on non-static member address");
2292 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2293 == UO_AddrOf &&
2294 "Non-address-of operator on non-static member address");
2295 FromType = S.Context.getMemberPointerType(
2296 T: FromType, /*Qualifier=*/nullptr, Cls: Method->getParent());
2297 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2298 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2299 UO_AddrOf &&
2300 "Non-address-of operator for overloaded function expression");
2301 FromType = S.Context.getPointerType(T: FromType);
2302 }
2303 } else {
2304 return false;
2305 }
2306 }
2307
2308 bool argIsLValue = From->isGLValue();
2309 // To handle conversion from ArrayParameterType to ConstantArrayType
2310 // this block must be above the one below because Array parameters
2311 // do not decay and when handling HLSLOutArgExprs and
2312 // the From expression is an LValue.
2313 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2314 ToType->isConstantArrayType()) {
2315 // HLSL constant array parameters do not decay, so if the argument is a
2316 // constant array and the parameter is an ArrayParameterType we have special
2317 // handling here.
2318 if (ToType->isArrayParameterType()) {
2319 FromType = S.Context.getArrayParameterType(Ty: FromType);
2320 } else if (FromType->isArrayParameterType()) {
2321 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2322 FromType = APT->getConstantArrayType(Ctx: S.Context);
2323 }
2324
2325 SCS.First = ICK_HLSL_Array_RValue;
2326
2327 // Don't consider qualifiers, which include things like address spaces
2328 if (FromType.getCanonicalType().getUnqualifiedType() !=
2329 ToType.getCanonicalType().getUnqualifiedType())
2330 return false;
2331
2332 SCS.setAllToTypes(ToType);
2333 return true;
2334 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2335 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2336 // Lvalue-to-rvalue conversion (C++11 4.1):
2337 // A glvalue (3.10) of a non-function, non-array type T can
2338 // be converted to a prvalue.
2339
2340 SCS.First = ICK_Lvalue_To_Rvalue;
2341
2342 // C11 6.3.2.1p2:
2343 // ... if the lvalue has atomic type, the value has the non-atomic version
2344 // of the type of the lvalue ...
2345 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2346 FromType = Atomic->getValueType();
2347
2348 // If T is a non-class type, the type of the rvalue is the
2349 // cv-unqualified version of T. Otherwise, the type of the rvalue
2350 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2351 // just strip the qualifiers because they don't matter.
2352 FromType = FromType.getUnqualifiedType();
2353 } else if (FromType->isArrayType()) {
2354 // Array-to-pointer conversion (C++ 4.2)
2355 SCS.First = ICK_Array_To_Pointer;
2356
2357 // An lvalue or rvalue of type "array of N T" or "array of unknown
2358 // bound of T" can be converted to an rvalue of type "pointer to
2359 // T" (C++ 4.2p1).
2360 FromType = S.Context.getArrayDecayedType(T: FromType);
2361
2362 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2363 // This conversion is deprecated in C++03 (D.4)
2364 SCS.DeprecatedStringLiteralToCharPtr = true;
2365
2366 // For the purpose of ranking in overload resolution
2367 // (13.3.3.1.1), this conversion is considered an
2368 // array-to-pointer conversion followed by a qualification
2369 // conversion (4.4). (C++ 4.2p2)
2370 SCS.Second = ICK_Identity;
2371 SCS.Third = ICK_Qualification;
2372 SCS.QualificationIncludesObjCLifetime = false;
2373 SCS.setAllToTypes(FromType);
2374 return true;
2375 }
2376 } else if (FromType->isFunctionType() && argIsLValue) {
2377 // Function-to-pointer conversion (C++ 4.3).
2378 SCS.First = ICK_Function_To_Pointer;
2379
2380 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2381 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2382 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2383 return false;
2384
2385 // An lvalue of function type T can be converted to an rvalue of
2386 // type "pointer to T." The result is a pointer to the
2387 // function. (C++ 4.3p1).
2388 FromType = S.Context.getPointerType(T: FromType);
2389 } else {
2390 // We don't require any conversions for the first step.
2391 SCS.First = ICK_Identity;
2392 }
2393 SCS.setToType(Idx: 0, T: FromType);
2394
2395 // The second conversion can be an integral promotion, floating
2396 // point promotion, integral conversion, floating point conversion,
2397 // floating-integral conversion, pointer conversion,
2398 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2399 // For overloading in C, this can also be a "compatible-type"
2400 // conversion.
2401 bool IncompatibleObjC = false;
2402 ImplicitConversionKind SecondICK = ICK_Identity;
2403 ImplicitConversionKind DimensionICK = ICK_Identity;
2404 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2405 // The unqualified versions of the types are the same: there's no
2406 // conversion to do.
2407 SCS.Second = ICK_Identity;
2408 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2409 // Integral promotion (C++ 4.5).
2410 SCS.Second = ICK_Integral_Promotion;
2411 FromType = ToType.getUnqualifiedType();
2412 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2413 // Floating point promotion (C++ 4.6).
2414 SCS.Second = ICK_Floating_Promotion;
2415 FromType = ToType.getUnqualifiedType();
2416 } else if (S.IsComplexPromotion(FromType, ToType)) {
2417 // Complex promotion (Clang extension)
2418 SCS.Second = ICK_Complex_Promotion;
2419 FromType = ToType.getUnqualifiedType();
2420 } else if (ToType->isBooleanType() &&
2421 (FromType->isArithmeticType() ||
2422 FromType->isAnyPointerType() ||
2423 FromType->isBlockPointerType() ||
2424 FromType->isMemberPointerType())) {
2425 // Boolean conversions (C++ 4.12).
2426 SCS.Second = ICK_Boolean_Conversion;
2427 FromType = S.Context.BoolTy;
2428 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2429 ToType->isIntegralType(Ctx: S.Context)) {
2430 // Integral conversions (C++ 4.7).
2431 SCS.Second = ICK_Integral_Conversion;
2432 FromType = ToType.getUnqualifiedType();
2433 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2434 // Complex conversions (C99 6.3.1.6)
2435 SCS.Second = ICK_Complex_Conversion;
2436 FromType = ToType.getUnqualifiedType();
2437 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2438 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2439 // Complex-real conversions (C99 6.3.1.7)
2440 SCS.Second = ICK_Complex_Real;
2441 FromType = ToType.getUnqualifiedType();
2442 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2443 // Floating point conversions (C++ 4.8).
2444 SCS.Second = ICK_Floating_Conversion;
2445 FromType = ToType.getUnqualifiedType();
2446 } else if ((FromType->isRealFloatingType() &&
2447 ToType->isIntegralType(Ctx: S.Context)) ||
2448 (FromType->isIntegralOrUnscopedEnumerationType() &&
2449 ToType->isRealFloatingType())) {
2450
2451 // Floating-integral conversions (C++ 4.9).
2452 SCS.Second = ICK_Floating_Integral;
2453 FromType = ToType.getUnqualifiedType();
2454 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2455 SCS.Second = ICK_Block_Pointer_Conversion;
2456 } else if (AllowObjCWritebackConversion &&
2457 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2458 SCS.Second = ICK_Writeback_Conversion;
2459 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2460 ConvertedType&: FromType, IncompatibleObjC)) {
2461 // Pointer conversions (C++ 4.10).
2462 SCS.Second = ICK_Pointer_Conversion;
2463 SCS.IncompatibleObjC = IncompatibleObjC;
2464 FromType = FromType.getUnqualifiedType();
2465 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2466 InOverloadResolution, ConvertedType&: FromType)) {
2467 // Pointer to member conversions (4.11).
2468 SCS.Second = ICK_Pointer_Member;
2469 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2470 From, InOverloadResolution, CStyle)) {
2471 SCS.Second = SecondICK;
2472 SCS.Dimension = DimensionICK;
2473 FromType = ToType.getUnqualifiedType();
2474 } else if (!S.getLangOpts().CPlusPlus &&
2475 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2476 // Compatible conversions (Clang extension for C function overloading)
2477 SCS.Second = ICK_Compatible_Conversion;
2478 FromType = ToType.getUnqualifiedType();
2479 } else if (IsTransparentUnionStandardConversion(
2480 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2481 SCS.Second = ICK_TransparentUnionConversion;
2482 FromType = ToType;
2483 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2484 CStyle)) {
2485 // tryAtomicConversion has updated the standard conversion sequence
2486 // appropriately.
2487 return true;
2488 } else if (ToType->isEventT() &&
2489 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2490 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2491 SCS.Second = ICK_Zero_Event_Conversion;
2492 FromType = ToType;
2493 } else if (ToType->isQueueT() &&
2494 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2495 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2496 SCS.Second = ICK_Zero_Queue_Conversion;
2497 FromType = ToType;
2498 } else if (ToType->isSamplerT() &&
2499 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2500 SCS.Second = ICK_Compatible_Conversion;
2501 FromType = ToType;
2502 } else if ((ToType->isFixedPointType() &&
2503 FromType->isConvertibleToFixedPointType()) ||
2504 (FromType->isFixedPointType() &&
2505 ToType->isConvertibleToFixedPointType())) {
2506 SCS.Second = ICK_Fixed_Point_Conversion;
2507 FromType = ToType;
2508 } else {
2509 // No second conversion required.
2510 SCS.Second = ICK_Identity;
2511 }
2512 SCS.setToType(Idx: 1, T: FromType);
2513
2514 // The third conversion can be a function pointer conversion or a
2515 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2516 bool ObjCLifetimeConversion;
2517 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2518 // Function pointer conversions (removing 'noexcept') including removal of
2519 // 'noreturn' (Clang extension).
2520 SCS.Third = ICK_Function_Conversion;
2521 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2522 ObjCLifetimeConversion)) {
2523 SCS.Third = ICK_Qualification;
2524 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2525 FromType = ToType;
2526 } else {
2527 // No conversion required
2528 SCS.Third = ICK_Identity;
2529 }
2530
2531 // C++ [over.best.ics]p6:
2532 // [...] Any difference in top-level cv-qualification is
2533 // subsumed by the initialization itself and does not constitute
2534 // a conversion. [...]
2535 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2536 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2537 if (CanonFrom.getLocalUnqualifiedType()
2538 == CanonTo.getLocalUnqualifiedType() &&
2539 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2540 FromType = ToType;
2541 CanonFrom = CanonTo;
2542 }
2543
2544 SCS.setToType(Idx: 2, T: FromType);
2545
2546 // If we have not converted the argument type to the parameter type,
2547 // this is a bad conversion sequence, unless we're resolving an overload in C.
2548 //
2549 // Permit conversions from a function without `cfi_unchecked_callee` to a
2550 // function with `cfi_unchecked_callee`.
2551 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(From: CanonFrom, To: CanonTo))
2552 return true;
2553
2554 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2555 return false;
2556
2557 ExprResult ER = ExprResult{From};
2558 AssignConvertType Conv =
2559 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2560 /*Diagnose=*/false,
2561 /*DiagnoseCFAudited=*/false,
2562 /*ConvertRHS=*/false);
2563 ImplicitConversionKind SecondConv;
2564 switch (Conv) {
2565 case AssignConvertType::Compatible:
2566 case AssignConvertType::
2567 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2568 SecondConv = ICK_C_Only_Conversion;
2569 break;
2570 // For our purposes, discarding qualifiers is just as bad as using an
2571 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2572 // qualifiers, as well.
2573 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2574 case AssignConvertType::IncompatiblePointer:
2575 case AssignConvertType::IncompatiblePointerSign:
2576 SecondConv = ICK_Incompatible_Pointer_Conversion;
2577 break;
2578 default:
2579 return false;
2580 }
2581
2582 // First can only be an lvalue conversion, so we pretend that this was the
2583 // second conversion. First should already be valid from earlier in the
2584 // function.
2585 SCS.Second = SecondConv;
2586 SCS.setToType(Idx: 1, T: ToType);
2587
2588 // Third is Identity, because Second should rank us worse than any other
2589 // conversion. This could also be ICK_Qualification, but it's simpler to just
2590 // lump everything in with the second conversion, and we don't gain anything
2591 // from making this ICK_Qualification.
2592 SCS.Third = ICK_Identity;
2593 SCS.setToType(Idx: 2, T: ToType);
2594 return true;
2595}
2596
2597static bool
2598IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2599 QualType &ToType,
2600 bool InOverloadResolution,
2601 StandardConversionSequence &SCS,
2602 bool CStyle) {
2603
2604 const RecordType *UT = ToType->getAsUnionType();
2605 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2606 return false;
2607 // The field to initialize within the transparent union.
2608 RecordDecl *UD = UT->getDecl();
2609 // It's compatible if the expression matches any of the fields.
2610 for (const auto *it : UD->fields()) {
2611 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2612 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2613 ToType = it->getType();
2614 return true;
2615 }
2616 }
2617 return false;
2618}
2619
2620bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2621 const BuiltinType *To = ToType->getAs<BuiltinType>();
2622 // All integers are built-in.
2623 if (!To) {
2624 return false;
2625 }
2626
2627 // An rvalue of type char, signed char, unsigned char, short int, or
2628 // unsigned short int can be converted to an rvalue of type int if
2629 // int can represent all the values of the source type; otherwise,
2630 // the source rvalue can be converted to an rvalue of type unsigned
2631 // int (C++ 4.5p1).
2632 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2633 !FromType->isEnumeralType()) {
2634 if ( // We can promote any signed, promotable integer type to an int
2635 (FromType->isSignedIntegerType() ||
2636 // We can promote any unsigned integer type whose size is
2637 // less than int to an int.
2638 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2639 return To->getKind() == BuiltinType::Int;
2640 }
2641
2642 return To->getKind() == BuiltinType::UInt;
2643 }
2644
2645 // C++11 [conv.prom]p3:
2646 // A prvalue of an unscoped enumeration type whose underlying type is not
2647 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2648 // following types that can represent all the values of the enumeration
2649 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2650 // unsigned int, long int, unsigned long int, long long int, or unsigned
2651 // long long int. If none of the types in that list can represent all the
2652 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2653 // type can be converted to an rvalue a prvalue of the extended integer type
2654 // with lowest integer conversion rank (4.13) greater than the rank of long
2655 // long in which all the values of the enumeration can be represented. If
2656 // there are two such extended types, the signed one is chosen.
2657 // C++11 [conv.prom]p4:
2658 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2659 // can be converted to a prvalue of its underlying type. Moreover, if
2660 // integral promotion can be applied to its underlying type, a prvalue of an
2661 // unscoped enumeration type whose underlying type is fixed can also be
2662 // converted to a prvalue of the promoted underlying type.
2663 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2664 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2665 // provided for a scoped enumeration.
2666 if (FromEnumType->getDecl()->isScoped())
2667 return false;
2668
2669 // We can perform an integral promotion to the underlying type of the enum,
2670 // even if that's not the promoted type. Note that the check for promoting
2671 // the underlying type is based on the type alone, and does not consider
2672 // the bitfield-ness of the actual source expression.
2673 if (FromEnumType->getDecl()->isFixed()) {
2674 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2675 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2676 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2677 }
2678
2679 // We have already pre-calculated the promotion type, so this is trivial.
2680 if (ToType->isIntegerType() &&
2681 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2682 return Context.hasSameUnqualifiedType(
2683 T1: ToType, T2: FromEnumType->getDecl()->getPromotionType());
2684
2685 // C++ [conv.prom]p5:
2686 // If the bit-field has an enumerated type, it is treated as any other
2687 // value of that type for promotion purposes.
2688 //
2689 // ... so do not fall through into the bit-field checks below in C++.
2690 if (getLangOpts().CPlusPlus)
2691 return false;
2692 }
2693
2694 // C++0x [conv.prom]p2:
2695 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2696 // to an rvalue a prvalue of the first of the following types that can
2697 // represent all the values of its underlying type: int, unsigned int,
2698 // long int, unsigned long int, long long int, or unsigned long long int.
2699 // If none of the types in that list can represent all the values of its
2700 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2701 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2702 // type.
2703 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2704 ToType->isIntegerType()) {
2705 // Determine whether the type we're converting from is signed or
2706 // unsigned.
2707 bool FromIsSigned = FromType->isSignedIntegerType();
2708 uint64_t FromSize = Context.getTypeSize(T: FromType);
2709
2710 // The types we'll try to promote to, in the appropriate
2711 // order. Try each of these types.
2712 QualType PromoteTypes[6] = {
2713 Context.IntTy, Context.UnsignedIntTy,
2714 Context.LongTy, Context.UnsignedLongTy ,
2715 Context.LongLongTy, Context.UnsignedLongLongTy
2716 };
2717 for (int Idx = 0; Idx < 6; ++Idx) {
2718 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2719 if (FromSize < ToSize ||
2720 (FromSize == ToSize &&
2721 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2722 // We found the type that we can promote to. If this is the
2723 // type we wanted, we have a promotion. Otherwise, no
2724 // promotion.
2725 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2726 }
2727 }
2728 }
2729
2730 // An rvalue for an integral bit-field (9.6) can be converted to an
2731 // rvalue of type int if int can represent all the values of the
2732 // bit-field; otherwise, it can be converted to unsigned int if
2733 // unsigned int can represent all the values of the bit-field. If
2734 // the bit-field is larger yet, no integral promotion applies to
2735 // it. If the bit-field has an enumerated type, it is treated as any
2736 // other value of that type for promotion purposes (C++ 4.5p3).
2737 // FIXME: We should delay checking of bit-fields until we actually perform the
2738 // conversion.
2739 //
2740 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2741 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2742 // bit-fields and those whose underlying type is larger than int) for GCC
2743 // compatibility.
2744 if (From) {
2745 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2746 std::optional<llvm::APSInt> BitWidth;
2747 if (FromType->isIntegralType(Ctx: Context) &&
2748 (BitWidth =
2749 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2750 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2751 ToSize = Context.getTypeSize(T: ToType);
2752
2753 // Are we promoting to an int from a bitfield that fits in an int?
2754 if (*BitWidth < ToSize ||
2755 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2756 return To->getKind() == BuiltinType::Int;
2757 }
2758
2759 // Are we promoting to an unsigned int from an unsigned bitfield
2760 // that fits into an unsigned int?
2761 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2762 return To->getKind() == BuiltinType::UInt;
2763 }
2764
2765 return false;
2766 }
2767 }
2768 }
2769
2770 // An rvalue of type bool can be converted to an rvalue of type int,
2771 // with false becoming zero and true becoming one (C++ 4.5p4).
2772 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2773 return true;
2774 }
2775
2776 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2777 // integral type.
2778 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2779 ToType->isIntegerType())
2780 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2781
2782 return false;
2783}
2784
2785bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2786 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2787 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2788 /// An rvalue of type float can be converted to an rvalue of type
2789 /// double. (C++ 4.6p1).
2790 if (FromBuiltin->getKind() == BuiltinType::Float &&
2791 ToBuiltin->getKind() == BuiltinType::Double)
2792 return true;
2793
2794 // C99 6.3.1.5p1:
2795 // When a float is promoted to double or long double, or a
2796 // double is promoted to long double [...].
2797 if (!getLangOpts().CPlusPlus &&
2798 (FromBuiltin->getKind() == BuiltinType::Float ||
2799 FromBuiltin->getKind() == BuiltinType::Double) &&
2800 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2801 ToBuiltin->getKind() == BuiltinType::Float128 ||
2802 ToBuiltin->getKind() == BuiltinType::Ibm128))
2803 return true;
2804
2805 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2806 // or not native half types are enabled.
2807 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2808 (ToBuiltin->getKind() == BuiltinType::Float ||
2809 ToBuiltin->getKind() == BuiltinType::Double))
2810 return true;
2811
2812 // Half can be promoted to float.
2813 if (!getLangOpts().NativeHalfType &&
2814 FromBuiltin->getKind() == BuiltinType::Half &&
2815 ToBuiltin->getKind() == BuiltinType::Float)
2816 return true;
2817 }
2818
2819 return false;
2820}
2821
2822bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2823 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2824 if (!FromComplex)
2825 return false;
2826
2827 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2828 if (!ToComplex)
2829 return false;
2830
2831 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2832 ToType: ToComplex->getElementType()) ||
2833 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2834 ToType: ToComplex->getElementType());
2835}
2836
2837/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2838/// the pointer type FromPtr to a pointer to type ToPointee, with the
2839/// same type qualifiers as FromPtr has on its pointee type. ToType,
2840/// if non-empty, will be a pointer to ToType that may or may not have
2841/// the right set of qualifiers on its pointee.
2842///
2843static QualType
2844BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2845 QualType ToPointee, QualType ToType,
2846 ASTContext &Context,
2847 bool StripObjCLifetime = false) {
2848 assert((FromPtr->getTypeClass() == Type::Pointer ||
2849 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2850 "Invalid similarly-qualified pointer type");
2851
2852 /// Conversions to 'id' subsume cv-qualifier conversions.
2853 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2854 return ToType.getUnqualifiedType();
2855
2856 QualType CanonFromPointee
2857 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2858 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2859 Qualifiers Quals = CanonFromPointee.getQualifiers();
2860
2861 if (StripObjCLifetime)
2862 Quals.removeObjCLifetime();
2863
2864 // Exact qualifier match -> return the pointer type we're converting to.
2865 if (CanonToPointee.getLocalQualifiers() == Quals) {
2866 // ToType is exactly what we need. Return it.
2867 if (!ToType.isNull())
2868 return ToType.getUnqualifiedType();
2869
2870 // Build a pointer to ToPointee. It has the right qualifiers
2871 // already.
2872 if (isa<ObjCObjectPointerType>(Val: ToType))
2873 return Context.getObjCObjectPointerType(OIT: ToPointee);
2874 return Context.getPointerType(T: ToPointee);
2875 }
2876
2877 // Just build a canonical type that has the right qualifiers.
2878 QualType QualifiedCanonToPointee
2879 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
2880
2881 if (isa<ObjCObjectPointerType>(Val: ToType))
2882 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
2883 return Context.getPointerType(T: QualifiedCanonToPointee);
2884}
2885
2886static bool isNullPointerConstantForConversion(Expr *Expr,
2887 bool InOverloadResolution,
2888 ASTContext &Context) {
2889 // Handle value-dependent integral null pointer constants correctly.
2890 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2891 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2892 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2893 return !InOverloadResolution;
2894
2895 return Expr->isNullPointerConstant(Ctx&: Context,
2896 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2897 : Expr::NPC_ValueDependentIsNull);
2898}
2899
2900bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2901 bool InOverloadResolution,
2902 QualType& ConvertedType,
2903 bool &IncompatibleObjC) {
2904 IncompatibleObjC = false;
2905 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2906 IncompatibleObjC))
2907 return true;
2908
2909 // Conversion from a null pointer constant to any Objective-C pointer type.
2910 if (ToType->isObjCObjectPointerType() &&
2911 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2912 ConvertedType = ToType;
2913 return true;
2914 }
2915
2916 // Blocks: Block pointers can be converted to void*.
2917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2918 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2919 ConvertedType = ToType;
2920 return true;
2921 }
2922 // Blocks: A null pointer constant can be converted to a block
2923 // pointer type.
2924 if (ToType->isBlockPointerType() &&
2925 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2926 ConvertedType = ToType;
2927 return true;
2928 }
2929
2930 // If the left-hand-side is nullptr_t, the right side can be a null
2931 // pointer constant.
2932 if (ToType->isNullPtrType() &&
2933 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2934 ConvertedType = ToType;
2935 return true;
2936 }
2937
2938 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2939 if (!ToTypePtr)
2940 return false;
2941
2942 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2943 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2944 ConvertedType = ToType;
2945 return true;
2946 }
2947
2948 // Beyond this point, both types need to be pointers
2949 // , including objective-c pointers.
2950 QualType ToPointeeType = ToTypePtr->getPointeeType();
2951 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2952 !getLangOpts().ObjCAutoRefCount) {
2953 ConvertedType = BuildSimilarlyQualifiedPointerType(
2954 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
2955 Context);
2956 return true;
2957 }
2958 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2959 if (!FromTypePtr)
2960 return false;
2961
2962 QualType FromPointeeType = FromTypePtr->getPointeeType();
2963
2964 // If the unqualified pointee types are the same, this can't be a
2965 // pointer conversion, so don't do all of the work below.
2966 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
2967 return false;
2968
2969 // An rvalue of type "pointer to cv T," where T is an object type,
2970 // can be converted to an rvalue of type "pointer to cv void" (C++
2971 // 4.10p2).
2972 if (FromPointeeType->isIncompleteOrObjectType() &&
2973 ToPointeeType->isVoidType()) {
2974 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2975 ToPointee: ToPointeeType,
2976 ToType, Context,
2977 /*StripObjCLifetime=*/true);
2978 return true;
2979 }
2980
2981 // MSVC allows implicit function to void* type conversion.
2982 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2983 ToPointeeType->isVoidType()) {
2984 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2985 ToPointee: ToPointeeType,
2986 ToType, Context);
2987 return true;
2988 }
2989
2990 // When we're overloading in C, we allow a special kind of pointer
2991 // conversion for compatible-but-not-identical pointee types.
2992 if (!getLangOpts().CPlusPlus &&
2993 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
2994 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
2995 ToPointee: ToPointeeType,
2996 ToType, Context);
2997 return true;
2998 }
2999
3000 // C++ [conv.ptr]p3:
3001 //
3002 // An rvalue of type "pointer to cv D," where D is a class type,
3003 // can be converted to an rvalue of type "pointer to cv B," where
3004 // B is a base class (clause 10) of D. If B is an inaccessible
3005 // (clause 11) or ambiguous (10.2) base class of D, a program that
3006 // necessitates this conversion is ill-formed. The result of the
3007 // conversion is a pointer to the base class sub-object of the
3008 // derived class object. The null pointer value is converted to
3009 // the null pointer value of the destination type.
3010 //
3011 // Note that we do not check for ambiguity or inaccessibility
3012 // here. That is handled by CheckPointerConversion.
3013 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3014 ToPointeeType->isRecordType() &&
3015 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3016 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3017 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3018 ToPointee: ToPointeeType,
3019 ToType, Context);
3020 return true;
3021 }
3022
3023 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3024 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3026 ToPointee: ToPointeeType,
3027 ToType, Context);
3028 return true;
3029 }
3030
3031 return false;
3032}
3033
3034/// Adopt the given qualifiers for the given type.
3035static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3036 Qualifiers TQs = T.getQualifiers();
3037
3038 // Check whether qualifiers already match.
3039 if (TQs == Qs)
3040 return T;
3041
3042 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3043 return Context.getQualifiedType(T, Qs);
3044
3045 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3046}
3047
3048bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3049 QualType& ConvertedType,
3050 bool &IncompatibleObjC) {
3051 if (!getLangOpts().ObjC)
3052 return false;
3053
3054 // The set of qualifiers on the type we're converting from.
3055 Qualifiers FromQualifiers = FromType.getQualifiers();
3056
3057 // First, we handle all conversions on ObjC object pointer types.
3058 const ObjCObjectPointerType* ToObjCPtr =
3059 ToType->getAs<ObjCObjectPointerType>();
3060 const ObjCObjectPointerType *FromObjCPtr =
3061 FromType->getAs<ObjCObjectPointerType>();
3062
3063 if (ToObjCPtr && FromObjCPtr) {
3064 // If the pointee types are the same (ignoring qualifications),
3065 // then this is not a pointer conversion.
3066 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3067 T2: FromObjCPtr->getPointeeType()))
3068 return false;
3069
3070 // Conversion between Objective-C pointers.
3071 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3072 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3073 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3074 if (getLangOpts().CPlusPlus && LHS && RHS &&
3075 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3076 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3077 return false;
3078 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3079 ToPointee: ToObjCPtr->getPointeeType(),
3080 ToType, Context);
3081 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3082 return true;
3083 }
3084
3085 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3086 // Okay: this is some kind of implicit downcast of Objective-C
3087 // interfaces, which is permitted. However, we're going to
3088 // complain about it.
3089 IncompatibleObjC = true;
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3091 ToPointee: ToObjCPtr->getPointeeType(),
3092 ToType, Context);
3093 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3094 return true;
3095 }
3096 }
3097 // Beyond this point, both types need to be C pointers or block pointers.
3098 QualType ToPointeeType;
3099 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3100 ToPointeeType = ToCPtr->getPointeeType();
3101 else if (const BlockPointerType *ToBlockPtr =
3102 ToType->getAs<BlockPointerType>()) {
3103 // Objective C++: We're able to convert from a pointer to any object
3104 // to a block pointer type.
3105 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3106 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3107 return true;
3108 }
3109 ToPointeeType = ToBlockPtr->getPointeeType();
3110 }
3111 else if (FromType->getAs<BlockPointerType>() &&
3112 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3113 // Objective C++: We're able to convert from a block pointer type to a
3114 // pointer to any object.
3115 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3116 return true;
3117 }
3118 else
3119 return false;
3120
3121 QualType FromPointeeType;
3122 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3123 FromPointeeType = FromCPtr->getPointeeType();
3124 else if (const BlockPointerType *FromBlockPtr =
3125 FromType->getAs<BlockPointerType>())
3126 FromPointeeType = FromBlockPtr->getPointeeType();
3127 else
3128 return false;
3129
3130 // If we have pointers to pointers, recursively check whether this
3131 // is an Objective-C conversion.
3132 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3133 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3134 IncompatibleObjC)) {
3135 // We always complain about this conversion.
3136 IncompatibleObjC = true;
3137 ConvertedType = Context.getPointerType(T: ConvertedType);
3138 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3139 return true;
3140 }
3141 // Allow conversion of pointee being objective-c pointer to another one;
3142 // as in I* to id.
3143 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3144 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3145 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3146 IncompatibleObjC)) {
3147
3148 ConvertedType = Context.getPointerType(T: ConvertedType);
3149 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3150 return true;
3151 }
3152
3153 // If we have pointers to functions or blocks, check whether the only
3154 // differences in the argument and result types are in Objective-C
3155 // pointer conversions. If so, we permit the conversion (but
3156 // complain about it).
3157 const FunctionProtoType *FromFunctionType
3158 = FromPointeeType->getAs<FunctionProtoType>();
3159 const FunctionProtoType *ToFunctionType
3160 = ToPointeeType->getAs<FunctionProtoType>();
3161 if (FromFunctionType && ToFunctionType) {
3162 // If the function types are exactly the same, this isn't an
3163 // Objective-C pointer conversion.
3164 if (Context.getCanonicalType(T: FromPointeeType)
3165 == Context.getCanonicalType(T: ToPointeeType))
3166 return false;
3167
3168 // Perform the quick checks that will tell us whether these
3169 // function types are obviously different.
3170 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3171 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3172 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3173 return false;
3174
3175 bool HasObjCConversion = false;
3176 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3177 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3178 // Okay, the types match exactly. Nothing to do.
3179 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3180 ToType: ToFunctionType->getReturnType(),
3181 ConvertedType, IncompatibleObjC)) {
3182 // Okay, we have an Objective-C pointer conversion.
3183 HasObjCConversion = true;
3184 } else {
3185 // Function types are too different. Abort.
3186 return false;
3187 }
3188
3189 // Check argument types.
3190 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3191 ArgIdx != NumArgs; ++ArgIdx) {
3192 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3193 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3194 if (Context.getCanonicalType(T: FromArgType)
3195 == Context.getCanonicalType(T: ToArgType)) {
3196 // Okay, the types match exactly. Nothing to do.
3197 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3198 ConvertedType, IncompatibleObjC)) {
3199 // Okay, we have an Objective-C pointer conversion.
3200 HasObjCConversion = true;
3201 } else {
3202 // Argument types are too different. Abort.
3203 return false;
3204 }
3205 }
3206
3207 if (HasObjCConversion) {
3208 // We had an Objective-C conversion. Allow this pointer
3209 // conversion, but complain about it.
3210 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3211 IncompatibleObjC = true;
3212 return true;
3213 }
3214 }
3215
3216 return false;
3217}
3218
3219bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3220 QualType& ConvertedType) {
3221 QualType ToPointeeType;
3222 if (const BlockPointerType *ToBlockPtr =
3223 ToType->getAs<BlockPointerType>())
3224 ToPointeeType = ToBlockPtr->getPointeeType();
3225 else
3226 return false;
3227
3228 QualType FromPointeeType;
3229 if (const BlockPointerType *FromBlockPtr =
3230 FromType->getAs<BlockPointerType>())
3231 FromPointeeType = FromBlockPtr->getPointeeType();
3232 else
3233 return false;
3234 // We have pointer to blocks, check whether the only
3235 // differences in the argument and result types are in Objective-C
3236 // pointer conversions. If so, we permit the conversion.
3237
3238 const FunctionProtoType *FromFunctionType
3239 = FromPointeeType->getAs<FunctionProtoType>();
3240 const FunctionProtoType *ToFunctionType
3241 = ToPointeeType->getAs<FunctionProtoType>();
3242
3243 if (!FromFunctionType || !ToFunctionType)
3244 return false;
3245
3246 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3247 return true;
3248
3249 // Perform the quick checks that will tell us whether these
3250 // function types are obviously different.
3251 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3252 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3253 return false;
3254
3255 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3256 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3257 if (FromEInfo != ToEInfo)
3258 return false;
3259
3260 bool IncompatibleObjC = false;
3261 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3262 T2: ToFunctionType->getReturnType())) {
3263 // Okay, the types match exactly. Nothing to do.
3264 } else {
3265 QualType RHS = FromFunctionType->getReturnType();
3266 QualType LHS = ToFunctionType->getReturnType();
3267 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3268 !RHS.hasQualifiers() && LHS.hasQualifiers())
3269 LHS = LHS.getUnqualifiedType();
3270
3271 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3272 // OK exact match.
3273 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3274 ConvertedType, IncompatibleObjC)) {
3275 if (IncompatibleObjC)
3276 return false;
3277 // Okay, we have an Objective-C pointer conversion.
3278 }
3279 else
3280 return false;
3281 }
3282
3283 // Check argument types.
3284 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3285 ArgIdx != NumArgs; ++ArgIdx) {
3286 IncompatibleObjC = false;
3287 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3288 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3289 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3290 // Okay, the types match exactly. Nothing to do.
3291 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3292 ConvertedType, IncompatibleObjC)) {
3293 if (IncompatibleObjC)
3294 return false;
3295 // Okay, we have an Objective-C pointer conversion.
3296 } else
3297 // Argument types are too different. Abort.
3298 return false;
3299 }
3300
3301 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3302 bool CanUseToFPT, CanUseFromFPT;
3303 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3304 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3305 NewParamInfos))
3306 return false;
3307
3308 ConvertedType = ToType;
3309 return true;
3310}
3311
3312enum {
3313 ft_default,
3314 ft_different_class,
3315 ft_parameter_arity,
3316 ft_parameter_mismatch,
3317 ft_return_type,
3318 ft_qualifer_mismatch,
3319 ft_noexcept
3320};
3321
3322/// Attempts to get the FunctionProtoType from a Type. Handles
3323/// MemberFunctionPointers properly.
3324static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3325 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3326 return FPT;
3327
3328 if (auto *MPT = FromType->getAs<MemberPointerType>())
3329 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3330
3331 return nullptr;
3332}
3333
3334void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3335 QualType FromType, QualType ToType) {
3336 // If either type is not valid, include no extra info.
3337 if (FromType.isNull() || ToType.isNull()) {
3338 PDiag << ft_default;
3339 return;
3340 }
3341
3342 // Get the function type from the pointers.
3343 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3344 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3345 *ToMember = ToType->castAs<MemberPointerType>();
3346 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3347 D2: ToMember->getMostRecentCXXRecordDecl())) {
3348 PDiag << ft_different_class;
3349 if (ToMember->isSugared())
3350 PDiag << Context.getTypeDeclType(
3351 Decl: ToMember->getMostRecentCXXRecordDecl());
3352 else
3353 PDiag << ToMember->getQualifier();
3354 if (FromMember->isSugared())
3355 PDiag << Context.getTypeDeclType(
3356 Decl: FromMember->getMostRecentCXXRecordDecl());
3357 else
3358 PDiag << FromMember->getQualifier();
3359 return;
3360 }
3361 FromType = FromMember->getPointeeType();
3362 ToType = ToMember->getPointeeType();
3363 }
3364
3365 if (FromType->isPointerType())
3366 FromType = FromType->getPointeeType();
3367 if (ToType->isPointerType())
3368 ToType = ToType->getPointeeType();
3369
3370 // Remove references.
3371 FromType = FromType.getNonReferenceType();
3372 ToType = ToType.getNonReferenceType();
3373
3374 // Don't print extra info for non-specialized template functions.
3375 if (FromType->isInstantiationDependentType() &&
3376 !FromType->getAs<TemplateSpecializationType>()) {
3377 PDiag << ft_default;
3378 return;
3379 }
3380
3381 // No extra info for same types.
3382 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3383 PDiag << ft_default;
3384 return;
3385 }
3386
3387 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3388 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3389
3390 // Both types need to be function types.
3391 if (!FromFunction || !ToFunction) {
3392 PDiag << ft_default;
3393 return;
3394 }
3395
3396 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3397 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3398 << FromFunction->getNumParams();
3399 return;
3400 }
3401
3402 // Handle different parameter types.
3403 unsigned ArgPos;
3404 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3405 PDiag << ft_parameter_mismatch << ArgPos + 1
3406 << ToFunction->getParamType(i: ArgPos)
3407 << FromFunction->getParamType(i: ArgPos);
3408 return;
3409 }
3410
3411 // Handle different return type.
3412 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3413 T2: ToFunction->getReturnType())) {
3414 PDiag << ft_return_type << ToFunction->getReturnType()
3415 << FromFunction->getReturnType();
3416 return;
3417 }
3418
3419 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3420 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3421 << FromFunction->getMethodQuals();
3422 return;
3423 }
3424
3425 // Handle exception specification differences on canonical type (in C++17
3426 // onwards).
3427 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3428 ->isNothrow() !=
3429 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3430 ->isNothrow()) {
3431 PDiag << ft_noexcept;
3432 return;
3433 }
3434
3435 // Unable to find a difference, so add no extra info.
3436 PDiag << ft_default;
3437}
3438
3439bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3440 ArrayRef<QualType> New, unsigned *ArgPos,
3441 bool Reversed) {
3442 assert(llvm::size(Old) == llvm::size(New) &&
3443 "Can't compare parameters of functions with different number of "
3444 "parameters!");
3445
3446 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3447 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3448 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3449
3450 // Ignore address spaces in pointee type. This is to disallow overloading
3451 // on __ptr32/__ptr64 address spaces.
3452 QualType OldType =
3453 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3454 QualType NewType =
3455 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3456
3457 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3458 if (ArgPos)
3459 *ArgPos = Idx;
3460 return false;
3461 }
3462 }
3463 return true;
3464}
3465
3466bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3467 const FunctionProtoType *NewType,
3468 unsigned *ArgPos, bool Reversed) {
3469 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3470 New: NewType->param_types(), ArgPos, Reversed);
3471}
3472
3473bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3474 const FunctionDecl *NewFunction,
3475 unsigned *ArgPos,
3476 bool Reversed) {
3477
3478 if (OldFunction->getNumNonObjectParams() !=
3479 NewFunction->getNumNonObjectParams())
3480 return false;
3481
3482 unsigned OldIgnore =
3483 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3484 unsigned NewIgnore =
3485 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3486
3487 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3488 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3489
3490 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3491 New: NewPT->param_types().slice(N: NewIgnore),
3492 ArgPos, Reversed);
3493}
3494
3495bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3496 CastKind &Kind,
3497 CXXCastPath& BasePath,
3498 bool IgnoreBaseAccess,
3499 bool Diagnose) {
3500 QualType FromType = From->getType();
3501 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3502
3503 Kind = CK_BitCast;
3504
3505 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3506 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3507 Expr::NPCK_ZeroExpression) {
3508 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3509 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3510 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3511 << ToType << From->getSourceRange());
3512 else if (!isUnevaluatedContext())
3513 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3514 << ToType << From->getSourceRange();
3515 }
3516 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3517 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3518 QualType FromPointeeType = FromPtrType->getPointeeType(),
3519 ToPointeeType = ToPtrType->getPointeeType();
3520
3521 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3522 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3523 // We must have a derived-to-base conversion. Check an
3524 // ambiguous or inaccessible conversion.
3525 unsigned InaccessibleID = 0;
3526 unsigned AmbiguousID = 0;
3527 if (Diagnose) {
3528 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3529 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3530 }
3531 if (CheckDerivedToBaseConversion(
3532 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3533 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3534 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3535 return true;
3536
3537 // The conversion was successful.
3538 Kind = CK_DerivedToBase;
3539 }
3540
3541 if (Diagnose && !IsCStyleOrFunctionalCast &&
3542 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3543 assert(getLangOpts().MSVCCompat &&
3544 "this should only be possible with MSVCCompat!");
3545 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3546 << From->getSourceRange();
3547 }
3548 }
3549 } else if (const ObjCObjectPointerType *ToPtrType =
3550 ToType->getAs<ObjCObjectPointerType>()) {
3551 if (const ObjCObjectPointerType *FromPtrType =
3552 FromType->getAs<ObjCObjectPointerType>()) {
3553 // Objective-C++ conversions are always okay.
3554 // FIXME: We should have a different class of conversions for the
3555 // Objective-C++ implicit conversions.
3556 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3557 return false;
3558 } else if (FromType->isBlockPointerType()) {
3559 Kind = CK_BlockPointerToObjCPointerCast;
3560 } else {
3561 Kind = CK_CPointerToObjCPointerCast;
3562 }
3563 } else if (ToType->isBlockPointerType()) {
3564 if (!FromType->isBlockPointerType())
3565 Kind = CK_AnyPointerToBlockPointerCast;
3566 }
3567
3568 // We shouldn't fall into this case unless it's valid for other
3569 // reasons.
3570 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3571 Kind = CK_NullToPointer;
3572
3573 return false;
3574}
3575
3576bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3577 QualType ToType,
3578 bool InOverloadResolution,
3579 QualType &ConvertedType) {
3580 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3581 if (!ToTypePtr)
3582 return false;
3583
3584 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3585 if (From->isNullPointerConstant(Ctx&: Context,
3586 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3587 : Expr::NPC_ValueDependentIsNull)) {
3588 ConvertedType = ToType;
3589 return true;
3590 }
3591
3592 // Otherwise, both types have to be member pointers.
3593 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3594 if (!FromTypePtr)
3595 return false;
3596
3597 // A pointer to member of B can be converted to a pointer to member of D,
3598 // where D is derived from B (C++ 4.11p2).
3599 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3600 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3601
3602 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3603 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3604 ConvertedType = Context.getMemberPointerType(
3605 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3606 return true;
3607 }
3608
3609 return false;
3610}
3611
3612Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3613 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3614 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3615 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3616 // Lock down the inheritance model right now in MS ABI, whether or not the
3617 // pointee types are the same.
3618 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3619 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3620 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3621 }
3622
3623 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3624 if (!FromPtrType) {
3625 // This must be a null pointer to member pointer conversion
3626 Kind = CK_NullToMemberPointer;
3627 return MemberPointerConversionResult::Success;
3628 }
3629
3630 // T == T, modulo cv
3631 if (Direction == MemberPointerConversionDirection::Upcast &&
3632 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3633 T2: ToPtrType->getPointeeType()))
3634 return MemberPointerConversionResult::DifferentPointee;
3635
3636 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3637 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3638
3639 auto DiagCls = [](PartialDiagnostic &PD, NestedNameSpecifier *Qual,
3640 const CXXRecordDecl *Cls) {
3641 if (declaresSameEntity(D1: Qual->getAsRecordDecl(), D2: Cls))
3642 PD << Qual;
3643 else
3644 PD << QualType(Cls->getTypeForDecl(), 0);
3645 };
3646 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3647 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3648 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3649 return PD;
3650 };
3651
3652 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3653 if (Direction == MemberPointerConversionDirection::Upcast)
3654 std::swap(a&: Base, b&: Derived);
3655
3656 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3657 /*DetectVirtual=*/true);
3658 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3659 return MemberPointerConversionResult::NotDerived;
3660
3661 if (Paths.isAmbiguous(
3662 BaseType: Base->getTypeForDecl()->getCanonicalTypeUnqualified())) {
3663 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3664 PD << int(Direction);
3665 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3666 Diag(Loc: CheckLoc, PD);
3667 return MemberPointerConversionResult::Ambiguous;
3668 }
3669
3670 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3671 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3672 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3673 Diag(Loc: CheckLoc, PD);
3674 return MemberPointerConversionResult::Virtual;
3675 }
3676
3677 // Must be a base to derived member conversion.
3678 BuildBasePathArray(Paths, BasePath);
3679 Kind = Direction == MemberPointerConversionDirection::Upcast
3680 ? CK_DerivedToBaseMemberPointer
3681 : CK_BaseToDerivedMemberPointer;
3682
3683 if (!IgnoreBaseAccess)
3684 switch (CheckBaseClassAccess(
3685 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3686 DiagID: Direction == MemberPointerConversionDirection::Upcast
3687 ? diag::err_upcast_to_inaccessible_base
3688 : diag::err_downcast_from_inaccessible_base,
3689 SetupPDiag: [&](PartialDiagnostic &PD) {
3690 NestedNameSpecifier *BaseQual = FromPtrType->getQualifier(),
3691 *DerivedQual = ToPtrType->getQualifier();
3692 if (Direction == MemberPointerConversionDirection::Upcast)
3693 std::swap(a&: BaseQual, b&: DerivedQual);
3694 DiagCls(PD, DerivedQual, Derived);
3695 DiagCls(PD, BaseQual, Base);
3696 })) {
3697 case Sema::AR_accessible:
3698 case Sema::AR_delayed:
3699 case Sema::AR_dependent:
3700 // Optimistically assume that the delayed and dependent cases
3701 // will work out.
3702 break;
3703
3704 case Sema::AR_inaccessible:
3705 return MemberPointerConversionResult::Inaccessible;
3706 }
3707
3708 return MemberPointerConversionResult::Success;
3709}
3710
3711/// Determine whether the lifetime conversion between the two given
3712/// qualifiers sets is nontrivial.
3713static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3714 Qualifiers ToQuals) {
3715 // Converting anything to const __unsafe_unretained is trivial.
3716 if (ToQuals.hasConst() &&
3717 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3718 return false;
3719
3720 return true;
3721}
3722
3723/// Perform a single iteration of the loop for checking if a qualification
3724/// conversion is valid.
3725///
3726/// Specifically, check whether any change between the qualifiers of \p
3727/// FromType and \p ToType is permissible, given knowledge about whether every
3728/// outer layer is const-qualified.
3729static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3730 bool CStyle, bool IsTopLevel,
3731 bool &PreviousToQualsIncludeConst,
3732 bool &ObjCLifetimeConversion,
3733 const ASTContext &Ctx) {
3734 Qualifiers FromQuals = FromType.getQualifiers();
3735 Qualifiers ToQuals = ToType.getQualifiers();
3736
3737 // Ignore __unaligned qualifier.
3738 FromQuals.removeUnaligned();
3739
3740 // Objective-C ARC:
3741 // Check Objective-C lifetime conversions.
3742 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3743 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3744 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3745 ObjCLifetimeConversion = true;
3746 FromQuals.removeObjCLifetime();
3747 ToQuals.removeObjCLifetime();
3748 } else {
3749 // Qualification conversions cannot cast between different
3750 // Objective-C lifetime qualifiers.
3751 return false;
3752 }
3753 }
3754
3755 // Allow addition/removal of GC attributes but not changing GC attributes.
3756 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3757 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3758 FromQuals.removeObjCGCAttr();
3759 ToQuals.removeObjCGCAttr();
3760 }
3761
3762 // __ptrauth qualifiers must match exactly.
3763 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3764 return false;
3765
3766 // -- for every j > 0, if const is in cv 1,j then const is in cv
3767 // 2,j, and similarly for volatile.
3768 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3769 return false;
3770
3771 // If address spaces mismatch:
3772 // - in top level it is only valid to convert to addr space that is a
3773 // superset in all cases apart from C-style casts where we allow
3774 // conversions between overlapping address spaces.
3775 // - in non-top levels it is not a valid conversion.
3776 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3777 (!IsTopLevel ||
3778 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3779 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3780 return false;
3781
3782 // -- if the cv 1,j and cv 2,j are different, then const is in
3783 // every cv for 0 < k < j.
3784 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3785 !PreviousToQualsIncludeConst)
3786 return false;
3787
3788 // The following wording is from C++20, where the result of the conversion
3789 // is T3, not T2.
3790 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3791 // "array of unknown bound of"
3792 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3793 return false;
3794
3795 // -- if the resulting P3,i is different from P1,i [...], then const is
3796 // added to every cv 3_k for 0 < k < i.
3797 if (!CStyle && FromType->isConstantArrayType() &&
3798 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3799 return false;
3800
3801 // Keep track of whether all prior cv-qualifiers in the "to" type
3802 // include const.
3803 PreviousToQualsIncludeConst =
3804 PreviousToQualsIncludeConst && ToQuals.hasConst();
3805 return true;
3806}
3807
3808bool
3809Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3810 bool CStyle, bool &ObjCLifetimeConversion) {
3811 FromType = Context.getCanonicalType(T: FromType);
3812 ToType = Context.getCanonicalType(T: ToType);
3813 ObjCLifetimeConversion = false;
3814
3815 // If FromType and ToType are the same type, this is not a
3816 // qualification conversion.
3817 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3818 return false;
3819
3820 // (C++ 4.4p4):
3821 // A conversion can add cv-qualifiers at levels other than the first
3822 // in multi-level pointers, subject to the following rules: [...]
3823 bool PreviousToQualsIncludeConst = true;
3824 bool UnwrappedAnyPointer = false;
3825 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3826 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3827 IsTopLevel: !UnwrappedAnyPointer,
3828 PreviousToQualsIncludeConst,
3829 ObjCLifetimeConversion, Ctx: getASTContext()))
3830 return false;
3831 UnwrappedAnyPointer = true;
3832 }
3833
3834 // We are left with FromType and ToType being the pointee types
3835 // after unwrapping the original FromType and ToType the same number
3836 // of times. If we unwrapped any pointers, and if FromType and
3837 // ToType have the same unqualified type (since we checked
3838 // qualifiers above), then this is a qualification conversion.
3839 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3840}
3841
3842/// - Determine whether this is a conversion from a scalar type to an
3843/// atomic type.
3844///
3845/// If successful, updates \c SCS's second and third steps in the conversion
3846/// sequence to finish the conversion.
3847static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3848 bool InOverloadResolution,
3849 StandardConversionSequence &SCS,
3850 bool CStyle) {
3851 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3852 if (!ToAtomic)
3853 return false;
3854
3855 StandardConversionSequence InnerSCS;
3856 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3857 InOverloadResolution, SCS&: InnerSCS,
3858 CStyle, /*AllowObjCWritebackConversion=*/false))
3859 return false;
3860
3861 SCS.Second = InnerSCS.Second;
3862 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3863 SCS.Third = InnerSCS.Third;
3864 SCS.QualificationIncludesObjCLifetime
3865 = InnerSCS.QualificationIncludesObjCLifetime;
3866 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3867 return true;
3868}
3869
3870static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3871 CXXConstructorDecl *Constructor,
3872 QualType Type) {
3873 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3874 if (CtorType->getNumParams() > 0) {
3875 QualType FirstArg = CtorType->getParamType(i: 0);
3876 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
3877 return true;
3878 }
3879 return false;
3880}
3881
3882static OverloadingResult
3883IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3884 CXXRecordDecl *To,
3885 UserDefinedConversionSequence &User,
3886 OverloadCandidateSet &CandidateSet,
3887 bool AllowExplicit) {
3888 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3889 for (auto *D : S.LookupConstructors(Class: To)) {
3890 auto Info = getConstructorInfo(ND: D);
3891 if (!Info)
3892 continue;
3893
3894 bool Usable = !Info.Constructor->isInvalidDecl() &&
3895 S.isInitListConstructor(Ctor: Info.Constructor);
3896 if (Usable) {
3897 bool SuppressUserConversions = false;
3898 if (Info.ConstructorTmpl)
3899 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3900 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
3901 CandidateSet, SuppressUserConversions,
3902 /*PartialOverloading*/ false,
3903 AllowExplicit);
3904 else
3905 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
3906 CandidateSet, SuppressUserConversions,
3907 /*PartialOverloading*/ false, AllowExplicit);
3908 }
3909 }
3910
3911 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3912
3913 OverloadCandidateSet::iterator Best;
3914 switch (auto Result =
3915 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
3916 case OR_Deleted:
3917 case OR_Success: {
3918 // Record the standard conversion we used and the conversion function.
3919 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
3920 QualType ThisType = Constructor->getFunctionObjectParameterType();
3921 // Initializer lists don't have conversions as such.
3922 User.Before.setAsIdentityConversion();
3923 User.HadMultipleCandidates = HadMultipleCandidates;
3924 User.ConversionFunction = Constructor;
3925 User.FoundConversionFunction = Best->FoundDecl;
3926 User.After.setAsIdentityConversion();
3927 User.After.setFromType(ThisType);
3928 User.After.setAllToTypes(ToType);
3929 return Result;
3930 }
3931
3932 case OR_No_Viable_Function:
3933 return OR_No_Viable_Function;
3934 case OR_Ambiguous:
3935 return OR_Ambiguous;
3936 }
3937
3938 llvm_unreachable("Invalid OverloadResult!");
3939}
3940
3941/// Determines whether there is a user-defined conversion sequence
3942/// (C++ [over.ics.user]) that converts expression From to the type
3943/// ToType. If such a conversion exists, User will contain the
3944/// user-defined conversion sequence that performs such a conversion
3945/// and this routine will return true. Otherwise, this routine returns
3946/// false and User is unspecified.
3947///
3948/// \param AllowExplicit true if the conversion should consider C++0x
3949/// "explicit" conversion functions as well as non-explicit conversion
3950/// functions (C++0x [class.conv.fct]p2).
3951///
3952/// \param AllowObjCConversionOnExplicit true if the conversion should
3953/// allow an extra Objective-C pointer conversion on uses of explicit
3954/// constructors. Requires \c AllowExplicit to also be set.
3955static OverloadingResult
3956IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3957 UserDefinedConversionSequence &User,
3958 OverloadCandidateSet &CandidateSet,
3959 AllowedExplicit AllowExplicit,
3960 bool AllowObjCConversionOnExplicit) {
3961 assert(AllowExplicit != AllowedExplicit::None ||
3962 !AllowObjCConversionOnExplicit);
3963 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3964
3965 // Whether we will only visit constructors.
3966 bool ConstructorsOnly = false;
3967
3968 // If the type we are conversion to is a class type, enumerate its
3969 // constructors.
3970 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3971 // C++ [over.match.ctor]p1:
3972 // When objects of class type are direct-initialized (8.5), or
3973 // copy-initialized from an expression of the same or a
3974 // derived class type (8.5), overload resolution selects the
3975 // constructor. [...] For copy-initialization, the candidate
3976 // functions are all the converting constructors (12.3.1) of
3977 // that class. The argument list is the expression-list within
3978 // the parentheses of the initializer.
3979 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
3980 (From->getType()->getAs<RecordType>() &&
3981 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
3982 ConstructorsOnly = true;
3983
3984 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
3985 // We're not going to find any constructors.
3986 } else if (CXXRecordDecl *ToRecordDecl
3987 = dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
3988
3989 Expr **Args = &From;
3990 unsigned NumArgs = 1;
3991 bool ListInitializing = false;
3992 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
3993 // But first, see if there is an init-list-constructor that will work.
3994 OverloadingResult Result = IsInitializerListConstructorConversion(
3995 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
3996 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3997 if (Result != OR_No_Viable_Function)
3998 return Result;
3999 // Never mind.
4000 CandidateSet.clear(
4001 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4002
4003 // If we're list-initializing, we pass the individual elements as
4004 // arguments, not the entire list.
4005 Args = InitList->getInits();
4006 NumArgs = InitList->getNumInits();
4007 ListInitializing = true;
4008 }
4009
4010 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4011 auto Info = getConstructorInfo(ND: D);
4012 if (!Info)
4013 continue;
4014
4015 bool Usable = !Info.Constructor->isInvalidDecl();
4016 if (!ListInitializing)
4017 Usable = Usable && Info.Constructor->isConvertingConstructor(
4018 /*AllowExplicit*/ true);
4019 if (Usable) {
4020 bool SuppressUserConversions = !ConstructorsOnly;
4021 // C++20 [over.best.ics.general]/4.5:
4022 // if the target is the first parameter of a constructor [of class
4023 // X] and the constructor [...] is a candidate by [...] the second
4024 // phase of [over.match.list] when the initializer list has exactly
4025 // one element that is itself an initializer list, [...] and the
4026 // conversion is to X or reference to cv X, user-defined conversion
4027 // sequences are not considered.
4028 if (SuppressUserConversions && ListInitializing) {
4029 SuppressUserConversions =
4030 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4031 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4032 Type: ToType);
4033 }
4034 if (Info.ConstructorTmpl)
4035 S.AddTemplateOverloadCandidate(
4036 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4037 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4038 CandidateSet, SuppressUserConversions,
4039 /*PartialOverloading*/ false,
4040 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4041 else
4042 // Allow one user-defined conversion when user specifies a
4043 // From->ToType conversion via an static cast (c-style, etc).
4044 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4045 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4046 SuppressUserConversions,
4047 /*PartialOverloading*/ false,
4048 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4049 }
4050 }
4051 }
4052 }
4053
4054 // Enumerate conversion functions, if we're allowed to.
4055 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4056 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4057 // No conversion functions from incomplete types.
4058 } else if (const RecordType *FromRecordType =
4059 From->getType()->getAs<RecordType>()) {
4060 if (CXXRecordDecl *FromRecordDecl
4061 = dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4062 // Add all of the conversion functions as candidates.
4063 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4064 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4065 DeclAccessPair FoundDecl = I.getPair();
4066 NamedDecl *D = FoundDecl.getDecl();
4067 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4068 if (isa<UsingShadowDecl>(Val: D))
4069 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4070
4071 CXXConversionDecl *Conv;
4072 FunctionTemplateDecl *ConvTemplate;
4073 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4074 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4075 else
4076 Conv = cast<CXXConversionDecl>(Val: D);
4077
4078 if (ConvTemplate)
4079 S.AddTemplateConversionCandidate(
4080 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4081 CandidateSet, AllowObjCConversionOnExplicit,
4082 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4083 else
4084 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4085 CandidateSet, AllowObjCConversionOnExplicit,
4086 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4087 }
4088 }
4089 }
4090
4091 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4092
4093 OverloadCandidateSet::iterator Best;
4094 switch (auto Result =
4095 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4096 case OR_Success:
4097 case OR_Deleted:
4098 // Record the standard conversion we used and the conversion function.
4099 if (CXXConstructorDecl *Constructor
4100 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4101 // C++ [over.ics.user]p1:
4102 // If the user-defined conversion is specified by a
4103 // constructor (12.3.1), the initial standard conversion
4104 // sequence converts the source type to the type required by
4105 // the argument of the constructor.
4106 //
4107 if (isa<InitListExpr>(Val: From)) {
4108 // Initializer lists don't have conversions as such.
4109 User.Before.setAsIdentityConversion();
4110 User.Before.FromBracedInitList = true;
4111 } else {
4112 if (Best->Conversions[0].isEllipsis())
4113 User.EllipsisConversion = true;
4114 else {
4115 User.Before = Best->Conversions[0].Standard;
4116 User.EllipsisConversion = false;
4117 }
4118 }
4119 User.HadMultipleCandidates = HadMultipleCandidates;
4120 User.ConversionFunction = Constructor;
4121 User.FoundConversionFunction = Best->FoundDecl;
4122 User.After.setAsIdentityConversion();
4123 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4124 User.After.setAllToTypes(ToType);
4125 return Result;
4126 }
4127 if (CXXConversionDecl *Conversion
4128 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4129
4130 assert(Best->HasFinalConversion);
4131
4132 // C++ [over.ics.user]p1:
4133 //
4134 // [...] If the user-defined conversion is specified by a
4135 // conversion function (12.3.2), the initial standard
4136 // conversion sequence converts the source type to the
4137 // implicit object parameter of the conversion function.
4138 User.Before = Best->Conversions[0].Standard;
4139 User.HadMultipleCandidates = HadMultipleCandidates;
4140 User.ConversionFunction = Conversion;
4141 User.FoundConversionFunction = Best->FoundDecl;
4142 User.EllipsisConversion = false;
4143
4144 // C++ [over.ics.user]p2:
4145 // The second standard conversion sequence converts the
4146 // result of the user-defined conversion to the target type
4147 // for the sequence. Since an implicit conversion sequence
4148 // is an initialization, the special rules for
4149 // initialization by user-defined conversion apply when
4150 // selecting the best user-defined conversion for a
4151 // user-defined conversion sequence (see 13.3.3 and
4152 // 13.3.3.1).
4153 User.After = Best->FinalConversion;
4154 return Result;
4155 }
4156 llvm_unreachable("Not a constructor or conversion function?");
4157
4158 case OR_No_Viable_Function:
4159 return OR_No_Viable_Function;
4160
4161 case OR_Ambiguous:
4162 return OR_Ambiguous;
4163 }
4164
4165 llvm_unreachable("Invalid OverloadResult!");
4166}
4167
4168bool
4169Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4170 ImplicitConversionSequence ICS;
4171 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4172 OverloadCandidateSet::CSK_Normal);
4173 OverloadingResult OvResult =
4174 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4175 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4176
4177 if (!(OvResult == OR_Ambiguous ||
4178 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4179 return false;
4180
4181 auto Cands = CandidateSet.CompleteCandidates(
4182 S&: *this,
4183 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4184 Args: From);
4185 if (OvResult == OR_Ambiguous)
4186 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4187 << From->getType() << ToType << From->getSourceRange();
4188 else { // OR_No_Viable_Function && !CandidateSet.empty()
4189 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4190 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4191 Args: From->getType(), Args: From->getSourceRange()))
4192 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4193 << false << From->getType() << From->getSourceRange() << ToType;
4194 }
4195
4196 CandidateSet.NoteCandidates(
4197 S&: *this, Args: From, Cands);
4198 return true;
4199}
4200
4201// Helper for compareConversionFunctions that gets the FunctionType that the
4202// conversion-operator return value 'points' to, or nullptr.
4203static const FunctionType *
4204getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4205 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4206 const PointerType *RetPtrTy =
4207 ConvFuncTy->getReturnType()->getAs<PointerType>();
4208
4209 if (!RetPtrTy)
4210 return nullptr;
4211
4212 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4213}
4214
4215/// Compare the user-defined conversion functions or constructors
4216/// of two user-defined conversion sequences to determine whether any ordering
4217/// is possible.
4218static ImplicitConversionSequence::CompareKind
4219compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4220 FunctionDecl *Function2) {
4221 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4222 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4223 if (!Conv1 || !Conv2)
4224 return ImplicitConversionSequence::Indistinguishable;
4225
4226 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4227 return ImplicitConversionSequence::Indistinguishable;
4228
4229 // Objective-C++:
4230 // If both conversion functions are implicitly-declared conversions from
4231 // a lambda closure type to a function pointer and a block pointer,
4232 // respectively, always prefer the conversion to a function pointer,
4233 // because the function pointer is more lightweight and is more likely
4234 // to keep code working.
4235 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4236 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4237 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4238 if (Block1 != Block2)
4239 return Block1 ? ImplicitConversionSequence::Worse
4240 : ImplicitConversionSequence::Better;
4241 }
4242
4243 // In order to support multiple calling conventions for the lambda conversion
4244 // operator (such as when the free and member function calling convention is
4245 // different), prefer the 'free' mechanism, followed by the calling-convention
4246 // of operator(). The latter is in place to support the MSVC-like solution of
4247 // defining ALL of the possible conversions in regards to calling-convention.
4248 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4249 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4250
4251 if (Conv1FuncRet && Conv2FuncRet &&
4252 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4253 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4254 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4255
4256 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4257 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4258
4259 CallingConv CallOpCC =
4260 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4261 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4262 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4263 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4264 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4265
4266 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4267 for (CallingConv CC : PrefOrder) {
4268 if (Conv1CC == CC)
4269 return ImplicitConversionSequence::Better;
4270 if (Conv2CC == CC)
4271 return ImplicitConversionSequence::Worse;
4272 }
4273 }
4274
4275 return ImplicitConversionSequence::Indistinguishable;
4276}
4277
4278static bool hasDeprecatedStringLiteralToCharPtrConversion(
4279 const ImplicitConversionSequence &ICS) {
4280 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4281 (ICS.isUserDefined() &&
4282 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4283}
4284
4285/// CompareImplicitConversionSequences - Compare two implicit
4286/// conversion sequences to determine whether one is better than the
4287/// other or if they are indistinguishable (C++ 13.3.3.2).
4288static ImplicitConversionSequence::CompareKind
4289CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4290 const ImplicitConversionSequence& ICS1,
4291 const ImplicitConversionSequence& ICS2)
4292{
4293 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4294 // conversion sequences (as defined in 13.3.3.1)
4295 // -- a standard conversion sequence (13.3.3.1.1) is a better
4296 // conversion sequence than a user-defined conversion sequence or
4297 // an ellipsis conversion sequence, and
4298 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4299 // conversion sequence than an ellipsis conversion sequence
4300 // (13.3.3.1.3).
4301 //
4302 // C++0x [over.best.ics]p10:
4303 // For the purpose of ranking implicit conversion sequences as
4304 // described in 13.3.3.2, the ambiguous conversion sequence is
4305 // treated as a user-defined sequence that is indistinguishable
4306 // from any other user-defined conversion sequence.
4307
4308 // String literal to 'char *' conversion has been deprecated in C++03. It has
4309 // been removed from C++11. We still accept this conversion, if it happens at
4310 // the best viable function. Otherwise, this conversion is considered worse
4311 // than ellipsis conversion. Consider this as an extension; this is not in the
4312 // standard. For example:
4313 //
4314 // int &f(...); // #1
4315 // void f(char*); // #2
4316 // void g() { int &r = f("foo"); }
4317 //
4318 // In C++03, we pick #2 as the best viable function.
4319 // In C++11, we pick #1 as the best viable function, because ellipsis
4320 // conversion is better than string-literal to char* conversion (since there
4321 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4322 // convert arguments, #2 would be the best viable function in C++11.
4323 // If the best viable function has this conversion, a warning will be issued
4324 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4325
4326 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4327 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4328 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4329 // Ill-formedness must not differ
4330 ICS1.isBad() == ICS2.isBad())
4331 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4332 ? ImplicitConversionSequence::Worse
4333 : ImplicitConversionSequence::Better;
4334
4335 if (ICS1.getKindRank() < ICS2.getKindRank())
4336 return ImplicitConversionSequence::Better;
4337 if (ICS2.getKindRank() < ICS1.getKindRank())
4338 return ImplicitConversionSequence::Worse;
4339
4340 // The following checks require both conversion sequences to be of
4341 // the same kind.
4342 if (ICS1.getKind() != ICS2.getKind())
4343 return ImplicitConversionSequence::Indistinguishable;
4344
4345 ImplicitConversionSequence::CompareKind Result =
4346 ImplicitConversionSequence::Indistinguishable;
4347
4348 // Two implicit conversion sequences of the same form are
4349 // indistinguishable conversion sequences unless one of the
4350 // following rules apply: (C++ 13.3.3.2p3):
4351
4352 // List-initialization sequence L1 is a better conversion sequence than
4353 // list-initialization sequence L2 if:
4354 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4355 // if not that,
4356 // — L1 and L2 convert to arrays of the same element type, and either the
4357 // number of elements n_1 initialized by L1 is less than the number of
4358 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4359 // an array of unknown bound and L1 does not,
4360 // even if one of the other rules in this paragraph would otherwise apply.
4361 if (!ICS1.isBad()) {
4362 bool StdInit1 = false, StdInit2 = false;
4363 if (ICS1.hasInitializerListContainerType())
4364 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4365 Element: nullptr);
4366 if (ICS2.hasInitializerListContainerType())
4367 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4368 Element: nullptr);
4369 if (StdInit1 != StdInit2)
4370 return StdInit1 ? ImplicitConversionSequence::Better
4371 : ImplicitConversionSequence::Worse;
4372
4373 if (ICS1.hasInitializerListContainerType() &&
4374 ICS2.hasInitializerListContainerType())
4375 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4376 T: ICS1.getInitializerListContainerType()))
4377 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4378 T: ICS2.getInitializerListContainerType())) {
4379 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4380 T2: CAT2->getElementType())) {
4381 // Both to arrays of the same element type
4382 if (CAT1->getSize() != CAT2->getSize())
4383 // Different sized, the smaller wins
4384 return CAT1->getSize().ult(RHS: CAT2->getSize())
4385 ? ImplicitConversionSequence::Better
4386 : ImplicitConversionSequence::Worse;
4387 if (ICS1.isInitializerListOfIncompleteArray() !=
4388 ICS2.isInitializerListOfIncompleteArray())
4389 // One is incomplete, it loses
4390 return ICS2.isInitializerListOfIncompleteArray()
4391 ? ImplicitConversionSequence::Better
4392 : ImplicitConversionSequence::Worse;
4393 }
4394 }
4395 }
4396
4397 if (ICS1.isStandard())
4398 // Standard conversion sequence S1 is a better conversion sequence than
4399 // standard conversion sequence S2 if [...]
4400 Result = CompareStandardConversionSequences(S, Loc,
4401 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4402 else if (ICS1.isUserDefined()) {
4403 // User-defined conversion sequence U1 is a better conversion
4404 // sequence than another user-defined conversion sequence U2 if
4405 // they contain the same user-defined conversion function or
4406 // constructor and if the second standard conversion sequence of
4407 // U1 is better than the second standard conversion sequence of
4408 // U2 (C++ 13.3.3.2p3).
4409 if (ICS1.UserDefined.ConversionFunction ==
4410 ICS2.UserDefined.ConversionFunction)
4411 Result = CompareStandardConversionSequences(S, Loc,
4412 SCS1: ICS1.UserDefined.After,
4413 SCS2: ICS2.UserDefined.After);
4414 else
4415 Result = compareConversionFunctions(S,
4416 Function1: ICS1.UserDefined.ConversionFunction,
4417 Function2: ICS2.UserDefined.ConversionFunction);
4418 }
4419
4420 return Result;
4421}
4422
4423// Per 13.3.3.2p3, compare the given standard conversion sequences to
4424// determine if one is a proper subset of the other.
4425static ImplicitConversionSequence::CompareKind
4426compareStandardConversionSubsets(ASTContext &Context,
4427 const StandardConversionSequence& SCS1,
4428 const StandardConversionSequence& SCS2) {
4429 ImplicitConversionSequence::CompareKind Result
4430 = ImplicitConversionSequence::Indistinguishable;
4431
4432 // the identity conversion sequence is considered to be a subsequence of
4433 // any non-identity conversion sequence
4434 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4435 return ImplicitConversionSequence::Better;
4436 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4437 return ImplicitConversionSequence::Worse;
4438
4439 if (SCS1.Second != SCS2.Second) {
4440 if (SCS1.Second == ICK_Identity)
4441 Result = ImplicitConversionSequence::Better;
4442 else if (SCS2.Second == ICK_Identity)
4443 Result = ImplicitConversionSequence::Worse;
4444 else
4445 return ImplicitConversionSequence::Indistinguishable;
4446 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4447 return ImplicitConversionSequence::Indistinguishable;
4448
4449 if (SCS1.Third == SCS2.Third) {
4450 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4451 : ImplicitConversionSequence::Indistinguishable;
4452 }
4453
4454 if (SCS1.Third == ICK_Identity)
4455 return Result == ImplicitConversionSequence::Worse
4456 ? ImplicitConversionSequence::Indistinguishable
4457 : ImplicitConversionSequence::Better;
4458
4459 if (SCS2.Third == ICK_Identity)
4460 return Result == ImplicitConversionSequence::Better
4461 ? ImplicitConversionSequence::Indistinguishable
4462 : ImplicitConversionSequence::Worse;
4463
4464 return ImplicitConversionSequence::Indistinguishable;
4465}
4466
4467/// Determine whether one of the given reference bindings is better
4468/// than the other based on what kind of bindings they are.
4469static bool
4470isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4471 const StandardConversionSequence &SCS2) {
4472 // C++0x [over.ics.rank]p3b4:
4473 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4474 // implicit object parameter of a non-static member function declared
4475 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4476 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4477 // lvalue reference to a function lvalue and S2 binds an rvalue
4478 // reference*.
4479 //
4480 // FIXME: Rvalue references. We're going rogue with the above edits,
4481 // because the semantics in the current C++0x working paper (N3225 at the
4482 // time of this writing) break the standard definition of std::forward
4483 // and std::reference_wrapper when dealing with references to functions.
4484 // Proposed wording changes submitted to CWG for consideration.
4485 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4486 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4487 return false;
4488
4489 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4490 SCS2.IsLvalueReference) ||
4491 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4492 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4493}
4494
4495enum class FixedEnumPromotion {
4496 None,
4497 ToUnderlyingType,
4498 ToPromotedUnderlyingType
4499};
4500
4501/// Returns kind of fixed enum promotion the \a SCS uses.
4502static FixedEnumPromotion
4503getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4504
4505 if (SCS.Second != ICK_Integral_Promotion)
4506 return FixedEnumPromotion::None;
4507
4508 QualType FromType = SCS.getFromType();
4509 if (!FromType->isEnumeralType())
4510 return FixedEnumPromotion::None;
4511
4512 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4513 if (!Enum->isFixed())
4514 return FixedEnumPromotion::None;
4515
4516 QualType UnderlyingType = Enum->getIntegerType();
4517 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4518 return FixedEnumPromotion::ToUnderlyingType;
4519
4520 return FixedEnumPromotion::ToPromotedUnderlyingType;
4521}
4522
4523/// CompareStandardConversionSequences - Compare two standard
4524/// conversion sequences to determine whether one is better than the
4525/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4526static ImplicitConversionSequence::CompareKind
4527CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4528 const StandardConversionSequence& SCS1,
4529 const StandardConversionSequence& SCS2)
4530{
4531 // Standard conversion sequence S1 is a better conversion sequence
4532 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4533
4534 // -- S1 is a proper subsequence of S2 (comparing the conversion
4535 // sequences in the canonical form defined by 13.3.3.1.1,
4536 // excluding any Lvalue Transformation; the identity conversion
4537 // sequence is considered to be a subsequence of any
4538 // non-identity conversion sequence) or, if not that,
4539 if (ImplicitConversionSequence::CompareKind CK
4540 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4541 return CK;
4542
4543 // -- the rank of S1 is better than the rank of S2 (by the rules
4544 // defined below), or, if not that,
4545 ImplicitConversionRank Rank1 = SCS1.getRank();
4546 ImplicitConversionRank Rank2 = SCS2.getRank();
4547 if (Rank1 < Rank2)
4548 return ImplicitConversionSequence::Better;
4549 else if (Rank2 < Rank1)
4550 return ImplicitConversionSequence::Worse;
4551
4552 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4553 // are indistinguishable unless one of the following rules
4554 // applies:
4555
4556 // A conversion that is not a conversion of a pointer, or
4557 // pointer to member, to bool is better than another conversion
4558 // that is such a conversion.
4559 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4560 return SCS2.isPointerConversionToBool()
4561 ? ImplicitConversionSequence::Better
4562 : ImplicitConversionSequence::Worse;
4563
4564 // C++14 [over.ics.rank]p4b2:
4565 // This is retroactively applied to C++11 by CWG 1601.
4566 //
4567 // A conversion that promotes an enumeration whose underlying type is fixed
4568 // to its underlying type is better than one that promotes to the promoted
4569 // underlying type, if the two are different.
4570 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4571 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4572 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4573 FEP1 != FEP2)
4574 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4575 ? ImplicitConversionSequence::Better
4576 : ImplicitConversionSequence::Worse;
4577
4578 // C++ [over.ics.rank]p4b2:
4579 //
4580 // If class B is derived directly or indirectly from class A,
4581 // conversion of B* to A* is better than conversion of B* to
4582 // void*, and conversion of A* to void* is better than conversion
4583 // of B* to void*.
4584 bool SCS1ConvertsToVoid
4585 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4586 bool SCS2ConvertsToVoid
4587 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4588 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4589 // Exactly one of the conversion sequences is a conversion to
4590 // a void pointer; it's the worse conversion.
4591 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4592 : ImplicitConversionSequence::Worse;
4593 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4594 // Neither conversion sequence converts to a void pointer; compare
4595 // their derived-to-base conversions.
4596 if (ImplicitConversionSequence::CompareKind DerivedCK
4597 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4598 return DerivedCK;
4599 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4600 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4601 // Both conversion sequences are conversions to void
4602 // pointers. Compare the source types to determine if there's an
4603 // inheritance relationship in their sources.
4604 QualType FromType1 = SCS1.getFromType();
4605 QualType FromType2 = SCS2.getFromType();
4606
4607 // Adjust the types we're converting from via the array-to-pointer
4608 // conversion, if we need to.
4609 if (SCS1.First == ICK_Array_To_Pointer)
4610 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4611 if (SCS2.First == ICK_Array_To_Pointer)
4612 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4613
4614 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4615 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4616
4617 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4618 return ImplicitConversionSequence::Better;
4619 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4620 return ImplicitConversionSequence::Worse;
4621
4622 // Objective-C++: If one interface is more specific than the
4623 // other, it is the better one.
4624 const ObjCObjectPointerType* FromObjCPtr1
4625 = FromType1->getAs<ObjCObjectPointerType>();
4626 const ObjCObjectPointerType* FromObjCPtr2
4627 = FromType2->getAs<ObjCObjectPointerType>();
4628 if (FromObjCPtr1 && FromObjCPtr2) {
4629 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4630 RHSOPT: FromObjCPtr2);
4631 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4632 RHSOPT: FromObjCPtr1);
4633 if (AssignLeft != AssignRight) {
4634 return AssignLeft? ImplicitConversionSequence::Better
4635 : ImplicitConversionSequence::Worse;
4636 }
4637 }
4638 }
4639
4640 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4641 // Check for a better reference binding based on the kind of bindings.
4642 if (isBetterReferenceBindingKind(SCS1, SCS2))
4643 return ImplicitConversionSequence::Better;
4644 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4645 return ImplicitConversionSequence::Worse;
4646 }
4647
4648 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4649 // bullet 3).
4650 if (ImplicitConversionSequence::CompareKind QualCK
4651 = CompareQualificationConversions(S, SCS1, SCS2))
4652 return QualCK;
4653
4654 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4655 // C++ [over.ics.rank]p3b4:
4656 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4657 // which the references refer are the same type except for
4658 // top-level cv-qualifiers, and the type to which the reference
4659 // initialized by S2 refers is more cv-qualified than the type
4660 // to which the reference initialized by S1 refers.
4661 QualType T1 = SCS1.getToType(Idx: 2);
4662 QualType T2 = SCS2.getToType(Idx: 2);
4663 T1 = S.Context.getCanonicalType(T: T1);
4664 T2 = S.Context.getCanonicalType(T: T2);
4665 Qualifiers T1Quals, T2Quals;
4666 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4667 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4668 if (UnqualT1 == UnqualT2) {
4669 // Objective-C++ ARC: If the references refer to objects with different
4670 // lifetimes, prefer bindings that don't change lifetime.
4671 if (SCS1.ObjCLifetimeConversionBinding !=
4672 SCS2.ObjCLifetimeConversionBinding) {
4673 return SCS1.ObjCLifetimeConversionBinding
4674 ? ImplicitConversionSequence::Worse
4675 : ImplicitConversionSequence::Better;
4676 }
4677
4678 // If the type is an array type, promote the element qualifiers to the
4679 // type for comparison.
4680 if (isa<ArrayType>(Val: T1) && T1Quals)
4681 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4682 if (isa<ArrayType>(Val: T2) && T2Quals)
4683 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4684 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4685 return ImplicitConversionSequence::Better;
4686 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4687 return ImplicitConversionSequence::Worse;
4688 }
4689 }
4690
4691 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4692 // floating-to-integral conversion if the integral conversion
4693 // is between types of the same size.
4694 // For example:
4695 // void f(float);
4696 // void f(int);
4697 // int main {
4698 // long a;
4699 // f(a);
4700 // }
4701 // Here, MSVC will call f(int) instead of generating a compile error
4702 // as clang will do in standard mode.
4703 if (S.getLangOpts().MSVCCompat &&
4704 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4705 SCS1.Second == ICK_Integral_Conversion &&
4706 SCS2.Second == ICK_Floating_Integral &&
4707 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4708 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4709 return ImplicitConversionSequence::Better;
4710
4711 // Prefer a compatible vector conversion over a lax vector conversion
4712 // For example:
4713 //
4714 // typedef float __v4sf __attribute__((__vector_size__(16)));
4715 // void f(vector float);
4716 // void f(vector signed int);
4717 // int main() {
4718 // __v4sf a;
4719 // f(a);
4720 // }
4721 // Here, we'd like to choose f(vector float) and not
4722 // report an ambiguous call error
4723 if (SCS1.Second == ICK_Vector_Conversion &&
4724 SCS2.Second == ICK_Vector_Conversion) {
4725 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4726 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4727 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4728 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4729
4730 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4731 return SCS1IsCompatibleVectorConversion
4732 ? ImplicitConversionSequence::Better
4733 : ImplicitConversionSequence::Worse;
4734 }
4735
4736 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4737 SCS2.Second == ICK_SVE_Vector_Conversion) {
4738 bool SCS1IsCompatibleSVEVectorConversion =
4739 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4740 bool SCS2IsCompatibleSVEVectorConversion =
4741 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4742
4743 if (SCS1IsCompatibleSVEVectorConversion !=
4744 SCS2IsCompatibleSVEVectorConversion)
4745 return SCS1IsCompatibleSVEVectorConversion
4746 ? ImplicitConversionSequence::Better
4747 : ImplicitConversionSequence::Worse;
4748 }
4749
4750 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4751 SCS2.Second == ICK_RVV_Vector_Conversion) {
4752 bool SCS1IsCompatibleRVVVectorConversion =
4753 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4754 bool SCS2IsCompatibleRVVVectorConversion =
4755 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4756
4757 if (SCS1IsCompatibleRVVVectorConversion !=
4758 SCS2IsCompatibleRVVVectorConversion)
4759 return SCS1IsCompatibleRVVVectorConversion
4760 ? ImplicitConversionSequence::Better
4761 : ImplicitConversionSequence::Worse;
4762 }
4763 return ImplicitConversionSequence::Indistinguishable;
4764}
4765
4766/// CompareQualificationConversions - Compares two standard conversion
4767/// sequences to determine whether they can be ranked based on their
4768/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4769static ImplicitConversionSequence::CompareKind
4770CompareQualificationConversions(Sema &S,
4771 const StandardConversionSequence& SCS1,
4772 const StandardConversionSequence& SCS2) {
4773 // C++ [over.ics.rank]p3:
4774 // -- S1 and S2 differ only in their qualification conversion and
4775 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4776 // [C++98]
4777 // [...] and the cv-qualification signature of type T1 is a proper subset
4778 // of the cv-qualification signature of type T2, and S1 is not the
4779 // deprecated string literal array-to-pointer conversion (4.2).
4780 // [C++2a]
4781 // [...] where T1 can be converted to T2 by a qualification conversion.
4782 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4783 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4784 return ImplicitConversionSequence::Indistinguishable;
4785
4786 // FIXME: the example in the standard doesn't use a qualification
4787 // conversion (!)
4788 QualType T1 = SCS1.getToType(Idx: 2);
4789 QualType T2 = SCS2.getToType(Idx: 2);
4790 T1 = S.Context.getCanonicalType(T: T1);
4791 T2 = S.Context.getCanonicalType(T: T2);
4792 assert(!T1->isReferenceType() && !T2->isReferenceType());
4793 Qualifiers T1Quals, T2Quals;
4794 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4795 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4796
4797 // If the types are the same, we won't learn anything by unwrapping
4798 // them.
4799 if (UnqualT1 == UnqualT2)
4800 return ImplicitConversionSequence::Indistinguishable;
4801
4802 // Don't ever prefer a standard conversion sequence that uses the deprecated
4803 // string literal array to pointer conversion.
4804 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4805 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4806
4807 // Objective-C++ ARC:
4808 // Prefer qualification conversions not involving a change in lifetime
4809 // to qualification conversions that do change lifetime.
4810 if (SCS1.QualificationIncludesObjCLifetime &&
4811 !SCS2.QualificationIncludesObjCLifetime)
4812 CanPick1 = false;
4813 if (SCS2.QualificationIncludesObjCLifetime &&
4814 !SCS1.QualificationIncludesObjCLifetime)
4815 CanPick2 = false;
4816
4817 bool ObjCLifetimeConversion;
4818 if (CanPick1 &&
4819 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
4820 CanPick1 = false;
4821 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4822 // directions, so we can't short-cut this second check in general.
4823 if (CanPick2 &&
4824 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
4825 CanPick2 = false;
4826
4827 if (CanPick1 != CanPick2)
4828 return CanPick1 ? ImplicitConversionSequence::Better
4829 : ImplicitConversionSequence::Worse;
4830 return ImplicitConversionSequence::Indistinguishable;
4831}
4832
4833/// CompareDerivedToBaseConversions - Compares two standard conversion
4834/// sequences to determine whether they can be ranked based on their
4835/// various kinds of derived-to-base conversions (C++
4836/// [over.ics.rank]p4b3). As part of these checks, we also look at
4837/// conversions between Objective-C interface types.
4838static ImplicitConversionSequence::CompareKind
4839CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4840 const StandardConversionSequence& SCS1,
4841 const StandardConversionSequence& SCS2) {
4842 QualType FromType1 = SCS1.getFromType();
4843 QualType ToType1 = SCS1.getToType(Idx: 1);
4844 QualType FromType2 = SCS2.getFromType();
4845 QualType ToType2 = SCS2.getToType(Idx: 1);
4846
4847 // Adjust the types we're converting from via the array-to-pointer
4848 // conversion, if we need to.
4849 if (SCS1.First == ICK_Array_To_Pointer)
4850 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4851 if (SCS2.First == ICK_Array_To_Pointer)
4852 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4853
4854 // Canonicalize all of the types.
4855 FromType1 = S.Context.getCanonicalType(T: FromType1);
4856 ToType1 = S.Context.getCanonicalType(T: ToType1);
4857 FromType2 = S.Context.getCanonicalType(T: FromType2);
4858 ToType2 = S.Context.getCanonicalType(T: ToType2);
4859
4860 // C++ [over.ics.rank]p4b3:
4861 //
4862 // If class B is derived directly or indirectly from class A and
4863 // class C is derived directly or indirectly from B,
4864 //
4865 // Compare based on pointer conversions.
4866 if (SCS1.Second == ICK_Pointer_Conversion &&
4867 SCS2.Second == ICK_Pointer_Conversion &&
4868 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4869 FromType1->isPointerType() && FromType2->isPointerType() &&
4870 ToType1->isPointerType() && ToType2->isPointerType()) {
4871 QualType FromPointee1 =
4872 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4873 QualType ToPointee1 =
4874 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4875 QualType FromPointee2 =
4876 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4877 QualType ToPointee2 =
4878 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4879
4880 // -- conversion of C* to B* is better than conversion of C* to A*,
4881 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4882 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4883 return ImplicitConversionSequence::Better;
4884 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4885 return ImplicitConversionSequence::Worse;
4886 }
4887
4888 // -- conversion of B* to A* is better than conversion of C* to A*,
4889 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4890 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4891 return ImplicitConversionSequence::Better;
4892 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4893 return ImplicitConversionSequence::Worse;
4894 }
4895 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4896 SCS2.Second == ICK_Pointer_Conversion) {
4897 const ObjCObjectPointerType *FromPtr1
4898 = FromType1->getAs<ObjCObjectPointerType>();
4899 const ObjCObjectPointerType *FromPtr2
4900 = FromType2->getAs<ObjCObjectPointerType>();
4901 const ObjCObjectPointerType *ToPtr1
4902 = ToType1->getAs<ObjCObjectPointerType>();
4903 const ObjCObjectPointerType *ToPtr2
4904 = ToType2->getAs<ObjCObjectPointerType>();
4905
4906 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4907 // Apply the same conversion ranking rules for Objective-C pointer types
4908 // that we do for C++ pointers to class types. However, we employ the
4909 // Objective-C pseudo-subtyping relationship used for assignment of
4910 // Objective-C pointer types.
4911 bool FromAssignLeft
4912 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
4913 bool FromAssignRight
4914 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
4915 bool ToAssignLeft
4916 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
4917 bool ToAssignRight
4918 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
4919
4920 // A conversion to an a non-id object pointer type or qualified 'id'
4921 // type is better than a conversion to 'id'.
4922 if (ToPtr1->isObjCIdType() &&
4923 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4924 return ImplicitConversionSequence::Worse;
4925 if (ToPtr2->isObjCIdType() &&
4926 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4927 return ImplicitConversionSequence::Better;
4928
4929 // A conversion to a non-id object pointer type is better than a
4930 // conversion to a qualified 'id' type
4931 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4932 return ImplicitConversionSequence::Worse;
4933 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4934 return ImplicitConversionSequence::Better;
4935
4936 // A conversion to an a non-Class object pointer type or qualified 'Class'
4937 // type is better than a conversion to 'Class'.
4938 if (ToPtr1->isObjCClassType() &&
4939 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4940 return ImplicitConversionSequence::Worse;
4941 if (ToPtr2->isObjCClassType() &&
4942 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4943 return ImplicitConversionSequence::Better;
4944
4945 // A conversion to a non-Class object pointer type is better than a
4946 // conversion to a qualified 'Class' type.
4947 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4948 return ImplicitConversionSequence::Worse;
4949 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4950 return ImplicitConversionSequence::Better;
4951
4952 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4953 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
4954 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4955 (ToAssignLeft != ToAssignRight)) {
4956 if (FromPtr1->isSpecialized()) {
4957 // "conversion of B<A> * to B * is better than conversion of B * to
4958 // C *.
4959 bool IsFirstSame =
4960 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4961 bool IsSecondSame =
4962 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4963 if (IsFirstSame) {
4964 if (!IsSecondSame)
4965 return ImplicitConversionSequence::Better;
4966 } else if (IsSecondSame)
4967 return ImplicitConversionSequence::Worse;
4968 }
4969 return ToAssignLeft? ImplicitConversionSequence::Worse
4970 : ImplicitConversionSequence::Better;
4971 }
4972
4973 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4974 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
4975 (FromAssignLeft != FromAssignRight))
4976 return FromAssignLeft? ImplicitConversionSequence::Better
4977 : ImplicitConversionSequence::Worse;
4978 }
4979 }
4980
4981 // Ranking of member-pointer types.
4982 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4983 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4984 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4985 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4986 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4987 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4988 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4989 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4990 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4991 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4992 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4993 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4994 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4995 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4996 return ImplicitConversionSequence::Worse;
4997 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4998 return ImplicitConversionSequence::Better;
4999 }
5000 // conversion of B::* to C::* is better than conversion of A::* to C::*
5001 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5002 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5003 return ImplicitConversionSequence::Better;
5004 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5005 return ImplicitConversionSequence::Worse;
5006 }
5007 }
5008
5009 if (SCS1.Second == ICK_Derived_To_Base) {
5010 // -- conversion of C to B is better than conversion of C to A,
5011 // -- binding of an expression of type C to a reference of type
5012 // B& is better than binding an expression of type C to a
5013 // reference of type A&,
5014 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5015 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5016 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5017 return ImplicitConversionSequence::Better;
5018 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5019 return ImplicitConversionSequence::Worse;
5020 }
5021
5022 // -- conversion of B to A is better than conversion of C to A.
5023 // -- binding of an expression of type B to a reference of type
5024 // A& is better than binding an expression of type C to a
5025 // reference of type A&,
5026 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5027 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5028 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5029 return ImplicitConversionSequence::Better;
5030 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5031 return ImplicitConversionSequence::Worse;
5032 }
5033 }
5034
5035 return ImplicitConversionSequence::Indistinguishable;
5036}
5037
5038static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5039 if (!T.getQualifiers().hasUnaligned())
5040 return T;
5041
5042 Qualifiers Q;
5043 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5044 Q.removeUnaligned();
5045 return Ctx.getQualifiedType(T, Qs: Q);
5046}
5047
5048Sema::ReferenceCompareResult
5049Sema::CompareReferenceRelationship(SourceLocation Loc,
5050 QualType OrigT1, QualType OrigT2,
5051 ReferenceConversions *ConvOut) {
5052 assert(!OrigT1->isReferenceType() &&
5053 "T1 must be the pointee type of the reference type");
5054 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5055
5056 QualType T1 = Context.getCanonicalType(T: OrigT1);
5057 QualType T2 = Context.getCanonicalType(T: OrigT2);
5058 Qualifiers T1Quals, T2Quals;
5059 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5060 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5061
5062 ReferenceConversions ConvTmp;
5063 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5064 Conv = ReferenceConversions();
5065
5066 // C++2a [dcl.init.ref]p4:
5067 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5068 // reference-related to "cv2 T2" if T1 is similar to T2, or
5069 // T1 is a base class of T2.
5070 // "cv1 T1" is reference-compatible with "cv2 T2" if
5071 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5072 // "pointer to cv1 T1" via a standard conversion sequence.
5073
5074 // Check for standard conversions we can apply to pointers: derived-to-base
5075 // conversions, ObjC pointer conversions, and function pointer conversions.
5076 // (Qualification conversions are checked last.)
5077 if (UnqualT1 == UnqualT2) {
5078 // Nothing to do.
5079 } else if (isCompleteType(Loc, T: OrigT2) &&
5080 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5081 Conv |= ReferenceConversions::DerivedToBase;
5082 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5083 UnqualT2->isObjCObjectOrInterfaceType() &&
5084 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5085 Conv |= ReferenceConversions::ObjC;
5086 else if (UnqualT2->isFunctionType() &&
5087 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5088 Conv |= ReferenceConversions::Function;
5089 // No need to check qualifiers; function types don't have them.
5090 return Ref_Compatible;
5091 }
5092 bool ConvertedReferent = Conv != 0;
5093
5094 // We can have a qualification conversion. Compute whether the types are
5095 // similar at the same time.
5096 bool PreviousToQualsIncludeConst = true;
5097 bool TopLevel = true;
5098 do {
5099 if (T1 == T2)
5100 break;
5101
5102 // We will need a qualification conversion.
5103 Conv |= ReferenceConversions::Qualification;
5104
5105 // Track whether we performed a qualification conversion anywhere other
5106 // than the top level. This matters for ranking reference bindings in
5107 // overload resolution.
5108 if (!TopLevel)
5109 Conv |= ReferenceConversions::NestedQualification;
5110
5111 // MS compiler ignores __unaligned qualifier for references; do the same.
5112 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5113 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5114
5115 // If we find a qualifier mismatch, the types are not reference-compatible,
5116 // but are still be reference-related if they're similar.
5117 bool ObjCLifetimeConversion = false;
5118 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5119 PreviousToQualsIncludeConst,
5120 ObjCLifetimeConversion, Ctx: getASTContext()))
5121 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5122 ? Ref_Related
5123 : Ref_Incompatible;
5124
5125 // FIXME: Should we track this for any level other than the first?
5126 if (ObjCLifetimeConversion)
5127 Conv |= ReferenceConversions::ObjCLifetime;
5128
5129 TopLevel = false;
5130 } while (Context.UnwrapSimilarTypes(T1, T2));
5131
5132 // At this point, if the types are reference-related, we must either have the
5133 // same inner type (ignoring qualifiers), or must have already worked out how
5134 // to convert the referent.
5135 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5136 ? Ref_Compatible
5137 : Ref_Incompatible;
5138}
5139
5140/// Look for a user-defined conversion to a value reference-compatible
5141/// with DeclType. Return true if something definite is found.
5142static bool
5143FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5144 QualType DeclType, SourceLocation DeclLoc,
5145 Expr *Init, QualType T2, bool AllowRvalues,
5146 bool AllowExplicit) {
5147 assert(T2->isRecordType() && "Can only find conversions of record types.");
5148 auto *T2RecordDecl = cast<CXXRecordDecl>(Val: T2->castAs<RecordType>()->getDecl());
5149
5150 OverloadCandidateSet CandidateSet(
5151 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5152 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5153 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5154 NamedDecl *D = *I;
5155 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5156 if (isa<UsingShadowDecl>(Val: D))
5157 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5158
5159 FunctionTemplateDecl *ConvTemplate
5160 = dyn_cast<FunctionTemplateDecl>(Val: D);
5161 CXXConversionDecl *Conv;
5162 if (ConvTemplate)
5163 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5164 else
5165 Conv = cast<CXXConversionDecl>(Val: D);
5166
5167 if (AllowRvalues) {
5168 // If we are initializing an rvalue reference, don't permit conversion
5169 // functions that return lvalues.
5170 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5171 const ReferenceType *RefType
5172 = Conv->getConversionType()->getAs<LValueReferenceType>();
5173 if (RefType && !RefType->getPointeeType()->isFunctionType())
5174 continue;
5175 }
5176
5177 if (!ConvTemplate &&
5178 S.CompareReferenceRelationship(
5179 Loc: DeclLoc,
5180 OrigT1: Conv->getConversionType()
5181 .getNonReferenceType()
5182 .getUnqualifiedType(),
5183 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5184 Sema::Ref_Incompatible)
5185 continue;
5186 } else {
5187 // If the conversion function doesn't return a reference type,
5188 // it can't be considered for this conversion. An rvalue reference
5189 // is only acceptable if its referencee is a function type.
5190
5191 const ReferenceType *RefType =
5192 Conv->getConversionType()->getAs<ReferenceType>();
5193 if (!RefType ||
5194 (!RefType->isLValueReferenceType() &&
5195 !RefType->getPointeeType()->isFunctionType()))
5196 continue;
5197 }
5198
5199 if (ConvTemplate)
5200 S.AddTemplateConversionCandidate(
5201 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5202 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5203 else
5204 S.AddConversionCandidate(
5205 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5206 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5207 }
5208
5209 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5210
5211 OverloadCandidateSet::iterator Best;
5212 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5213 case OR_Success:
5214
5215 assert(Best->HasFinalConversion);
5216
5217 // C++ [over.ics.ref]p1:
5218 //
5219 // [...] If the parameter binds directly to the result of
5220 // applying a conversion function to the argument
5221 // expression, the implicit conversion sequence is a
5222 // user-defined conversion sequence (13.3.3.1.2), with the
5223 // second standard conversion sequence either an identity
5224 // conversion or, if the conversion function returns an
5225 // entity of a type that is a derived class of the parameter
5226 // type, a derived-to-base Conversion.
5227 if (!Best->FinalConversion.DirectBinding)
5228 return false;
5229
5230 ICS.setUserDefined();
5231 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5232 ICS.UserDefined.After = Best->FinalConversion;
5233 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5234 ICS.UserDefined.ConversionFunction = Best->Function;
5235 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5236 ICS.UserDefined.EllipsisConversion = false;
5237 assert(ICS.UserDefined.After.ReferenceBinding &&
5238 ICS.UserDefined.After.DirectBinding &&
5239 "Expected a direct reference binding!");
5240 return true;
5241
5242 case OR_Ambiguous:
5243 ICS.setAmbiguous();
5244 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5245 Cand != CandidateSet.end(); ++Cand)
5246 if (Cand->Best)
5247 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5248 return true;
5249
5250 case OR_No_Viable_Function:
5251 case OR_Deleted:
5252 // There was no suitable conversion, or we found a deleted
5253 // conversion; continue with other checks.
5254 return false;
5255 }
5256
5257 llvm_unreachable("Invalid OverloadResult!");
5258}
5259
5260/// Compute an implicit conversion sequence for reference
5261/// initialization.
5262static ImplicitConversionSequence
5263TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5264 SourceLocation DeclLoc,
5265 bool SuppressUserConversions,
5266 bool AllowExplicit) {
5267 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5268
5269 // Most paths end in a failed conversion.
5270 ImplicitConversionSequence ICS;
5271 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5272
5273 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5274 QualType T2 = Init->getType();
5275
5276 // If the initializer is the address of an overloaded function, try
5277 // to resolve the overloaded function. If all goes well, T2 is the
5278 // type of the resulting function.
5279 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5280 DeclAccessPair Found;
5281 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5282 Complain: false, Found))
5283 T2 = Fn->getType();
5284 }
5285
5286 // Compute some basic properties of the types and the initializer.
5287 bool isRValRef = DeclType->isRValueReferenceType();
5288 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5289
5290 Sema::ReferenceConversions RefConv;
5291 Sema::ReferenceCompareResult RefRelationship =
5292 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5293
5294 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5295 ICS.setStandard();
5296 ICS.Standard.First = ICK_Identity;
5297 // FIXME: A reference binding can be a function conversion too. We should
5298 // consider that when ordering reference-to-function bindings.
5299 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5300 ? ICK_Derived_To_Base
5301 : (RefConv & Sema::ReferenceConversions::ObjC)
5302 ? ICK_Compatible_Conversion
5303 : ICK_Identity;
5304 ICS.Standard.Dimension = ICK_Identity;
5305 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5306 // a reference binding that performs a non-top-level qualification
5307 // conversion as a qualification conversion, not as an identity conversion.
5308 ICS.Standard.Third = (RefConv &
5309 Sema::ReferenceConversions::NestedQualification)
5310 ? ICK_Qualification
5311 : ICK_Identity;
5312 ICS.Standard.setFromType(T2);
5313 ICS.Standard.setToType(Idx: 0, T: T2);
5314 ICS.Standard.setToType(Idx: 1, T: T1);
5315 ICS.Standard.setToType(Idx: 2, T: T1);
5316 ICS.Standard.ReferenceBinding = true;
5317 ICS.Standard.DirectBinding = BindsDirectly;
5318 ICS.Standard.IsLvalueReference = !isRValRef;
5319 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5320 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5321 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5322 ICS.Standard.ObjCLifetimeConversionBinding =
5323 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5324 ICS.Standard.FromBracedInitList = false;
5325 ICS.Standard.CopyConstructor = nullptr;
5326 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5327 };
5328
5329 // C++0x [dcl.init.ref]p5:
5330 // A reference to type "cv1 T1" is initialized by an expression
5331 // of type "cv2 T2" as follows:
5332
5333 // -- If reference is an lvalue reference and the initializer expression
5334 if (!isRValRef) {
5335 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5336 // reference-compatible with "cv2 T2," or
5337 //
5338 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5339 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5340 // C++ [over.ics.ref]p1:
5341 // When a parameter of reference type binds directly (8.5.3)
5342 // to an argument expression, the implicit conversion sequence
5343 // is the identity conversion, unless the argument expression
5344 // has a type that is a derived class of the parameter type,
5345 // in which case the implicit conversion sequence is a
5346 // derived-to-base Conversion (13.3.3.1).
5347 SetAsReferenceBinding(/*BindsDirectly=*/true);
5348
5349 // Nothing more to do: the inaccessibility/ambiguity check for
5350 // derived-to-base conversions is suppressed when we're
5351 // computing the implicit conversion sequence (C++
5352 // [over.best.ics]p2).
5353 return ICS;
5354 }
5355
5356 // -- has a class type (i.e., T2 is a class type), where T1 is
5357 // not reference-related to T2, and can be implicitly
5358 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5359 // is reference-compatible with "cv3 T3" 92) (this
5360 // conversion is selected by enumerating the applicable
5361 // conversion functions (13.3.1.6) and choosing the best
5362 // one through overload resolution (13.3)),
5363 if (!SuppressUserConversions && T2->isRecordType() &&
5364 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5365 RefRelationship == Sema::Ref_Incompatible) {
5366 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5367 Init, T2, /*AllowRvalues=*/false,
5368 AllowExplicit))
5369 return ICS;
5370 }
5371 }
5372
5373 // -- Otherwise, the reference shall be an lvalue reference to a
5374 // non-volatile const type (i.e., cv1 shall be const), or the reference
5375 // shall be an rvalue reference.
5376 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5377 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5378 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5379 return ICS;
5380 }
5381
5382 // -- If the initializer expression
5383 //
5384 // -- is an xvalue, class prvalue, array prvalue or function
5385 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5386 if (RefRelationship == Sema::Ref_Compatible &&
5387 (InitCategory.isXValue() ||
5388 (InitCategory.isPRValue() &&
5389 (T2->isRecordType() || T2->isArrayType())) ||
5390 (InitCategory.isLValue() && T2->isFunctionType()))) {
5391 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5392 // binding unless we're binding to a class prvalue.
5393 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5394 // allow the use of rvalue references in C++98/03 for the benefit of
5395 // standard library implementors; therefore, we need the xvalue check here.
5396 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5397 !(InitCategory.isPRValue() || T2->isRecordType()));
5398 return ICS;
5399 }
5400
5401 // -- has a class type (i.e., T2 is a class type), where T1 is not
5402 // reference-related to T2, and can be implicitly converted to
5403 // an xvalue, class prvalue, or function lvalue of type
5404 // "cv3 T3", where "cv1 T1" is reference-compatible with
5405 // "cv3 T3",
5406 //
5407 // then the reference is bound to the value of the initializer
5408 // expression in the first case and to the result of the conversion
5409 // in the second case (or, in either case, to an appropriate base
5410 // class subobject).
5411 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5412 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5413 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5414 Init, T2, /*AllowRvalues=*/true,
5415 AllowExplicit)) {
5416 // In the second case, if the reference is an rvalue reference
5417 // and the second standard conversion sequence of the
5418 // user-defined conversion sequence includes an lvalue-to-rvalue
5419 // conversion, the program is ill-formed.
5420 if (ICS.isUserDefined() && isRValRef &&
5421 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5422 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5423
5424 return ICS;
5425 }
5426
5427 // A temporary of function type cannot be created; don't even try.
5428 if (T1->isFunctionType())
5429 return ICS;
5430
5431 // -- Otherwise, a temporary of type "cv1 T1" is created and
5432 // initialized from the initializer expression using the
5433 // rules for a non-reference copy initialization (8.5). The
5434 // reference is then bound to the temporary. If T1 is
5435 // reference-related to T2, cv1 must be the same
5436 // cv-qualification as, or greater cv-qualification than,
5437 // cv2; otherwise, the program is ill-formed.
5438 if (RefRelationship == Sema::Ref_Related) {
5439 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5440 // we would be reference-compatible or reference-compatible with
5441 // added qualification. But that wasn't the case, so the reference
5442 // initialization fails.
5443 //
5444 // Note that we only want to check address spaces and cvr-qualifiers here.
5445 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5446 Qualifiers T1Quals = T1.getQualifiers();
5447 Qualifiers T2Quals = T2.getQualifiers();
5448 T1Quals.removeObjCGCAttr();
5449 T1Quals.removeObjCLifetime();
5450 T2Quals.removeObjCGCAttr();
5451 T2Quals.removeObjCLifetime();
5452 // MS compiler ignores __unaligned qualifier for references; do the same.
5453 T1Quals.removeUnaligned();
5454 T2Quals.removeUnaligned();
5455 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5456 return ICS;
5457 }
5458
5459 // If at least one of the types is a class type, the types are not
5460 // related, and we aren't allowed any user conversions, the
5461 // reference binding fails. This case is important for breaking
5462 // recursion, since TryImplicitConversion below will attempt to
5463 // create a temporary through the use of a copy constructor.
5464 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5465 (T1->isRecordType() || T2->isRecordType()))
5466 return ICS;
5467
5468 // If T1 is reference-related to T2 and the reference is an rvalue
5469 // reference, the initializer expression shall not be an lvalue.
5470 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5471 Init->Classify(Ctx&: S.Context).isLValue()) {
5472 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5473 return ICS;
5474 }
5475
5476 // C++ [over.ics.ref]p2:
5477 // When a parameter of reference type is not bound directly to
5478 // an argument expression, the conversion sequence is the one
5479 // required to convert the argument expression to the
5480 // underlying type of the reference according to
5481 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5482 // to copy-initializing a temporary of the underlying type with
5483 // the argument expression. Any difference in top-level
5484 // cv-qualification is subsumed by the initialization itself
5485 // and does not constitute a conversion.
5486 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5487 AllowExplicit: AllowedExplicit::None,
5488 /*InOverloadResolution=*/false,
5489 /*CStyle=*/false,
5490 /*AllowObjCWritebackConversion=*/false,
5491 /*AllowObjCConversionOnExplicit=*/false);
5492
5493 // Of course, that's still a reference binding.
5494 if (ICS.isStandard()) {
5495 ICS.Standard.ReferenceBinding = true;
5496 ICS.Standard.IsLvalueReference = !isRValRef;
5497 ICS.Standard.BindsToFunctionLvalue = false;
5498 ICS.Standard.BindsToRvalue = true;
5499 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5500 ICS.Standard.ObjCLifetimeConversionBinding = false;
5501 } else if (ICS.isUserDefined()) {
5502 const ReferenceType *LValRefType =
5503 ICS.UserDefined.ConversionFunction->getReturnType()
5504 ->getAs<LValueReferenceType>();
5505
5506 // C++ [over.ics.ref]p3:
5507 // Except for an implicit object parameter, for which see 13.3.1, a
5508 // standard conversion sequence cannot be formed if it requires [...]
5509 // binding an rvalue reference to an lvalue other than a function
5510 // lvalue.
5511 // Note that the function case is not possible here.
5512 if (isRValRef && LValRefType) {
5513 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5514 return ICS;
5515 }
5516
5517 ICS.UserDefined.After.ReferenceBinding = true;
5518 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5519 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5520 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5521 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5522 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5523 ICS.UserDefined.After.FromBracedInitList = false;
5524 }
5525
5526 return ICS;
5527}
5528
5529static ImplicitConversionSequence
5530TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5531 bool SuppressUserConversions,
5532 bool InOverloadResolution,
5533 bool AllowObjCWritebackConversion,
5534 bool AllowExplicit = false);
5535
5536/// TryListConversion - Try to copy-initialize a value of type ToType from the
5537/// initializer list From.
5538static ImplicitConversionSequence
5539TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5540 bool SuppressUserConversions,
5541 bool InOverloadResolution,
5542 bool AllowObjCWritebackConversion) {
5543 // C++11 [over.ics.list]p1:
5544 // When an argument is an initializer list, it is not an expression and
5545 // special rules apply for converting it to a parameter type.
5546
5547 ImplicitConversionSequence Result;
5548 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5549
5550 // We need a complete type for what follows. With one C++20 exception,
5551 // incomplete types can never be initialized from init lists.
5552 QualType InitTy = ToType;
5553 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5554 if (AT && S.getLangOpts().CPlusPlus20)
5555 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5556 // C++20 allows list initialization of an incomplete array type.
5557 InitTy = IAT->getElementType();
5558 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5559 return Result;
5560
5561 // C++20 [over.ics.list]/2:
5562 // If the initializer list is a designated-initializer-list, a conversion
5563 // is only possible if the parameter has an aggregate type
5564 //
5565 // FIXME: The exception for reference initialization here is not part of the
5566 // language rules, but follow other compilers in adding it as a tentative DR
5567 // resolution.
5568 bool IsDesignatedInit = From->hasDesignatedInit();
5569 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5570 IsDesignatedInit)
5571 return Result;
5572
5573 // Per DR1467 and DR2137:
5574 // If the parameter type is an aggregate class X and the initializer list
5575 // has a single element of type cv U, where U is X or a class derived from
5576 // X, the implicit conversion sequence is the one required to convert the
5577 // element to the parameter type.
5578 //
5579 // Otherwise, if the parameter type is a character array [... ]
5580 // and the initializer list has a single element that is an
5581 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5582 // implicit conversion sequence is the identity conversion.
5583 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5584 if (ToType->isRecordType() && ToType->isAggregateType()) {
5585 QualType InitType = From->getInit(Init: 0)->getType();
5586 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5587 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5588 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5589 SuppressUserConversions,
5590 InOverloadResolution,
5591 AllowObjCWritebackConversion);
5592 }
5593
5594 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5595 InitializedEntity Entity =
5596 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5597 /*Consumed=*/false);
5598 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5599 Result.setStandard();
5600 Result.Standard.setAsIdentityConversion();
5601 Result.Standard.setFromType(ToType);
5602 Result.Standard.setAllToTypes(ToType);
5603 return Result;
5604 }
5605 }
5606 }
5607
5608 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5609 // C++11 [over.ics.list]p2:
5610 // If the parameter type is std::initializer_list<X> or "array of X" and
5611 // all the elements can be implicitly converted to X, the implicit
5612 // conversion sequence is the worst conversion necessary to convert an
5613 // element of the list to X.
5614 //
5615 // C++14 [over.ics.list]p3:
5616 // Otherwise, if the parameter type is "array of N X", if the initializer
5617 // list has exactly N elements or if it has fewer than N elements and X is
5618 // default-constructible, and if all the elements of the initializer list
5619 // can be implicitly converted to X, the implicit conversion sequence is
5620 // the worst conversion necessary to convert an element of the list to X.
5621 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5622 unsigned e = From->getNumInits();
5623 ImplicitConversionSequence DfltElt;
5624 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5625 ToType: QualType());
5626 QualType ContTy = ToType;
5627 bool IsUnbounded = false;
5628 if (AT) {
5629 InitTy = AT->getElementType();
5630 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5631 if (CT->getSize().ult(RHS: e)) {
5632 // Too many inits, fatally bad
5633 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5634 ToType);
5635 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5636 return Result;
5637 }
5638 if (CT->getSize().ugt(RHS: e)) {
5639 // Need an init from empty {}, is there one?
5640 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5641 From->getEndLoc());
5642 EmptyList.setType(S.Context.VoidTy);
5643 DfltElt = TryListConversion(
5644 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5645 InOverloadResolution, AllowObjCWritebackConversion);
5646 if (DfltElt.isBad()) {
5647 // No {} init, fatally bad
5648 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5649 ToType);
5650 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5651 return Result;
5652 }
5653 }
5654 } else {
5655 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5656 IsUnbounded = true;
5657 if (!e) {
5658 // Cannot convert to zero-sized.
5659 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5660 ToType);
5661 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5662 return Result;
5663 }
5664 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5665 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5666 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5667 }
5668 }
5669
5670 Result.setStandard();
5671 Result.Standard.setAsIdentityConversion();
5672 Result.Standard.setFromType(InitTy);
5673 Result.Standard.setAllToTypes(InitTy);
5674 for (unsigned i = 0; i < e; ++i) {
5675 Expr *Init = From->getInit(Init: i);
5676 ImplicitConversionSequence ICS = TryCopyInitialization(
5677 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5678 AllowObjCWritebackConversion);
5679
5680 // Keep the worse conversion seen so far.
5681 // FIXME: Sequences are not totally ordered, so 'worse' can be
5682 // ambiguous. CWG has been informed.
5683 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5684 ICS2: Result) ==
5685 ImplicitConversionSequence::Worse) {
5686 Result = ICS;
5687 // Bail as soon as we find something unconvertible.
5688 if (Result.isBad()) {
5689 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5690 return Result;
5691 }
5692 }
5693 }
5694
5695 // If we needed any implicit {} initialization, compare that now.
5696 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5697 // has been informed that this might not be the best thing.
5698 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5699 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5700 ImplicitConversionSequence::Worse)
5701 Result = DfltElt;
5702 // Record the type being initialized so that we may compare sequences
5703 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5704 return Result;
5705 }
5706
5707 // C++14 [over.ics.list]p4:
5708 // C++11 [over.ics.list]p3:
5709 // Otherwise, if the parameter is a non-aggregate class X and overload
5710 // resolution chooses a single best constructor [...] the implicit
5711 // conversion sequence is a user-defined conversion sequence. If multiple
5712 // constructors are viable but none is better than the others, the
5713 // implicit conversion sequence is a user-defined conversion sequence.
5714 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5715 // This function can deal with initializer lists.
5716 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5717 AllowExplicit: AllowedExplicit::None,
5718 InOverloadResolution, /*CStyle=*/false,
5719 AllowObjCWritebackConversion,
5720 /*AllowObjCConversionOnExplicit=*/false);
5721 }
5722
5723 // C++14 [over.ics.list]p5:
5724 // C++11 [over.ics.list]p4:
5725 // Otherwise, if the parameter has an aggregate type which can be
5726 // initialized from the initializer list [...] the implicit conversion
5727 // sequence is a user-defined conversion sequence.
5728 if (ToType->isAggregateType()) {
5729 // Type is an aggregate, argument is an init list. At this point it comes
5730 // down to checking whether the initialization works.
5731 // FIXME: Find out whether this parameter is consumed or not.
5732 InitializedEntity Entity =
5733 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5734 /*Consumed=*/false);
5735 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5736 From)) {
5737 Result.setUserDefined();
5738 Result.UserDefined.Before.setAsIdentityConversion();
5739 // Initializer lists don't have a type.
5740 Result.UserDefined.Before.setFromType(QualType());
5741 Result.UserDefined.Before.setAllToTypes(QualType());
5742
5743 Result.UserDefined.After.setAsIdentityConversion();
5744 Result.UserDefined.After.setFromType(ToType);
5745 Result.UserDefined.After.setAllToTypes(ToType);
5746 Result.UserDefined.ConversionFunction = nullptr;
5747 }
5748 return Result;
5749 }
5750
5751 // C++14 [over.ics.list]p6:
5752 // C++11 [over.ics.list]p5:
5753 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5754 if (ToType->isReferenceType()) {
5755 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5756 // mention initializer lists in any way. So we go by what list-
5757 // initialization would do and try to extrapolate from that.
5758
5759 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5760
5761 // If the initializer list has a single element that is reference-related
5762 // to the parameter type, we initialize the reference from that.
5763 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5764 Expr *Init = From->getInit(Init: 0);
5765
5766 QualType T2 = Init->getType();
5767
5768 // If the initializer is the address of an overloaded function, try
5769 // to resolve the overloaded function. If all goes well, T2 is the
5770 // type of the resulting function.
5771 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5772 DeclAccessPair Found;
5773 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5774 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5775 T2 = Fn->getType();
5776 }
5777
5778 // Compute some basic properties of the types and the initializer.
5779 Sema::ReferenceCompareResult RefRelationship =
5780 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5781
5782 if (RefRelationship >= Sema::Ref_Related) {
5783 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5784 SuppressUserConversions,
5785 /*AllowExplicit=*/false);
5786 }
5787 }
5788
5789 // Otherwise, we bind the reference to a temporary created from the
5790 // initializer list.
5791 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5792 InOverloadResolution,
5793 AllowObjCWritebackConversion);
5794 if (Result.isFailure())
5795 return Result;
5796 assert(!Result.isEllipsis() &&
5797 "Sub-initialization cannot result in ellipsis conversion.");
5798
5799 // Can we even bind to a temporary?
5800 if (ToType->isRValueReferenceType() ||
5801 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5802 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5803 Result.UserDefined.After;
5804 SCS.ReferenceBinding = true;
5805 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5806 SCS.BindsToRvalue = true;
5807 SCS.BindsToFunctionLvalue = false;
5808 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5809 SCS.ObjCLifetimeConversionBinding = false;
5810 SCS.FromBracedInitList = false;
5811
5812 } else
5813 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
5814 FromExpr: From, ToType);
5815 return Result;
5816 }
5817
5818 // C++14 [over.ics.list]p7:
5819 // C++11 [over.ics.list]p6:
5820 // Otherwise, if the parameter type is not a class:
5821 if (!ToType->isRecordType()) {
5822 // - if the initializer list has one element that is not itself an
5823 // initializer list, the implicit conversion sequence is the one
5824 // required to convert the element to the parameter type.
5825 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5826 // single integer.
5827 unsigned NumInits = From->getNumInits();
5828 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
5829 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
5830 Result = TryCopyInitialization(
5831 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
5832 InOverloadResolution, AllowObjCWritebackConversion);
5833 if (Result.isStandard())
5834 Result.Standard.FromBracedInitList = true;
5835 }
5836 // - if the initializer list has no elements, the implicit conversion
5837 // sequence is the identity conversion.
5838 else if (NumInits == 0) {
5839 Result.setStandard();
5840 Result.Standard.setAsIdentityConversion();
5841 Result.Standard.setFromType(ToType);
5842 Result.Standard.setAllToTypes(ToType);
5843 }
5844 return Result;
5845 }
5846
5847 // C++14 [over.ics.list]p8:
5848 // C++11 [over.ics.list]p7:
5849 // In all cases other than those enumerated above, no conversion is possible
5850 return Result;
5851}
5852
5853/// TryCopyInitialization - Try to copy-initialize a value of type
5854/// ToType from the expression From. Return the implicit conversion
5855/// sequence required to pass this argument, which may be a bad
5856/// conversion sequence (meaning that the argument cannot be passed to
5857/// a parameter of this type). If @p SuppressUserConversions, then we
5858/// do not permit any user-defined conversion sequences.
5859static ImplicitConversionSequence
5860TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5861 bool SuppressUserConversions,
5862 bool InOverloadResolution,
5863 bool AllowObjCWritebackConversion,
5864 bool AllowExplicit) {
5865 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
5866 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
5867 InOverloadResolution,AllowObjCWritebackConversion);
5868
5869 if (ToType->isReferenceType())
5870 return TryReferenceInit(S, Init: From, DeclType: ToType,
5871 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
5872 SuppressUserConversions, AllowExplicit);
5873
5874 return TryImplicitConversion(S, From, ToType,
5875 SuppressUserConversions,
5876 AllowExplicit: AllowedExplicit::None,
5877 InOverloadResolution,
5878 /*CStyle=*/false,
5879 AllowObjCWritebackConversion,
5880 /*AllowObjCConversionOnExplicit=*/false);
5881}
5882
5883static bool TryCopyInitialization(const CanQualType FromQTy,
5884 const CanQualType ToQTy,
5885 Sema &S,
5886 SourceLocation Loc,
5887 ExprValueKind FromVK) {
5888 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5889 ImplicitConversionSequence ICS =
5890 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
5891
5892 return !ICS.isBad();
5893}
5894
5895/// TryObjectArgumentInitialization - Try to initialize the object
5896/// parameter of the given member function (@c Method) from the
5897/// expression @p From.
5898static ImplicitConversionSequence TryObjectArgumentInitialization(
5899 Sema &S, SourceLocation Loc, QualType FromType,
5900 Expr::Classification FromClassification, CXXMethodDecl *Method,
5901 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5902 QualType ExplicitParameterType = QualType(),
5903 bool SuppressUserConversion = false) {
5904
5905 // We need to have an object of class type.
5906 if (const auto *PT = FromType->getAs<PointerType>()) {
5907 FromType = PT->getPointeeType();
5908
5909 // When we had a pointer, it's implicitly dereferenced, so we
5910 // better have an lvalue.
5911 assert(FromClassification.isLValue());
5912 }
5913
5914 auto ValueKindFromClassification = [](Expr::Classification C) {
5915 if (C.isPRValue())
5916 return clang::VK_PRValue;
5917 if (C.isXValue())
5918 return VK_XValue;
5919 return clang::VK_LValue;
5920 };
5921
5922 if (Method->isExplicitObjectMemberFunction()) {
5923 if (ExplicitParameterType.isNull())
5924 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5925 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5926 ValueKindFromClassification(FromClassification));
5927 ImplicitConversionSequence ICS = TryCopyInitialization(
5928 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
5929 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
5930 if (ICS.isBad())
5931 ICS.Bad.FromExpr = nullptr;
5932 return ICS;
5933 }
5934
5935 assert(FromType->isRecordType());
5936
5937 QualType ClassType = S.Context.getTypeDeclType(Decl: ActingContext);
5938 // C++98 [class.dtor]p2:
5939 // A destructor can be invoked for a const, volatile or const volatile
5940 // object.
5941 // C++98 [over.match.funcs]p4:
5942 // For static member functions, the implicit object parameter is considered
5943 // to match any object (since if the function is selected, the object is
5944 // discarded).
5945 Qualifiers Quals = Method->getMethodQualifiers();
5946 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
5947 Quals.addConst();
5948 Quals.addVolatile();
5949 }
5950
5951 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
5952
5953 // Set up the conversion sequence as a "bad" conversion, to allow us
5954 // to exit early.
5955 ImplicitConversionSequence ICS;
5956
5957 // C++0x [over.match.funcs]p4:
5958 // For non-static member functions, the type of the implicit object
5959 // parameter is
5960 //
5961 // - "lvalue reference to cv X" for functions declared without a
5962 // ref-qualifier or with the & ref-qualifier
5963 // - "rvalue reference to cv X" for functions declared with the &&
5964 // ref-qualifier
5965 //
5966 // where X is the class of which the function is a member and cv is the
5967 // cv-qualification on the member function declaration.
5968 //
5969 // However, when finding an implicit conversion sequence for the argument, we
5970 // are not allowed to perform user-defined conversions
5971 // (C++ [over.match.funcs]p5). We perform a simplified version of
5972 // reference binding here, that allows class rvalues to bind to
5973 // non-constant references.
5974
5975 // First check the qualifiers.
5976 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
5977 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5978 if (ImplicitParamType.getCVRQualifiers() !=
5979 FromTypeCanon.getLocalCVRQualifiers() &&
5980 !ImplicitParamType.isAtLeastAsQualifiedAs(
5981 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
5982 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5983 FromType, ToType: ImplicitParamType);
5984 return ICS;
5985 }
5986
5987 if (FromTypeCanon.hasAddressSpace()) {
5988 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5989 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5990 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
5991 Ctx: S.getASTContext())) {
5992 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5993 FromType, ToType: ImplicitParamType);
5994 return ICS;
5995 }
5996 }
5997
5998 // Check that we have either the same type or a derived type. It
5999 // affects the conversion rank.
6000 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6001 ImplicitConversionKind SecondKind;
6002 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6003 SecondKind = ICK_Identity;
6004 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6005 SecondKind = ICK_Derived_To_Base;
6006 } else if (!Method->isExplicitObjectMemberFunction()) {
6007 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6008 FromType, ToType: ImplicitParamType);
6009 return ICS;
6010 }
6011
6012 // Check the ref-qualifier.
6013 switch (Method->getRefQualifier()) {
6014 case RQ_None:
6015 // Do nothing; we don't care about lvalueness or rvalueness.
6016 break;
6017
6018 case RQ_LValue:
6019 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6020 // non-const lvalue reference cannot bind to an rvalue
6021 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6022 ToType: ImplicitParamType);
6023 return ICS;
6024 }
6025 break;
6026
6027 case RQ_RValue:
6028 if (!FromClassification.isRValue()) {
6029 // rvalue reference cannot bind to an lvalue
6030 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6031 ToType: ImplicitParamType);
6032 return ICS;
6033 }
6034 break;
6035 }
6036
6037 // Success. Mark this as a reference binding.
6038 ICS.setStandard();
6039 ICS.Standard.setAsIdentityConversion();
6040 ICS.Standard.Second = SecondKind;
6041 ICS.Standard.setFromType(FromType);
6042 ICS.Standard.setAllToTypes(ImplicitParamType);
6043 ICS.Standard.ReferenceBinding = true;
6044 ICS.Standard.DirectBinding = true;
6045 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6046 ICS.Standard.BindsToFunctionLvalue = false;
6047 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6048 ICS.Standard.FromBracedInitList = false;
6049 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6050 = (Method->getRefQualifier() == RQ_None);
6051 return ICS;
6052}
6053
6054/// PerformObjectArgumentInitialization - Perform initialization of
6055/// the implicit object parameter for the given Method with the given
6056/// expression.
6057ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6058 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
6059 CXXMethodDecl *Method) {
6060 QualType FromRecordType, DestType;
6061 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6062
6063 Expr::Classification FromClassification;
6064 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6065 FromRecordType = PT->getPointeeType();
6066 DestType = Method->getThisType();
6067 FromClassification = Expr::Classification::makeSimpleLValue();
6068 } else {
6069 FromRecordType = From->getType();
6070 DestType = ImplicitParamRecordType;
6071 FromClassification = From->Classify(Ctx&: Context);
6072
6073 // CWG2813 [expr.call]p6:
6074 // If the function is an implicit object member function, the object
6075 // expression of the class member access shall be a glvalue [...]
6076 if (From->isPRValue()) {
6077 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6078 BoundToLvalueReference: Method->getRefQualifier() !=
6079 RefQualifierKind::RQ_RValue);
6080 }
6081 }
6082
6083 // Note that we always use the true parent context when performing
6084 // the actual argument initialization.
6085 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6086 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6087 ActingContext: Method->getParent());
6088 if (ICS.isBad()) {
6089 switch (ICS.Bad.Kind) {
6090 case BadConversionSequence::bad_qualifiers: {
6091 Qualifiers FromQs = FromRecordType.getQualifiers();
6092 Qualifiers ToQs = DestType.getQualifiers();
6093 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6094 if (CVR) {
6095 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6096 << Method->getDeclName() << FromRecordType << (CVR - 1)
6097 << From->getSourceRange();
6098 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6099 << Method->getDeclName();
6100 return ExprError();
6101 }
6102 break;
6103 }
6104
6105 case BadConversionSequence::lvalue_ref_to_rvalue:
6106 case BadConversionSequence::rvalue_ref_to_lvalue: {
6107 bool IsRValueQualified =
6108 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6109 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6110 << Method->getDeclName() << FromClassification.isRValue()
6111 << IsRValueQualified;
6112 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6113 << Method->getDeclName();
6114 return ExprError();
6115 }
6116
6117 case BadConversionSequence::no_conversion:
6118 case BadConversionSequence::unrelated_class:
6119 break;
6120
6121 case BadConversionSequence::too_few_initializers:
6122 case BadConversionSequence::too_many_initializers:
6123 llvm_unreachable("Lists are not objects");
6124 }
6125
6126 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6127 << ImplicitParamRecordType << FromRecordType
6128 << From->getSourceRange();
6129 }
6130
6131 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6132 ExprResult FromRes =
6133 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6134 if (FromRes.isInvalid())
6135 return ExprError();
6136 From = FromRes.get();
6137 }
6138
6139 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6140 CastKind CK;
6141 QualType PteeTy = DestType->getPointeeType();
6142 LangAS DestAS =
6143 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6144 if (FromRecordType.getAddressSpace() != DestAS)
6145 CK = CK_AddressSpaceConversion;
6146 else
6147 CK = CK_NoOp;
6148 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6149 }
6150 return From;
6151}
6152
6153/// TryContextuallyConvertToBool - Attempt to contextually convert the
6154/// expression From to bool (C++0x [conv]p3).
6155static ImplicitConversionSequence
6156TryContextuallyConvertToBool(Sema &S, Expr *From) {
6157 // C++ [dcl.init]/17.8:
6158 // - Otherwise, if the initialization is direct-initialization, the source
6159 // type is std::nullptr_t, and the destination type is bool, the initial
6160 // value of the object being initialized is false.
6161 if (From->getType()->isNullPtrType())
6162 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6163 DestType: S.Context.BoolTy,
6164 NeedLValToRVal: From->isGLValue());
6165
6166 // All other direct-initialization of bool is equivalent to an implicit
6167 // conversion to bool in which explicit conversions are permitted.
6168 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6169 /*SuppressUserConversions=*/false,
6170 AllowExplicit: AllowedExplicit::Conversions,
6171 /*InOverloadResolution=*/false,
6172 /*CStyle=*/false,
6173 /*AllowObjCWritebackConversion=*/false,
6174 /*AllowObjCConversionOnExplicit=*/false);
6175}
6176
6177ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6178 if (checkPlaceholderForOverload(S&: *this, E&: From))
6179 return ExprError();
6180
6181 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6182 if (!ICS.isBad())
6183 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6184 Action: AssignmentAction::Converting);
6185
6186 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6187 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6188 << From->getType() << From->getSourceRange();
6189 return ExprError();
6190}
6191
6192/// Check that the specified conversion is permitted in a converted constant
6193/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6194/// is acceptable.
6195static bool CheckConvertedConstantConversions(Sema &S,
6196 StandardConversionSequence &SCS) {
6197 // Since we know that the target type is an integral or unscoped enumeration
6198 // type, most conversion kinds are impossible. All possible First and Third
6199 // conversions are fine.
6200 switch (SCS.Second) {
6201 case ICK_Identity:
6202 case ICK_Integral_Promotion:
6203 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6204 case ICK_Zero_Queue_Conversion:
6205 return true;
6206
6207 case ICK_Boolean_Conversion:
6208 // Conversion from an integral or unscoped enumeration type to bool is
6209 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6210 // conversion, so we allow it in a converted constant expression.
6211 //
6212 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6213 // a lot of popular code. We should at least add a warning for this
6214 // (non-conforming) extension.
6215 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6216 SCS.getToType(Idx: 2)->isBooleanType();
6217
6218 case ICK_Pointer_Conversion:
6219 case ICK_Pointer_Member:
6220 // C++1z: null pointer conversions and null member pointer conversions are
6221 // only permitted if the source type is std::nullptr_t.
6222 return SCS.getFromType()->isNullPtrType();
6223
6224 case ICK_Floating_Promotion:
6225 case ICK_Complex_Promotion:
6226 case ICK_Floating_Conversion:
6227 case ICK_Complex_Conversion:
6228 case ICK_Floating_Integral:
6229 case ICK_Compatible_Conversion:
6230 case ICK_Derived_To_Base:
6231 case ICK_Vector_Conversion:
6232 case ICK_SVE_Vector_Conversion:
6233 case ICK_RVV_Vector_Conversion:
6234 case ICK_HLSL_Vector_Splat:
6235 case ICK_Vector_Splat:
6236 case ICK_Complex_Real:
6237 case ICK_Block_Pointer_Conversion:
6238 case ICK_TransparentUnionConversion:
6239 case ICK_Writeback_Conversion:
6240 case ICK_Zero_Event_Conversion:
6241 case ICK_C_Only_Conversion:
6242 case ICK_Incompatible_Pointer_Conversion:
6243 case ICK_Fixed_Point_Conversion:
6244 case ICK_HLSL_Vector_Truncation:
6245 return false;
6246
6247 case ICK_Lvalue_To_Rvalue:
6248 case ICK_Array_To_Pointer:
6249 case ICK_Function_To_Pointer:
6250 case ICK_HLSL_Array_RValue:
6251 llvm_unreachable("found a first conversion kind in Second");
6252
6253 case ICK_Function_Conversion:
6254 case ICK_Qualification:
6255 llvm_unreachable("found a third conversion kind in Second");
6256
6257 case ICK_Num_Conversion_Kinds:
6258 break;
6259 }
6260
6261 llvm_unreachable("unknown conversion kind");
6262}
6263
6264/// BuildConvertedConstantExpression - Check that the expression From is a
6265/// converted constant expression of type T, perform the conversion but
6266/// does not evaluate the expression
6267static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6268 QualType T, CCEKind CCE,
6269 NamedDecl *Dest,
6270 APValue &PreNarrowingValue) {
6271 assert((S.getLangOpts().CPlusPlus11 || CCE == CCEKind::TempArgStrict) &&
6272 "converted constant expression outside C++11 or TTP matching");
6273
6274 if (checkPlaceholderForOverload(S, E&: From))
6275 return ExprError();
6276
6277 // C++1z [expr.const]p3:
6278 // A converted constant expression of type T is an expression,
6279 // implicitly converted to type T, where the converted
6280 // expression is a constant expression and the implicit conversion
6281 // sequence contains only [... list of conversions ...].
6282 ImplicitConversionSequence ICS =
6283 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6284 ? TryContextuallyConvertToBool(S, From)
6285 : TryCopyInitialization(S, From, ToType: T,
6286 /*SuppressUserConversions=*/false,
6287 /*InOverloadResolution=*/false,
6288 /*AllowObjCWritebackConversion=*/false,
6289 /*AllowExplicit=*/false);
6290 StandardConversionSequence *SCS = nullptr;
6291 switch (ICS.getKind()) {
6292 case ImplicitConversionSequence::StandardConversion:
6293 SCS = &ICS.Standard;
6294 break;
6295 case ImplicitConversionSequence::UserDefinedConversion:
6296 if (T->isRecordType())
6297 SCS = &ICS.UserDefined.Before;
6298 else
6299 SCS = &ICS.UserDefined.After;
6300 break;
6301 case ImplicitConversionSequence::AmbiguousConversion:
6302 case ImplicitConversionSequence::BadConversion:
6303 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6304 return S.Diag(Loc: From->getBeginLoc(),
6305 DiagID: diag::err_typecheck_converted_constant_expression)
6306 << From->getType() << From->getSourceRange() << T;
6307 return ExprError();
6308
6309 case ImplicitConversionSequence::EllipsisConversion:
6310 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6311 llvm_unreachable("bad conversion in converted constant expression");
6312 }
6313
6314 // Check that we would only use permitted conversions.
6315 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6316 return S.Diag(Loc: From->getBeginLoc(),
6317 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6318 << From->getType() << From->getSourceRange() << T;
6319 }
6320 // [...] and where the reference binding (if any) binds directly.
6321 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6322 return S.Diag(Loc: From->getBeginLoc(),
6323 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6324 << From->getType() << From->getSourceRange() << T;
6325 }
6326 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6327 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6328 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6329 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6330 // case explicitly.
6331 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6332 return S.Diag(Loc: From->getBeginLoc(),
6333 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6334 << From->getSourceRange();
6335 }
6336
6337 // Usually we can simply apply the ImplicitConversionSequence we formed
6338 // earlier, but that's not guaranteed to work when initializing an object of
6339 // class type.
6340 ExprResult Result;
6341 bool IsTemplateArgument =
6342 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6343 if (T->isRecordType()) {
6344 assert(IsTemplateArgument &&
6345 "unexpected class type converted constant expr");
6346 Result = S.PerformCopyInitialization(
6347 Entity: InitializedEntity::InitializeTemplateParameter(
6348 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6349 EqualLoc: SourceLocation(), Init: From);
6350 } else {
6351 Result =
6352 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6353 }
6354 if (Result.isInvalid())
6355 return Result;
6356
6357 // C++2a [intro.execution]p5:
6358 // A full-expression is [...] a constant-expression [...]
6359 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6360 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6361 IsTemplateArgument);
6362 if (Result.isInvalid())
6363 return Result;
6364
6365 // Check for a narrowing implicit conversion.
6366 bool ReturnPreNarrowingValue = false;
6367 QualType PreNarrowingType;
6368 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6369 ConstantType&: PreNarrowingType)) {
6370 case NK_Variable_Narrowing:
6371 // Implicit conversion to a narrower type, and the value is not a constant
6372 // expression. We'll diagnose this in a moment.
6373 case NK_Not_Narrowing:
6374 break;
6375
6376 case NK_Constant_Narrowing:
6377 if (CCE == CCEKind::ArrayBound &&
6378 PreNarrowingType->isIntegralOrEnumerationType() &&
6379 PreNarrowingValue.isInt()) {
6380 // Don't diagnose array bound narrowing here; we produce more precise
6381 // errors by allowing the un-narrowed value through.
6382 ReturnPreNarrowingValue = true;
6383 break;
6384 }
6385 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6386 << CCE << /*Constant*/ 1
6387 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6388 break;
6389
6390 case NK_Dependent_Narrowing:
6391 // Implicit conversion to a narrower type, but the expression is
6392 // value-dependent so we can't tell whether it's actually narrowing.
6393 // For matching the parameters of a TTP, the conversion is ill-formed
6394 // if it may narrow.
6395 if (CCE != CCEKind::TempArgStrict)
6396 break;
6397 [[fallthrough]];
6398 case NK_Type_Narrowing:
6399 // FIXME: It would be better to diagnose that the expression is not a
6400 // constant expression.
6401 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6402 << CCE << /*Constant*/ 0 << From->getType() << T;
6403 break;
6404 }
6405 if (!ReturnPreNarrowingValue)
6406 PreNarrowingValue = {};
6407
6408 return Result;
6409}
6410
6411/// CheckConvertedConstantExpression - Check that the expression From is a
6412/// converted constant expression of type T, perform the conversion and produce
6413/// the converted expression, per C++11 [expr.const]p3.
6414static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6415 QualType T, APValue &Value,
6416 CCEKind CCE, bool RequireInt,
6417 NamedDecl *Dest) {
6418
6419 APValue PreNarrowingValue;
6420 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6421 PreNarrowingValue);
6422 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6423 Value = APValue();
6424 return Result;
6425 }
6426 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6427 RequireInt, PreNarrowingValue);
6428}
6429
6430ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6431 CCEKind CCE,
6432 NamedDecl *Dest) {
6433 APValue PreNarrowingValue;
6434 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6435 PreNarrowingValue);
6436}
6437
6438ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6439 APValue &Value, CCEKind CCE,
6440 NamedDecl *Dest) {
6441 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6442 Dest);
6443}
6444
6445ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6446 llvm::APSInt &Value,
6447 CCEKind CCE) {
6448 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6449
6450 APValue V;
6451 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6452 /*Dest=*/nullptr);
6453 if (!R.isInvalid() && !R.get()->isValueDependent())
6454 Value = V.getInt();
6455 return R;
6456}
6457
6458ExprResult
6459Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6460 CCEKind CCE, bool RequireInt,
6461 const APValue &PreNarrowingValue) {
6462
6463 ExprResult Result = E;
6464 // Check the expression is a constant expression.
6465 SmallVector<PartialDiagnosticAt, 8> Notes;
6466 Expr::EvalResult Eval;
6467 Eval.Diag = &Notes;
6468
6469 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6470
6471 ConstantExprKind Kind;
6472 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6473 Kind = ConstantExprKind::ClassTemplateArgument;
6474 else if (CCE == CCEKind::TemplateArg)
6475 Kind = ConstantExprKind::NonClassTemplateArgument;
6476 else
6477 Kind = ConstantExprKind::Normal;
6478
6479 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6480 (RequireInt && !Eval.Val.isInt())) {
6481 // The expression can't be folded, so we can't keep it at this position in
6482 // the AST.
6483 Result = ExprError();
6484 } else {
6485 Value = Eval.Val;
6486
6487 if (Notes.empty()) {
6488 // It's a constant expression.
6489 Expr *E = Result.get();
6490 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6491 // We expect a ConstantExpr to have a value associated with it
6492 // by this point.
6493 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6494 "ConstantExpr has no value associated with it");
6495 (void)CE;
6496 } else {
6497 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6498 }
6499 if (!PreNarrowingValue.isAbsent())
6500 Value = std::move(PreNarrowingValue);
6501 return E;
6502 }
6503 }
6504
6505 // It's not a constant expression. Produce an appropriate diagnostic.
6506 if (Notes.size() == 1 &&
6507 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6508 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6509 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6510 diag::note_constexpr_invalid_template_arg) {
6511 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6512 for (unsigned I = 0; I < Notes.size(); ++I)
6513 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6514 } else {
6515 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6516 << CCE << E->getSourceRange();
6517 for (unsigned I = 0; I < Notes.size(); ++I)
6518 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6519 }
6520 return ExprError();
6521}
6522
6523/// dropPointerConversions - If the given standard conversion sequence
6524/// involves any pointer conversions, remove them. This may change
6525/// the result type of the conversion sequence.
6526static void dropPointerConversion(StandardConversionSequence &SCS) {
6527 if (SCS.Second == ICK_Pointer_Conversion) {
6528 SCS.Second = ICK_Identity;
6529 SCS.Dimension = ICK_Identity;
6530 SCS.Third = ICK_Identity;
6531 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6532 }
6533}
6534
6535/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6536/// convert the expression From to an Objective-C pointer type.
6537static ImplicitConversionSequence
6538TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6539 // Do an implicit conversion to 'id'.
6540 QualType Ty = S.Context.getObjCIdType();
6541 ImplicitConversionSequence ICS
6542 = TryImplicitConversion(S, From, ToType: Ty,
6543 // FIXME: Are these flags correct?
6544 /*SuppressUserConversions=*/false,
6545 AllowExplicit: AllowedExplicit::Conversions,
6546 /*InOverloadResolution=*/false,
6547 /*CStyle=*/false,
6548 /*AllowObjCWritebackConversion=*/false,
6549 /*AllowObjCConversionOnExplicit=*/true);
6550
6551 // Strip off any final conversions to 'id'.
6552 switch (ICS.getKind()) {
6553 case ImplicitConversionSequence::BadConversion:
6554 case ImplicitConversionSequence::AmbiguousConversion:
6555 case ImplicitConversionSequence::EllipsisConversion:
6556 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6557 break;
6558
6559 case ImplicitConversionSequence::UserDefinedConversion:
6560 dropPointerConversion(SCS&: ICS.UserDefined.After);
6561 break;
6562
6563 case ImplicitConversionSequence::StandardConversion:
6564 dropPointerConversion(SCS&: ICS.Standard);
6565 break;
6566 }
6567
6568 return ICS;
6569}
6570
6571ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6572 if (checkPlaceholderForOverload(S&: *this, E&: From))
6573 return ExprError();
6574
6575 QualType Ty = Context.getObjCIdType();
6576 ImplicitConversionSequence ICS =
6577 TryContextuallyConvertToObjCPointer(S&: *this, From);
6578 if (!ICS.isBad())
6579 return PerformImplicitConversion(From, ToType: Ty, ICS,
6580 Action: AssignmentAction::Converting);
6581 return ExprResult();
6582}
6583
6584static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6585 const Expr *Base = nullptr;
6586 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6587 "expected a member expression");
6588
6589 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6590 M && !M->isImplicitAccess())
6591 Base = M->getBase();
6592 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6593 M && !M->isImplicitAccess())
6594 Base = M->getBase();
6595
6596 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6597
6598 if (T->isPointerType())
6599 T = T->getPointeeType();
6600
6601 return T;
6602}
6603
6604static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6605 const FunctionDecl *Fun) {
6606 QualType ObjType = Obj->getType();
6607 if (ObjType->isPointerType()) {
6608 ObjType = ObjType->getPointeeType();
6609 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6610 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6611 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6612 }
6613 return Obj;
6614}
6615
6616ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6617 FunctionDecl *Fun) {
6618 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6619 return S.PerformCopyInitialization(
6620 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6621 EqualLoc: Obj->getExprLoc(), Init: Obj);
6622}
6623
6624static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6625 Expr *Object, MultiExprArg &Args,
6626 SmallVectorImpl<Expr *> &NewArgs) {
6627 assert(Method->isExplicitObjectMemberFunction() &&
6628 "Method is not an explicit member function");
6629 assert(NewArgs.empty() && "NewArgs should be empty");
6630
6631 NewArgs.reserve(N: Args.size() + 1);
6632 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6633 NewArgs.push_back(Elt: This);
6634 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6635 Args = NewArgs;
6636 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6637 Method, CallLoc: Object->getBeginLoc());
6638}
6639
6640/// Determine whether the provided type is an integral type, or an enumeration
6641/// type of a permitted flavor.
6642bool Sema::ICEConvertDiagnoser::match(QualType T) {
6643 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6644 : T->isIntegralOrUnscopedEnumerationType();
6645}
6646
6647static ExprResult
6648diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6649 Sema::ContextualImplicitConverter &Converter,
6650 QualType T, UnresolvedSetImpl &ViableConversions) {
6651
6652 if (Converter.Suppress)
6653 return ExprError();
6654
6655 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6656 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6657 CXXConversionDecl *Conv =
6658 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6659 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6660 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6661 }
6662 return From;
6663}
6664
6665static bool
6666diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6667 Sema::ContextualImplicitConverter &Converter,
6668 QualType T, bool HadMultipleCandidates,
6669 UnresolvedSetImpl &ExplicitConversions) {
6670 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6671 DeclAccessPair Found = ExplicitConversions[0];
6672 CXXConversionDecl *Conversion =
6673 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6674
6675 // The user probably meant to invoke the given explicit
6676 // conversion; use it.
6677 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6678 std::string TypeStr;
6679 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6680
6681 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6682 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6683 Code: "static_cast<" + TypeStr + ">(")
6684 << FixItHint::CreateInsertion(
6685 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6686 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6687
6688 // If we aren't in a SFINAE context, build a call to the
6689 // explicit conversion function.
6690 if (SemaRef.isSFINAEContext())
6691 return true;
6692
6693 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6694 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6695 HadMultipleCandidates);
6696 if (Result.isInvalid())
6697 return true;
6698
6699 // Replace the conversion with a RecoveryExpr, so we don't try to
6700 // instantiate it later, but can further diagnose here.
6701 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6702 SubExprs: From, T: Result.get()->getType());
6703 if (Result.isInvalid())
6704 return true;
6705 From = Result.get();
6706 }
6707 return false;
6708}
6709
6710static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6711 Sema::ContextualImplicitConverter &Converter,
6712 QualType T, bool HadMultipleCandidates,
6713 DeclAccessPair &Found) {
6714 CXXConversionDecl *Conversion =
6715 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6716 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6717
6718 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6719 if (!Converter.SuppressConversion) {
6720 if (SemaRef.isSFINAEContext())
6721 return true;
6722
6723 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6724 << From->getSourceRange();
6725 }
6726
6727 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6728 HadMultipleCandidates);
6729 if (Result.isInvalid())
6730 return true;
6731 // Record usage of conversion in an implicit cast.
6732 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6733 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6734 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6735 FPO: SemaRef.CurFPFeatureOverrides());
6736 return false;
6737}
6738
6739static ExprResult finishContextualImplicitConversion(
6740 Sema &SemaRef, SourceLocation Loc, Expr *From,
6741 Sema::ContextualImplicitConverter &Converter) {
6742 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6743 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6744 << From->getSourceRange();
6745
6746 return SemaRef.DefaultLvalueConversion(E: From);
6747}
6748
6749static void
6750collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6751 UnresolvedSetImpl &ViableConversions,
6752 OverloadCandidateSet &CandidateSet) {
6753 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6754 NamedDecl *D = FoundDecl.getDecl();
6755 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6756 if (isa<UsingShadowDecl>(Val: D))
6757 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6758
6759 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6760 SemaRef.AddTemplateConversionCandidate(
6761 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6762 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6763 continue;
6764 }
6765 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6766 SemaRef.AddConversionCandidate(
6767 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6768 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6769 }
6770}
6771
6772/// Attempt to convert the given expression to a type which is accepted
6773/// by the given converter.
6774///
6775/// This routine will attempt to convert an expression of class type to a
6776/// type accepted by the specified converter. In C++11 and before, the class
6777/// must have a single non-explicit conversion function converting to a matching
6778/// type. In C++1y, there can be multiple such conversion functions, but only
6779/// one target type.
6780///
6781/// \param Loc The source location of the construct that requires the
6782/// conversion.
6783///
6784/// \param From The expression we're converting from.
6785///
6786/// \param Converter Used to control and diagnose the conversion process.
6787///
6788/// \returns The expression, converted to an integral or enumeration type if
6789/// successful.
6790ExprResult Sema::PerformContextualImplicitConversion(
6791 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6792 // We can't perform any more checking for type-dependent expressions.
6793 if (From->isTypeDependent())
6794 return From;
6795
6796 // Process placeholders immediately.
6797 if (From->hasPlaceholderType()) {
6798 ExprResult result = CheckPlaceholderExpr(E: From);
6799 if (result.isInvalid())
6800 return result;
6801 From = result.get();
6802 }
6803
6804 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6805 ExprResult Converted = DefaultLvalueConversion(E: From);
6806 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6807 // If the expression already has a matching type, we're golden.
6808 if (Converter.match(T))
6809 return Converted;
6810
6811 // FIXME: Check for missing '()' if T is a function type?
6812
6813 // We can only perform contextual implicit conversions on objects of class
6814 // type.
6815 const RecordType *RecordTy = T->getAs<RecordType>();
6816 if (!RecordTy || !getLangOpts().CPlusPlus) {
6817 if (!Converter.Suppress)
6818 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
6819 return From;
6820 }
6821
6822 // We must have a complete class type.
6823 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6824 ContextualImplicitConverter &Converter;
6825 Expr *From;
6826
6827 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6828 : Converter(Converter), From(From) {}
6829
6830 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6831 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6832 }
6833 } IncompleteDiagnoser(Converter, From);
6834
6835 if (Converter.Suppress ? !isCompleteType(Loc, T)
6836 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
6837 return From;
6838
6839 // Look for a conversion to an integral or enumeration type.
6840 UnresolvedSet<4>
6841 ViableConversions; // These are *potentially* viable in C++1y.
6842 UnresolvedSet<4> ExplicitConversions;
6843 const auto &Conversions =
6844 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getVisibleConversionFunctions();
6845
6846 bool HadMultipleCandidates =
6847 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
6848
6849 // To check that there is only one target type, in C++1y:
6850 QualType ToType;
6851 bool HasUniqueTargetType = true;
6852
6853 // Collect explicit or viable (potentially in C++1y) conversions.
6854 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6855 NamedDecl *D = (*I)->getUnderlyingDecl();
6856 CXXConversionDecl *Conversion;
6857 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6858 if (ConvTemplate) {
6859 if (getLangOpts().CPlusPlus14)
6860 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6861 else
6862 continue; // C++11 does not consider conversion operator templates(?).
6863 } else
6864 Conversion = cast<CXXConversionDecl>(Val: D);
6865
6866 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6867 "Conversion operator templates are considered potentially "
6868 "viable in C++1y");
6869
6870 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6871 if (Converter.match(T: CurToType) || ConvTemplate) {
6872
6873 if (Conversion->isExplicit()) {
6874 // FIXME: For C++1y, do we need this restriction?
6875 // cf. diagnoseNoViableConversion()
6876 if (!ConvTemplate)
6877 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6878 } else {
6879 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6880 if (ToType.isNull())
6881 ToType = CurToType.getUnqualifiedType();
6882 else if (HasUniqueTargetType &&
6883 (CurToType.getUnqualifiedType() != ToType))
6884 HasUniqueTargetType = false;
6885 }
6886 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6887 }
6888 }
6889 }
6890
6891 if (getLangOpts().CPlusPlus14) {
6892 // C++1y [conv]p6:
6893 // ... An expression e of class type E appearing in such a context
6894 // is said to be contextually implicitly converted to a specified
6895 // type T and is well-formed if and only if e can be implicitly
6896 // converted to a type T that is determined as follows: E is searched
6897 // for conversion functions whose return type is cv T or reference to
6898 // cv T such that T is allowed by the context. There shall be
6899 // exactly one such T.
6900
6901 // If no unique T is found:
6902 if (ToType.isNull()) {
6903 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6904 HadMultipleCandidates,
6905 ExplicitConversions))
6906 return ExprError();
6907 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6908 }
6909
6910 // If more than one unique Ts are found:
6911 if (!HasUniqueTargetType)
6912 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6913 ViableConversions);
6914
6915 // If one unique T is found:
6916 // First, build a candidate set from the previously recorded
6917 // potentially viable conversions.
6918 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6919 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
6920 CandidateSet);
6921
6922 // Then, perform overload resolution over the candidate set.
6923 OverloadCandidateSet::iterator Best;
6924 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
6925 case OR_Success: {
6926 // Apply this conversion.
6927 DeclAccessPair Found =
6928 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
6929 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6930 HadMultipleCandidates, Found))
6931 return ExprError();
6932 break;
6933 }
6934 case OR_Ambiguous:
6935 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6936 ViableConversions);
6937 case OR_No_Viable_Function:
6938 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6939 HadMultipleCandidates,
6940 ExplicitConversions))
6941 return ExprError();
6942 [[fallthrough]];
6943 case OR_Deleted:
6944 // We'll complain below about a non-integral condition type.
6945 break;
6946 }
6947 } else {
6948 switch (ViableConversions.size()) {
6949 case 0: {
6950 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6951 HadMultipleCandidates,
6952 ExplicitConversions))
6953 return ExprError();
6954
6955 // We'll complain below about a non-integral condition type.
6956 break;
6957 }
6958 case 1: {
6959 // Apply this conversion.
6960 DeclAccessPair Found = ViableConversions[0];
6961 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6962 HadMultipleCandidates, Found))
6963 return ExprError();
6964 break;
6965 }
6966 default:
6967 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6968 ViableConversions);
6969 }
6970 }
6971
6972 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6973}
6974
6975/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6976/// an acceptable non-member overloaded operator for a call whose
6977/// arguments have types T1 (and, if non-empty, T2). This routine
6978/// implements the check in C++ [over.match.oper]p3b2 concerning
6979/// enumeration types.
6980static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6981 FunctionDecl *Fn,
6982 ArrayRef<Expr *> Args) {
6983 QualType T1 = Args[0]->getType();
6984 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6985
6986 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6987 return true;
6988
6989 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6990 return true;
6991
6992 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6993 if (Proto->getNumParams() < 1)
6994 return false;
6995
6996 if (T1->isEnumeralType()) {
6997 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
6998 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
6999 return true;
7000 }
7001
7002 if (Proto->getNumParams() < 2)
7003 return false;
7004
7005 if (!T2.isNull() && T2->isEnumeralType()) {
7006 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7007 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7008 return true;
7009 }
7010
7011 return false;
7012}
7013
7014static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7015 if (FD->isTargetMultiVersionDefault())
7016 return false;
7017
7018 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7019 return FD->isTargetMultiVersion();
7020
7021 if (!FD->isMultiVersion())
7022 return false;
7023
7024 // Among multiple target versions consider either the default,
7025 // or the first non-default in the absence of default version.
7026 unsigned SeenAt = 0;
7027 unsigned I = 0;
7028 bool HasDefault = false;
7029 FD->getASTContext().forEachMultiversionedFunctionVersion(
7030 FD, Pred: [&](const FunctionDecl *CurFD) {
7031 if (FD == CurFD)
7032 SeenAt = I;
7033 else if (CurFD->isTargetMultiVersionDefault())
7034 HasDefault = true;
7035 ++I;
7036 });
7037 return HasDefault || SeenAt != 0;
7038}
7039
7040void Sema::AddOverloadCandidate(
7041 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7042 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7043 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7044 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7045 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7046 bool StrictPackMatch) {
7047 const FunctionProtoType *Proto
7048 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7049 assert(Proto && "Functions without a prototype cannot be overloaded");
7050 assert(!Function->getDescribedFunctionTemplate() &&
7051 "Use AddTemplateOverloadCandidate for function templates");
7052
7053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7054 if (!isa<CXXConstructorDecl>(Val: Method)) {
7055 // If we get here, it's because we're calling a member function
7056 // that is named without a member access expression (e.g.,
7057 // "this->f") that was either written explicitly or created
7058 // implicitly. This can happen with a qualified call to a member
7059 // function, e.g., X::f(). We use an empty type for the implied
7060 // object argument (C++ [over.call.func]p3), and the acting context
7061 // is irrelevant.
7062 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7063 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7064 CandidateSet, SuppressUserConversions,
7065 PartialOverloading, EarlyConversions, PO,
7066 StrictPackMatch);
7067 return;
7068 }
7069 // We treat a constructor like a non-member function, since its object
7070 // argument doesn't participate in overload resolution.
7071 }
7072
7073 if (!CandidateSet.isNewCandidate(F: Function, PO))
7074 return;
7075
7076 // C++11 [class.copy]p11: [DR1402]
7077 // A defaulted move constructor that is defined as deleted is ignored by
7078 // overload resolution.
7079 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7080 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7081 Constructor->isMoveConstructor())
7082 return;
7083
7084 // Overload resolution is always an unevaluated context.
7085 EnterExpressionEvaluationContext Unevaluated(
7086 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7087
7088 // C++ [over.match.oper]p3:
7089 // if no operand has a class type, only those non-member functions in the
7090 // lookup set that have a first parameter of type T1 or "reference to
7091 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7092 // is a right operand) a second parameter of type T2 or "reference to
7093 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7094 // candidate functions.
7095 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7096 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7097 return;
7098
7099 // Add this candidate
7100 OverloadCandidate &Candidate =
7101 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7102 Candidate.FoundDecl = FoundDecl;
7103 Candidate.Function = Function;
7104 Candidate.Viable = true;
7105 Candidate.RewriteKind =
7106 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7107 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7108 Candidate.ExplicitCallArguments = Args.size();
7109 Candidate.StrictPackMatch = StrictPackMatch;
7110
7111 // Explicit functions are not actually candidates at all if we're not
7112 // allowing them in this context, but keep them around so we can point
7113 // to them in diagnostics.
7114 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7115 Candidate.Viable = false;
7116 Candidate.FailureKind = ovl_fail_explicit;
7117 return;
7118 }
7119
7120 // Functions with internal linkage are only viable in the same module unit.
7121 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7122 /// FIXME: Currently, the semantics of linkage in clang is slightly
7123 /// different from the semantics in C++ spec. In C++ spec, only names
7124 /// have linkage. So that all entities of the same should share one
7125 /// linkage. But in clang, different entities of the same could have
7126 /// different linkage.
7127 const NamedDecl *ND = Function;
7128 bool IsImplicitlyInstantiated = false;
7129 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7130 ND = SpecInfo->getTemplate();
7131 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7132 TSK_ImplicitInstantiation;
7133 }
7134
7135 /// Don't remove inline functions with internal linkage from the overload
7136 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7137 /// However:
7138 /// - Inline functions with internal linkage are a common pattern in
7139 /// headers to avoid ODR issues.
7140 /// - The global module is meant to be a transition mechanism for C and C++
7141 /// headers, and the current rules as written work against that goal.
7142 const bool IsInlineFunctionInGMF =
7143 Function->isFromGlobalModule() &&
7144 (IsImplicitlyInstantiated || Function->isInlined());
7145
7146 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7147 Candidate.Viable = false;
7148 Candidate.FailureKind = ovl_fail_module_mismatched;
7149 return;
7150 }
7151 }
7152
7153 if (isNonViableMultiVersionOverload(FD: Function)) {
7154 Candidate.Viable = false;
7155 Candidate.FailureKind = ovl_non_default_multiversion_function;
7156 return;
7157 }
7158
7159 if (Constructor) {
7160 // C++ [class.copy]p3:
7161 // A member function template is never instantiated to perform the copy
7162 // of a class object to an object of its class type.
7163 QualType ClassType = Context.getTypeDeclType(Decl: Constructor->getParent());
7164 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7165 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7166 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7167 Base: ClassType))) {
7168 Candidate.Viable = false;
7169 Candidate.FailureKind = ovl_fail_illegal_constructor;
7170 return;
7171 }
7172
7173 // C++ [over.match.funcs]p8: (proposed DR resolution)
7174 // A constructor inherited from class type C that has a first parameter
7175 // of type "reference to P" (including such a constructor instantiated
7176 // from a template) is excluded from the set of candidate functions when
7177 // constructing an object of type cv D if the argument list has exactly
7178 // one argument and D is reference-related to P and P is reference-related
7179 // to C.
7180 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7181 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7182 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7183 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7184 QualType C = Context.getRecordType(Decl: Constructor->getParent());
7185 QualType D = Context.getRecordType(Decl: Shadow->getParent());
7186 SourceLocation Loc = Args.front()->getExprLoc();
7187 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7188 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7189 Candidate.Viable = false;
7190 Candidate.FailureKind = ovl_fail_inhctor_slice;
7191 return;
7192 }
7193 }
7194
7195 // Check that the constructor is capable of constructing an object in the
7196 // destination address space.
7197 if (!Qualifiers::isAddressSpaceSupersetOf(
7198 A: Constructor->getMethodQualifiers().getAddressSpace(),
7199 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7200 Candidate.Viable = false;
7201 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7202 }
7203 }
7204
7205 unsigned NumParams = Proto->getNumParams();
7206
7207 // (C++ 13.3.2p2): A candidate function having fewer than m
7208 // parameters is viable only if it has an ellipsis in its parameter
7209 // list (8.3.5).
7210 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7211 !Proto->isVariadic() &&
7212 shouldEnforceArgLimit(PartialOverloading, Function)) {
7213 Candidate.Viable = false;
7214 Candidate.FailureKind = ovl_fail_too_many_arguments;
7215 return;
7216 }
7217
7218 // (C++ 13.3.2p2): A candidate function having more than m parameters
7219 // is viable only if the (m+1)st parameter has a default argument
7220 // (8.3.6). For the purposes of overload resolution, the
7221 // parameter list is truncated on the right, so that there are
7222 // exactly m parameters.
7223 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7224 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7225 !PartialOverloading) {
7226 // Not enough arguments.
7227 Candidate.Viable = false;
7228 Candidate.FailureKind = ovl_fail_too_few_arguments;
7229 return;
7230 }
7231
7232 // (CUDA B.1): Check for invalid calls between targets.
7233 if (getLangOpts().CUDA) {
7234 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7235 // Skip the check for callers that are implicit members, because in this
7236 // case we may not yet know what the member's target is; the target is
7237 // inferred for the member automatically, based on the bases and fields of
7238 // the class.
7239 if (!(Caller && Caller->isImplicit()) &&
7240 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7241 Candidate.Viable = false;
7242 Candidate.FailureKind = ovl_fail_bad_target;
7243 return;
7244 }
7245 }
7246
7247 if (Function->getTrailingRequiresClause()) {
7248 ConstraintSatisfaction Satisfaction;
7249 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7250 /*ForOverloadResolution*/ true) ||
7251 !Satisfaction.IsSatisfied) {
7252 Candidate.Viable = false;
7253 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7254 return;
7255 }
7256 }
7257
7258 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7259 // Determine the implicit conversion sequences for each of the
7260 // arguments.
7261 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7262 unsigned ConvIdx =
7263 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7264 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7265 // We already formed a conversion sequence for this parameter during
7266 // template argument deduction.
7267 } else if (ArgIdx < NumParams) {
7268 // (C++ 13.3.2p3): for F to be a viable function, there shall
7269 // exist for each argument an implicit conversion sequence
7270 // (13.3.3.1) that converts that argument to the corresponding
7271 // parameter of F.
7272 QualType ParamType = Proto->getParamType(i: ArgIdx);
7273 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7274 if (ParamABI == ParameterABI::HLSLOut ||
7275 ParamABI == ParameterABI::HLSLInOut)
7276 ParamType = ParamType.getNonReferenceType();
7277 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7278 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7279 /*InOverloadResolution=*/true,
7280 /*AllowObjCWritebackConversion=*/
7281 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7282 if (Candidate.Conversions[ConvIdx].isBad()) {
7283 Candidate.Viable = false;
7284 Candidate.FailureKind = ovl_fail_bad_conversion;
7285 return;
7286 }
7287 } else {
7288 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7289 // argument for which there is no corresponding parameter is
7290 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7291 Candidate.Conversions[ConvIdx].setEllipsis();
7292 }
7293 }
7294
7295 if (EnableIfAttr *FailedAttr =
7296 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7297 Candidate.Viable = false;
7298 Candidate.FailureKind = ovl_fail_enable_if;
7299 Candidate.DeductionFailure.Data = FailedAttr;
7300 return;
7301 }
7302}
7303
7304ObjCMethodDecl *
7305Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7306 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7307 if (Methods.size() <= 1)
7308 return nullptr;
7309
7310 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7311 bool Match = true;
7312 ObjCMethodDecl *Method = Methods[b];
7313 unsigned NumNamedArgs = Sel.getNumArgs();
7314 // Method might have more arguments than selector indicates. This is due
7315 // to addition of c-style arguments in method.
7316 if (Method->param_size() > NumNamedArgs)
7317 NumNamedArgs = Method->param_size();
7318 if (Args.size() < NumNamedArgs)
7319 continue;
7320
7321 for (unsigned i = 0; i < NumNamedArgs; i++) {
7322 // We can't do any type-checking on a type-dependent argument.
7323 if (Args[i]->isTypeDependent()) {
7324 Match = false;
7325 break;
7326 }
7327
7328 ParmVarDecl *param = Method->parameters()[i];
7329 Expr *argExpr = Args[i];
7330 assert(argExpr && "SelectBestMethod(): missing expression");
7331
7332 // Strip the unbridged-cast placeholder expression off unless it's
7333 // a consumed argument.
7334 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7335 !param->hasAttr<CFConsumedAttr>())
7336 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7337
7338 // If the parameter is __unknown_anytype, move on to the next method.
7339 if (param->getType() == Context.UnknownAnyTy) {
7340 Match = false;
7341 break;
7342 }
7343
7344 ImplicitConversionSequence ConversionState
7345 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7346 /*SuppressUserConversions*/false,
7347 /*InOverloadResolution=*/true,
7348 /*AllowObjCWritebackConversion=*/
7349 getLangOpts().ObjCAutoRefCount,
7350 /*AllowExplicit*/false);
7351 // This function looks for a reasonably-exact match, so we consider
7352 // incompatible pointer conversions to be a failure here.
7353 if (ConversionState.isBad() ||
7354 (ConversionState.isStandard() &&
7355 ConversionState.Standard.Second ==
7356 ICK_Incompatible_Pointer_Conversion)) {
7357 Match = false;
7358 break;
7359 }
7360 }
7361 // Promote additional arguments to variadic methods.
7362 if (Match && Method->isVariadic()) {
7363 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7364 if (Args[i]->isTypeDependent()) {
7365 Match = false;
7366 break;
7367 }
7368 ExprResult Arg = DefaultVariadicArgumentPromotion(
7369 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7370 if (Arg.isInvalid()) {
7371 Match = false;
7372 break;
7373 }
7374 }
7375 } else {
7376 // Check for extra arguments to non-variadic methods.
7377 if (Args.size() != NumNamedArgs)
7378 Match = false;
7379 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7380 // Special case when selectors have no argument. In this case, select
7381 // one with the most general result type of 'id'.
7382 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7383 QualType ReturnT = Methods[b]->getReturnType();
7384 if (ReturnT->isObjCIdType())
7385 return Methods[b];
7386 }
7387 }
7388 }
7389
7390 if (Match)
7391 return Method;
7392 }
7393 return nullptr;
7394}
7395
7396static bool convertArgsForAvailabilityChecks(
7397 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7398 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7399 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7400 if (ThisArg) {
7401 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7402 assert(!isa<CXXConstructorDecl>(Method) &&
7403 "Shouldn't have `this` for ctors!");
7404 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7405 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7406 From: ThisArg, /*Qualifier=*/nullptr, FoundDecl: Method, Method);
7407 if (R.isInvalid())
7408 return false;
7409 ConvertedThis = R.get();
7410 } else {
7411 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7412 (void)MD;
7413 assert((MissingImplicitThis || MD->isStatic() ||
7414 isa<CXXConstructorDecl>(MD)) &&
7415 "Expected `this` for non-ctor instance methods");
7416 }
7417 ConvertedThis = nullptr;
7418 }
7419
7420 // Ignore any variadic arguments. Converting them is pointless, since the
7421 // user can't refer to them in the function condition.
7422 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7423
7424 // Convert the arguments.
7425 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7426 ExprResult R;
7427 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7428 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7429 EqualLoc: SourceLocation(), Init: Args[I]);
7430
7431 if (R.isInvalid())
7432 return false;
7433
7434 ConvertedArgs.push_back(Elt: R.get());
7435 }
7436
7437 if (Trap.hasErrorOccurred())
7438 return false;
7439
7440 // Push default arguments if needed.
7441 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7442 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7443 ParmVarDecl *P = Function->getParamDecl(i);
7444 if (!P->hasDefaultArg())
7445 return false;
7446 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7447 if (R.isInvalid())
7448 return false;
7449 ConvertedArgs.push_back(Elt: R.get());
7450 }
7451
7452 if (Trap.hasErrorOccurred())
7453 return false;
7454 }
7455 return true;
7456}
7457
7458EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7459 SourceLocation CallLoc,
7460 ArrayRef<Expr *> Args,
7461 bool MissingImplicitThis) {
7462 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7463 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7464 return nullptr;
7465
7466 SFINAETrap Trap(*this);
7467 SmallVector<Expr *, 16> ConvertedArgs;
7468 // FIXME: We should look into making enable_if late-parsed.
7469 Expr *DiscardedThis;
7470 if (!convertArgsForAvailabilityChecks(
7471 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7472 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7473 return *EnableIfAttrs.begin();
7474
7475 for (auto *EIA : EnableIfAttrs) {
7476 APValue Result;
7477 // FIXME: This doesn't consider value-dependent cases, because doing so is
7478 // very difficult. Ideally, we should handle them more gracefully.
7479 if (EIA->getCond()->isValueDependent() ||
7480 !EIA->getCond()->EvaluateWithSubstitution(
7481 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7482 return EIA;
7483
7484 if (!Result.isInt() || !Result.getInt().getBoolValue())
7485 return EIA;
7486 }
7487 return nullptr;
7488}
7489
7490template <typename CheckFn>
7491static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7492 bool ArgDependent, SourceLocation Loc,
7493 CheckFn &&IsSuccessful) {
7494 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7495 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7496 if (ArgDependent == DIA->getArgDependent())
7497 Attrs.push_back(Elt: DIA);
7498 }
7499
7500 // Common case: No diagnose_if attributes, so we can quit early.
7501 if (Attrs.empty())
7502 return false;
7503
7504 auto WarningBegin = std::stable_partition(
7505 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7506 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7507 DIA->getWarningGroup().empty();
7508 });
7509
7510 // Note that diagnose_if attributes are late-parsed, so they appear in the
7511 // correct order (unlike enable_if attributes).
7512 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7513 IsSuccessful);
7514 if (ErrAttr != WarningBegin) {
7515 const DiagnoseIfAttr *DIA = *ErrAttr;
7516 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7517 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7518 << DIA->getParent() << DIA->getCond()->getSourceRange();
7519 return true;
7520 }
7521
7522 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7523 switch (Sev) {
7524 case DiagnoseIfAttr::DS_warning:
7525 return diag::Severity::Warning;
7526 case DiagnoseIfAttr::DS_error:
7527 return diag::Severity::Error;
7528 }
7529 llvm_unreachable("Fully covered switch above!");
7530 };
7531
7532 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7533 if (IsSuccessful(DIA)) {
7534 if (DIA->getWarningGroup().empty() &&
7535 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7536 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7537 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7538 << DIA->getParent() << DIA->getCond()->getSourceRange();
7539 } else {
7540 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7541 DIA->getWarningGroup());
7542 assert(DiagGroup);
7543 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7544 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7545 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7546 S.Diag(Loc, DiagID) << DIA->getMessage();
7547 }
7548 }
7549
7550 return false;
7551}
7552
7553bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7554 const Expr *ThisArg,
7555 ArrayRef<const Expr *> Args,
7556 SourceLocation Loc) {
7557 return diagnoseDiagnoseIfAttrsWith(
7558 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7559 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7560 APValue Result;
7561 // It's sane to use the same Args for any redecl of this function, since
7562 // EvaluateWithSubstitution only cares about the position of each
7563 // argument in the arg list, not the ParmVarDecl* it maps to.
7564 if (!DIA->getCond()->EvaluateWithSubstitution(
7565 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7566 return false;
7567 return Result.isInt() && Result.getInt().getBoolValue();
7568 });
7569}
7570
7571bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7572 SourceLocation Loc) {
7573 return diagnoseDiagnoseIfAttrsWith(
7574 S&: *this, ND, /*ArgDependent=*/false, Loc,
7575 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7576 bool Result;
7577 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7578 Result;
7579 });
7580}
7581
7582void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7583 ArrayRef<Expr *> Args,
7584 OverloadCandidateSet &CandidateSet,
7585 TemplateArgumentListInfo *ExplicitTemplateArgs,
7586 bool SuppressUserConversions,
7587 bool PartialOverloading,
7588 bool FirstArgumentIsBase) {
7589 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7590 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7591 ArrayRef<Expr *> FunctionArgs = Args;
7592
7593 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7594 FunctionDecl *FD =
7595 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7596
7597 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7598 QualType ObjectType;
7599 Expr::Classification ObjectClassification;
7600 if (Args.size() > 0) {
7601 if (Expr *E = Args[0]) {
7602 // Use the explicit base to restrict the lookup:
7603 ObjectType = E->getType();
7604 // Pointers in the object arguments are implicitly dereferenced, so we
7605 // always classify them as l-values.
7606 if (!ObjectType.isNull() && ObjectType->isPointerType())
7607 ObjectClassification = Expr::Classification::makeSimpleLValue();
7608 else
7609 ObjectClassification = E->Classify(Ctx&: Context);
7610 } // .. else there is an implicit base.
7611 FunctionArgs = Args.slice(N: 1);
7612 }
7613 if (FunTmpl) {
7614 AddMethodTemplateCandidate(
7615 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7616 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7617 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7618 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7619 PartialOverloading);
7620 } else {
7621 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7622 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7623 ObjectClassification, Args: FunctionArgs, CandidateSet,
7624 SuppressUserConversions, PartialOverloading);
7625 }
7626 } else {
7627 // This branch handles both standalone functions and static methods.
7628
7629 // Slice the first argument (which is the base) when we access
7630 // static method as non-static.
7631 if (Args.size() > 0 &&
7632 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7633 !isa<CXXConstructorDecl>(Val: FD)))) {
7634 assert(cast<CXXMethodDecl>(FD)->isStatic());
7635 FunctionArgs = Args.slice(N: 1);
7636 }
7637 if (FunTmpl) {
7638 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7639 ExplicitTemplateArgs, Args: FunctionArgs,
7640 CandidateSet, SuppressUserConversions,
7641 PartialOverloading);
7642 } else {
7643 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7644 SuppressUserConversions, PartialOverloading);
7645 }
7646 }
7647 }
7648}
7649
7650void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7651 Expr::Classification ObjectClassification,
7652 ArrayRef<Expr *> Args,
7653 OverloadCandidateSet &CandidateSet,
7654 bool SuppressUserConversions,
7655 OverloadCandidateParamOrder PO) {
7656 NamedDecl *Decl = FoundDecl.getDecl();
7657 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7658
7659 if (isa<UsingShadowDecl>(Val: Decl))
7660 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7661
7662 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7663 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7664 "Expected a member function template");
7665 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7666 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7667 ObjectClassification, Args, CandidateSet,
7668 SuppressUserConversions, PartialOverloading: false, PO);
7669 } else {
7670 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7671 ObjectType, ObjectClassification, Args, CandidateSet,
7672 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7673 }
7674}
7675
7676void Sema::AddMethodCandidate(
7677 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7678 CXXRecordDecl *ActingContext, QualType ObjectType,
7679 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7680 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7681 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7682 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7683 const FunctionProtoType *Proto
7684 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7685 assert(Proto && "Methods without a prototype cannot be overloaded");
7686 assert(!isa<CXXConstructorDecl>(Method) &&
7687 "Use AddOverloadCandidate for constructors");
7688
7689 if (!CandidateSet.isNewCandidate(F: Method, PO))
7690 return;
7691
7692 // C++11 [class.copy]p23: [DR1402]
7693 // A defaulted move assignment operator that is defined as deleted is
7694 // ignored by overload resolution.
7695 if (Method->isDefaulted() && Method->isDeleted() &&
7696 Method->isMoveAssignmentOperator())
7697 return;
7698
7699 // Overload resolution is always an unevaluated context.
7700 EnterExpressionEvaluationContext Unevaluated(
7701 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7702
7703 // Add this candidate
7704 OverloadCandidate &Candidate =
7705 CandidateSet.addCandidate(NumConversions: Args.size() + 1, Conversions: EarlyConversions);
7706 Candidate.FoundDecl = FoundDecl;
7707 Candidate.Function = Method;
7708 Candidate.RewriteKind =
7709 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7710 Candidate.TookAddressOfOverload =
7711 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7712 Candidate.ExplicitCallArguments = Args.size();
7713 Candidate.StrictPackMatch = StrictPackMatch;
7714
7715 bool IgnoreExplicitObject =
7716 (Method->isExplicitObjectMemberFunction() &&
7717 CandidateSet.getKind() ==
7718 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7719 bool ImplicitObjectMethodTreatedAsStatic =
7720 CandidateSet.getKind() ==
7721 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7722 Method->isImplicitObjectMemberFunction();
7723
7724 unsigned ExplicitOffset =
7725 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7726
7727 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7728 int(ImplicitObjectMethodTreatedAsStatic);
7729
7730 // (C++ 13.3.2p2): A candidate function having fewer than m
7731 // parameters is viable only if it has an ellipsis in its parameter
7732 // list (8.3.5).
7733 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7734 !Proto->isVariadic() &&
7735 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7736 Candidate.Viable = false;
7737 Candidate.FailureKind = ovl_fail_too_many_arguments;
7738 return;
7739 }
7740
7741 // (C++ 13.3.2p2): A candidate function having more than m parameters
7742 // is viable only if the (m+1)st parameter has a default argument
7743 // (8.3.6). For the purposes of overload resolution, the
7744 // parameter list is truncated on the right, so that there are
7745 // exactly m parameters.
7746 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7747 ExplicitOffset +
7748 int(ImplicitObjectMethodTreatedAsStatic);
7749
7750 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7751 // Not enough arguments.
7752 Candidate.Viable = false;
7753 Candidate.FailureKind = ovl_fail_too_few_arguments;
7754 return;
7755 }
7756
7757 Candidate.Viable = true;
7758
7759 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7760 if (ObjectType.isNull())
7761 Candidate.IgnoreObjectArgument = true;
7762 else if (Method->isStatic()) {
7763 // [over.best.ics.general]p8
7764 // When the parameter is the implicit object parameter of a static member
7765 // function, the implicit conversion sequence is a standard conversion
7766 // sequence that is neither better nor worse than any other standard
7767 // conversion sequence.
7768 //
7769 // This is a rule that was introduced in C++23 to support static lambdas. We
7770 // apply it retroactively because we want to support static lambdas as an
7771 // extension and it doesn't hurt previous code.
7772 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7773 } else {
7774 // Determine the implicit conversion sequence for the object
7775 // parameter.
7776 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7777 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7778 Method, ActingContext, /*InOverloadResolution=*/true);
7779 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7780 Candidate.Viable = false;
7781 Candidate.FailureKind = ovl_fail_bad_conversion;
7782 return;
7783 }
7784 }
7785
7786 // (CUDA B.1): Check for invalid calls between targets.
7787 if (getLangOpts().CUDA)
7788 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
7789 Callee: Method)) {
7790 Candidate.Viable = false;
7791 Candidate.FailureKind = ovl_fail_bad_target;
7792 return;
7793 }
7794
7795 if (Method->getTrailingRequiresClause()) {
7796 ConstraintSatisfaction Satisfaction;
7797 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
7798 /*ForOverloadResolution*/ true) ||
7799 !Satisfaction.IsSatisfied) {
7800 Candidate.Viable = false;
7801 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7802 return;
7803 }
7804 }
7805
7806 // Determine the implicit conversion sequences for each of the
7807 // arguments.
7808 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7809 unsigned ConvIdx =
7810 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7811 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7812 // We already formed a conversion sequence for this parameter during
7813 // template argument deduction.
7814 } else if (ArgIdx < NumParams) {
7815 // (C++ 13.3.2p3): for F to be a viable function, there shall
7816 // exist for each argument an implicit conversion sequence
7817 // (13.3.3.1) that converts that argument to the corresponding
7818 // parameter of F.
7819 QualType ParamType;
7820 if (ImplicitObjectMethodTreatedAsStatic) {
7821 ParamType = ArgIdx == 0
7822 ? Method->getFunctionObjectParameterReferenceType()
7823 : Proto->getParamType(i: ArgIdx - 1);
7824 } else {
7825 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
7826 }
7827 Candidate.Conversions[ConvIdx]
7828 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
7829 SuppressUserConversions,
7830 /*InOverloadResolution=*/true,
7831 /*AllowObjCWritebackConversion=*/
7832 getLangOpts().ObjCAutoRefCount);
7833 if (Candidate.Conversions[ConvIdx].isBad()) {
7834 Candidate.Viable = false;
7835 Candidate.FailureKind = ovl_fail_bad_conversion;
7836 return;
7837 }
7838 } else {
7839 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7840 // argument for which there is no corresponding parameter is
7841 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7842 Candidate.Conversions[ConvIdx].setEllipsis();
7843 }
7844 }
7845
7846 if (EnableIfAttr *FailedAttr =
7847 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
7848 Candidate.Viable = false;
7849 Candidate.FailureKind = ovl_fail_enable_if;
7850 Candidate.DeductionFailure.Data = FailedAttr;
7851 return;
7852 }
7853
7854 if (isNonViableMultiVersionOverload(FD: Method)) {
7855 Candidate.Viable = false;
7856 Candidate.FailureKind = ovl_non_default_multiversion_function;
7857 }
7858}
7859
7860static void AddMethodTemplateCandidateImmediately(
7861 Sema &S, OverloadCandidateSet &CandidateSet,
7862 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7863 CXXRecordDecl *ActingContext,
7864 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7865 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7866 bool SuppressUserConversions, bool PartialOverloading,
7867 OverloadCandidateParamOrder PO) {
7868
7869 // C++ [over.match.funcs]p7:
7870 // In each case where a candidate is a function template, candidate
7871 // function template specializations are generated using template argument
7872 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7873 // candidate functions in the usual way.113) A given name can refer to one
7874 // or more function templates and also to a set of overloaded non-template
7875 // functions. In such a case, the candidate functions generated from each
7876 // function template are combined with the set of non-template candidate
7877 // functions.
7878 TemplateDeductionInfo Info(CandidateSet.getLocation());
7879 FunctionDecl *Specialization = nullptr;
7880 ConversionSequenceList Conversions;
7881 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7882 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7883 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7884 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7885 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
7886 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
7887 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
7888 bool OnlyInitializeNonUserDefinedConversions) {
7889 return S.CheckNonDependentConversions(
7890 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7891 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
7892 SuppressUserConversions,
7893 OnlyInitializeNonUserDefinedConversions),
7894 ActingContext, ObjectType, ObjectClassification, PO);
7895 });
7896 Result != TemplateDeductionResult::Success) {
7897 OverloadCandidate &Candidate =
7898 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
7899 Candidate.FoundDecl = FoundDecl;
7900 Candidate.Function = MethodTmpl->getTemplatedDecl();
7901 Candidate.Viable = false;
7902 Candidate.RewriteKind =
7903 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
7904 Candidate.IsSurrogate = false;
7905 Candidate.IgnoreObjectArgument =
7906 cast<CXXMethodDecl>(Val: Candidate.Function)->isStatic() ||
7907 ObjectType.isNull();
7908 Candidate.ExplicitCallArguments = Args.size();
7909 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7910 Candidate.FailureKind = ovl_fail_bad_conversion;
7911 else {
7912 Candidate.FailureKind = ovl_fail_bad_deduction;
7913 Candidate.DeductionFailure =
7914 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
7915 }
7916 return;
7917 }
7918
7919 // Add the function template specialization produced by template argument
7920 // deduction as a candidate.
7921 assert(Specialization && "Missing member function template specialization?");
7922 assert(isa<CXXMethodDecl>(Specialization) &&
7923 "Specialization is not a member function?");
7924 S.AddMethodCandidate(
7925 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
7926 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7927 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
7928}
7929
7930void Sema::AddMethodTemplateCandidate(
7931 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7932 CXXRecordDecl *ActingContext,
7933 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7934 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7935 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7936 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7937 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
7938 return;
7939
7940 if (ExplicitTemplateArgs ||
7941 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts())) {
7942 AddMethodTemplateCandidateImmediately(
7943 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7944 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7945 SuppressUserConversions, PartialOverloading, PO);
7946 return;
7947 }
7948
7949 CandidateSet.AddDeferredMethodTemplateCandidate(
7950 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7951 Args, SuppressUserConversions, PartialOverloading, PO);
7952}
7953
7954/// Determine whether a given function template has a simple explicit specifier
7955/// or a non-value-dependent explicit-specification that evaluates to true.
7956static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7957 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
7958}
7959
7960static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
7961 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
7962 ExplicitSpecKind::Unresolved;
7963}
7964
7965static void AddTemplateOverloadCandidateImmediately(
7966 Sema &S, OverloadCandidateSet &CandidateSet,
7967 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7968 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7969 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7970 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
7971 bool AggregateCandidateDeduction) {
7972
7973 // If the function template has a non-dependent explicit specification,
7974 // exclude it now if appropriate; we are not permitted to perform deduction
7975 // and substitution in this case.
7976 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
7977 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7978 Candidate.FoundDecl = FoundDecl;
7979 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7980 Candidate.Viable = false;
7981 Candidate.FailureKind = ovl_fail_explicit;
7982 return;
7983 }
7984
7985 // C++ [over.match.funcs]p7:
7986 // In each case where a candidate is a function template, candidate
7987 // function template specializations are generated using template argument
7988 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7989 // candidate functions in the usual way.113) A given name can refer to one
7990 // or more function templates and also to a set of overloaded non-template
7991 // functions. In such a case, the candidate functions generated from each
7992 // function template are combined with the set of non-template candidate
7993 // functions.
7994 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7995 FunctionTemplate->getTemplateDepth());
7996 FunctionDecl *Specialization = nullptr;
7997 ConversionSequenceList Conversions;
7998 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7999 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8000 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8001 /*PartialOrdering=*/false,
8002 /*ObjectType=*/QualType(),
8003 /*ObjectClassification=*/Expr::Classification(),
8004 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8005 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8006 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8007 bool OnlyInitializeNonUserDefinedConversions) {
8008 return S.CheckNonDependentConversions(
8009 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8010 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8011 SuppressUserConversions,
8012 OnlyInitializeNonUserDefinedConversions),
8013 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8014 });
8015 Result != TemplateDeductionResult::Success) {
8016 OverloadCandidate &Candidate =
8017 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8018 Candidate.FoundDecl = FoundDecl;
8019 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8020 Candidate.Viable = false;
8021 Candidate.RewriteKind =
8022 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8023 Candidate.IsSurrogate = false;
8024 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8025 // Ignore the object argument if there is one, since we don't have an object
8026 // type.
8027 Candidate.IgnoreObjectArgument =
8028 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8029 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8030 Candidate.ExplicitCallArguments = Args.size();
8031 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8032 Candidate.FailureKind = ovl_fail_bad_conversion;
8033 else {
8034 Candidate.FailureKind = ovl_fail_bad_deduction;
8035 Candidate.DeductionFailure =
8036 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8037 }
8038 return;
8039 }
8040
8041 // Add the function template specialization produced by template argument
8042 // deduction as a candidate.
8043 assert(Specialization && "Missing function template specialization?");
8044 S.AddOverloadCandidate(
8045 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8046 PartialOverloading, AllowExplicit,
8047 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8048 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8049 StrictPackMatch: Info.hasStrictPackMatch());
8050}
8051
8052void Sema::AddTemplateOverloadCandidate(
8053 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8054 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8055 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8056 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8057 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8058 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8059 return;
8060
8061 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8062
8063 if (ExplicitTemplateArgs ||
8064 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8065 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8066 DependentExplicitSpecifier)) {
8067
8068 AddTemplateOverloadCandidateImmediately(
8069 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8070 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8071 IsADLCandidate, PO, AggregateCandidateDeduction);
8072
8073 if (DependentExplicitSpecifier)
8074 CandidateSet.DisableResolutionByPerfectCandidate();
8075 return;
8076 }
8077
8078 CandidateSet.AddDeferredTemplateCandidate(
8079 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8080 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8081 AggregateCandidateDeduction);
8082}
8083
8084bool Sema::CheckNonDependentConversions(
8085 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8086 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8087 ConversionSequenceList &Conversions,
8088 CheckNonDependentConversionsFlag UserConversionFlag,
8089 CXXRecordDecl *ActingContext, QualType ObjectType,
8090 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8091 // FIXME: The cases in which we allow explicit conversions for constructor
8092 // arguments never consider calling a constructor template. It's not clear
8093 // that is correct.
8094 const bool AllowExplicit = false;
8095
8096 auto *FD = FunctionTemplate->getTemplatedDecl();
8097 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8098 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Val: Method);
8099 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8100
8101 if (Conversions.empty())
8102 Conversions =
8103 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8104
8105 // Overload resolution is always an unevaluated context.
8106 EnterExpressionEvaluationContext Unevaluated(
8107 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8108
8109 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8110 // require that, but this check should never result in a hard error, and
8111 // overload resolution is permitted to sidestep instantiations.
8112 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8113 !ObjectType.isNull()) {
8114 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8115 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8116 !ParamTypes[0]->isDependentType()) {
8117 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8118 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8119 Method, ActingContext, /*InOverloadResolution=*/true,
8120 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8121 : QualType());
8122 if (Conversions[ConvIdx].isBad())
8123 return true;
8124 }
8125 }
8126
8127 // A speculative workaround for self-dependent constraint bugs that manifest
8128 // after CWG2369.
8129 // FIXME: Add references to the standard once P3606 is adopted.
8130 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8131 QualType ArgType) {
8132 ParamType = ParamType.getNonReferenceType();
8133 ArgType = ArgType.getNonReferenceType();
8134 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8135 if (PointerConv) {
8136 ParamType = ParamType->getPointeeType();
8137 ArgType = ArgType->getPointeeType();
8138 }
8139
8140 if (auto *RT = ParamType->getAs<RecordType>())
8141 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl());
8142 RD && RD->hasDefinition()) {
8143 if (llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8144 auto Info = getConstructorInfo(ND);
8145 if (!Info)
8146 return false;
8147 CXXConstructorDecl *Ctor = Info.Constructor;
8148 /// isConvertingConstructor takes copy/move constructors into
8149 /// account!
8150 return !Ctor->isCopyOrMoveConstructor() &&
8151 Ctor->isConvertingConstructor(
8152 /*AllowExplicit=*/true);
8153 }))
8154 return true;
8155 }
8156
8157 if (auto *RT = ArgType->getAs<RecordType>())
8158 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl());
8159 RD && RD->hasDefinition() &&
8160 !RD->getVisibleConversionFunctions().empty()) {
8161 return true;
8162 }
8163
8164 return false;
8165 };
8166
8167 unsigned Offset =
8168 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
8169
8170 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8171 I != N; ++I) {
8172 QualType ParamType = ParamTypes[I + Offset];
8173 if (!ParamType->isDependentType()) {
8174 unsigned ConvIdx;
8175 if (PO == OverloadCandidateParamOrder::Reversed) {
8176 ConvIdx = Args.size() - 1 - I;
8177 assert(Args.size() + ThisConversions == 2 &&
8178 "number of args (including 'this') must be exactly 2 for "
8179 "reversed order");
8180 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8181 // would also be 0. 'this' got ConvIdx = 1 previously.
8182 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8183 } else {
8184 // For members, 'this' got ConvIdx = 0 previously.
8185 ConvIdx = ThisConversions + I;
8186 }
8187 if (Conversions[ConvIdx].isInitialized())
8188 continue;
8189 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8190 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8191 continue;
8192 Conversions[ConvIdx] = TryCopyInitialization(
8193 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8194 /*InOverloadResolution=*/true,
8195 /*AllowObjCWritebackConversion=*/
8196 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8197 if (Conversions[ConvIdx].isBad())
8198 return true;
8199 }
8200 }
8201
8202 return false;
8203}
8204
8205/// Determine whether this is an allowable conversion from the result
8206/// of an explicit conversion operator to the expected type, per C++
8207/// [over.match.conv]p1 and [over.match.ref]p1.
8208///
8209/// \param ConvType The return type of the conversion function.
8210///
8211/// \param ToType The type we are converting to.
8212///
8213/// \param AllowObjCPointerConversion Allow a conversion from one
8214/// Objective-C pointer to another.
8215///
8216/// \returns true if the conversion is allowable, false otherwise.
8217static bool isAllowableExplicitConversion(Sema &S,
8218 QualType ConvType, QualType ToType,
8219 bool AllowObjCPointerConversion) {
8220 QualType ToNonRefType = ToType.getNonReferenceType();
8221
8222 // Easy case: the types are the same.
8223 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8224 return true;
8225
8226 // Allow qualification conversions.
8227 bool ObjCLifetimeConversion;
8228 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8229 ObjCLifetimeConversion))
8230 return true;
8231
8232 // If we're not allowed to consider Objective-C pointer conversions,
8233 // we're done.
8234 if (!AllowObjCPointerConversion)
8235 return false;
8236
8237 // Is this an Objective-C pointer conversion?
8238 bool IncompatibleObjC = false;
8239 QualType ConvertedType;
8240 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8241 IncompatibleObjC);
8242}
8243
8244void Sema::AddConversionCandidate(
8245 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8246 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8247 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8248 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8249 assert(!Conversion->getDescribedFunctionTemplate() &&
8250 "Conversion function templates use AddTemplateConversionCandidate");
8251 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8252 if (!CandidateSet.isNewCandidate(F: Conversion))
8253 return;
8254
8255 // If the conversion function has an undeduced return type, trigger its
8256 // deduction now.
8257 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8258 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8259 return;
8260 ConvType = Conversion->getConversionType().getNonReferenceType();
8261 }
8262
8263 // If we don't allow any conversion of the result type, ignore conversion
8264 // functions that don't convert to exactly (possibly cv-qualified) T.
8265 if (!AllowResultConversion &&
8266 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8267 return;
8268
8269 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8270 // operator is only a candidate if its return type is the target type or
8271 // can be converted to the target type with a qualification conversion.
8272 //
8273 // FIXME: Include such functions in the candidate list and explain why we
8274 // can't select them.
8275 if (Conversion->isExplicit() &&
8276 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8277 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8278 return;
8279
8280 // Overload resolution is always an unevaluated context.
8281 EnterExpressionEvaluationContext Unevaluated(
8282 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8283
8284 // Add this candidate
8285 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8286 Candidate.FoundDecl = FoundDecl;
8287 Candidate.Function = Conversion;
8288 Candidate.FinalConversion.setAsIdentityConversion();
8289 Candidate.FinalConversion.setFromType(ConvType);
8290 Candidate.FinalConversion.setAllToTypes(ToType);
8291 Candidate.HasFinalConversion = true;
8292 Candidate.Viable = true;
8293 Candidate.ExplicitCallArguments = 1;
8294 Candidate.StrictPackMatch = StrictPackMatch;
8295
8296 // Explicit functions are not actually candidates at all if we're not
8297 // allowing them in this context, but keep them around so we can point
8298 // to them in diagnostics.
8299 if (!AllowExplicit && Conversion->isExplicit()) {
8300 Candidate.Viable = false;
8301 Candidate.FailureKind = ovl_fail_explicit;
8302 return;
8303 }
8304
8305 // C++ [over.match.funcs]p4:
8306 // For conversion functions, the function is considered to be a member of
8307 // the class of the implicit implied object argument for the purpose of
8308 // defining the type of the implicit object parameter.
8309 //
8310 // Determine the implicit conversion sequence for the implicit
8311 // object parameter.
8312 QualType ObjectType = From->getType();
8313 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8314 ObjectType = FromPtrType->getPointeeType();
8315 const auto *ConversionContext =
8316 cast<CXXRecordDecl>(Val: ObjectType->castAs<RecordType>()->getDecl());
8317
8318 // C++23 [over.best.ics.general]
8319 // However, if the target is [...]
8320 // - the object parameter of a user-defined conversion function
8321 // [...] user-defined conversion sequences are not considered.
8322 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8323 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8324 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8325 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8326 /*SuppressUserConversion*/ true);
8327
8328 if (Candidate.Conversions[0].isBad()) {
8329 Candidate.Viable = false;
8330 Candidate.FailureKind = ovl_fail_bad_conversion;
8331 return;
8332 }
8333
8334 if (Conversion->getTrailingRequiresClause()) {
8335 ConstraintSatisfaction Satisfaction;
8336 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8337 !Satisfaction.IsSatisfied) {
8338 Candidate.Viable = false;
8339 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8340 return;
8341 }
8342 }
8343
8344 // We won't go through a user-defined type conversion function to convert a
8345 // derived to base as such conversions are given Conversion Rank. They only
8346 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8347 QualType FromCanon
8348 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8349 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8350 if (FromCanon == ToCanon ||
8351 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8352 Candidate.Viable = false;
8353 Candidate.FailureKind = ovl_fail_trivial_conversion;
8354 return;
8355 }
8356
8357 // To determine what the conversion from the result of calling the
8358 // conversion function to the type we're eventually trying to
8359 // convert to (ToType), we need to synthesize a call to the
8360 // conversion function and attempt copy initialization from it. This
8361 // makes sure that we get the right semantics with respect to
8362 // lvalues/rvalues and the type. Fortunately, we can allocate this
8363 // call on the stack and we don't need its arguments to be
8364 // well-formed.
8365 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8366 VK_LValue, From->getBeginLoc());
8367 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8368 Context.getPointerType(T: Conversion->getType()),
8369 CK_FunctionToPointerDecay, &ConversionRef,
8370 VK_PRValue, FPOptionsOverride());
8371
8372 QualType ConversionType = Conversion->getConversionType();
8373 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8374 Candidate.Viable = false;
8375 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8376 return;
8377 }
8378
8379 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8380
8381 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8382
8383 // Introduce a temporary expression with the right type and value category
8384 // that we can use for deduction purposes.
8385 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8386
8387 ImplicitConversionSequence ICS =
8388 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8389 /*SuppressUserConversions=*/true,
8390 /*InOverloadResolution=*/false,
8391 /*AllowObjCWritebackConversion=*/false);
8392
8393 switch (ICS.getKind()) {
8394 case ImplicitConversionSequence::StandardConversion:
8395 Candidate.FinalConversion = ICS.Standard;
8396 Candidate.HasFinalConversion = true;
8397
8398 // C++ [over.ics.user]p3:
8399 // If the user-defined conversion is specified by a specialization of a
8400 // conversion function template, the second standard conversion sequence
8401 // shall have exact match rank.
8402 if (Conversion->getPrimaryTemplate() &&
8403 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8404 Candidate.Viable = false;
8405 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8406 return;
8407 }
8408
8409 // C++0x [dcl.init.ref]p5:
8410 // In the second case, if the reference is an rvalue reference and
8411 // the second standard conversion sequence of the user-defined
8412 // conversion sequence includes an lvalue-to-rvalue conversion, the
8413 // program is ill-formed.
8414 if (ToType->isRValueReferenceType() &&
8415 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8416 Candidate.Viable = false;
8417 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8418 return;
8419 }
8420 break;
8421
8422 case ImplicitConversionSequence::BadConversion:
8423 Candidate.Viable = false;
8424 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8425 return;
8426
8427 default:
8428 llvm_unreachable(
8429 "Can only end up with a standard conversion sequence or failure");
8430 }
8431
8432 if (EnableIfAttr *FailedAttr =
8433 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8434 Candidate.Viable = false;
8435 Candidate.FailureKind = ovl_fail_enable_if;
8436 Candidate.DeductionFailure.Data = FailedAttr;
8437 return;
8438 }
8439
8440 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8441 Candidate.Viable = false;
8442 Candidate.FailureKind = ovl_non_default_multiversion_function;
8443 }
8444}
8445
8446static void AddTemplateConversionCandidateImmediately(
8447 Sema &S, OverloadCandidateSet &CandidateSet,
8448 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8449 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8450 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8451 bool AllowResultConversion) {
8452
8453 // If the function template has a non-dependent explicit specification,
8454 // exclude it now if appropriate; we are not permitted to perform deduction
8455 // and substitution in this case.
8456 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8457 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8458 Candidate.FoundDecl = FoundDecl;
8459 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8460 Candidate.Viable = false;
8461 Candidate.FailureKind = ovl_fail_explicit;
8462 return;
8463 }
8464
8465 QualType ObjectType = From->getType();
8466 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8467
8468 TemplateDeductionInfo Info(CandidateSet.getLocation());
8469 CXXConversionDecl *Specialization = nullptr;
8470 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8471 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8472 Specialization, Info);
8473 Result != TemplateDeductionResult::Success) {
8474 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8475 Candidate.FoundDecl = FoundDecl;
8476 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8477 Candidate.Viable = false;
8478 Candidate.FailureKind = ovl_fail_bad_deduction;
8479 Candidate.ExplicitCallArguments = 1;
8480 Candidate.DeductionFailure =
8481 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8482 return;
8483 }
8484
8485 // Add the conversion function template specialization produced by
8486 // template argument deduction as a candidate.
8487 assert(Specialization && "Missing function template specialization?");
8488 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8489 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8490 AllowExplicit, AllowResultConversion,
8491 StrictPackMatch: Info.hasStrictPackMatch());
8492}
8493
8494void Sema::AddTemplateConversionCandidate(
8495 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8496 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8497 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8498 bool AllowExplicit, bool AllowResultConversion) {
8499 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8500 "Only conversion function templates permitted here");
8501
8502 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8503 return;
8504
8505 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8506 CandidateSet.getKind() ==
8507 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8508 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8509 AddTemplateConversionCandidateImmediately(
8510 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8511 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8512 AllowResultConversion);
8513
8514 CandidateSet.DisableResolutionByPerfectCandidate();
8515 return;
8516 }
8517
8518 CandidateSet.AddDeferredConversionTemplateCandidate(
8519 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8520 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8521}
8522
8523void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8524 DeclAccessPair FoundDecl,
8525 CXXRecordDecl *ActingContext,
8526 const FunctionProtoType *Proto,
8527 Expr *Object,
8528 ArrayRef<Expr *> Args,
8529 OverloadCandidateSet& CandidateSet) {
8530 if (!CandidateSet.isNewCandidate(F: Conversion))
8531 return;
8532
8533 // Overload resolution is always an unevaluated context.
8534 EnterExpressionEvaluationContext Unevaluated(
8535 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8536
8537 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8538 Candidate.FoundDecl = FoundDecl;
8539 Candidate.Function = nullptr;
8540 Candidate.Surrogate = Conversion;
8541 Candidate.IsSurrogate = true;
8542 Candidate.Viable = true;
8543 Candidate.ExplicitCallArguments = Args.size();
8544
8545 // Determine the implicit conversion sequence for the implicit
8546 // object parameter.
8547 ImplicitConversionSequence ObjectInit;
8548 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8549 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8550 ToType: Conversion->getParamDecl(i: 0)->getType(),
8551 /*SuppressUserConversions=*/false,
8552 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8553 } else {
8554 ObjectInit = TryObjectArgumentInitialization(
8555 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8556 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8557 }
8558
8559 if (ObjectInit.isBad()) {
8560 Candidate.Viable = false;
8561 Candidate.FailureKind = ovl_fail_bad_conversion;
8562 Candidate.Conversions[0] = ObjectInit;
8563 return;
8564 }
8565
8566 // The first conversion is actually a user-defined conversion whose
8567 // first conversion is ObjectInit's standard conversion (which is
8568 // effectively a reference binding). Record it as such.
8569 Candidate.Conversions[0].setUserDefined();
8570 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8571 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8572 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8573 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8574 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8575 Candidate.Conversions[0].UserDefined.After
8576 = Candidate.Conversions[0].UserDefined.Before;
8577 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8578
8579 // Find the
8580 unsigned NumParams = Proto->getNumParams();
8581
8582 // (C++ 13.3.2p2): A candidate function having fewer than m
8583 // parameters is viable only if it has an ellipsis in its parameter
8584 // list (8.3.5).
8585 if (Args.size() > NumParams && !Proto->isVariadic()) {
8586 Candidate.Viable = false;
8587 Candidate.FailureKind = ovl_fail_too_many_arguments;
8588 return;
8589 }
8590
8591 // Function types don't have any default arguments, so just check if
8592 // we have enough arguments.
8593 if (Args.size() < NumParams) {
8594 // Not enough arguments.
8595 Candidate.Viable = false;
8596 Candidate.FailureKind = ovl_fail_too_few_arguments;
8597 return;
8598 }
8599
8600 // Determine the implicit conversion sequences for each of the
8601 // arguments.
8602 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8603 if (ArgIdx < NumParams) {
8604 // (C++ 13.3.2p3): for F to be a viable function, there shall
8605 // exist for each argument an implicit conversion sequence
8606 // (13.3.3.1) that converts that argument to the corresponding
8607 // parameter of F.
8608 QualType ParamType = Proto->getParamType(i: ArgIdx);
8609 Candidate.Conversions[ArgIdx + 1]
8610 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8611 /*SuppressUserConversions=*/false,
8612 /*InOverloadResolution=*/false,
8613 /*AllowObjCWritebackConversion=*/
8614 getLangOpts().ObjCAutoRefCount);
8615 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8616 Candidate.Viable = false;
8617 Candidate.FailureKind = ovl_fail_bad_conversion;
8618 return;
8619 }
8620 } else {
8621 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8622 // argument for which there is no corresponding parameter is
8623 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8624 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8625 }
8626 }
8627
8628 if (Conversion->getTrailingRequiresClause()) {
8629 ConstraintSatisfaction Satisfaction;
8630 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8631 /*ForOverloadResolution*/ true) ||
8632 !Satisfaction.IsSatisfied) {
8633 Candidate.Viable = false;
8634 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8635 return;
8636 }
8637 }
8638
8639 if (EnableIfAttr *FailedAttr =
8640 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8641 Candidate.Viable = false;
8642 Candidate.FailureKind = ovl_fail_enable_if;
8643 Candidate.DeductionFailure.Data = FailedAttr;
8644 return;
8645 }
8646}
8647
8648void Sema::AddNonMemberOperatorCandidates(
8649 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8650 OverloadCandidateSet &CandidateSet,
8651 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8652 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8653 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8654 ArrayRef<Expr *> FunctionArgs = Args;
8655
8656 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8657 FunctionDecl *FD =
8658 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8659
8660 // Don't consider rewritten functions if we're not rewriting.
8661 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8662 continue;
8663
8664 assert(!isa<CXXMethodDecl>(FD) &&
8665 "unqualified operator lookup found a member function");
8666
8667 if (FunTmpl) {
8668 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8669 Args: FunctionArgs, CandidateSet);
8670 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8671
8672 // As template candidates are not deduced immediately,
8673 // persist the array in the overload set.
8674 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8675 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8676 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8677 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8678 IsADLCandidate: ADLCallKind::NotADL,
8679 PO: OverloadCandidateParamOrder::Reversed);
8680 }
8681 } else {
8682 if (ExplicitTemplateArgs)
8683 continue;
8684 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8685 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8686 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8687 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8688 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8689 PO: OverloadCandidateParamOrder::Reversed);
8690 }
8691 }
8692}
8693
8694void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8695 SourceLocation OpLoc,
8696 ArrayRef<Expr *> Args,
8697 OverloadCandidateSet &CandidateSet,
8698 OverloadCandidateParamOrder PO) {
8699 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8700
8701 // C++ [over.match.oper]p3:
8702 // For a unary operator @ with an operand of a type whose
8703 // cv-unqualified version is T1, and for a binary operator @ with
8704 // a left operand of a type whose cv-unqualified version is T1 and
8705 // a right operand of a type whose cv-unqualified version is T2,
8706 // three sets of candidate functions, designated member
8707 // candidates, non-member candidates and built-in candidates, are
8708 // constructed as follows:
8709 QualType T1 = Args[0]->getType();
8710
8711 // -- If T1 is a complete class type or a class currently being
8712 // defined, the set of member candidates is the result of the
8713 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8714 // the set of member candidates is empty.
8715 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8716 // Complete the type if it can be completed.
8717 if (!isCompleteType(Loc: OpLoc, T: T1) && !T1Rec->isBeingDefined())
8718 return;
8719 // If the type is neither complete nor being defined, bail out now.
8720 if (!T1Rec->getDecl()->getDefinition())
8721 return;
8722
8723 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8724 LookupQualifiedName(R&: Operators, LookupCtx: T1Rec->getDecl());
8725 Operators.suppressAccessDiagnostics();
8726
8727 for (LookupResult::iterator Oper = Operators.begin(),
8728 OperEnd = Operators.end();
8729 Oper != OperEnd; ++Oper) {
8730 if (Oper->getAsFunction() &&
8731 PO == OverloadCandidateParamOrder::Reversed &&
8732 !CandidateSet.getRewriteInfo().shouldAddReversed(
8733 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8734 continue;
8735 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8736 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8737 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8738 }
8739 }
8740}
8741
8742void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8743 OverloadCandidateSet& CandidateSet,
8744 bool IsAssignmentOperator,
8745 unsigned NumContextualBoolArguments) {
8746 // Overload resolution is always an unevaluated context.
8747 EnterExpressionEvaluationContext Unevaluated(
8748 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8749
8750 // Add this candidate
8751 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8752 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8753 Candidate.Function = nullptr;
8754 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
8755
8756 // Determine the implicit conversion sequences for each of the
8757 // arguments.
8758 Candidate.Viable = true;
8759 Candidate.ExplicitCallArguments = Args.size();
8760 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8761 // C++ [over.match.oper]p4:
8762 // For the built-in assignment operators, conversions of the
8763 // left operand are restricted as follows:
8764 // -- no temporaries are introduced to hold the left operand, and
8765 // -- no user-defined conversions are applied to the left
8766 // operand to achieve a type match with the left-most
8767 // parameter of a built-in candidate.
8768 //
8769 // We block these conversions by turning off user-defined
8770 // conversions, since that is the only way that initialization of
8771 // a reference to a non-class type can occur from something that
8772 // is not of the same type.
8773 if (ArgIdx < NumContextualBoolArguments) {
8774 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8775 "Contextual conversion to bool requires bool type");
8776 Candidate.Conversions[ArgIdx]
8777 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
8778 } else {
8779 Candidate.Conversions[ArgIdx]
8780 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
8781 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
8782 /*InOverloadResolution=*/false,
8783 /*AllowObjCWritebackConversion=*/
8784 getLangOpts().ObjCAutoRefCount);
8785 }
8786 if (Candidate.Conversions[ArgIdx].isBad()) {
8787 Candidate.Viable = false;
8788 Candidate.FailureKind = ovl_fail_bad_conversion;
8789 break;
8790 }
8791 }
8792}
8793
8794namespace {
8795
8796/// BuiltinCandidateTypeSet - A set of types that will be used for the
8797/// candidate operator functions for built-in operators (C++
8798/// [over.built]). The types are separated into pointer types and
8799/// enumeration types.
8800class BuiltinCandidateTypeSet {
8801 /// TypeSet - A set of types.
8802 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8803
8804 /// PointerTypes - The set of pointer types that will be used in the
8805 /// built-in candidates.
8806 TypeSet PointerTypes;
8807
8808 /// MemberPointerTypes - The set of member pointer types that will be
8809 /// used in the built-in candidates.
8810 TypeSet MemberPointerTypes;
8811
8812 /// EnumerationTypes - The set of enumeration types that will be
8813 /// used in the built-in candidates.
8814 TypeSet EnumerationTypes;
8815
8816 /// The set of vector types that will be used in the built-in
8817 /// candidates.
8818 TypeSet VectorTypes;
8819
8820 /// The set of matrix types that will be used in the built-in
8821 /// candidates.
8822 TypeSet MatrixTypes;
8823
8824 /// The set of _BitInt types that will be used in the built-in candidates.
8825 TypeSet BitIntTypes;
8826
8827 /// A flag indicating non-record types are viable candidates
8828 bool HasNonRecordTypes;
8829
8830 /// A flag indicating whether either arithmetic or enumeration types
8831 /// were present in the candidate set.
8832 bool HasArithmeticOrEnumeralTypes;
8833
8834 /// A flag indicating whether the nullptr type was present in the
8835 /// candidate set.
8836 bool HasNullPtrType;
8837
8838 /// Sema - The semantic analysis instance where we are building the
8839 /// candidate type set.
8840 Sema &SemaRef;
8841
8842 /// Context - The AST context in which we will build the type sets.
8843 ASTContext &Context;
8844
8845 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8846 const Qualifiers &VisibleQuals);
8847 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8848
8849public:
8850 /// iterator - Iterates through the types that are part of the set.
8851 typedef TypeSet::iterator iterator;
8852
8853 BuiltinCandidateTypeSet(Sema &SemaRef)
8854 : HasNonRecordTypes(false),
8855 HasArithmeticOrEnumeralTypes(false),
8856 HasNullPtrType(false),
8857 SemaRef(SemaRef),
8858 Context(SemaRef.Context) { }
8859
8860 void AddTypesConvertedFrom(QualType Ty,
8861 SourceLocation Loc,
8862 bool AllowUserConversions,
8863 bool AllowExplicitConversions,
8864 const Qualifiers &VisibleTypeConversionsQuals);
8865
8866 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8867 llvm::iterator_range<iterator> member_pointer_types() {
8868 return MemberPointerTypes;
8869 }
8870 llvm::iterator_range<iterator> enumeration_types() {
8871 return EnumerationTypes;
8872 }
8873 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8874 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8875 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8876
8877 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
8878 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8879 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8880 bool hasNullPtrType() const { return HasNullPtrType; }
8881};
8882
8883} // end anonymous namespace
8884
8885/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8886/// the set of pointer types along with any more-qualified variants of
8887/// that type. For example, if @p Ty is "int const *", this routine
8888/// will add "int const *", "int const volatile *", "int const
8889/// restrict *", and "int const volatile restrict *" to the set of
8890/// pointer types. Returns true if the add of @p Ty itself succeeded,
8891/// false otherwise.
8892///
8893/// FIXME: what to do about extended qualifiers?
8894bool
8895BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8896 const Qualifiers &VisibleQuals) {
8897
8898 // Insert this type.
8899 if (!PointerTypes.insert(X: Ty))
8900 return false;
8901
8902 QualType PointeeTy;
8903 const PointerType *PointerTy = Ty->getAs<PointerType>();
8904 bool buildObjCPtr = false;
8905 if (!PointerTy) {
8906 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8907 PointeeTy = PTy->getPointeeType();
8908 buildObjCPtr = true;
8909 } else {
8910 PointeeTy = PointerTy->getPointeeType();
8911 }
8912
8913 // Don't add qualified variants of arrays. For one, they're not allowed
8914 // (the qualifier would sink to the element type), and for another, the
8915 // only overload situation where it matters is subscript or pointer +- int,
8916 // and those shouldn't have qualifier variants anyway.
8917 if (PointeeTy->isArrayType())
8918 return true;
8919
8920 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8921 bool hasVolatile = VisibleQuals.hasVolatile();
8922 bool hasRestrict = VisibleQuals.hasRestrict();
8923
8924 // Iterate through all strict supersets of BaseCVR.
8925 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8926 if ((CVR | BaseCVR) != CVR) continue;
8927 // Skip over volatile if no volatile found anywhere in the types.
8928 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8929
8930 // Skip over restrict if no restrict found anywhere in the types, or if
8931 // the type cannot be restrict-qualified.
8932 if ((CVR & Qualifiers::Restrict) &&
8933 (!hasRestrict ||
8934 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8935 continue;
8936
8937 // Build qualified pointee type.
8938 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8939
8940 // Build qualified pointer type.
8941 QualType QPointerTy;
8942 if (!buildObjCPtr)
8943 QPointerTy = Context.getPointerType(T: QPointeeTy);
8944 else
8945 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
8946
8947 // Insert qualified pointer type.
8948 PointerTypes.insert(X: QPointerTy);
8949 }
8950
8951 return true;
8952}
8953
8954/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8955/// to the set of pointer types along with any more-qualified variants of
8956/// that type. For example, if @p Ty is "int const *", this routine
8957/// will add "int const *", "int const volatile *", "int const
8958/// restrict *", and "int const volatile restrict *" to the set of
8959/// pointer types. Returns true if the add of @p Ty itself succeeded,
8960/// false otherwise.
8961///
8962/// FIXME: what to do about extended qualifiers?
8963bool
8964BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8965 QualType Ty) {
8966 // Insert this type.
8967 if (!MemberPointerTypes.insert(X: Ty))
8968 return false;
8969
8970 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8971 assert(PointerTy && "type was not a member pointer type!");
8972
8973 QualType PointeeTy = PointerTy->getPointeeType();
8974 // Don't add qualified variants of arrays. For one, they're not allowed
8975 // (the qualifier would sink to the element type), and for another, the
8976 // only overload situation where it matters is subscript or pointer +- int,
8977 // and those shouldn't have qualifier variants anyway.
8978 if (PointeeTy->isArrayType())
8979 return true;
8980 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
8981
8982 // Iterate through all strict supersets of the pointee type's CVR
8983 // qualifiers.
8984 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8985 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8986 if ((CVR | BaseCVR) != CVR) continue;
8987
8988 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8989 MemberPointerTypes.insert(
8990 X: Context.getMemberPointerType(T: QPointeeTy, /*Qualifier=*/nullptr, Cls));
8991 }
8992
8993 return true;
8994}
8995
8996/// AddTypesConvertedFrom - Add each of the types to which the type @p
8997/// Ty can be implicit converted to the given set of @p Types. We're
8998/// primarily interested in pointer types and enumeration types. We also
8999/// take member pointer types, for the conditional operator.
9000/// AllowUserConversions is true if we should look at the conversion
9001/// functions of a class type, and AllowExplicitConversions if we
9002/// should also include the explicit conversion functions of a class
9003/// type.
9004void
9005BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9006 SourceLocation Loc,
9007 bool AllowUserConversions,
9008 bool AllowExplicitConversions,
9009 const Qualifiers &VisibleQuals) {
9010 // Only deal with canonical types.
9011 Ty = Context.getCanonicalType(T: Ty);
9012
9013 // Look through reference types; they aren't part of the type of an
9014 // expression for the purposes of conversions.
9015 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9016 Ty = RefTy->getPointeeType();
9017
9018 // If we're dealing with an array type, decay to the pointer.
9019 if (Ty->isArrayType())
9020 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9021
9022 // Otherwise, we don't care about qualifiers on the type.
9023 Ty = Ty.getLocalUnqualifiedType();
9024
9025 // Flag if we ever add a non-record type.
9026 const RecordType *TyRec = Ty->getAs<RecordType>();
9027 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
9028
9029 // Flag if we encounter an arithmetic type.
9030 HasArithmeticOrEnumeralTypes =
9031 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9032
9033 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9034 PointerTypes.insert(X: Ty);
9035 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9036 // Insert our type, and its more-qualified variants, into the set
9037 // of types.
9038 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9039 return;
9040 } else if (Ty->isMemberPointerType()) {
9041 // Member pointers are far easier, since the pointee can't be converted.
9042 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9043 return;
9044 } else if (Ty->isEnumeralType()) {
9045 HasArithmeticOrEnumeralTypes = true;
9046 EnumerationTypes.insert(X: Ty);
9047 } else if (Ty->isBitIntType()) {
9048 HasArithmeticOrEnumeralTypes = true;
9049 BitIntTypes.insert(X: Ty);
9050 } else if (Ty->isVectorType()) {
9051 // We treat vector types as arithmetic types in many contexts as an
9052 // extension.
9053 HasArithmeticOrEnumeralTypes = true;
9054 VectorTypes.insert(X: Ty);
9055 } else if (Ty->isMatrixType()) {
9056 // Similar to vector types, we treat vector types as arithmetic types in
9057 // many contexts as an extension.
9058 HasArithmeticOrEnumeralTypes = true;
9059 MatrixTypes.insert(X: Ty);
9060 } else if (Ty->isNullPtrType()) {
9061 HasNullPtrType = true;
9062 } else if (AllowUserConversions && TyRec) {
9063 // No conversion functions in incomplete types.
9064 if (!SemaRef.isCompleteType(Loc, T: Ty))
9065 return;
9066
9067 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl());
9068 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9069 if (isa<UsingShadowDecl>(Val: D))
9070 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9071
9072 // Skip conversion function templates; they don't tell us anything
9073 // about which builtin types we can convert to.
9074 if (isa<FunctionTemplateDecl>(Val: D))
9075 continue;
9076
9077 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9078 if (AllowExplicitConversions || !Conv->isExplicit()) {
9079 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9080 VisibleQuals);
9081 }
9082 }
9083 }
9084}
9085/// Helper function for adjusting address spaces for the pointer or reference
9086/// operands of builtin operators depending on the argument.
9087static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9088 Expr *Arg) {
9089 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9090}
9091
9092/// Helper function for AddBuiltinOperatorCandidates() that adds
9093/// the volatile- and non-volatile-qualified assignment operators for the
9094/// given type to the candidate set.
9095static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9096 QualType T,
9097 ArrayRef<Expr *> Args,
9098 OverloadCandidateSet &CandidateSet) {
9099 QualType ParamTypes[2];
9100
9101 // T& operator=(T&, T)
9102 ParamTypes[0] = S.Context.getLValueReferenceType(
9103 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9104 ParamTypes[1] = T;
9105 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9106 /*IsAssignmentOperator=*/true);
9107
9108 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9109 // volatile T& operator=(volatile T&, T)
9110 ParamTypes[0] = S.Context.getLValueReferenceType(
9111 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9112 Arg: Args[0]));
9113 ParamTypes[1] = T;
9114 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9115 /*IsAssignmentOperator=*/true);
9116 }
9117}
9118
9119/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9120/// if any, found in visible type conversion functions found in ArgExpr's type.
9121static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9122 Qualifiers VRQuals;
9123 CXXRecordDecl *ClassDecl;
9124 if (const MemberPointerType *RHSMPType =
9125 ArgExpr->getType()->getAs<MemberPointerType>())
9126 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9127 else
9128 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9129 if (!ClassDecl) {
9130 // Just to be safe, assume the worst case.
9131 VRQuals.addVolatile();
9132 VRQuals.addRestrict();
9133 return VRQuals;
9134 }
9135 if (!ClassDecl->hasDefinition())
9136 return VRQuals;
9137
9138 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9139 if (isa<UsingShadowDecl>(Val: D))
9140 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9141 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9142 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9143 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9144 CanTy = ResTypeRef->getPointeeType();
9145 // Need to go down the pointer/mempointer chain and add qualifiers
9146 // as see them.
9147 bool done = false;
9148 while (!done) {
9149 if (CanTy.isRestrictQualified())
9150 VRQuals.addRestrict();
9151 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9152 CanTy = ResTypePtr->getPointeeType();
9153 else if (const MemberPointerType *ResTypeMPtr =
9154 CanTy->getAs<MemberPointerType>())
9155 CanTy = ResTypeMPtr->getPointeeType();
9156 else
9157 done = true;
9158 if (CanTy.isVolatileQualified())
9159 VRQuals.addVolatile();
9160 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9161 return VRQuals;
9162 }
9163 }
9164 }
9165 return VRQuals;
9166}
9167
9168// Note: We're currently only handling qualifiers that are meaningful for the
9169// LHS of compound assignment overloading.
9170static void forAllQualifierCombinationsImpl(
9171 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9172 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9173 // _Atomic
9174 if (Available.hasAtomic()) {
9175 Available.removeAtomic();
9176 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9177 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9178 return;
9179 }
9180
9181 // volatile
9182 if (Available.hasVolatile()) {
9183 Available.removeVolatile();
9184 assert(!Applied.hasVolatile());
9185 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9186 Callback);
9187 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9188 return;
9189 }
9190
9191 Callback(Applied);
9192}
9193
9194static void forAllQualifierCombinations(
9195 QualifiersAndAtomic Quals,
9196 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9197 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9198 Callback);
9199}
9200
9201static QualType makeQualifiedLValueReferenceType(QualType Base,
9202 QualifiersAndAtomic Quals,
9203 Sema &S) {
9204 if (Quals.hasAtomic())
9205 Base = S.Context.getAtomicType(T: Base);
9206 if (Quals.hasVolatile())
9207 Base = S.Context.getVolatileType(T: Base);
9208 return S.Context.getLValueReferenceType(T: Base);
9209}
9210
9211namespace {
9212
9213/// Helper class to manage the addition of builtin operator overload
9214/// candidates. It provides shared state and utility methods used throughout
9215/// the process, as well as a helper method to add each group of builtin
9216/// operator overloads from the standard to a candidate set.
9217class BuiltinOperatorOverloadBuilder {
9218 // Common instance state available to all overload candidate addition methods.
9219 Sema &S;
9220 ArrayRef<Expr *> Args;
9221 QualifiersAndAtomic VisibleTypeConversionsQuals;
9222 bool HasArithmeticOrEnumeralCandidateType;
9223 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9224 OverloadCandidateSet &CandidateSet;
9225
9226 static constexpr int ArithmeticTypesCap = 26;
9227 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9228
9229 // Define some indices used to iterate over the arithmetic types in
9230 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9231 // types are that preserved by promotion (C++ [over.built]p2).
9232 unsigned FirstIntegralType,
9233 LastIntegralType;
9234 unsigned FirstPromotedIntegralType,
9235 LastPromotedIntegralType;
9236 unsigned FirstPromotedArithmeticType,
9237 LastPromotedArithmeticType;
9238 unsigned NumArithmeticTypes;
9239
9240 void InitArithmeticTypes() {
9241 // Start of promoted types.
9242 FirstPromotedArithmeticType = 0;
9243 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9244 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9245 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9246 if (S.Context.getTargetInfo().hasFloat128Type())
9247 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9248 if (S.Context.getTargetInfo().hasIbm128Type())
9249 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9250
9251 // Start of integral types.
9252 FirstIntegralType = ArithmeticTypes.size();
9253 FirstPromotedIntegralType = ArithmeticTypes.size();
9254 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9255 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9256 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9257 if (S.Context.getTargetInfo().hasInt128Type() ||
9258 (S.Context.getAuxTargetInfo() &&
9259 S.Context.getAuxTargetInfo()->hasInt128Type()))
9260 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9261 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9262 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9263 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9264 if (S.Context.getTargetInfo().hasInt128Type() ||
9265 (S.Context.getAuxTargetInfo() &&
9266 S.Context.getAuxTargetInfo()->hasInt128Type()))
9267 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9268
9269 /// We add candidates for the unique, unqualified _BitInt types present in
9270 /// the candidate type set. The candidate set already handled ensuring the
9271 /// type is unqualified and canonical, but because we're adding from N
9272 /// different sets, we need to do some extra work to unique things. Insert
9273 /// the candidates into a unique set, then move from that set into the list
9274 /// of arithmetic types.
9275 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9276 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9277 for (QualType BitTy : Candidate.bitint_types())
9278 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9279 }
9280 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9281 LastPromotedIntegralType = ArithmeticTypes.size();
9282 LastPromotedArithmeticType = ArithmeticTypes.size();
9283 // End of promoted types.
9284
9285 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9286 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9287 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9288 if (S.Context.getLangOpts().Char8)
9289 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9290 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9291 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9292 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9293 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9294 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9295 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9296 LastIntegralType = ArithmeticTypes.size();
9297 NumArithmeticTypes = ArithmeticTypes.size();
9298 // End of integral types.
9299 // FIXME: What about complex? What about half?
9300
9301 // We don't know for sure how many bit-precise candidates were involved, so
9302 // we subtract those from the total when testing whether we're under the
9303 // cap or not.
9304 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9305 ArithmeticTypesCap &&
9306 "Enough inline storage for all arithmetic types.");
9307 }
9308
9309 /// Helper method to factor out the common pattern of adding overloads
9310 /// for '++' and '--' builtin operators.
9311 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9312 bool HasVolatile,
9313 bool HasRestrict) {
9314 QualType ParamTypes[2] = {
9315 S.Context.getLValueReferenceType(T: CandidateTy),
9316 S.Context.IntTy
9317 };
9318
9319 // Non-volatile version.
9320 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9321
9322 // Use a heuristic to reduce number of builtin candidates in the set:
9323 // add volatile version only if there are conversions to a volatile type.
9324 if (HasVolatile) {
9325 ParamTypes[0] =
9326 S.Context.getLValueReferenceType(
9327 T: S.Context.getVolatileType(T: CandidateTy));
9328 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9329 }
9330
9331 // Add restrict version only if there are conversions to a restrict type
9332 // and our candidate type is a non-restrict-qualified pointer.
9333 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9334 !CandidateTy.isRestrictQualified()) {
9335 ParamTypes[0]
9336 = S.Context.getLValueReferenceType(
9337 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9338 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9339
9340 if (HasVolatile) {
9341 ParamTypes[0]
9342 = S.Context.getLValueReferenceType(
9343 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9344 CVR: (Qualifiers::Volatile |
9345 Qualifiers::Restrict)));
9346 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9347 }
9348 }
9349
9350 }
9351
9352 /// Helper to add an overload candidate for a binary builtin with types \p L
9353 /// and \p R.
9354 void AddCandidate(QualType L, QualType R) {
9355 QualType LandR[2] = {L, R};
9356 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9357 }
9358
9359public:
9360 BuiltinOperatorOverloadBuilder(
9361 Sema &S, ArrayRef<Expr *> Args,
9362 QualifiersAndAtomic VisibleTypeConversionsQuals,
9363 bool HasArithmeticOrEnumeralCandidateType,
9364 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9365 OverloadCandidateSet &CandidateSet)
9366 : S(S), Args(Args),
9367 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9368 HasArithmeticOrEnumeralCandidateType(
9369 HasArithmeticOrEnumeralCandidateType),
9370 CandidateTypes(CandidateTypes),
9371 CandidateSet(CandidateSet) {
9372
9373 InitArithmeticTypes();
9374 }
9375
9376 // Increment is deprecated for bool since C++17.
9377 //
9378 // C++ [over.built]p3:
9379 //
9380 // For every pair (T, VQ), where T is an arithmetic type other
9381 // than bool, and VQ is either volatile or empty, there exist
9382 // candidate operator functions of the form
9383 //
9384 // VQ T& operator++(VQ T&);
9385 // T operator++(VQ T&, int);
9386 //
9387 // C++ [over.built]p4:
9388 //
9389 // For every pair (T, VQ), where T is an arithmetic type other
9390 // than bool, and VQ is either volatile or empty, there exist
9391 // candidate operator functions of the form
9392 //
9393 // VQ T& operator--(VQ T&);
9394 // T operator--(VQ T&, int);
9395 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9396 if (!HasArithmeticOrEnumeralCandidateType)
9397 return;
9398
9399 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9400 const auto TypeOfT = ArithmeticTypes[Arith];
9401 if (TypeOfT == S.Context.BoolTy) {
9402 if (Op == OO_MinusMinus)
9403 continue;
9404 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9405 continue;
9406 }
9407 addPlusPlusMinusMinusStyleOverloads(
9408 CandidateTy: TypeOfT,
9409 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9410 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9411 }
9412 }
9413
9414 // C++ [over.built]p5:
9415 //
9416 // For every pair (T, VQ), where T is a cv-qualified or
9417 // cv-unqualified object type, and VQ is either volatile or
9418 // empty, there exist candidate operator functions of the form
9419 //
9420 // T*VQ& operator++(T*VQ&);
9421 // T*VQ& operator--(T*VQ&);
9422 // T* operator++(T*VQ&, int);
9423 // T* operator--(T*VQ&, int);
9424 void addPlusPlusMinusMinusPointerOverloads() {
9425 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9426 // Skip pointer types that aren't pointers to object types.
9427 if (!PtrTy->getPointeeType()->isObjectType())
9428 continue;
9429
9430 addPlusPlusMinusMinusStyleOverloads(
9431 CandidateTy: PtrTy,
9432 HasVolatile: (!PtrTy.isVolatileQualified() &&
9433 VisibleTypeConversionsQuals.hasVolatile()),
9434 HasRestrict: (!PtrTy.isRestrictQualified() &&
9435 VisibleTypeConversionsQuals.hasRestrict()));
9436 }
9437 }
9438
9439 // C++ [over.built]p6:
9440 // For every cv-qualified or cv-unqualified object type T, there
9441 // exist candidate operator functions of the form
9442 //
9443 // T& operator*(T*);
9444 //
9445 // C++ [over.built]p7:
9446 // For every function type T that does not have cv-qualifiers or a
9447 // ref-qualifier, there exist candidate operator functions of the form
9448 // T& operator*(T*);
9449 void addUnaryStarPointerOverloads() {
9450 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9451 QualType PointeeTy = ParamTy->getPointeeType();
9452 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9453 continue;
9454
9455 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9456 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9457 continue;
9458
9459 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9460 }
9461 }
9462
9463 // C++ [over.built]p9:
9464 // For every promoted arithmetic type T, there exist candidate
9465 // operator functions of the form
9466 //
9467 // T operator+(T);
9468 // T operator-(T);
9469 void addUnaryPlusOrMinusArithmeticOverloads() {
9470 if (!HasArithmeticOrEnumeralCandidateType)
9471 return;
9472
9473 for (unsigned Arith = FirstPromotedArithmeticType;
9474 Arith < LastPromotedArithmeticType; ++Arith) {
9475 QualType ArithTy = ArithmeticTypes[Arith];
9476 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9477 }
9478
9479 // Extension: We also add these operators for vector types.
9480 for (QualType VecTy : CandidateTypes[0].vector_types())
9481 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9482 }
9483
9484 // C++ [over.built]p8:
9485 // For every type T, there exist candidate operator functions of
9486 // the form
9487 //
9488 // T* operator+(T*);
9489 void addUnaryPlusPointerOverloads() {
9490 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9491 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9492 }
9493
9494 // C++ [over.built]p10:
9495 // For every promoted integral type T, there exist candidate
9496 // operator functions of the form
9497 //
9498 // T operator~(T);
9499 void addUnaryTildePromotedIntegralOverloads() {
9500 if (!HasArithmeticOrEnumeralCandidateType)
9501 return;
9502
9503 for (unsigned Int = FirstPromotedIntegralType;
9504 Int < LastPromotedIntegralType; ++Int) {
9505 QualType IntTy = ArithmeticTypes[Int];
9506 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9507 }
9508
9509 // Extension: We also add this operator for vector types.
9510 for (QualType VecTy : CandidateTypes[0].vector_types())
9511 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9512 }
9513
9514 // C++ [over.match.oper]p16:
9515 // For every pointer to member type T or type std::nullptr_t, there
9516 // exist candidate operator functions of the form
9517 //
9518 // bool operator==(T,T);
9519 // bool operator!=(T,T);
9520 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9521 /// Set of (canonical) types that we've already handled.
9522 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9523
9524 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9525 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9526 // Don't add the same builtin candidate twice.
9527 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9528 continue;
9529
9530 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9531 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9532 }
9533
9534 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9535 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9536 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9537 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9538 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9539 }
9540 }
9541 }
9542 }
9543
9544 // C++ [over.built]p15:
9545 //
9546 // For every T, where T is an enumeration type or a pointer type,
9547 // there exist candidate operator functions of the form
9548 //
9549 // bool operator<(T, T);
9550 // bool operator>(T, T);
9551 // bool operator<=(T, T);
9552 // bool operator>=(T, T);
9553 // bool operator==(T, T);
9554 // bool operator!=(T, T);
9555 // R operator<=>(T, T)
9556 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9557 // C++ [over.match.oper]p3:
9558 // [...]the built-in candidates include all of the candidate operator
9559 // functions defined in 13.6 that, compared to the given operator, [...]
9560 // do not have the same parameter-type-list as any non-template non-member
9561 // candidate.
9562 //
9563 // Note that in practice, this only affects enumeration types because there
9564 // aren't any built-in candidates of record type, and a user-defined operator
9565 // must have an operand of record or enumeration type. Also, the only other
9566 // overloaded operator with enumeration arguments, operator=,
9567 // cannot be overloaded for enumeration types, so this is the only place
9568 // where we must suppress candidates like this.
9569 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9570 UserDefinedBinaryOperators;
9571
9572 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9573 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9574 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9575 CEnd = CandidateSet.end();
9576 C != CEnd; ++C) {
9577 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9578 continue;
9579
9580 if (C->Function->isFunctionTemplateSpecialization())
9581 continue;
9582
9583 // We interpret "same parameter-type-list" as applying to the
9584 // "synthesized candidate, with the order of the two parameters
9585 // reversed", not to the original function.
9586 bool Reversed = C->isReversed();
9587 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9588 ->getType()
9589 .getUnqualifiedType();
9590 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9591 ->getType()
9592 .getUnqualifiedType();
9593
9594 // Skip if either parameter isn't of enumeral type.
9595 if (!FirstParamType->isEnumeralType() ||
9596 !SecondParamType->isEnumeralType())
9597 continue;
9598
9599 // Add this operator to the set of known user-defined operators.
9600 UserDefinedBinaryOperators.insert(
9601 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9602 y: S.Context.getCanonicalType(T: SecondParamType)));
9603 }
9604 }
9605 }
9606
9607 /// Set of (canonical) types that we've already handled.
9608 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9609
9610 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9611 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9612 // Don't add the same builtin candidate twice.
9613 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9614 continue;
9615 if (IsSpaceship && PtrTy->isFunctionPointerType())
9616 continue;
9617
9618 QualType ParamTypes[2] = {PtrTy, PtrTy};
9619 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9620 }
9621 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9622 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9623
9624 // Don't add the same builtin candidate twice, or if a user defined
9625 // candidate exists.
9626 if (!AddedTypes.insert(Ptr: CanonType).second ||
9627 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9628 y&: CanonType)))
9629 continue;
9630 QualType ParamTypes[2] = {EnumTy, EnumTy};
9631 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9632 }
9633 }
9634 }
9635
9636 // C++ [over.built]p13:
9637 //
9638 // For every cv-qualified or cv-unqualified object type T
9639 // there exist candidate operator functions of the form
9640 //
9641 // T* operator+(T*, ptrdiff_t);
9642 // T& operator[](T*, ptrdiff_t); [BELOW]
9643 // T* operator-(T*, ptrdiff_t);
9644 // T* operator+(ptrdiff_t, T*);
9645 // T& operator[](ptrdiff_t, T*); [BELOW]
9646 //
9647 // C++ [over.built]p14:
9648 //
9649 // For every T, where T is a pointer to object type, there
9650 // exist candidate operator functions of the form
9651 //
9652 // ptrdiff_t operator-(T, T);
9653 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9654 /// Set of (canonical) types that we've already handled.
9655 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9656
9657 for (int Arg = 0; Arg < 2; ++Arg) {
9658 QualType AsymmetricParamTypes[2] = {
9659 S.Context.getPointerDiffType(),
9660 S.Context.getPointerDiffType(),
9661 };
9662 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9663 QualType PointeeTy = PtrTy->getPointeeType();
9664 if (!PointeeTy->isObjectType())
9665 continue;
9666
9667 AsymmetricParamTypes[Arg] = PtrTy;
9668 if (Arg == 0 || Op == OO_Plus) {
9669 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9670 // T* operator+(ptrdiff_t, T*);
9671 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9672 }
9673 if (Op == OO_Minus) {
9674 // ptrdiff_t operator-(T, T);
9675 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9676 continue;
9677
9678 QualType ParamTypes[2] = {PtrTy, PtrTy};
9679 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9680 }
9681 }
9682 }
9683 }
9684
9685 // C++ [over.built]p12:
9686 //
9687 // For every pair of promoted arithmetic types L and R, there
9688 // exist candidate operator functions of the form
9689 //
9690 // LR operator*(L, R);
9691 // LR operator/(L, R);
9692 // LR operator+(L, R);
9693 // LR operator-(L, R);
9694 // bool operator<(L, R);
9695 // bool operator>(L, R);
9696 // bool operator<=(L, R);
9697 // bool operator>=(L, R);
9698 // bool operator==(L, R);
9699 // bool operator!=(L, R);
9700 //
9701 // where LR is the result of the usual arithmetic conversions
9702 // between types L and R.
9703 //
9704 // C++ [over.built]p24:
9705 //
9706 // For every pair of promoted arithmetic types L and R, there exist
9707 // candidate operator functions of the form
9708 //
9709 // LR operator?(bool, L, R);
9710 //
9711 // where LR is the result of the usual arithmetic conversions
9712 // between types L and R.
9713 // Our candidates ignore the first parameter.
9714 void addGenericBinaryArithmeticOverloads() {
9715 if (!HasArithmeticOrEnumeralCandidateType)
9716 return;
9717
9718 for (unsigned Left = FirstPromotedArithmeticType;
9719 Left < LastPromotedArithmeticType; ++Left) {
9720 for (unsigned Right = FirstPromotedArithmeticType;
9721 Right < LastPromotedArithmeticType; ++Right) {
9722 QualType LandR[2] = { ArithmeticTypes[Left],
9723 ArithmeticTypes[Right] };
9724 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9725 }
9726 }
9727
9728 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9729 // conditional operator for vector types.
9730 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9731 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9732 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9733 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9734 }
9735 }
9736
9737 /// Add binary operator overloads for each candidate matrix type M1, M2:
9738 /// * (M1, M1) -> M1
9739 /// * (M1, M1.getElementType()) -> M1
9740 /// * (M2.getElementType(), M2) -> M2
9741 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9742 void addMatrixBinaryArithmeticOverloads() {
9743 if (!HasArithmeticOrEnumeralCandidateType)
9744 return;
9745
9746 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9747 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9748 AddCandidate(L: M1, R: M1);
9749 }
9750
9751 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9752 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9753 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9754 AddCandidate(L: M2, R: M2);
9755 }
9756 }
9757
9758 // C++2a [over.built]p14:
9759 //
9760 // For every integral type T there exists a candidate operator function
9761 // of the form
9762 //
9763 // std::strong_ordering operator<=>(T, T)
9764 //
9765 // C++2a [over.built]p15:
9766 //
9767 // For every pair of floating-point types L and R, there exists a candidate
9768 // operator function of the form
9769 //
9770 // std::partial_ordering operator<=>(L, R);
9771 //
9772 // FIXME: The current specification for integral types doesn't play nice with
9773 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9774 // comparisons. Under the current spec this can lead to ambiguity during
9775 // overload resolution. For example:
9776 //
9777 // enum A : int {a};
9778 // auto x = (a <=> (long)42);
9779 //
9780 // error: call is ambiguous for arguments 'A' and 'long'.
9781 // note: candidate operator<=>(int, int)
9782 // note: candidate operator<=>(long, long)
9783 //
9784 // To avoid this error, this function deviates from the specification and adds
9785 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9786 // arithmetic types (the same as the generic relational overloads).
9787 //
9788 // For now this function acts as a placeholder.
9789 void addThreeWayArithmeticOverloads() {
9790 addGenericBinaryArithmeticOverloads();
9791 }
9792
9793 // C++ [over.built]p17:
9794 //
9795 // For every pair of promoted integral types L and R, there
9796 // exist candidate operator functions of the form
9797 //
9798 // LR operator%(L, R);
9799 // LR operator&(L, R);
9800 // LR operator^(L, R);
9801 // LR operator|(L, R);
9802 // L operator<<(L, R);
9803 // L operator>>(L, R);
9804 //
9805 // where LR is the result of the usual arithmetic conversions
9806 // between types L and R.
9807 void addBinaryBitwiseArithmeticOverloads() {
9808 if (!HasArithmeticOrEnumeralCandidateType)
9809 return;
9810
9811 for (unsigned Left = FirstPromotedIntegralType;
9812 Left < LastPromotedIntegralType; ++Left) {
9813 for (unsigned Right = FirstPromotedIntegralType;
9814 Right < LastPromotedIntegralType; ++Right) {
9815 QualType LandR[2] = { ArithmeticTypes[Left],
9816 ArithmeticTypes[Right] };
9817 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9818 }
9819 }
9820 }
9821
9822 // C++ [over.built]p20:
9823 //
9824 // For every pair (T, VQ), where T is an enumeration or
9825 // pointer to member type and VQ is either volatile or
9826 // empty, there exist candidate operator functions of the form
9827 //
9828 // VQ T& operator=(VQ T&, T);
9829 void addAssignmentMemberPointerOrEnumeralOverloads() {
9830 /// Set of (canonical) types that we've already handled.
9831 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9832
9833 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9834 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9835 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9836 continue;
9837
9838 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
9839 }
9840
9841 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9842 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9843 continue;
9844
9845 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
9846 }
9847 }
9848 }
9849
9850 // C++ [over.built]p19:
9851 //
9852 // For every pair (T, VQ), where T is any type and VQ is either
9853 // volatile or empty, there exist candidate operator functions
9854 // of the form
9855 //
9856 // T*VQ& operator=(T*VQ&, T*);
9857 //
9858 // C++ [over.built]p21:
9859 //
9860 // For every pair (T, VQ), where T is a cv-qualified or
9861 // cv-unqualified object type and VQ is either volatile or
9862 // empty, there exist candidate operator functions of the form
9863 //
9864 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9865 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9866 void addAssignmentPointerOverloads(bool isEqualOp) {
9867 /// Set of (canonical) types that we've already handled.
9868 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9869
9870 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9871 // If this is operator=, keep track of the builtin candidates we added.
9872 if (isEqualOp)
9873 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
9874 else if (!PtrTy->getPointeeType()->isObjectType())
9875 continue;
9876
9877 // non-volatile version
9878 QualType ParamTypes[2] = {
9879 S.Context.getLValueReferenceType(T: PtrTy),
9880 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9881 };
9882 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9883 /*IsAssignmentOperator=*/ isEqualOp);
9884
9885 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9886 VisibleTypeConversionsQuals.hasVolatile();
9887 if (NeedVolatile) {
9888 // volatile version
9889 ParamTypes[0] =
9890 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
9891 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9892 /*IsAssignmentOperator=*/isEqualOp);
9893 }
9894
9895 if (!PtrTy.isRestrictQualified() &&
9896 VisibleTypeConversionsQuals.hasRestrict()) {
9897 // restrict version
9898 ParamTypes[0] =
9899 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
9900 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9901 /*IsAssignmentOperator=*/isEqualOp);
9902
9903 if (NeedVolatile) {
9904 // volatile restrict version
9905 ParamTypes[0] =
9906 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9907 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9908 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9909 /*IsAssignmentOperator=*/isEqualOp);
9910 }
9911 }
9912 }
9913
9914 if (isEqualOp) {
9915 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9916 // Make sure we don't add the same candidate twice.
9917 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9918 continue;
9919
9920 QualType ParamTypes[2] = {
9921 S.Context.getLValueReferenceType(T: PtrTy),
9922 PtrTy,
9923 };
9924
9925 // non-volatile version
9926 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9927 /*IsAssignmentOperator=*/true);
9928
9929 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9930 VisibleTypeConversionsQuals.hasVolatile();
9931 if (NeedVolatile) {
9932 // volatile version
9933 ParamTypes[0] = S.Context.getLValueReferenceType(
9934 T: S.Context.getVolatileType(T: PtrTy));
9935 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9936 /*IsAssignmentOperator=*/true);
9937 }
9938
9939 if (!PtrTy.isRestrictQualified() &&
9940 VisibleTypeConversionsQuals.hasRestrict()) {
9941 // restrict version
9942 ParamTypes[0] = S.Context.getLValueReferenceType(
9943 T: S.Context.getRestrictType(T: PtrTy));
9944 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9945 /*IsAssignmentOperator=*/true);
9946
9947 if (NeedVolatile) {
9948 // volatile restrict version
9949 ParamTypes[0] =
9950 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9951 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9952 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9953 /*IsAssignmentOperator=*/true);
9954 }
9955 }
9956 }
9957 }
9958 }
9959
9960 // C++ [over.built]p18:
9961 //
9962 // For every triple (L, VQ, R), where L is an arithmetic type,
9963 // VQ is either volatile or empty, and R is a promoted
9964 // arithmetic type, there exist candidate operator functions of
9965 // the form
9966 //
9967 // VQ L& operator=(VQ L&, R);
9968 // VQ L& operator*=(VQ L&, R);
9969 // VQ L& operator/=(VQ L&, R);
9970 // VQ L& operator+=(VQ L&, R);
9971 // VQ L& operator-=(VQ L&, R);
9972 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9973 if (!HasArithmeticOrEnumeralCandidateType)
9974 return;
9975
9976 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9977 for (unsigned Right = FirstPromotedArithmeticType;
9978 Right < LastPromotedArithmeticType; ++Right) {
9979 QualType ParamTypes[2];
9980 ParamTypes[1] = ArithmeticTypes[Right];
9981 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9982 S, T: ArithmeticTypes[Left], Arg: Args[0]);
9983
9984 forAllQualifierCombinations(
9985 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
9986 ParamTypes[0] =
9987 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
9988 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9989 /*IsAssignmentOperator=*/isEqualOp);
9990 });
9991 }
9992 }
9993
9994 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9995 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9996 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9997 QualType ParamTypes[2];
9998 ParamTypes[1] = Vec2Ty;
9999 // Add this built-in operator as a candidate (VQ is empty).
10000 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10001 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10002 /*IsAssignmentOperator=*/isEqualOp);
10003
10004 // Add this built-in operator as a candidate (VQ is 'volatile').
10005 if (VisibleTypeConversionsQuals.hasVolatile()) {
10006 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10007 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10008 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10009 /*IsAssignmentOperator=*/isEqualOp);
10010 }
10011 }
10012 }
10013
10014 // C++ [over.built]p22:
10015 //
10016 // For every triple (L, VQ, R), where L is an integral type, VQ
10017 // is either volatile or empty, and R is a promoted integral
10018 // type, there exist candidate operator functions of the form
10019 //
10020 // VQ L& operator%=(VQ L&, R);
10021 // VQ L& operator<<=(VQ L&, R);
10022 // VQ L& operator>>=(VQ L&, R);
10023 // VQ L& operator&=(VQ L&, R);
10024 // VQ L& operator^=(VQ L&, R);
10025 // VQ L& operator|=(VQ L&, R);
10026 void addAssignmentIntegralOverloads() {
10027 if (!HasArithmeticOrEnumeralCandidateType)
10028 return;
10029
10030 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10031 for (unsigned Right = FirstPromotedIntegralType;
10032 Right < LastPromotedIntegralType; ++Right) {
10033 QualType ParamTypes[2];
10034 ParamTypes[1] = ArithmeticTypes[Right];
10035 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10036 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10037
10038 forAllQualifierCombinations(
10039 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10040 ParamTypes[0] =
10041 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10042 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10043 });
10044 }
10045 }
10046 }
10047
10048 // C++ [over.operator]p23:
10049 //
10050 // There also exist candidate operator functions of the form
10051 //
10052 // bool operator!(bool);
10053 // bool operator&&(bool, bool);
10054 // bool operator||(bool, bool);
10055 void addExclaimOverload() {
10056 QualType ParamTy = S.Context.BoolTy;
10057 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10058 /*IsAssignmentOperator=*/false,
10059 /*NumContextualBoolArguments=*/1);
10060 }
10061 void addAmpAmpOrPipePipeOverload() {
10062 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10063 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10064 /*IsAssignmentOperator=*/false,
10065 /*NumContextualBoolArguments=*/2);
10066 }
10067
10068 // C++ [over.built]p13:
10069 //
10070 // For every cv-qualified or cv-unqualified object type T there
10071 // exist candidate operator functions of the form
10072 //
10073 // T* operator+(T*, ptrdiff_t); [ABOVE]
10074 // T& operator[](T*, ptrdiff_t);
10075 // T* operator-(T*, ptrdiff_t); [ABOVE]
10076 // T* operator+(ptrdiff_t, T*); [ABOVE]
10077 // T& operator[](ptrdiff_t, T*);
10078 void addSubscriptOverloads() {
10079 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10080 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10081 QualType PointeeType = PtrTy->getPointeeType();
10082 if (!PointeeType->isObjectType())
10083 continue;
10084
10085 // T& operator[](T*, ptrdiff_t)
10086 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10087 }
10088
10089 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10090 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10091 QualType PointeeType = PtrTy->getPointeeType();
10092 if (!PointeeType->isObjectType())
10093 continue;
10094
10095 // T& operator[](ptrdiff_t, T*)
10096 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10097 }
10098 }
10099
10100 // C++ [over.built]p11:
10101 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10102 // C1 is the same type as C2 or is a derived class of C2, T is an object
10103 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10104 // there exist candidate operator functions of the form
10105 //
10106 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10107 //
10108 // where CV12 is the union of CV1 and CV2.
10109 void addArrowStarOverloads() {
10110 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10111 QualType C1Ty = PtrTy;
10112 QualType C1;
10113 QualifierCollector Q1;
10114 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10115 if (!isa<RecordType>(Val: C1))
10116 continue;
10117 // heuristic to reduce number of builtin candidates in the set.
10118 // Add volatile/restrict version only if there are conversions to a
10119 // volatile/restrict type.
10120 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10121 continue;
10122 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10123 continue;
10124 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10125 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10126 CXXRecordDecl *D1 = C1->getAsCXXRecordDecl(),
10127 *D2 = mptr->getMostRecentCXXRecordDecl();
10128 if (!declaresSameEntity(D1, D2) &&
10129 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10130 break;
10131 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10132 // build CV12 T&
10133 QualType T = mptr->getPointeeType();
10134 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10135 T.isVolatileQualified())
10136 continue;
10137 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10138 T.isRestrictQualified())
10139 continue;
10140 T = Q1.apply(Context: S.Context, QT: T);
10141 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10142 }
10143 }
10144 }
10145
10146 // Note that we don't consider the first argument, since it has been
10147 // contextually converted to bool long ago. The candidates below are
10148 // therefore added as binary.
10149 //
10150 // C++ [over.built]p25:
10151 // For every type T, where T is a pointer, pointer-to-member, or scoped
10152 // enumeration type, there exist candidate operator functions of the form
10153 //
10154 // T operator?(bool, T, T);
10155 //
10156 void addConditionalOperatorOverloads() {
10157 /// Set of (canonical) types that we've already handled.
10158 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10159
10160 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10161 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10162 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10163 continue;
10164
10165 QualType ParamTypes[2] = {PtrTy, PtrTy};
10166 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10167 }
10168
10169 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10170 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10171 continue;
10172
10173 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10174 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10175 }
10176
10177 if (S.getLangOpts().CPlusPlus11) {
10178 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10179 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
10180 continue;
10181
10182 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10183 continue;
10184
10185 QualType ParamTypes[2] = {EnumTy, EnumTy};
10186 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10187 }
10188 }
10189 }
10190 }
10191};
10192
10193} // end anonymous namespace
10194
10195void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10196 SourceLocation OpLoc,
10197 ArrayRef<Expr *> Args,
10198 OverloadCandidateSet &CandidateSet) {
10199 // Find all of the types that the arguments can convert to, but only
10200 // if the operator we're looking at has built-in operator candidates
10201 // that make use of these types. Also record whether we encounter non-record
10202 // candidate types or either arithmetic or enumeral candidate types.
10203 QualifiersAndAtomic VisibleTypeConversionsQuals;
10204 VisibleTypeConversionsQuals.addConst();
10205 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10206 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10207 if (Args[ArgIdx]->getType()->isAtomicType())
10208 VisibleTypeConversionsQuals.addAtomic();
10209 }
10210
10211 bool HasNonRecordCandidateType = false;
10212 bool HasArithmeticOrEnumeralCandidateType = false;
10213 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10214 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10215 CandidateTypes.emplace_back(Args&: *this);
10216 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10217 Loc: OpLoc,
10218 AllowUserConversions: true,
10219 AllowExplicitConversions: (Op == OO_Exclaim ||
10220 Op == OO_AmpAmp ||
10221 Op == OO_PipePipe),
10222 VisibleQuals: VisibleTypeConversionsQuals);
10223 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10224 CandidateTypes[ArgIdx].hasNonRecordTypes();
10225 HasArithmeticOrEnumeralCandidateType =
10226 HasArithmeticOrEnumeralCandidateType ||
10227 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10228 }
10229
10230 // Exit early when no non-record types have been added to the candidate set
10231 // for any of the arguments to the operator.
10232 //
10233 // We can't exit early for !, ||, or &&, since there we have always have
10234 // 'bool' overloads.
10235 if (!HasNonRecordCandidateType &&
10236 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10237 return;
10238
10239 // Setup an object to manage the common state for building overloads.
10240 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10241 VisibleTypeConversionsQuals,
10242 HasArithmeticOrEnumeralCandidateType,
10243 CandidateTypes, CandidateSet);
10244
10245 // Dispatch over the operation to add in only those overloads which apply.
10246 switch (Op) {
10247 case OO_None:
10248 case NUM_OVERLOADED_OPERATORS:
10249 llvm_unreachable("Expected an overloaded operator");
10250
10251 case OO_New:
10252 case OO_Delete:
10253 case OO_Array_New:
10254 case OO_Array_Delete:
10255 case OO_Call:
10256 llvm_unreachable(
10257 "Special operators don't use AddBuiltinOperatorCandidates");
10258
10259 case OO_Comma:
10260 case OO_Arrow:
10261 case OO_Coawait:
10262 // C++ [over.match.oper]p3:
10263 // -- For the operator ',', the unary operator '&', the
10264 // operator '->', or the operator 'co_await', the
10265 // built-in candidates set is empty.
10266 break;
10267
10268 case OO_Plus: // '+' is either unary or binary
10269 if (Args.size() == 1)
10270 OpBuilder.addUnaryPlusPointerOverloads();
10271 [[fallthrough]];
10272
10273 case OO_Minus: // '-' is either unary or binary
10274 if (Args.size() == 1) {
10275 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10276 } else {
10277 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10278 OpBuilder.addGenericBinaryArithmeticOverloads();
10279 OpBuilder.addMatrixBinaryArithmeticOverloads();
10280 }
10281 break;
10282
10283 case OO_Star: // '*' is either unary or binary
10284 if (Args.size() == 1)
10285 OpBuilder.addUnaryStarPointerOverloads();
10286 else {
10287 OpBuilder.addGenericBinaryArithmeticOverloads();
10288 OpBuilder.addMatrixBinaryArithmeticOverloads();
10289 }
10290 break;
10291
10292 case OO_Slash:
10293 OpBuilder.addGenericBinaryArithmeticOverloads();
10294 break;
10295
10296 case OO_PlusPlus:
10297 case OO_MinusMinus:
10298 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10299 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10300 break;
10301
10302 case OO_EqualEqual:
10303 case OO_ExclaimEqual:
10304 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10305 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10306 OpBuilder.addGenericBinaryArithmeticOverloads();
10307 break;
10308
10309 case OO_Less:
10310 case OO_Greater:
10311 case OO_LessEqual:
10312 case OO_GreaterEqual:
10313 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10314 OpBuilder.addGenericBinaryArithmeticOverloads();
10315 break;
10316
10317 case OO_Spaceship:
10318 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10319 OpBuilder.addThreeWayArithmeticOverloads();
10320 break;
10321
10322 case OO_Percent:
10323 case OO_Caret:
10324 case OO_Pipe:
10325 case OO_LessLess:
10326 case OO_GreaterGreater:
10327 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10328 break;
10329
10330 case OO_Amp: // '&' is either unary or binary
10331 if (Args.size() == 1)
10332 // C++ [over.match.oper]p3:
10333 // -- For the operator ',', the unary operator '&', or the
10334 // operator '->', the built-in candidates set is empty.
10335 break;
10336
10337 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10338 break;
10339
10340 case OO_Tilde:
10341 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10342 break;
10343
10344 case OO_Equal:
10345 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10346 [[fallthrough]];
10347
10348 case OO_PlusEqual:
10349 case OO_MinusEqual:
10350 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10351 [[fallthrough]];
10352
10353 case OO_StarEqual:
10354 case OO_SlashEqual:
10355 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10356 break;
10357
10358 case OO_PercentEqual:
10359 case OO_LessLessEqual:
10360 case OO_GreaterGreaterEqual:
10361 case OO_AmpEqual:
10362 case OO_CaretEqual:
10363 case OO_PipeEqual:
10364 OpBuilder.addAssignmentIntegralOverloads();
10365 break;
10366
10367 case OO_Exclaim:
10368 OpBuilder.addExclaimOverload();
10369 break;
10370
10371 case OO_AmpAmp:
10372 case OO_PipePipe:
10373 OpBuilder.addAmpAmpOrPipePipeOverload();
10374 break;
10375
10376 case OO_Subscript:
10377 if (Args.size() == 2)
10378 OpBuilder.addSubscriptOverloads();
10379 break;
10380
10381 case OO_ArrowStar:
10382 OpBuilder.addArrowStarOverloads();
10383 break;
10384
10385 case OO_Conditional:
10386 OpBuilder.addConditionalOperatorOverloads();
10387 OpBuilder.addGenericBinaryArithmeticOverloads();
10388 break;
10389 }
10390}
10391
10392void
10393Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10394 SourceLocation Loc,
10395 ArrayRef<Expr *> Args,
10396 TemplateArgumentListInfo *ExplicitTemplateArgs,
10397 OverloadCandidateSet& CandidateSet,
10398 bool PartialOverloading) {
10399 ADLResult Fns;
10400
10401 // FIXME: This approach for uniquing ADL results (and removing
10402 // redundant candidates from the set) relies on pointer-equality,
10403 // which means we need to key off the canonical decl. However,
10404 // always going back to the canonical decl might not get us the
10405 // right set of default arguments. What default arguments are
10406 // we supposed to consider on ADL candidates, anyway?
10407
10408 // FIXME: Pass in the explicit template arguments?
10409 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10410
10411 ArrayRef<Expr *> ReversedArgs;
10412
10413 // Erase all of the candidates we already knew about.
10414 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10415 CandEnd = CandidateSet.end();
10416 Cand != CandEnd; ++Cand)
10417 if (Cand->Function) {
10418 FunctionDecl *Fn = Cand->Function;
10419 Fns.erase(D: Fn);
10420 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10421 Fns.erase(D: FunTmpl);
10422 }
10423
10424 // For each of the ADL candidates we found, add it to the overload
10425 // set.
10426 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10427 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10428
10429 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10430 if (ExplicitTemplateArgs)
10431 continue;
10432
10433 AddOverloadCandidate(
10434 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10435 PartialOverloading, /*AllowExplicit=*/true,
10436 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10437 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10438 AddOverloadCandidate(
10439 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10440 /*SuppressUserConversions=*/false, PartialOverloading,
10441 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10442 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10443 }
10444 } else {
10445 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10446 AddTemplateOverloadCandidate(
10447 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10448 /*SuppressUserConversions=*/false, PartialOverloading,
10449 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10450 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10451 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10452
10453 // As template candidates are not deduced immediately,
10454 // persist the array in the overload set.
10455 if (ReversedArgs.empty())
10456 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10457
10458 AddTemplateOverloadCandidate(
10459 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10460 /*SuppressUserConversions=*/false, PartialOverloading,
10461 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10462 PO: OverloadCandidateParamOrder::Reversed);
10463 }
10464 }
10465 }
10466}
10467
10468namespace {
10469enum class Comparison { Equal, Better, Worse };
10470}
10471
10472/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10473/// overload resolution.
10474///
10475/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10476/// Cand1's first N enable_if attributes have precisely the same conditions as
10477/// Cand2's first N enable_if attributes (where N = the number of enable_if
10478/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10479///
10480/// Note that you can have a pair of candidates such that Cand1's enable_if
10481/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10482/// worse than Cand1's.
10483static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10484 const FunctionDecl *Cand2) {
10485 // Common case: One (or both) decls don't have enable_if attrs.
10486 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10487 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10488 if (!Cand1Attr || !Cand2Attr) {
10489 if (Cand1Attr == Cand2Attr)
10490 return Comparison::Equal;
10491 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10492 }
10493
10494 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10495 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10496
10497 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10498 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10499 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10500 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10501
10502 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10503 // has fewer enable_if attributes than Cand2, and vice versa.
10504 if (!Cand1A)
10505 return Comparison::Worse;
10506 if (!Cand2A)
10507 return Comparison::Better;
10508
10509 Cand1ID.clear();
10510 Cand2ID.clear();
10511
10512 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10513 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10514 if (Cand1ID != Cand2ID)
10515 return Comparison::Worse;
10516 }
10517
10518 return Comparison::Equal;
10519}
10520
10521static Comparison
10522isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10523 const OverloadCandidate &Cand2) {
10524 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10525 !Cand2.Function->isMultiVersion())
10526 return Comparison::Equal;
10527
10528 // If both are invalid, they are equal. If one of them is invalid, the other
10529 // is better.
10530 if (Cand1.Function->isInvalidDecl()) {
10531 if (Cand2.Function->isInvalidDecl())
10532 return Comparison::Equal;
10533 return Comparison::Worse;
10534 }
10535 if (Cand2.Function->isInvalidDecl())
10536 return Comparison::Better;
10537
10538 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10539 // cpu_dispatch, else arbitrarily based on the identifiers.
10540 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10541 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10542 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10543 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10544
10545 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10546 return Comparison::Equal;
10547
10548 if (Cand1CPUDisp && !Cand2CPUDisp)
10549 return Comparison::Better;
10550 if (Cand2CPUDisp && !Cand1CPUDisp)
10551 return Comparison::Worse;
10552
10553 if (Cand1CPUSpec && Cand2CPUSpec) {
10554 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10555 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10556 ? Comparison::Better
10557 : Comparison::Worse;
10558
10559 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10560 FirstDiff = std::mismatch(
10561 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10562 first2: Cand2CPUSpec->cpus_begin(),
10563 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10564 return LHS->getName() == RHS->getName();
10565 });
10566
10567 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10568 "Two different cpu-specific versions should not have the same "
10569 "identifier list, otherwise they'd be the same decl!");
10570 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10571 ? Comparison::Better
10572 : Comparison::Worse;
10573 }
10574 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10575}
10576
10577/// Compute the type of the implicit object parameter for the given function,
10578/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10579/// null QualType if there is a 'matches anything' implicit object parameter.
10580static std::optional<QualType>
10581getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10582 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10583 return std::nullopt;
10584
10585 auto *M = cast<CXXMethodDecl>(Val: F);
10586 // Static member functions' object parameters match all types.
10587 if (M->isStatic())
10588 return QualType();
10589 return M->getFunctionObjectParameterReferenceType();
10590}
10591
10592// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10593// represent the same entity.
10594static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10595 const FunctionDecl *F2) {
10596 if (declaresSameEntity(D1: F1, D2: F2))
10597 return true;
10598 auto PT1 = F1->getPrimaryTemplate();
10599 auto PT2 = F2->getPrimaryTemplate();
10600 if (PT1 && PT2) {
10601 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10602 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10603 D2: PT2->getInstantiatedFromMemberTemplate()))
10604 return true;
10605 }
10606 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10607 // different functions with same params). Consider removing this (as no test
10608 // fail w/o it).
10609 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10610 if (First) {
10611 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10612 return *T;
10613 }
10614 assert(I < F->getNumParams());
10615 return F->getParamDecl(i: I++)->getType();
10616 };
10617
10618 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10619 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10620
10621 if (F1NumParams != F2NumParams)
10622 return false;
10623
10624 unsigned I1 = 0, I2 = 0;
10625 for (unsigned I = 0; I != F1NumParams; ++I) {
10626 QualType T1 = NextParam(F1, I1, I == 0);
10627 QualType T2 = NextParam(F2, I2, I == 0);
10628 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10629 if (!Context.hasSameUnqualifiedType(T1, T2))
10630 return false;
10631 }
10632 return true;
10633}
10634
10635/// We're allowed to use constraints partial ordering only if the candidates
10636/// have the same parameter types:
10637/// [over.match.best.general]p2.6
10638/// F1 and F2 are non-template functions with the same
10639/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10640static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10641 FunctionDecl *Fn2,
10642 bool IsFn1Reversed,
10643 bool IsFn2Reversed) {
10644 assert(Fn1 && Fn2);
10645 if (Fn1->isVariadic() != Fn2->isVariadic())
10646 return false;
10647
10648 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10649 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10650 return false;
10651
10652 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10653 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10654 if (Mem1 && Mem2) {
10655 // if they are member functions, both are direct members of the same class,
10656 // and
10657 if (Mem1->getParent() != Mem2->getParent())
10658 return false;
10659 // if both are non-static member functions, they have the same types for
10660 // their object parameters
10661 if (Mem1->isInstance() && Mem2->isInstance() &&
10662 !S.getASTContext().hasSameType(
10663 T1: Mem1->getFunctionObjectParameterReferenceType(),
10664 T2: Mem1->getFunctionObjectParameterReferenceType()))
10665 return false;
10666 }
10667 return true;
10668}
10669
10670static FunctionDecl *
10671getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10672 bool IsFn1Reversed, bool IsFn2Reversed) {
10673 if (!Fn1 || !Fn2)
10674 return nullptr;
10675
10676 // C++ [temp.constr.order]:
10677 // A non-template function F1 is more partial-ordering-constrained than a
10678 // non-template function F2 if:
10679 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10680 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10681
10682 if (Cand1IsSpecialization || Cand2IsSpecialization)
10683 return nullptr;
10684
10685 // - they have the same non-object-parameter-type-lists, and [...]
10686 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10687 IsFn2Reversed))
10688 return nullptr;
10689
10690 // - the declaration of F1 is more constrained than the declaration of F2.
10691 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10692}
10693
10694/// isBetterOverloadCandidate - Determines whether the first overload
10695/// candidate is a better candidate than the second (C++ 13.3.3p1).
10696bool clang::isBetterOverloadCandidate(
10697 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10698 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10699 bool PartialOverloading) {
10700 // Define viable functions to be better candidates than non-viable
10701 // functions.
10702 if (!Cand2.Viable)
10703 return Cand1.Viable;
10704 else if (!Cand1.Viable)
10705 return false;
10706
10707 // [CUDA] A function with 'never' preference is marked not viable, therefore
10708 // is never shown up here. The worst preference shown up here is 'wrong side',
10709 // e.g. an H function called by a HD function in device compilation. This is
10710 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10711 // function which is called only by an H function. A deferred diagnostic will
10712 // be triggered if it is emitted. However a wrong-sided function is still
10713 // a viable candidate here.
10714 //
10715 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10716 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10717 // can be emitted, Cand1 is not better than Cand2. This rule should have
10718 // precedence over other rules.
10719 //
10720 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10721 // other rules should be used to determine which is better. This is because
10722 // host/device based overloading resolution is mostly for determining
10723 // viability of a function. If two functions are both viable, other factors
10724 // should take precedence in preference, e.g. the standard-defined preferences
10725 // like argument conversion ranks or enable_if partial-ordering. The
10726 // preference for pass-object-size parameters is probably most similar to a
10727 // type-based-overloading decision and so should take priority.
10728 //
10729 // If other rules cannot determine which is better, CUDA preference will be
10730 // used again to determine which is better.
10731 //
10732 // TODO: Currently IdentifyPreference does not return correct values
10733 // for functions called in global variable initializers due to missing
10734 // correct context about device/host. Therefore we can only enforce this
10735 // rule when there is a caller. We should enforce this rule for functions
10736 // in global variable initializers once proper context is added.
10737 //
10738 // TODO: We can only enable the hostness based overloading resolution when
10739 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10740 // overloading resolution diagnostics.
10741 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10742 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10743 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10744 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10745 bool IsCand1ImplicitHD =
10746 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10747 bool IsCand2ImplicitHD =
10748 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10749 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10750 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10751 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10752 // The implicit HD function may be a function in a system header which
10753 // is forced by pragma. In device compilation, if we prefer HD candidates
10754 // over wrong-sided candidates, overloading resolution may change, which
10755 // may result in non-deferrable diagnostics. As a workaround, we let
10756 // implicit HD candidates take equal preference as wrong-sided candidates.
10757 // This will preserve the overloading resolution.
10758 // TODO: We still need special handling of implicit HD functions since
10759 // they may incur other diagnostics to be deferred. We should make all
10760 // host/device related diagnostics deferrable and remove special handling
10761 // of implicit HD functions.
10762 auto EmitThreshold =
10763 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10764 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10765 ? SemaCUDA::CFP_Never
10766 : SemaCUDA::CFP_WrongSide;
10767 auto Cand1Emittable = P1 > EmitThreshold;
10768 auto Cand2Emittable = P2 > EmitThreshold;
10769 if (Cand1Emittable && !Cand2Emittable)
10770 return true;
10771 if (!Cand1Emittable && Cand2Emittable)
10772 return false;
10773 }
10774 }
10775
10776 // C++ [over.match.best]p1: (Changed in C++23)
10777 //
10778 // -- if F is a static member function, ICS1(F) is defined such
10779 // that ICS1(F) is neither better nor worse than ICS1(G) for
10780 // any function G, and, symmetrically, ICS1(G) is neither
10781 // better nor worse than ICS1(F).
10782 unsigned StartArg = 0;
10783 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10784 StartArg = 1;
10785
10786 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10787 // We don't allow incompatible pointer conversions in C++.
10788 if (!S.getLangOpts().CPlusPlus)
10789 return ICS.isStandard() &&
10790 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10791
10792 // The only ill-formed conversion we allow in C++ is the string literal to
10793 // char* conversion, which is only considered ill-formed after C++11.
10794 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10795 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10796 };
10797
10798 // Define functions that don't require ill-formed conversions for a given
10799 // argument to be better candidates than functions that do.
10800 unsigned NumArgs = Cand1.Conversions.size();
10801 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10802 bool HasBetterConversion = false;
10803 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10804 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10805 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10806 if (Cand1Bad != Cand2Bad) {
10807 if (Cand1Bad)
10808 return false;
10809 HasBetterConversion = true;
10810 }
10811 }
10812
10813 if (HasBetterConversion)
10814 return true;
10815
10816 // C++ [over.match.best]p1:
10817 // A viable function F1 is defined to be a better function than another
10818 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10819 // conversion sequence than ICSi(F2), and then...
10820 bool HasWorseConversion = false;
10821 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10822 switch (CompareImplicitConversionSequences(S, Loc,
10823 ICS1: Cand1.Conversions[ArgIdx],
10824 ICS2: Cand2.Conversions[ArgIdx])) {
10825 case ImplicitConversionSequence::Better:
10826 // Cand1 has a better conversion sequence.
10827 HasBetterConversion = true;
10828 break;
10829
10830 case ImplicitConversionSequence::Worse:
10831 if (Cand1.Function && Cand2.Function &&
10832 Cand1.isReversed() != Cand2.isReversed() &&
10833 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
10834 // Work around large-scale breakage caused by considering reversed
10835 // forms of operator== in C++20:
10836 //
10837 // When comparing a function against a reversed function, if we have a
10838 // better conversion for one argument and a worse conversion for the
10839 // other, the implicit conversion sequences are treated as being equally
10840 // good.
10841 //
10842 // This prevents a comparison function from being considered ambiguous
10843 // with a reversed form that is written in the same way.
10844 //
10845 // We diagnose this as an extension from CreateOverloadedBinOp.
10846 HasWorseConversion = true;
10847 break;
10848 }
10849
10850 // Cand1 can't be better than Cand2.
10851 return false;
10852
10853 case ImplicitConversionSequence::Indistinguishable:
10854 // Do nothing.
10855 break;
10856 }
10857 }
10858
10859 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10860 // ICSj(F2), or, if not that,
10861 if (HasBetterConversion && !HasWorseConversion)
10862 return true;
10863
10864 // -- the context is an initialization by user-defined conversion
10865 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10866 // from the return type of F1 to the destination type (i.e.,
10867 // the type of the entity being initialized) is a better
10868 // conversion sequence than the standard conversion sequence
10869 // from the return type of F2 to the destination type.
10870 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10871 Cand1.Function && Cand2.Function &&
10872 isa<CXXConversionDecl>(Val: Cand1.Function) &&
10873 isa<CXXConversionDecl>(Val: Cand2.Function)) {
10874
10875 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10876 // First check whether we prefer one of the conversion functions over the
10877 // other. This only distinguishes the results in non-standard, extension
10878 // cases such as the conversion from a lambda closure type to a function
10879 // pointer or block.
10880 ImplicitConversionSequence::CompareKind Result =
10881 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
10882 if (Result == ImplicitConversionSequence::Indistinguishable)
10883 Result = CompareStandardConversionSequences(S, Loc,
10884 SCS1: Cand1.FinalConversion,
10885 SCS2: Cand2.FinalConversion);
10886
10887 if (Result != ImplicitConversionSequence::Indistinguishable)
10888 return Result == ImplicitConversionSequence::Better;
10889
10890 // FIXME: Compare kind of reference binding if conversion functions
10891 // convert to a reference type used in direct reference binding, per
10892 // C++14 [over.match.best]p1 section 2 bullet 3.
10893 }
10894
10895 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10896 // as combined with the resolution to CWG issue 243.
10897 //
10898 // When the context is initialization by constructor ([over.match.ctor] or
10899 // either phase of [over.match.list]), a constructor is preferred over
10900 // a conversion function.
10901 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10902 Cand1.Function && Cand2.Function &&
10903 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
10904 isa<CXXConstructorDecl>(Val: Cand2.Function))
10905 return isa<CXXConstructorDecl>(Val: Cand1.Function);
10906
10907 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10908 return Cand2.StrictPackMatch;
10909
10910 // -- F1 is a non-template function and F2 is a function template
10911 // specialization, or, if not that,
10912 bool Cand1IsSpecialization = Cand1.Function &&
10913 Cand1.Function->getPrimaryTemplate();
10914 bool Cand2IsSpecialization = Cand2.Function &&
10915 Cand2.Function->getPrimaryTemplate();
10916 if (Cand1IsSpecialization != Cand2IsSpecialization)
10917 return Cand2IsSpecialization;
10918
10919 // -- F1 and F2 are function template specializations, and the function
10920 // template for F1 is more specialized than the template for F2
10921 // according to the partial ordering rules described in 14.5.5.2, or,
10922 // if not that,
10923 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10924 const auto *Obj1Context =
10925 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
10926 const auto *Obj2Context =
10927 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
10928 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10929 FT1: Cand1.Function->getPrimaryTemplate(),
10930 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
10931 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
10932 : TPOC_Call,
10933 NumCallArguments1: Cand1.ExplicitCallArguments,
10934 RawObj1Ty: Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10935 : QualType{},
10936 RawObj2Ty: Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10937 : QualType{},
10938 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10939 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10940 }
10941 }
10942
10943 // -— F1 and F2 are non-template functions and F1 is more
10944 // partial-ordering-constrained than F2 [...],
10945 if (FunctionDecl *F = getMorePartialOrderingConstrained(
10946 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
10947 IsFn2Reversed: Cand2.isReversed());
10948 F && F == Cand1.Function)
10949 return true;
10950
10951 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10952 // class B of D, and for all arguments the corresponding parameters of
10953 // F1 and F2 have the same type.
10954 // FIXME: Implement the "all parameters have the same type" check.
10955 bool Cand1IsInherited =
10956 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
10957 bool Cand2IsInherited =
10958 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
10959 if (Cand1IsInherited != Cand2IsInherited)
10960 return Cand2IsInherited;
10961 else if (Cand1IsInherited) {
10962 assert(Cand2IsInherited);
10963 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
10964 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
10965 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
10966 return true;
10967 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
10968 return false;
10969 // Inherited from sibling base classes: still ambiguous.
10970 }
10971
10972 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10973 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10974 // with reversed order of parameters and F1 is not
10975 //
10976 // We rank reversed + different operator as worse than just reversed, but
10977 // that comparison can never happen, because we only consider reversing for
10978 // the maximally-rewritten operator (== or <=>).
10979 if (Cand1.RewriteKind != Cand2.RewriteKind)
10980 return Cand1.RewriteKind < Cand2.RewriteKind;
10981
10982 // Check C++17 tie-breakers for deduction guides.
10983 {
10984 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
10985 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
10986 if (Guide1 && Guide2) {
10987 // -- F1 is generated from a deduction-guide and F2 is not
10988 if (Guide1->isImplicit() != Guide2->isImplicit())
10989 return Guide2->isImplicit();
10990
10991 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10992 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10993 return true;
10994 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10995 return false;
10996
10997 // --F1 is generated from a non-template constructor and F2 is generated
10998 // from a constructor template
10999 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11000 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11001 if (Constructor1 && Constructor2) {
11002 bool isC1Templated = Constructor1->getTemplatedKind() !=
11003 FunctionDecl::TemplatedKind::TK_NonTemplate;
11004 bool isC2Templated = Constructor2->getTemplatedKind() !=
11005 FunctionDecl::TemplatedKind::TK_NonTemplate;
11006 if (isC1Templated != isC2Templated)
11007 return isC2Templated;
11008 }
11009 }
11010 }
11011
11012 // Check for enable_if value-based overload resolution.
11013 if (Cand1.Function && Cand2.Function) {
11014 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11015 if (Cmp != Comparison::Equal)
11016 return Cmp == Comparison::Better;
11017 }
11018
11019 bool HasPS1 = Cand1.Function != nullptr &&
11020 functionHasPassObjectSizeParams(FD: Cand1.Function);
11021 bool HasPS2 = Cand2.Function != nullptr &&
11022 functionHasPassObjectSizeParams(FD: Cand2.Function);
11023 if (HasPS1 != HasPS2 && HasPS1)
11024 return true;
11025
11026 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11027 if (MV == Comparison::Better)
11028 return true;
11029 if (MV == Comparison::Worse)
11030 return false;
11031
11032 // If other rules cannot determine which is better, CUDA preference is used
11033 // to determine which is better.
11034 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11035 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11036 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11037 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11038 }
11039
11040 // General member function overloading is handled above, so this only handles
11041 // constructors with address spaces.
11042 // This only handles address spaces since C++ has no other
11043 // qualifier that can be used with constructors.
11044 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11045 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11046 if (CD1 && CD2) {
11047 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11048 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11049 if (AS1 != AS2) {
11050 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11051 return true;
11052 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11053 return false;
11054 }
11055 }
11056
11057 return false;
11058}
11059
11060/// Determine whether two declarations are "equivalent" for the purposes of
11061/// name lookup and overload resolution. This applies when the same internal/no
11062/// linkage entity is defined by two modules (probably by textually including
11063/// the same header). In such a case, we don't consider the declarations to
11064/// declare the same entity, but we also don't want lookups with both
11065/// declarations visible to be ambiguous in some cases (this happens when using
11066/// a modularized libstdc++).
11067bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11068 const NamedDecl *B) {
11069 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11070 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11071 if (!VA || !VB)
11072 return false;
11073
11074 // The declarations must be declaring the same name as an internal linkage
11075 // entity in different modules.
11076 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11077 DC: VB->getDeclContext()->getRedeclContext()) ||
11078 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11079 VA->isExternallyVisible() || VB->isExternallyVisible())
11080 return false;
11081
11082 // Check that the declarations appear to be equivalent.
11083 //
11084 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11085 // For constants and functions, we should check the initializer or body is
11086 // the same. For non-constant variables, we shouldn't allow it at all.
11087 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11088 return true;
11089
11090 // Enum constants within unnamed enumerations will have different types, but
11091 // may still be similar enough to be interchangeable for our purposes.
11092 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11093 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11094 // Only handle anonymous enums. If the enumerations were named and
11095 // equivalent, they would have been merged to the same type.
11096 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11097 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11098 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11099 !Context.hasSameType(T1: EnumA->getIntegerType(),
11100 T2: EnumB->getIntegerType()))
11101 return false;
11102 // Allow this only if the value is the same for both enumerators.
11103 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11104 }
11105 }
11106
11107 // Nothing else is sufficiently similar.
11108 return false;
11109}
11110
11111void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11112 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11113 assert(D && "Unknown declaration");
11114 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11115
11116 Module *M = getOwningModule(Entity: D);
11117 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11118 << !M << (M ? M->getFullModuleName() : "");
11119
11120 for (auto *E : Equiv) {
11121 Module *M = getOwningModule(Entity: E);
11122 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11123 << !M << (M ? M->getFullModuleName() : "");
11124 }
11125}
11126
11127bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11128 return FailureKind == ovl_fail_bad_deduction &&
11129 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11130 TemplateDeductionResult::ConstraintsNotSatisfied &&
11131 static_cast<CNSInfo *>(DeductionFailure.Data)
11132 ->Satisfaction.ContainsErrors;
11133}
11134
11135void OverloadCandidateSet::AddDeferredTemplateCandidate(
11136 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11137 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11138 bool PartialOverloading, bool AllowExplicit,
11139 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11140 bool AggregateCandidateDeduction) {
11141
11142 auto *C =
11143 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11144
11145 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11146 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11147 /*AllowObjCConversionOnExplicit=*/false,
11148 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11149 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11150 .FunctionTemplate: FunctionTemplate,
11151 .FoundDecl: FoundDecl,
11152 .Args: Args,
11153 .IsADLCandidate: IsADLCandidate,
11154 .PO: PO};
11155
11156 HasDeferredTemplateConstructors |=
11157 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11158}
11159
11160void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11161 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11162 CXXRecordDecl *ActingContext, QualType ObjectType,
11163 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11164 bool SuppressUserConversions, bool PartialOverloading,
11165 OverloadCandidateParamOrder PO) {
11166
11167 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11168
11169 auto *C =
11170 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11171
11172 C = new (C) DeferredMethodTemplateOverloadCandidate{
11173 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11174 /*AllowObjCConversionOnExplicit=*/false,
11175 /*AllowResultConversion=*/false,
11176 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11177 /*AggregateCandidateDeduction=*/false},
11178 .FunctionTemplate: MethodTmpl,
11179 .FoundDecl: FoundDecl,
11180 .Args: Args,
11181 .ActingContext: ActingContext,
11182 .ObjectClassification: ObjectClassification,
11183 .ObjectType: ObjectType,
11184 .PO: PO};
11185}
11186
11187void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11188 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11189 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11190 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11191 bool AllowResultConversion) {
11192
11193 auto *C =
11194 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11195
11196 C = new (C) DeferredConversionTemplateOverloadCandidate{
11197 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11198 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11199 /*AllowExplicit=*/false,
11200 /*SuppressUserConversions=*/false,
11201 /*PartialOverloading*/ false,
11202 /*AggregateCandidateDeduction=*/false},
11203 .FunctionTemplate: FunctionTemplate,
11204 .FoundDecl: FoundDecl,
11205 .ActingContext: ActingContext,
11206 .From: From,
11207 .ToType: ToType};
11208}
11209
11210static void
11211AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11212 DeferredMethodTemplateOverloadCandidate &C) {
11213
11214 AddMethodTemplateCandidateImmediately(
11215 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11216 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11217 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11218}
11219
11220static void
11221AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11222 DeferredFunctionTemplateOverloadCandidate &C) {
11223 AddTemplateOverloadCandidateImmediately(
11224 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11225 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11226 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11227 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11228}
11229
11230static void
11231AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11232 DeferredConversionTemplateOverloadCandidate &C) {
11233 return AddTemplateConversionCandidateImmediately(
11234 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11235 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11236 AllowResultConversion: C.AllowResultConversion);
11237}
11238
11239void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11240 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11241 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11242 while (Cand) {
11243 switch (Cand->Kind) {
11244 case DeferredTemplateOverloadCandidate::Function:
11245 AddTemplateOverloadCandidate(
11246 S, CandidateSet&: *this,
11247 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11248 break;
11249 case DeferredTemplateOverloadCandidate::Method:
11250 AddTemplateOverloadCandidate(
11251 S, CandidateSet&: *this,
11252 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11253 break;
11254 case DeferredTemplateOverloadCandidate::Conversion:
11255 AddTemplateOverloadCandidate(
11256 S, CandidateSet&: *this,
11257 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11258 break;
11259 }
11260 Cand = Cand->Next;
11261 }
11262 FirstDeferredCandidate = nullptr;
11263 DeferredCandidatesCount = 0;
11264}
11265
11266OverloadingResult
11267OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11268 Best->Best = true;
11269 if (Best->Function && Best->Function->isDeleted())
11270 return OR_Deleted;
11271 return OR_Success;
11272}
11273
11274void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11275 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11276 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11277 // are accepted by both clang and NVCC. However, during a particular
11278 // compilation mode only one call variant is viable. We need to
11279 // exclude non-viable overload candidates from consideration based
11280 // only on their host/device attributes. Specifically, if one
11281 // candidate call is WrongSide and the other is SameSide, we ignore
11282 // the WrongSide candidate.
11283 // We only need to remove wrong-sided candidates here if
11284 // -fgpu-exclude-wrong-side-overloads is off. When
11285 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11286 // uniformly in isBetterOverloadCandidate.
11287 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11288 return;
11289 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11290
11291 bool ContainsSameSideCandidate =
11292 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11293 // Check viable function only.
11294 return Cand->Viable && Cand->Function &&
11295 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11296 SemaCUDA::CFP_SameSide;
11297 });
11298
11299 if (!ContainsSameSideCandidate)
11300 return;
11301
11302 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11303 // Check viable function only to avoid unnecessary data copying/moving.
11304 return Cand->Viable && Cand->Function &&
11305 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11306 SemaCUDA::CFP_WrongSide;
11307 };
11308 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11309}
11310
11311/// Computes the best viable function (C++ 13.3.3)
11312/// within an overload candidate set.
11313///
11314/// \param Loc The location of the function name (or operator symbol) for
11315/// which overload resolution occurs.
11316///
11317/// \param Best If overload resolution was successful or found a deleted
11318/// function, \p Best points to the candidate function found.
11319///
11320/// \returns The result of overload resolution.
11321OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11322 SourceLocation Loc,
11323 iterator &Best) {
11324
11325 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11326 DeferredCandidatesCount == 0) &&
11327 "Unexpected deferred template candidates");
11328
11329 bool TwoPhaseResolution =
11330 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11331
11332 if (TwoPhaseResolution) {
11333
11334 PerfectViableFunction(S, Loc, Best);
11335 if (Best != end())
11336 return ResultForBestCandidate(Best);
11337 }
11338
11339 InjectNonDeducedTemplateCandidates(S);
11340 return BestViableFunctionImpl(S, Loc, Best);
11341}
11342
11343void OverloadCandidateSet::PerfectViableFunction(
11344 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11345
11346 Best = end();
11347 for (auto It = Candidates.begin(); It != Candidates.end(); ++It) {
11348
11349 if (!It->isPerfectMatch(Ctx: S.getASTContext()))
11350 continue;
11351
11352 // We found a suitable conversion function
11353 // but if there is a template constructor in the target class
11354 // we might prefer that instead.
11355 if (HasDeferredTemplateConstructors &&
11356 isa_and_nonnull<CXXConversionDecl>(Val: It->Function)) {
11357 Best = end();
11358 break;
11359 }
11360
11361 if (Best == end()) {
11362 Best = It;
11363 continue;
11364 }
11365 if (Best->Function && It->Function) {
11366 FunctionDecl *D =
11367 S.getMoreConstrainedFunction(FD1: Best->Function, FD2: It->Function);
11368 if (D == nullptr) {
11369 Best = end();
11370 break;
11371 }
11372 if (D == It->Function)
11373 Best = It;
11374 continue;
11375 }
11376 // ambiguous
11377 Best = end();
11378 break;
11379 }
11380}
11381
11382OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11383 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11384
11385 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11386 Candidates.reserve(N: this->Candidates.size());
11387 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11388 result: std::back_inserter(x&: Candidates),
11389 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11390
11391 if (S.getLangOpts().CUDA)
11392 CudaExcludeWrongSideCandidates(S, Candidates);
11393
11394 Best = end();
11395 for (auto *Cand : Candidates) {
11396 Cand->Best = false;
11397 if (Cand->Viable) {
11398 if (Best == end() ||
11399 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11400 Best = Cand;
11401 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11402 // This candidate has constraint that we were unable to evaluate because
11403 // it referenced an expression that contained an error. Rather than fall
11404 // back onto a potentially unintended candidate (made worse by
11405 // subsuming constraints), treat this as 'no viable candidate'.
11406 Best = end();
11407 return OR_No_Viable_Function;
11408 }
11409 }
11410
11411 // If we didn't find any viable functions, abort.
11412 if (Best == end())
11413 return OR_No_Viable_Function;
11414
11415 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11416 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11417 PendingBest.push_back(Elt: &*Best);
11418 Best->Best = true;
11419
11420 // Make sure that this function is better than every other viable
11421 // function. If not, we have an ambiguity.
11422 while (!PendingBest.empty()) {
11423 auto *Curr = PendingBest.pop_back_val();
11424 for (auto *Cand : Candidates) {
11425 if (Cand->Viable && !Cand->Best &&
11426 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11427 PendingBest.push_back(Elt: Cand);
11428 Cand->Best = true;
11429
11430 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11431 B: Curr->Function))
11432 EquivalentCands.push_back(Elt: Cand->Function);
11433 else
11434 Best = end();
11435 }
11436 }
11437 }
11438
11439 if (Best == end())
11440 return OR_Ambiguous;
11441
11442 OverloadingResult R = ResultForBestCandidate(Best);
11443
11444 if (!EquivalentCands.empty())
11445 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11446 Equiv: EquivalentCands);
11447 return R;
11448}
11449
11450namespace {
11451
11452enum OverloadCandidateKind {
11453 oc_function,
11454 oc_method,
11455 oc_reversed_binary_operator,
11456 oc_constructor,
11457 oc_implicit_default_constructor,
11458 oc_implicit_copy_constructor,
11459 oc_implicit_move_constructor,
11460 oc_implicit_copy_assignment,
11461 oc_implicit_move_assignment,
11462 oc_implicit_equality_comparison,
11463 oc_inherited_constructor
11464};
11465
11466enum OverloadCandidateSelect {
11467 ocs_non_template,
11468 ocs_template,
11469 ocs_described_template,
11470};
11471
11472static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11473ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11474 const FunctionDecl *Fn,
11475 OverloadCandidateRewriteKind CRK,
11476 std::string &Description) {
11477
11478 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11479 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11480 isTemplate = true;
11481 Description = S.getTemplateArgumentBindingsText(
11482 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11483 }
11484
11485 OverloadCandidateSelect Select = [&]() {
11486 if (!Description.empty())
11487 return ocs_described_template;
11488 return isTemplate ? ocs_template : ocs_non_template;
11489 }();
11490
11491 OverloadCandidateKind Kind = [&]() {
11492 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11493 return oc_implicit_equality_comparison;
11494
11495 if (CRK & CRK_Reversed)
11496 return oc_reversed_binary_operator;
11497
11498 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11499 if (!Ctor->isImplicit()) {
11500 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11501 return oc_inherited_constructor;
11502 else
11503 return oc_constructor;
11504 }
11505
11506 if (Ctor->isDefaultConstructor())
11507 return oc_implicit_default_constructor;
11508
11509 if (Ctor->isMoveConstructor())
11510 return oc_implicit_move_constructor;
11511
11512 assert(Ctor->isCopyConstructor() &&
11513 "unexpected sort of implicit constructor");
11514 return oc_implicit_copy_constructor;
11515 }
11516
11517 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11518 // This actually gets spelled 'candidate function' for now, but
11519 // it doesn't hurt to split it out.
11520 if (!Meth->isImplicit())
11521 return oc_method;
11522
11523 if (Meth->isMoveAssignmentOperator())
11524 return oc_implicit_move_assignment;
11525
11526 if (Meth->isCopyAssignmentOperator())
11527 return oc_implicit_copy_assignment;
11528
11529 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11530 return oc_method;
11531 }
11532
11533 return oc_function;
11534 }();
11535
11536 return std::make_pair(x&: Kind, y&: Select);
11537}
11538
11539void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11540 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11541 // set.
11542 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11543 S.Diag(Loc: FoundDecl->getLocation(),
11544 DiagID: diag::note_ovl_candidate_inherited_constructor)
11545 << Shadow->getNominatedBaseClass();
11546}
11547
11548} // end anonymous namespace
11549
11550static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11551 const FunctionDecl *FD) {
11552 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11553 bool AlwaysTrue;
11554 if (EnableIf->getCond()->isValueDependent() ||
11555 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11556 return false;
11557 if (!AlwaysTrue)
11558 return false;
11559 }
11560 return true;
11561}
11562
11563/// Returns true if we can take the address of the function.
11564///
11565/// \param Complain - If true, we'll emit a diagnostic
11566/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11567/// we in overload resolution?
11568/// \param Loc - The location of the statement we're complaining about. Ignored
11569/// if we're not complaining, or if we're in overload resolution.
11570static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11571 bool Complain,
11572 bool InOverloadResolution,
11573 SourceLocation Loc) {
11574 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11575 if (Complain) {
11576 if (InOverloadResolution)
11577 S.Diag(Loc: FD->getBeginLoc(),
11578 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11579 else
11580 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11581 }
11582 return false;
11583 }
11584
11585 if (FD->getTrailingRequiresClause()) {
11586 ConstraintSatisfaction Satisfaction;
11587 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11588 return false;
11589 if (!Satisfaction.IsSatisfied) {
11590 if (Complain) {
11591 if (InOverloadResolution) {
11592 SmallString<128> TemplateArgString;
11593 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11594 TemplateArgString += " ";
11595 TemplateArgString += S.getTemplateArgumentBindingsText(
11596 Params: FunTmpl->getTemplateParameters(),
11597 Args: *FD->getTemplateSpecializationArgs());
11598 }
11599
11600 S.Diag(Loc: FD->getBeginLoc(),
11601 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11602 << TemplateArgString;
11603 } else
11604 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11605 << FD;
11606 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11607 }
11608 return false;
11609 }
11610 }
11611
11612 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11613 return P->hasAttr<PassObjectSizeAttr>();
11614 });
11615 if (I == FD->param_end())
11616 return true;
11617
11618 if (Complain) {
11619 // Add one to ParamNo because it's user-facing
11620 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11621 if (InOverloadResolution)
11622 S.Diag(Loc: FD->getLocation(),
11623 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11624 << ParamNo;
11625 else
11626 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11627 << FD << ParamNo;
11628 }
11629 return false;
11630}
11631
11632static bool checkAddressOfCandidateIsAvailable(Sema &S,
11633 const FunctionDecl *FD) {
11634 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11635 /*InOverloadResolution=*/true,
11636 /*Loc=*/SourceLocation());
11637}
11638
11639bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11640 bool Complain,
11641 SourceLocation Loc) {
11642 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11643 /*InOverloadResolution=*/false,
11644 Loc);
11645}
11646
11647// Don't print candidates other than the one that matches the calling
11648// convention of the call operator, since that is guaranteed to exist.
11649static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11650 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11651
11652 if (!ConvD)
11653 return false;
11654 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11655 if (!RD->isLambda())
11656 return false;
11657
11658 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11659 CallingConv CallOpCC =
11660 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11661 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11662 CallingConv ConvToCC =
11663 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11664
11665 return ConvToCC != CallOpCC;
11666}
11667
11668// Notes the location of an overload candidate.
11669void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11670 OverloadCandidateRewriteKind RewriteKind,
11671 QualType DestType, bool TakingAddress) {
11672 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11673 return;
11674 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11675 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11676 return;
11677 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11678 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11679 return;
11680 if (shouldSkipNotingLambdaConversionDecl(Fn))
11681 return;
11682
11683 std::string FnDesc;
11684 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11685 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11686 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11687 << (unsigned)KSPair.first << (unsigned)KSPair.second
11688 << Fn << FnDesc;
11689
11690 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11691 Diag(Loc: Fn->getLocation(), PD);
11692 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11693}
11694
11695static void
11696MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11697 // Perhaps the ambiguity was caused by two atomic constraints that are
11698 // 'identical' but not equivalent:
11699 //
11700 // void foo() requires (sizeof(T) > 4) { } // #1
11701 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11702 //
11703 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11704 // #2 to subsume #1, but these constraint are not considered equivalent
11705 // according to the subsumption rules because they are not the same
11706 // source-level construct. This behavior is quite confusing and we should try
11707 // to help the user figure out what happened.
11708
11709 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11710 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11711 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11712 if (!I->Function)
11713 continue;
11714 SmallVector<AssociatedConstraint, 3> AC;
11715 if (auto *Template = I->Function->getPrimaryTemplate())
11716 Template->getAssociatedConstraints(AC);
11717 else
11718 I->Function->getAssociatedConstraints(ACs&: AC);
11719 if (AC.empty())
11720 continue;
11721 if (FirstCand == nullptr) {
11722 FirstCand = I->Function;
11723 FirstAC = AC;
11724 } else if (SecondCand == nullptr) {
11725 SecondCand = I->Function;
11726 SecondAC = AC;
11727 } else {
11728 // We have more than one pair of constrained functions - this check is
11729 // expensive and we'd rather not try to diagnose it.
11730 return;
11731 }
11732 }
11733 if (!SecondCand)
11734 return;
11735 // The diagnostic can only happen if there are associated constraints on
11736 // both sides (there needs to be some identical atomic constraint).
11737 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11738 D2: SecondCand, AC2: SecondAC))
11739 // Just show the user one diagnostic, they'll probably figure it out
11740 // from here.
11741 return;
11742}
11743
11744// Notes the location of all overload candidates designated through
11745// OverloadedExpr
11746void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11747 bool TakingAddress) {
11748 assert(OverloadedExpr->getType() == Context.OverloadTy);
11749
11750 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11751 OverloadExpr *OvlExpr = Ovl.Expression;
11752
11753 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11754 IEnd = OvlExpr->decls_end();
11755 I != IEnd; ++I) {
11756 if (FunctionTemplateDecl *FunTmpl =
11757 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11758 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11759 TakingAddress);
11760 } else if (FunctionDecl *Fun
11761 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11762 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11763 }
11764 }
11765}
11766
11767/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11768/// "lead" diagnostic; it will be given two arguments, the source and
11769/// target types of the conversion.
11770void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11771 Sema &S,
11772 SourceLocation CaretLoc,
11773 const PartialDiagnostic &PDiag) const {
11774 S.Diag(Loc: CaretLoc, PD: PDiag)
11775 << Ambiguous.getFromType() << Ambiguous.getToType();
11776 unsigned CandsShown = 0;
11777 AmbiguousConversionSequence::const_iterator I, E;
11778 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11779 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11780 break;
11781 ++CandsShown;
11782 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11783 }
11784 S.Diags.overloadCandidatesShown(N: CandsShown);
11785 if (I != E)
11786 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
11787}
11788
11789static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11790 unsigned I, bool TakingCandidateAddress) {
11791 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11792 assert(Conv.isBad());
11793 assert(Cand->Function && "for now, candidate must be a function");
11794 FunctionDecl *Fn = Cand->Function;
11795
11796 // There's a conversion slot for the object argument if this is a
11797 // non-constructor method. Note that 'I' corresponds the
11798 // conversion-slot index.
11799 bool isObjectArgument = false;
11800 if (isa<CXXMethodDecl>(Val: Fn) && !isa<CXXConstructorDecl>(Val: Fn)) {
11801 if (I == 0)
11802 isObjectArgument = true;
11803 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11804 I--;
11805 }
11806
11807 std::string FnDesc;
11808 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11809 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
11810 Description&: FnDesc);
11811
11812 Expr *FromExpr = Conv.Bad.FromExpr;
11813 QualType FromTy = Conv.Bad.getFromType();
11814 QualType ToTy = Conv.Bad.getToType();
11815 SourceRange ToParamRange;
11816
11817 // FIXME: In presence of parameter packs we can't determine parameter range
11818 // reliably, as we don't have access to instantiation.
11819 bool HasParamPack =
11820 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
11821 return Parm->isParameterPack();
11822 });
11823 if (!isObjectArgument && !HasParamPack)
11824 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
11825
11826 if (FromTy == S.Context.OverloadTy) {
11827 assert(FromExpr && "overload set argument came from implicit argument?");
11828 Expr *E = FromExpr->IgnoreParens();
11829 if (isa<UnaryOperator>(Val: E))
11830 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
11831 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
11832
11833 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
11834 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11835 << ToParamRange << ToTy << Name << I + 1;
11836 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11837 return;
11838 }
11839
11840 // Do some hand-waving analysis to see if the non-viability is due
11841 // to a qualifier mismatch.
11842 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
11843 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
11844 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11845 CToTy = RT->getPointeeType();
11846 else {
11847 // TODO: detect and diagnose the full richness of const mismatches.
11848 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11849 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11850 CFromTy = FromPT->getPointeeType();
11851 CToTy = ToPT->getPointeeType();
11852 }
11853 }
11854
11855 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11856 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
11857 Qualifiers FromQs = CFromTy.getQualifiers();
11858 Qualifiers ToQs = CToTy.getQualifiers();
11859
11860 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11861 if (isObjectArgument)
11862 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
11863 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11864 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11865 else
11866 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
11867 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11868 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11869 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11870 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11871 return;
11872 }
11873
11874 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11875 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
11876 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11877 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11878 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11879 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11880 return;
11881 }
11882
11883 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11884 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
11885 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11886 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11887 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11888 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11889 return;
11890 }
11891
11892 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
11893 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
11894 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11895 << FromTy << !!FromQs.getPointerAuth()
11896 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11897 << ToQs.getPointerAuth().getAsString() << I + 1
11898 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11899 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11900 return;
11901 }
11902
11903 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11904 assert(CVR && "expected qualifiers mismatch");
11905
11906 if (isObjectArgument) {
11907 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
11908 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11909 << FromTy << (CVR - 1);
11910 } else {
11911 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
11912 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11913 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11914 }
11915 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11916 return;
11917 }
11918
11919 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11920 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11921 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
11922 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11923 << (unsigned)isObjectArgument << I + 1
11924 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11925 << ToParamRange;
11926 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11927 return;
11928 }
11929
11930 // Special diagnostic for failure to convert an initializer list, since
11931 // telling the user that it has type void is not useful.
11932 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
11933 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
11934 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11935 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11936 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11937 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11938 ? 2
11939 : 0);
11940 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11941 return;
11942 }
11943
11944 // Diagnose references or pointers to incomplete types differently,
11945 // since it's far from impossible that the incompleteness triggered
11946 // the failure.
11947 QualType TempFromTy = FromTy.getNonReferenceType();
11948 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11949 TempFromTy = PTy->getPointeeType();
11950 if (TempFromTy->isIncompleteType()) {
11951 // Emit the generic diagnostic and, optionally, add the hints to it.
11952 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
11953 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11954 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11955 << (unsigned)(Cand->Fix.Kind);
11956
11957 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11958 return;
11959 }
11960
11961 // Diagnose base -> derived pointer conversions.
11962 unsigned BaseToDerivedConversion = 0;
11963 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11964 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11965 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11966 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
11967 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11968 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11969 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
11970 Base: FromPtrTy->getPointeeType()))
11971 BaseToDerivedConversion = 1;
11972 }
11973 } else if (const ObjCObjectPointerType *FromPtrTy
11974 = FromTy->getAs<ObjCObjectPointerType>()) {
11975 if (const ObjCObjectPointerType *ToPtrTy
11976 = ToTy->getAs<ObjCObjectPointerType>())
11977 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11978 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11979 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11980 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
11981 FromIface->isSuperClassOf(I: ToIface))
11982 BaseToDerivedConversion = 2;
11983 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11984 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
11985 Ctx: S.getASTContext()) &&
11986 !FromTy->isIncompleteType() &&
11987 !ToRefTy->getPointeeType()->isIncompleteType() &&
11988 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
11989 BaseToDerivedConversion = 3;
11990 }
11991 }
11992
11993 if (BaseToDerivedConversion) {
11994 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
11995 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11996 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11997 << I + 1;
11998 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11999 return;
12000 }
12001
12002 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12003 isa<PointerType>(Val: CToTy)) {
12004 Qualifiers FromQs = CFromTy.getQualifiers();
12005 Qualifiers ToQs = CToTy.getQualifiers();
12006 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12007 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12008 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12009 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12010 << I + 1;
12011 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12012 return;
12013 }
12014 }
12015
12016 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12017 return;
12018
12019 // Emit the generic diagnostic and, optionally, add the hints to it.
12020 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12021 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12022 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12023 << (unsigned)(Cand->Fix.Kind);
12024
12025 // Check that location of Fn is not in system header.
12026 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12027 // If we can fix the conversion, suggest the FixIts.
12028 for (const FixItHint &HI : Cand->Fix.Hints)
12029 FDiag << HI;
12030 }
12031
12032 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12033
12034 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12035}
12036
12037/// Additional arity mismatch diagnosis specific to a function overload
12038/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12039/// over a candidate in any candidate set.
12040static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12041 unsigned NumArgs, bool IsAddressOf = false) {
12042 assert(Cand->Function && "Candidate is required to be a function.");
12043 FunctionDecl *Fn = Cand->Function;
12044 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12045 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12046
12047 // With invalid overloaded operators, it's possible that we think we
12048 // have an arity mismatch when in fact it looks like we have the
12049 // right number of arguments, because only overloaded operators have
12050 // the weird behavior of overloading member and non-member functions.
12051 // Just don't report anything.
12052 if (Fn->isInvalidDecl() &&
12053 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12054 return true;
12055
12056 if (NumArgs < MinParams) {
12057 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12058 (Cand->FailureKind == ovl_fail_bad_deduction &&
12059 Cand->DeductionFailure.getResult() ==
12060 TemplateDeductionResult::TooFewArguments));
12061 } else {
12062 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12063 (Cand->FailureKind == ovl_fail_bad_deduction &&
12064 Cand->DeductionFailure.getResult() ==
12065 TemplateDeductionResult::TooManyArguments));
12066 }
12067
12068 return false;
12069}
12070
12071/// General arity mismatch diagnosis over a candidate in a candidate set.
12072static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12073 unsigned NumFormalArgs,
12074 bool IsAddressOf = false) {
12075 assert(isa<FunctionDecl>(D) &&
12076 "The templated declaration should at least be a function"
12077 " when diagnosing bad template argument deduction due to too many"
12078 " or too few arguments");
12079
12080 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12081
12082 // TODO: treat calls to a missing default constructor as a special case
12083 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12084 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12085 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12086
12087 // at least / at most / exactly
12088 bool HasExplicitObjectParam =
12089 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12090
12091 unsigned ParamCount =
12092 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12093 unsigned mode, modeCount;
12094
12095 if (NumFormalArgs < MinParams) {
12096 if (MinParams != ParamCount || FnTy->isVariadic() ||
12097 FnTy->isTemplateVariadic())
12098 mode = 0; // "at least"
12099 else
12100 mode = 2; // "exactly"
12101 modeCount = MinParams;
12102 } else {
12103 if (MinParams != ParamCount)
12104 mode = 1; // "at most"
12105 else
12106 mode = 2; // "exactly"
12107 modeCount = ParamCount;
12108 }
12109
12110 std::string Description;
12111 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12112 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12113
12114 if (modeCount == 1 && !IsAddressOf &&
12115 Fn->getParamDecl(i: HasExplicitObjectParam ? 1 : 0)->getDeclName())
12116 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12117 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12118 << Description << mode
12119 << Fn->getParamDecl(i: HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12120 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12121 else
12122 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12123 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12124 << Description << mode << modeCount << NumFormalArgs
12125 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12126
12127 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12128}
12129
12130/// Arity mismatch diagnosis specific to a function overload candidate.
12131static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12132 unsigned NumFormalArgs) {
12133 assert(Cand->Function && "Candidate must be a function");
12134 FunctionDecl *Fn = Cand->Function;
12135 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12136 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12137 IsAddressOf: Cand->TookAddressOfOverload);
12138}
12139
12140static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12141 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12142 return TD;
12143 llvm_unreachable("Unsupported: Getting the described template declaration"
12144 " for bad deduction diagnosis");
12145}
12146
12147/// Diagnose a failed template-argument deduction.
12148static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12149 DeductionFailureInfo &DeductionFailure,
12150 unsigned NumArgs,
12151 bool TakingCandidateAddress) {
12152 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12153 NamedDecl *ParamD;
12154 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12155 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12156 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12157 switch (DeductionFailure.getResult()) {
12158 case TemplateDeductionResult::Success:
12159 llvm_unreachable(
12160 "TemplateDeductionResult::Success while diagnosing bad deduction");
12161 case TemplateDeductionResult::NonDependentConversionFailure:
12162 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12163 "while diagnosing bad deduction");
12164 case TemplateDeductionResult::Invalid:
12165 case TemplateDeductionResult::AlreadyDiagnosed:
12166 return;
12167
12168 case TemplateDeductionResult::Incomplete: {
12169 assert(ParamD && "no parameter found for incomplete deduction result");
12170 S.Diag(Loc: Templated->getLocation(),
12171 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12172 << ParamD->getDeclName();
12173 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12174 return;
12175 }
12176
12177 case TemplateDeductionResult::IncompletePack: {
12178 assert(ParamD && "no parameter found for incomplete deduction result");
12179 S.Diag(Loc: Templated->getLocation(),
12180 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12181 << ParamD->getDeclName()
12182 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12183 << *DeductionFailure.getFirstArg();
12184 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12185 return;
12186 }
12187
12188 case TemplateDeductionResult::Underqualified: {
12189 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12190 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12191
12192 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12193
12194 // Param will have been canonicalized, but it should just be a
12195 // qualified version of ParamD, so move the qualifiers to that.
12196 QualifierCollector Qs;
12197 Qs.strip(type: Param);
12198 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12199 assert(S.Context.hasSameType(Param, NonCanonParam));
12200
12201 // Arg has also been canonicalized, but there's nothing we can do
12202 // about that. It also doesn't matter as much, because it won't
12203 // have any template parameters in it (because deduction isn't
12204 // done on dependent types).
12205 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12206
12207 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12208 << ParamD->getDeclName() << Arg << NonCanonParam;
12209 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12210 return;
12211 }
12212
12213 case TemplateDeductionResult::Inconsistent: {
12214 assert(ParamD && "no parameter found for inconsistent deduction result");
12215 int which = 0;
12216 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12217 which = 0;
12218 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12219 // Deduction might have failed because we deduced arguments of two
12220 // different types for a non-type template parameter.
12221 // FIXME: Use a different TDK value for this.
12222 QualType T1 =
12223 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12224 QualType T2 =
12225 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12226 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12227 S.Diag(Loc: Templated->getLocation(),
12228 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12229 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12230 << *DeductionFailure.getSecondArg() << T2;
12231 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12232 return;
12233 }
12234
12235 which = 1;
12236 } else {
12237 which = 2;
12238 }
12239
12240 // Tweak the diagnostic if the problem is that we deduced packs of
12241 // different arities. We'll print the actual packs anyway in case that
12242 // includes additional useful information.
12243 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12244 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12245 DeductionFailure.getFirstArg()->pack_size() !=
12246 DeductionFailure.getSecondArg()->pack_size()) {
12247 which = 3;
12248 }
12249
12250 S.Diag(Loc: Templated->getLocation(),
12251 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12252 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12253 << *DeductionFailure.getSecondArg();
12254 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12255 return;
12256 }
12257
12258 case TemplateDeductionResult::InvalidExplicitArguments:
12259 assert(ParamD && "no parameter found for invalid explicit arguments");
12260 if (ParamD->getDeclName())
12261 S.Diag(Loc: Templated->getLocation(),
12262 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_named)
12263 << ParamD->getDeclName();
12264 else {
12265 int index = 0;
12266 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
12267 index = TTP->getIndex();
12268 else if (NonTypeTemplateParmDecl *NTTP
12269 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
12270 index = NTTP->getIndex();
12271 else
12272 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
12273 S.Diag(Loc: Templated->getLocation(),
12274 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12275 << (index + 1);
12276 }
12277 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12278 return;
12279
12280 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12281 // Format the template argument list into the argument string.
12282 SmallString<128> TemplateArgString;
12283 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12284 TemplateArgString = " ";
12285 TemplateArgString += S.getTemplateArgumentBindingsText(
12286 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12287 if (TemplateArgString.size() == 1)
12288 TemplateArgString.clear();
12289 S.Diag(Loc: Templated->getLocation(),
12290 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12291 << TemplateArgString;
12292
12293 S.DiagnoseUnsatisfiedConstraint(
12294 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12295 return;
12296 }
12297 case TemplateDeductionResult::TooManyArguments:
12298 case TemplateDeductionResult::TooFewArguments:
12299 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs);
12300 return;
12301
12302 case TemplateDeductionResult::InstantiationDepth:
12303 S.Diag(Loc: Templated->getLocation(),
12304 DiagID: diag::note_ovl_candidate_instantiation_depth);
12305 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12306 return;
12307
12308 case TemplateDeductionResult::SubstitutionFailure: {
12309 // Format the template argument list into the argument string.
12310 SmallString<128> TemplateArgString;
12311 if (TemplateArgumentList *Args =
12312 DeductionFailure.getTemplateArgumentList()) {
12313 TemplateArgString = " ";
12314 TemplateArgString += S.getTemplateArgumentBindingsText(
12315 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12316 if (TemplateArgString.size() == 1)
12317 TemplateArgString.clear();
12318 }
12319
12320 // If this candidate was disabled by enable_if, say so.
12321 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12322 if (PDiag && PDiag->second.getDiagID() ==
12323 diag::err_typename_nested_not_found_enable_if) {
12324 // FIXME: Use the source range of the condition, and the fully-qualified
12325 // name of the enable_if template. These are both present in PDiag.
12326 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12327 << "'enable_if'" << TemplateArgString;
12328 return;
12329 }
12330
12331 // We found a specific requirement that disabled the enable_if.
12332 if (PDiag && PDiag->second.getDiagID() ==
12333 diag::err_typename_nested_not_found_requirement) {
12334 S.Diag(Loc: Templated->getLocation(),
12335 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12336 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12337 return;
12338 }
12339
12340 // Format the SFINAE diagnostic into the argument string.
12341 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12342 // formatted message in another diagnostic.
12343 SmallString<128> SFINAEArgString;
12344 SourceRange R;
12345 if (PDiag) {
12346 SFINAEArgString = ": ";
12347 R = SourceRange(PDiag->first, PDiag->first);
12348 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12349 }
12350
12351 S.Diag(Loc: Templated->getLocation(),
12352 DiagID: diag::note_ovl_candidate_substitution_failure)
12353 << TemplateArgString << SFINAEArgString << R;
12354 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12355 return;
12356 }
12357
12358 case TemplateDeductionResult::DeducedMismatch:
12359 case TemplateDeductionResult::DeducedMismatchNested: {
12360 // Format the template argument list into the argument string.
12361 SmallString<128> TemplateArgString;
12362 if (TemplateArgumentList *Args =
12363 DeductionFailure.getTemplateArgumentList()) {
12364 TemplateArgString = " ";
12365 TemplateArgString += S.getTemplateArgumentBindingsText(
12366 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12367 if (TemplateArgString.size() == 1)
12368 TemplateArgString.clear();
12369 }
12370
12371 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12372 << (*DeductionFailure.getCallArgIndex() + 1)
12373 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12374 << TemplateArgString
12375 << (DeductionFailure.getResult() ==
12376 TemplateDeductionResult::DeducedMismatchNested);
12377 break;
12378 }
12379
12380 case TemplateDeductionResult::NonDeducedMismatch: {
12381 // FIXME: Provide a source location to indicate what we couldn't match.
12382 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12383 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12384 if (FirstTA.getKind() == TemplateArgument::Template &&
12385 SecondTA.getKind() == TemplateArgument::Template) {
12386 TemplateName FirstTN = FirstTA.getAsTemplate();
12387 TemplateName SecondTN = SecondTA.getAsTemplate();
12388 if (FirstTN.getKind() == TemplateName::Template &&
12389 SecondTN.getKind() == TemplateName::Template) {
12390 if (FirstTN.getAsTemplateDecl()->getName() ==
12391 SecondTN.getAsTemplateDecl()->getName()) {
12392 // FIXME: This fixes a bad diagnostic where both templates are named
12393 // the same. This particular case is a bit difficult since:
12394 // 1) It is passed as a string to the diagnostic printer.
12395 // 2) The diagnostic printer only attempts to find a better
12396 // name for types, not decls.
12397 // Ideally, this should folded into the diagnostic printer.
12398 S.Diag(Loc: Templated->getLocation(),
12399 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12400 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12401 return;
12402 }
12403 }
12404 }
12405
12406 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12407 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12408 return;
12409
12410 // FIXME: For generic lambda parameters, check if the function is a lambda
12411 // call operator, and if so, emit a prettier and more informative
12412 // diagnostic that mentions 'auto' and lambda in addition to
12413 // (or instead of?) the canonical template type parameters.
12414 S.Diag(Loc: Templated->getLocation(),
12415 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12416 << FirstTA << SecondTA;
12417 return;
12418 }
12419 // TODO: diagnose these individually, then kill off
12420 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12421 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12422 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12423 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12424 return;
12425 case TemplateDeductionResult::CUDATargetMismatch:
12426 S.Diag(Loc: Templated->getLocation(),
12427 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12428 return;
12429 }
12430}
12431
12432/// Diagnose a failed template-argument deduction, for function calls.
12433static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12434 unsigned NumArgs,
12435 bool TakingCandidateAddress) {
12436 assert(Cand->Function && "Candidate must be a function");
12437 FunctionDecl *Fn = Cand->Function;
12438 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12439 if (TDK == TemplateDeductionResult::TooFewArguments ||
12440 TDK == TemplateDeductionResult::TooManyArguments) {
12441 if (CheckArityMismatch(S, Cand, NumArgs))
12442 return;
12443 }
12444 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12445 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12446}
12447
12448/// CUDA: diagnose an invalid call across targets.
12449static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12450 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12451 assert(Cand->Function && "Candidate must be a Function.");
12452 FunctionDecl *Callee = Cand->Function;
12453
12454 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12455 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12456
12457 std::string FnDesc;
12458 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12459 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12460 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12461
12462 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12463 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12464 << FnDesc /* Ignored */
12465 << CalleeTarget << CallerTarget;
12466
12467 // This could be an implicit constructor for which we could not infer the
12468 // target due to a collsion. Diagnose that case.
12469 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12470 if (Meth != nullptr && Meth->isImplicit()) {
12471 CXXRecordDecl *ParentClass = Meth->getParent();
12472 CXXSpecialMemberKind CSM;
12473
12474 switch (FnKindPair.first) {
12475 default:
12476 return;
12477 case oc_implicit_default_constructor:
12478 CSM = CXXSpecialMemberKind::DefaultConstructor;
12479 break;
12480 case oc_implicit_copy_constructor:
12481 CSM = CXXSpecialMemberKind::CopyConstructor;
12482 break;
12483 case oc_implicit_move_constructor:
12484 CSM = CXXSpecialMemberKind::MoveConstructor;
12485 break;
12486 case oc_implicit_copy_assignment:
12487 CSM = CXXSpecialMemberKind::CopyAssignment;
12488 break;
12489 case oc_implicit_move_assignment:
12490 CSM = CXXSpecialMemberKind::MoveAssignment;
12491 break;
12492 };
12493
12494 bool ConstRHS = false;
12495 if (Meth->getNumParams()) {
12496 if (const ReferenceType *RT =
12497 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12498 ConstRHS = RT->getPointeeType().isConstQualified();
12499 }
12500 }
12501
12502 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12503 /* ConstRHS */ ConstRHS,
12504 /* Diagnose */ true);
12505 }
12506}
12507
12508static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12509 assert(Cand->Function && "Candidate must be a function");
12510 FunctionDecl *Callee = Cand->Function;
12511 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12512
12513 S.Diag(Loc: Callee->getLocation(),
12514 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12515 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12516}
12517
12518static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12519 assert(Cand->Function && "Candidate must be a function");
12520 FunctionDecl *Fn = Cand->Function;
12521 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12522 assert(ES.isExplicit() && "not an explicit candidate");
12523
12524 unsigned Kind;
12525 switch (Fn->getDeclKind()) {
12526 case Decl::Kind::CXXConstructor:
12527 Kind = 0;
12528 break;
12529 case Decl::Kind::CXXConversion:
12530 Kind = 1;
12531 break;
12532 case Decl::Kind::CXXDeductionGuide:
12533 Kind = Fn->isImplicit() ? 0 : 2;
12534 break;
12535 default:
12536 llvm_unreachable("invalid Decl");
12537 }
12538
12539 // Note the location of the first (in-class) declaration; a redeclaration
12540 // (particularly an out-of-class definition) will typically lack the
12541 // 'explicit' specifier.
12542 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12543 FunctionDecl *First = Fn->getFirstDecl();
12544 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12545 First = Pattern->getFirstDecl();
12546
12547 S.Diag(Loc: First->getLocation(),
12548 DiagID: diag::note_ovl_candidate_explicit)
12549 << Kind << (ES.getExpr() ? 1 : 0)
12550 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12551}
12552
12553static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12554 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12555 if (!DG)
12556 return;
12557 TemplateDecl *OriginTemplate =
12558 DG->getDeclName().getCXXDeductionGuideTemplate();
12559 // We want to always print synthesized deduction guides for type aliases.
12560 // They would retain the explicit bit of the corresponding constructor.
12561 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12562 return;
12563 std::string FunctionProto;
12564 llvm::raw_string_ostream OS(FunctionProto);
12565 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12566 if (!Template) {
12567 // This also could be an instantiation. Find out the primary template.
12568 FunctionDecl *Pattern =
12569 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12570 if (!Pattern) {
12571 // The implicit deduction guide is built on an explicit non-template
12572 // deduction guide. Currently, this might be the case only for type
12573 // aliases.
12574 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12575 // gets merged.
12576 assert(OriginTemplate->isTypeAlias() &&
12577 "Non-template implicit deduction guides are only possible for "
12578 "type aliases");
12579 DG->print(Out&: OS);
12580 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12581 << FunctionProto;
12582 return;
12583 }
12584 Template = Pattern->getDescribedFunctionTemplate();
12585 assert(Template && "Cannot find the associated function template of "
12586 "CXXDeductionGuideDecl?");
12587 }
12588 Template->print(Out&: OS);
12589 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12590 << FunctionProto;
12591}
12592
12593/// Generates a 'note' diagnostic for an overload candidate. We've
12594/// already generated a primary error at the call site.
12595///
12596/// It really does need to be a single diagnostic with its caret
12597/// pointed at the candidate declaration. Yes, this creates some
12598/// major challenges of technical writing. Yes, this makes pointing
12599/// out problems with specific arguments quite awkward. It's still
12600/// better than generating twenty screens of text for every failed
12601/// overload.
12602///
12603/// It would be great to be able to express per-candidate problems
12604/// more richly for those diagnostic clients that cared, but we'd
12605/// still have to be just as careful with the default diagnostics.
12606/// \param CtorDestAS Addr space of object being constructed (for ctor
12607/// candidates only).
12608static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12609 unsigned NumArgs,
12610 bool TakingCandidateAddress,
12611 LangAS CtorDestAS = LangAS::Default) {
12612 assert(Cand->Function && "Candidate must be a function");
12613 FunctionDecl *Fn = Cand->Function;
12614 if (shouldSkipNotingLambdaConversionDecl(Fn))
12615 return;
12616
12617 // There is no physical candidate declaration to point to for OpenCL builtins.
12618 // Except for failed conversions, the notes are identical for each candidate,
12619 // so do not generate such notes.
12620 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12621 Cand->FailureKind != ovl_fail_bad_conversion)
12622 return;
12623
12624 // Skip implicit member functions when trying to resolve
12625 // the address of a an overload set for a function pointer.
12626 if (Cand->TookAddressOfOverload &&
12627 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12628 return;
12629
12630 // Note deleted candidates, but only if they're viable.
12631 if (Cand->Viable) {
12632 if (Fn->isDeleted()) {
12633 std::string FnDesc;
12634 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12635 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12636 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12637
12638 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12639 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12640 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12641 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12642 return;
12643 }
12644
12645 // We don't really have anything else to say about viable candidates.
12646 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12647 return;
12648 }
12649
12650 // If this is a synthesized deduction guide we're deducing against, add a note
12651 // for it. These deduction guides are not explicitly spelled in the source
12652 // code, so simply printing a deduction failure note mentioning synthesized
12653 // template parameters or pointing to the header of the surrounding RecordDecl
12654 // would be confusing.
12655 //
12656 // We prefer adding such notes at the end of the deduction failure because
12657 // duplicate code snippets appearing in the diagnostic would likely become
12658 // noisy.
12659 auto _ = llvm::make_scope_exit(F: [&] { NoteImplicitDeductionGuide(S, Fn); });
12660
12661 switch (Cand->FailureKind) {
12662 case ovl_fail_too_many_arguments:
12663 case ovl_fail_too_few_arguments:
12664 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12665
12666 case ovl_fail_bad_deduction:
12667 return DiagnoseBadDeduction(S, Cand, NumArgs,
12668 TakingCandidateAddress);
12669
12670 case ovl_fail_illegal_constructor: {
12671 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12672 << (Fn->getPrimaryTemplate() ? 1 : 0);
12673 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12674 return;
12675 }
12676
12677 case ovl_fail_object_addrspace_mismatch: {
12678 Qualifiers QualsForPrinting;
12679 QualsForPrinting.setAddressSpace(CtorDestAS);
12680 S.Diag(Loc: Fn->getLocation(),
12681 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12682 << QualsForPrinting;
12683 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12684 return;
12685 }
12686
12687 case ovl_fail_trivial_conversion:
12688 case ovl_fail_bad_final_conversion:
12689 case ovl_fail_final_conversion_not_exact:
12690 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12691
12692 case ovl_fail_bad_conversion: {
12693 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12694 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12695 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12696 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12697
12698 // FIXME: this currently happens when we're called from SemaInit
12699 // when user-conversion overload fails. Figure out how to handle
12700 // those conditions and diagnose them well.
12701 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12702 }
12703
12704 case ovl_fail_bad_target:
12705 return DiagnoseBadTarget(S, Cand);
12706
12707 case ovl_fail_enable_if:
12708 return DiagnoseFailedEnableIfAttr(S, Cand);
12709
12710 case ovl_fail_explicit:
12711 return DiagnoseFailedExplicitSpec(S, Cand);
12712
12713 case ovl_fail_inhctor_slice:
12714 // It's generally not interesting to note copy/move constructors here.
12715 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12716 return;
12717 S.Diag(Loc: Fn->getLocation(),
12718 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12719 << (Fn->getPrimaryTemplate() ? 1 : 0)
12720 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12721 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12722 return;
12723
12724 case ovl_fail_addr_not_available: {
12725 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12726 (void)Available;
12727 assert(!Available);
12728 break;
12729 }
12730 case ovl_non_default_multiversion_function:
12731 // Do nothing, these should simply be ignored.
12732 break;
12733
12734 case ovl_fail_constraints_not_satisfied: {
12735 std::string FnDesc;
12736 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12737 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12738 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12739
12740 S.Diag(Loc: Fn->getLocation(),
12741 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12742 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12743 << FnDesc /* Ignored */;
12744 ConstraintSatisfaction Satisfaction;
12745 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction))
12746 break;
12747 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12748 }
12749 }
12750}
12751
12752static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12753 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12754 return;
12755
12756 // Desugar the type of the surrogate down to a function type,
12757 // retaining as many typedefs as possible while still showing
12758 // the function type (and, therefore, its parameter types).
12759 QualType FnType = Cand->Surrogate->getConversionType();
12760 bool isLValueReference = false;
12761 bool isRValueReference = false;
12762 bool isPointer = false;
12763 if (const LValueReferenceType *FnTypeRef =
12764 FnType->getAs<LValueReferenceType>()) {
12765 FnType = FnTypeRef->getPointeeType();
12766 isLValueReference = true;
12767 } else if (const RValueReferenceType *FnTypeRef =
12768 FnType->getAs<RValueReferenceType>()) {
12769 FnType = FnTypeRef->getPointeeType();
12770 isRValueReference = true;
12771 }
12772 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12773 FnType = FnTypePtr->getPointeeType();
12774 isPointer = true;
12775 }
12776 // Desugar down to a function type.
12777 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12778 // Reconstruct the pointer/reference as appropriate.
12779 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12780 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12781 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12782
12783 if (!Cand->Viable &&
12784 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12785 S.Diag(Loc: Cand->Surrogate->getLocation(),
12786 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
12787 << Cand->Surrogate;
12788 ConstraintSatisfaction Satisfaction;
12789 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
12790 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12791 } else {
12792 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
12793 << FnType;
12794 }
12795}
12796
12797static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12798 SourceLocation OpLoc,
12799 OverloadCandidate *Cand) {
12800 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12801 std::string TypeStr("operator");
12802 TypeStr += Opc;
12803 TypeStr += "(";
12804 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12805 if (Cand->Conversions.size() == 1) {
12806 TypeStr += ")";
12807 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12808 } else {
12809 TypeStr += ", ";
12810 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12811 TypeStr += ")";
12812 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12813 }
12814}
12815
12816static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12817 OverloadCandidate *Cand) {
12818 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12819 if (ICS.isBad()) break; // all meaningless after first invalid
12820 if (!ICS.isAmbiguous()) continue;
12821
12822 ICS.DiagnoseAmbiguousConversion(
12823 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
12824 }
12825}
12826
12827static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12828 if (Cand->Function)
12829 return Cand->Function->getLocation();
12830 if (Cand->IsSurrogate)
12831 return Cand->Surrogate->getLocation();
12832 return SourceLocation();
12833}
12834
12835static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12836 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12837 case TemplateDeductionResult::Success:
12838 case TemplateDeductionResult::NonDependentConversionFailure:
12839 case TemplateDeductionResult::AlreadyDiagnosed:
12840 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12841
12842 case TemplateDeductionResult::Invalid:
12843 case TemplateDeductionResult::Incomplete:
12844 case TemplateDeductionResult::IncompletePack:
12845 return 1;
12846
12847 case TemplateDeductionResult::Underqualified:
12848 case TemplateDeductionResult::Inconsistent:
12849 return 2;
12850
12851 case TemplateDeductionResult::SubstitutionFailure:
12852 case TemplateDeductionResult::DeducedMismatch:
12853 case TemplateDeductionResult::ConstraintsNotSatisfied:
12854 case TemplateDeductionResult::DeducedMismatchNested:
12855 case TemplateDeductionResult::NonDeducedMismatch:
12856 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12857 case TemplateDeductionResult::CUDATargetMismatch:
12858 return 3;
12859
12860 case TemplateDeductionResult::InstantiationDepth:
12861 return 4;
12862
12863 case TemplateDeductionResult::InvalidExplicitArguments:
12864 return 5;
12865
12866 case TemplateDeductionResult::TooManyArguments:
12867 case TemplateDeductionResult::TooFewArguments:
12868 return 6;
12869 }
12870 llvm_unreachable("Unhandled deduction result");
12871}
12872
12873namespace {
12874
12875struct CompareOverloadCandidatesForDisplay {
12876 Sema &S;
12877 SourceLocation Loc;
12878 size_t NumArgs;
12879 OverloadCandidateSet::CandidateSetKind CSK;
12880
12881 CompareOverloadCandidatesForDisplay(
12882 Sema &S, SourceLocation Loc, size_t NArgs,
12883 OverloadCandidateSet::CandidateSetKind CSK)
12884 : S(S), NumArgs(NArgs), CSK(CSK) {}
12885
12886 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12887 // If there are too many or too few arguments, that's the high-order bit we
12888 // want to sort by, even if the immediate failure kind was something else.
12889 if (C->FailureKind == ovl_fail_too_many_arguments ||
12890 C->FailureKind == ovl_fail_too_few_arguments)
12891 return static_cast<OverloadFailureKind>(C->FailureKind);
12892
12893 if (C->Function) {
12894 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12895 return ovl_fail_too_many_arguments;
12896 if (NumArgs < C->Function->getMinRequiredArguments())
12897 return ovl_fail_too_few_arguments;
12898 }
12899
12900 return static_cast<OverloadFailureKind>(C->FailureKind);
12901 }
12902
12903 bool operator()(const OverloadCandidate *L,
12904 const OverloadCandidate *R) {
12905 // Fast-path this check.
12906 if (L == R) return false;
12907
12908 // Order first by viability.
12909 if (L->Viable) {
12910 if (!R->Viable) return true;
12911
12912 if (int Ord = CompareConversions(L: *L, R: *R))
12913 return Ord < 0;
12914 // Use other tie breakers.
12915 } else if (R->Viable)
12916 return false;
12917
12918 assert(L->Viable == R->Viable);
12919
12920 // Criteria by which we can sort non-viable candidates:
12921 if (!L->Viable) {
12922 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
12923 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
12924
12925 // 1. Arity mismatches come after other candidates.
12926 if (LFailureKind == ovl_fail_too_many_arguments ||
12927 LFailureKind == ovl_fail_too_few_arguments) {
12928 if (RFailureKind == ovl_fail_too_many_arguments ||
12929 RFailureKind == ovl_fail_too_few_arguments) {
12930 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
12931 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
12932 if (LDist == RDist) {
12933 if (LFailureKind == RFailureKind)
12934 // Sort non-surrogates before surrogates.
12935 return !L->IsSurrogate && R->IsSurrogate;
12936 // Sort candidates requiring fewer parameters than there were
12937 // arguments given after candidates requiring more parameters
12938 // than there were arguments given.
12939 return LFailureKind == ovl_fail_too_many_arguments;
12940 }
12941 return LDist < RDist;
12942 }
12943 return false;
12944 }
12945 if (RFailureKind == ovl_fail_too_many_arguments ||
12946 RFailureKind == ovl_fail_too_few_arguments)
12947 return true;
12948
12949 // 2. Bad conversions come first and are ordered by the number
12950 // of bad conversions and quality of good conversions.
12951 if (LFailureKind == ovl_fail_bad_conversion) {
12952 if (RFailureKind != ovl_fail_bad_conversion)
12953 return true;
12954
12955 // The conversion that can be fixed with a smaller number of changes,
12956 // comes first.
12957 unsigned numLFixes = L->Fix.NumConversionsFixed;
12958 unsigned numRFixes = R->Fix.NumConversionsFixed;
12959 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12960 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12961 if (numLFixes != numRFixes) {
12962 return numLFixes < numRFixes;
12963 }
12964
12965 // If there's any ordering between the defined conversions...
12966 if (int Ord = CompareConversions(L: *L, R: *R))
12967 return Ord < 0;
12968 } else if (RFailureKind == ovl_fail_bad_conversion)
12969 return false;
12970
12971 if (LFailureKind == ovl_fail_bad_deduction) {
12972 if (RFailureKind != ovl_fail_bad_deduction)
12973 return true;
12974
12975 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12976 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
12977 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
12978 if (LRank != RRank)
12979 return LRank < RRank;
12980 }
12981 } else if (RFailureKind == ovl_fail_bad_deduction)
12982 return false;
12983
12984 // TODO: others?
12985 }
12986
12987 // Sort everything else by location.
12988 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
12989 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
12990
12991 // Put candidates without locations (e.g. builtins) at the end.
12992 if (LLoc.isValid() && RLoc.isValid())
12993 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
12994 if (LLoc.isValid() && !RLoc.isValid())
12995 return true;
12996 if (RLoc.isValid() && !LLoc.isValid())
12997 return false;
12998 assert(!LLoc.isValid() && !RLoc.isValid());
12999 // For builtins and other functions without locations, fallback to the order
13000 // in which they were added into the candidate set.
13001 return L < R;
13002 }
13003
13004private:
13005 struct ConversionSignals {
13006 unsigned KindRank = 0;
13007 ImplicitConversionRank Rank = ICR_Exact_Match;
13008
13009 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13010 ConversionSignals Sig;
13011 Sig.KindRank = Seq.getKindRank();
13012 if (Seq.isStandard())
13013 Sig.Rank = Seq.Standard.getRank();
13014 else if (Seq.isUserDefined())
13015 Sig.Rank = Seq.UserDefined.After.getRank();
13016 // We intend StaticObjectArgumentConversion to compare the same as
13017 // StandardConversion with ICR_ExactMatch rank.
13018 return Sig;
13019 }
13020
13021 static ConversionSignals ForObjectArgument() {
13022 // We intend StaticObjectArgumentConversion to compare the same as
13023 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13024 return {};
13025 }
13026 };
13027
13028 // Returns -1 if conversions in L are considered better.
13029 // 0 if they are considered indistinguishable.
13030 // 1 if conversions in R are better.
13031 int CompareConversions(const OverloadCandidate &L,
13032 const OverloadCandidate &R) {
13033 // We cannot use `isBetterOverloadCandidate` because it is defined
13034 // according to the C++ standard and provides a partial order, but we need
13035 // a total order as this function is used in sort.
13036 assert(L.Conversions.size() == R.Conversions.size());
13037 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13038 auto LS = L.IgnoreObjectArgument && I == 0
13039 ? ConversionSignals::ForObjectArgument()
13040 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13041 auto RS = R.IgnoreObjectArgument
13042 ? ConversionSignals::ForObjectArgument()
13043 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13044 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13045 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13046 ? -1
13047 : 1;
13048 }
13049 // FIXME: find a way to compare templates for being more or less
13050 // specialized that provides a strict weak ordering.
13051 return 0;
13052 }
13053};
13054}
13055
13056/// CompleteNonViableCandidate - Normally, overload resolution only
13057/// computes up to the first bad conversion. Produces the FixIt set if
13058/// possible.
13059static void
13060CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13061 ArrayRef<Expr *> Args,
13062 OverloadCandidateSet::CandidateSetKind CSK) {
13063 assert(!Cand->Viable);
13064
13065 // Don't do anything on failures other than bad conversion.
13066 if (Cand->FailureKind != ovl_fail_bad_conversion)
13067 return;
13068
13069 // We only want the FixIts if all the arguments can be corrected.
13070 bool Unfixable = false;
13071 // Use a implicit copy initialization to check conversion fixes.
13072 Cand->Fix.setConversionChecker(TryCopyInitialization);
13073
13074 // Attempt to fix the bad conversion.
13075 unsigned ConvCount = Cand->Conversions.size();
13076 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
13077 ++ConvIdx) {
13078 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13079 if (Cand->Conversions[ConvIdx].isInitialized() &&
13080 Cand->Conversions[ConvIdx].isBad()) {
13081 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13082 break;
13083 }
13084 }
13085
13086 // FIXME: this should probably be preserved from the overload
13087 // operation somehow.
13088 bool SuppressUserConversions = false;
13089
13090 unsigned ConvIdx = 0;
13091 unsigned ArgIdx = 0;
13092 ArrayRef<QualType> ParamTypes;
13093 bool Reversed = Cand->isReversed();
13094
13095 if (Cand->IsSurrogate) {
13096 QualType ConvType
13097 = Cand->Surrogate->getConversionType().getNonReferenceType();
13098 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13099 ConvType = ConvPtrType->getPointeeType();
13100 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13101 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13102 ConvIdx = 1;
13103 } else if (Cand->Function) {
13104 ParamTypes =
13105 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13106 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13107 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed) {
13108 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13109 ConvIdx = 1;
13110 if (CSK == OverloadCandidateSet::CSK_Operator &&
13111 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13112 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13113 OO_Subscript)
13114 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13115 ArgIdx = 1;
13116 }
13117 } else {
13118 // Builtin operator.
13119 assert(ConvCount <= 3);
13120 ParamTypes = Cand->BuiltinParamTypes;
13121 }
13122
13123 // Fill in the rest of the conversions.
13124 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13125 ConvIdx != ConvCount;
13126 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13127 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
13128 if (Cand->Conversions[ConvIdx].isInitialized()) {
13129 // We've already checked this conversion.
13130 } else if (ParamIdx < ParamTypes.size()) {
13131 if (ParamTypes[ParamIdx]->isDependentType())
13132 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13133 Args[ArgIdx]->getType());
13134 else {
13135 Cand->Conversions[ConvIdx] =
13136 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13137 SuppressUserConversions,
13138 /*InOverloadResolution=*/true,
13139 /*AllowObjCWritebackConversion=*/
13140 S.getLangOpts().ObjCAutoRefCount);
13141 // Store the FixIt in the candidate if it exists.
13142 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13143 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13144 }
13145 } else
13146 Cand->Conversions[ConvIdx].setEllipsis();
13147 }
13148}
13149
13150SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13151 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13152 SourceLocation OpLoc,
13153 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13154
13155 InjectNonDeducedTemplateCandidates(S);
13156
13157 // Sort the candidates by viability and position. Sorting directly would
13158 // be prohibitive, so we make a set of pointers and sort those.
13159 SmallVector<OverloadCandidate*, 32> Cands;
13160 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13161 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13162 Cand != LastCand; ++Cand) {
13163 if (!Filter(*Cand))
13164 continue;
13165 switch (OCD) {
13166 case OCD_AllCandidates:
13167 if (!Cand->Viable) {
13168 if (!Cand->Function && !Cand->IsSurrogate) {
13169 // This a non-viable builtin candidate. We do not, in general,
13170 // want to list every possible builtin candidate.
13171 continue;
13172 }
13173 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13174 }
13175 break;
13176
13177 case OCD_ViableCandidates:
13178 if (!Cand->Viable)
13179 continue;
13180 break;
13181
13182 case OCD_AmbiguousCandidates:
13183 if (!Cand->Best)
13184 continue;
13185 break;
13186 }
13187
13188 Cands.push_back(Elt: Cand);
13189 }
13190
13191 llvm::stable_sort(
13192 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13193
13194 return Cands;
13195}
13196
13197bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13198 SourceLocation OpLoc) {
13199 bool DeferHint = false;
13200 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13201 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13202 // host device candidates.
13203 auto WrongSidedCands =
13204 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13205 return (Cand.Viable == false &&
13206 Cand.FailureKind == ovl_fail_bad_target) ||
13207 (Cand.Function &&
13208 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13209 Cand.Function->template hasAttr<CUDADeviceAttr>());
13210 });
13211 DeferHint = !WrongSidedCands.empty();
13212 }
13213 return DeferHint;
13214}
13215
13216/// When overload resolution fails, prints diagnostic messages containing the
13217/// candidates in the candidate set.
13218void OverloadCandidateSet::NoteCandidates(
13219 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13220 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13221 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13222
13223 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13224
13225 S.Diag(Loc: PD.first, PD: PD.second, DeferHint: shouldDeferDiags(S, Args, OpLoc));
13226
13227 // In WebAssembly we don't want to emit further diagnostics if a table is
13228 // passed as an argument to a function.
13229 bool NoteCands = true;
13230 for (const Expr *Arg : Args) {
13231 if (Arg->getType()->isWebAssemblyTableType())
13232 NoteCands = false;
13233 }
13234
13235 if (NoteCands)
13236 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13237
13238 if (OCD == OCD_AmbiguousCandidates)
13239 MaybeDiagnoseAmbiguousConstraints(S,
13240 Cands: {Candidates.begin(), Candidates.end()});
13241}
13242
13243void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13244 ArrayRef<OverloadCandidate *> Cands,
13245 StringRef Opc, SourceLocation OpLoc) {
13246 bool ReportedAmbiguousConversions = false;
13247
13248 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13249 unsigned CandsShown = 0;
13250 auto I = Cands.begin(), E = Cands.end();
13251 for (; I != E; ++I) {
13252 OverloadCandidate *Cand = *I;
13253
13254 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13255 ShowOverloads == Ovl_Best) {
13256 break;
13257 }
13258 ++CandsShown;
13259
13260 if (Cand->Function)
13261 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13262 /*TakingCandidateAddress=*/false, CtorDestAS: DestAS);
13263 else if (Cand->IsSurrogate)
13264 NoteSurrogateCandidate(S, Cand);
13265 else {
13266 assert(Cand->Viable &&
13267 "Non-viable built-in candidates are not added to Cands.");
13268 // Generally we only see ambiguities including viable builtin
13269 // operators if overload resolution got screwed up by an
13270 // ambiguous user-defined conversion.
13271 //
13272 // FIXME: It's quite possible for different conversions to see
13273 // different ambiguities, though.
13274 if (!ReportedAmbiguousConversions) {
13275 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13276 ReportedAmbiguousConversions = true;
13277 }
13278
13279 // If this is a viable builtin, print it.
13280 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13281 }
13282 }
13283
13284 // Inform S.Diags that we've shown an overload set with N elements. This may
13285 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13286 S.Diags.overloadCandidatesShown(N: CandsShown);
13287
13288 if (I != E)
13289 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates,
13290 DeferHint: shouldDeferDiags(S, Args, OpLoc))
13291 << int(E - I);
13292}
13293
13294static SourceLocation
13295GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13296 return Cand->Specialization ? Cand->Specialization->getLocation()
13297 : SourceLocation();
13298}
13299
13300namespace {
13301struct CompareTemplateSpecCandidatesForDisplay {
13302 Sema &S;
13303 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13304
13305 bool operator()(const TemplateSpecCandidate *L,
13306 const TemplateSpecCandidate *R) {
13307 // Fast-path this check.
13308 if (L == R)
13309 return false;
13310
13311 // Assuming that both candidates are not matches...
13312
13313 // Sort by the ranking of deduction failures.
13314 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13315 return RankDeductionFailure(DFI: L->DeductionFailure) <
13316 RankDeductionFailure(DFI: R->DeductionFailure);
13317
13318 // Sort everything else by location.
13319 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13320 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13321
13322 // Put candidates without locations (e.g. builtins) at the end.
13323 if (LLoc.isInvalid())
13324 return false;
13325 if (RLoc.isInvalid())
13326 return true;
13327
13328 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13329 }
13330};
13331}
13332
13333/// Diagnose a template argument deduction failure.
13334/// We are treating these failures as overload failures due to bad
13335/// deductions.
13336void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13337 bool ForTakingAddress) {
13338 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13339 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13340}
13341
13342void TemplateSpecCandidateSet::destroyCandidates() {
13343 for (iterator i = begin(), e = end(); i != e; ++i) {
13344 i->DeductionFailure.Destroy();
13345 }
13346}
13347
13348void TemplateSpecCandidateSet::clear() {
13349 destroyCandidates();
13350 Candidates.clear();
13351}
13352
13353/// NoteCandidates - When no template specialization match is found, prints
13354/// diagnostic messages containing the non-matching specializations that form
13355/// the candidate set.
13356/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13357/// OCD == OCD_AllCandidates and Cand->Viable == false.
13358void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13359 // Sort the candidates by position (assuming no candidate is a match).
13360 // Sorting directly would be prohibitive, so we make a set of pointers
13361 // and sort those.
13362 SmallVector<TemplateSpecCandidate *, 32> Cands;
13363 Cands.reserve(N: size());
13364 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13365 if (Cand->Specialization)
13366 Cands.push_back(Elt: Cand);
13367 // Otherwise, this is a non-matching builtin candidate. We do not,
13368 // in general, want to list every possible builtin candidate.
13369 }
13370
13371 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13372
13373 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13374 // for generalization purposes (?).
13375 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13376
13377 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13378 unsigned CandsShown = 0;
13379 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13380 TemplateSpecCandidate *Cand = *I;
13381
13382 // Set an arbitrary limit on the number of candidates we'll spam
13383 // the user with. FIXME: This limit should depend on details of the
13384 // candidate list.
13385 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13386 break;
13387 ++CandsShown;
13388
13389 assert(Cand->Specialization &&
13390 "Non-matching built-in candidates are not added to Cands.");
13391 Cand->NoteDeductionFailure(S, ForTakingAddress);
13392 }
13393
13394 if (I != E)
13395 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13396}
13397
13398// [PossiblyAFunctionType] --> [Return]
13399// NonFunctionType --> NonFunctionType
13400// R (A) --> R(A)
13401// R (*)(A) --> R (A)
13402// R (&)(A) --> R (A)
13403// R (S::*)(A) --> R (A)
13404QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13405 QualType Ret = PossiblyAFunctionType;
13406 if (const PointerType *ToTypePtr =
13407 PossiblyAFunctionType->getAs<PointerType>())
13408 Ret = ToTypePtr->getPointeeType();
13409 else if (const ReferenceType *ToTypeRef =
13410 PossiblyAFunctionType->getAs<ReferenceType>())
13411 Ret = ToTypeRef->getPointeeType();
13412 else if (const MemberPointerType *MemTypePtr =
13413 PossiblyAFunctionType->getAs<MemberPointerType>())
13414 Ret = MemTypePtr->getPointeeType();
13415 Ret =
13416 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13417 return Ret;
13418}
13419
13420static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13421 bool Complain = true) {
13422 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13423 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13424 return true;
13425
13426 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13427 if (S.getLangOpts().CPlusPlus17 &&
13428 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13429 !S.ResolveExceptionSpec(Loc, FPT))
13430 return true;
13431
13432 return false;
13433}
13434
13435namespace {
13436// A helper class to help with address of function resolution
13437// - allows us to avoid passing around all those ugly parameters
13438class AddressOfFunctionResolver {
13439 Sema& S;
13440 Expr* SourceExpr;
13441 const QualType& TargetType;
13442 QualType TargetFunctionType; // Extracted function type from target type
13443
13444 bool Complain;
13445 //DeclAccessPair& ResultFunctionAccessPair;
13446 ASTContext& Context;
13447
13448 bool TargetTypeIsNonStaticMemberFunction;
13449 bool FoundNonTemplateFunction;
13450 bool StaticMemberFunctionFromBoundPointer;
13451 bool HasComplained;
13452
13453 OverloadExpr::FindResult OvlExprInfo;
13454 OverloadExpr *OvlExpr;
13455 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13456 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13457 TemplateSpecCandidateSet FailedCandidates;
13458
13459public:
13460 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13461 const QualType &TargetType, bool Complain)
13462 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13463 Complain(Complain), Context(S.getASTContext()),
13464 TargetTypeIsNonStaticMemberFunction(
13465 !!TargetType->getAs<MemberPointerType>()),
13466 FoundNonTemplateFunction(false),
13467 StaticMemberFunctionFromBoundPointer(false),
13468 HasComplained(false),
13469 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13470 OvlExpr(OvlExprInfo.Expression),
13471 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13472 ExtractUnqualifiedFunctionTypeFromTargetType();
13473
13474 if (TargetFunctionType->isFunctionType()) {
13475 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13476 if (!UME->isImplicitAccess() &&
13477 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13478 StaticMemberFunctionFromBoundPointer = true;
13479 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13480 DeclAccessPair dap;
13481 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13482 ovl: OvlExpr, Complain: false, Found: &dap)) {
13483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13484 if (!Method->isStatic()) {
13485 // If the target type is a non-function type and the function found
13486 // is a non-static member function, pretend as if that was the
13487 // target, it's the only possible type to end up with.
13488 TargetTypeIsNonStaticMemberFunction = true;
13489
13490 // And skip adding the function if its not in the proper form.
13491 // We'll diagnose this due to an empty set of functions.
13492 if (!OvlExprInfo.HasFormOfMemberPointer)
13493 return;
13494 }
13495
13496 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13497 }
13498 return;
13499 }
13500
13501 if (OvlExpr->hasExplicitTemplateArgs())
13502 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13503
13504 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13505 // C++ [over.over]p4:
13506 // If more than one function is selected, [...]
13507 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13508 if (FoundNonTemplateFunction) {
13509 EliminateAllTemplateMatches();
13510 EliminateLessPartialOrderingConstrainedMatches();
13511 } else
13512 EliminateAllExceptMostSpecializedTemplate();
13513 }
13514 }
13515
13516 if (S.getLangOpts().CUDA && Matches.size() > 1)
13517 EliminateSuboptimalCudaMatches();
13518 }
13519
13520 bool hasComplained() const { return HasComplained; }
13521
13522private:
13523 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13524 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13525 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13526 }
13527
13528 /// \return true if A is considered a better overload candidate for the
13529 /// desired type than B.
13530 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13531 // If A doesn't have exactly the correct type, we don't want to classify it
13532 // as "better" than anything else. This way, the user is required to
13533 // disambiguate for us if there are multiple candidates and no exact match.
13534 return candidateHasExactlyCorrectType(FD: A) &&
13535 (!candidateHasExactlyCorrectType(FD: B) ||
13536 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13537 }
13538
13539 /// \return true if we were able to eliminate all but one overload candidate,
13540 /// false otherwise.
13541 bool eliminiateSuboptimalOverloadCandidates() {
13542 // Same algorithm as overload resolution -- one pass to pick the "best",
13543 // another pass to be sure that nothing is better than the best.
13544 auto Best = Matches.begin();
13545 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13546 if (isBetterCandidate(A: I->second, B: Best->second))
13547 Best = I;
13548
13549 const FunctionDecl *BestFn = Best->second;
13550 auto IsBestOrInferiorToBest = [this, BestFn](
13551 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13552 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13553 };
13554
13555 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13556 // option, so we can potentially give the user a better error
13557 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13558 return false;
13559 Matches[0] = *Best;
13560 Matches.resize(N: 1);
13561 return true;
13562 }
13563
13564 bool isTargetTypeAFunction() const {
13565 return TargetFunctionType->isFunctionType();
13566 }
13567
13568 // [ToType] [Return]
13569
13570 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13571 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13572 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13573 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13574 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13575 }
13576
13577 // return true if any matching specializations were found
13578 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13579 const DeclAccessPair& CurAccessFunPair) {
13580 if (CXXMethodDecl *Method
13581 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13582 // Skip non-static function templates when converting to pointer, and
13583 // static when converting to member pointer.
13584 bool CanConvertToFunctionPointer =
13585 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13586 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13587 return false;
13588 }
13589 else if (TargetTypeIsNonStaticMemberFunction)
13590 return false;
13591
13592 // C++ [over.over]p2:
13593 // If the name is a function template, template argument deduction is
13594 // done (14.8.2.2), and if the argument deduction succeeds, the
13595 // resulting template argument list is used to generate a single
13596 // function template specialization, which is added to the set of
13597 // overloaded functions considered.
13598 FunctionDecl *Specialization = nullptr;
13599 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13600 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13601 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13602 Specialization, Info, /*IsAddressOfFunction*/ true);
13603 Result != TemplateDeductionResult::Success) {
13604 // Make a note of the failed deduction for diagnostics.
13605 FailedCandidates.addCandidate()
13606 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13607 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13608 return false;
13609 }
13610
13611 // Template argument deduction ensures that we have an exact match or
13612 // compatible pointer-to-function arguments that would be adjusted by ICS.
13613 // This function template specicalization works.
13614 assert(S.isSameOrCompatibleFunctionType(
13615 Context.getCanonicalType(Specialization->getType()),
13616 Context.getCanonicalType(TargetFunctionType)));
13617
13618 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13619 return false;
13620
13621 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13622 return true;
13623 }
13624
13625 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13626 const DeclAccessPair& CurAccessFunPair) {
13627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13628 // Skip non-static functions when converting to pointer, and static
13629 // when converting to member pointer.
13630 bool CanConvertToFunctionPointer =
13631 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13632 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13633 return false;
13634 }
13635 else if (TargetTypeIsNonStaticMemberFunction)
13636 return false;
13637
13638 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13639 if (S.getLangOpts().CUDA) {
13640 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13641 if (!(Caller && Caller->isImplicit()) &&
13642 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13643 return false;
13644 }
13645 if (FunDecl->isMultiVersion()) {
13646 const auto *TA = FunDecl->getAttr<TargetAttr>();
13647 if (TA && !TA->isDefaultVersion())
13648 return false;
13649 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13650 if (TVA && !TVA->isDefaultVersion())
13651 return false;
13652 }
13653
13654 // If any candidate has a placeholder return type, trigger its deduction
13655 // now.
13656 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13657 Complain)) {
13658 HasComplained |= Complain;
13659 return false;
13660 }
13661
13662 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13663 return false;
13664
13665 // If we're in C, we need to support types that aren't exactly identical.
13666 if (!S.getLangOpts().CPlusPlus ||
13667 candidateHasExactlyCorrectType(FD: FunDecl)) {
13668 Matches.push_back(Elt: std::make_pair(
13669 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13670 FoundNonTemplateFunction = true;
13671 return true;
13672 }
13673 }
13674
13675 return false;
13676 }
13677
13678 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13679 bool Ret = false;
13680
13681 // If the overload expression doesn't have the form of a pointer to
13682 // member, don't try to convert it to a pointer-to-member type.
13683 if (IsInvalidFormOfPointerToMemberFunction())
13684 return false;
13685
13686 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13687 E = OvlExpr->decls_end();
13688 I != E; ++I) {
13689 // Look through any using declarations to find the underlying function.
13690 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13691
13692 // C++ [over.over]p3:
13693 // Non-member functions and static member functions match
13694 // targets of type "pointer-to-function" or "reference-to-function."
13695 // Nonstatic member functions match targets of
13696 // type "pointer-to-member-function."
13697 // Note that according to DR 247, the containing class does not matter.
13698 if (FunctionTemplateDecl *FunctionTemplate
13699 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13700 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13701 Ret = true;
13702 }
13703 // If we have explicit template arguments supplied, skip non-templates.
13704 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13705 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13706 Ret = true;
13707 }
13708 assert(Ret || Matches.empty());
13709 return Ret;
13710 }
13711
13712 void EliminateAllExceptMostSpecializedTemplate() {
13713 // [...] and any given function template specialization F1 is
13714 // eliminated if the set contains a second function template
13715 // specialization whose function template is more specialized
13716 // than the function template of F1 according to the partial
13717 // ordering rules of 14.5.5.2.
13718
13719 // The algorithm specified above is quadratic. We instead use a
13720 // two-pass algorithm (similar to the one used to identify the
13721 // best viable function in an overload set) that identifies the
13722 // best function template (if it exists).
13723
13724 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13725 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13726 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13727
13728 // TODO: It looks like FailedCandidates does not serve much purpose
13729 // here, since the no_viable diagnostic has index 0.
13730 UnresolvedSetIterator Result = S.getMostSpecialized(
13731 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
13732 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
13733 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
13734 << Matches[0].second->getDeclName(),
13735 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
13736 << (unsigned)oc_function << (unsigned)ocs_described_template,
13737 Complain, TargetType: TargetFunctionType);
13738
13739 if (Result != MatchesCopy.end()) {
13740 // Make it the first and only element
13741 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13742 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13743 Matches.resize(N: 1);
13744 } else
13745 HasComplained |= Complain;
13746 }
13747
13748 void EliminateAllTemplateMatches() {
13749 // [...] any function template specializations in the set are
13750 // eliminated if the set also contains a non-template function, [...]
13751 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13752 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13753 ++I;
13754 else {
13755 Matches[I] = Matches[--N];
13756 Matches.resize(N);
13757 }
13758 }
13759 }
13760
13761 void EliminateLessPartialOrderingConstrainedMatches() {
13762 // C++ [over.over]p5:
13763 // [...] Any given non-template function F0 is eliminated if the set
13764 // contains a second non-template function that is more
13765 // partial-ordering-constrained than F0. [...]
13766 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13767 "Call EliminateAllTemplateMatches() first");
13768 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13769 Results.push_back(Elt: Matches[0]);
13770 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13771 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13772 FunctionDecl *F = getMorePartialOrderingConstrained(
13773 S, Fn1: Matches[I].second, Fn2: Results[0].second,
13774 /*IsFn1Reversed=*/false,
13775 /*IsFn2Reversed=*/false);
13776 if (!F) {
13777 Results.push_back(Elt: Matches[I]);
13778 continue;
13779 }
13780 if (F == Matches[I].second) {
13781 Results.clear();
13782 Results.push_back(Elt: Matches[I]);
13783 }
13784 }
13785 std::swap(LHS&: Matches, RHS&: Results);
13786 }
13787
13788 void EliminateSuboptimalCudaMatches() {
13789 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
13790 Matches);
13791 }
13792
13793public:
13794 void ComplainNoMatchesFound() const {
13795 assert(Matches.empty());
13796 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
13797 << OvlExpr->getName() << TargetFunctionType
13798 << OvlExpr->getSourceRange();
13799 if (FailedCandidates.empty())
13800 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13801 /*TakingAddress=*/true);
13802 else {
13803 // We have some deduction failure messages. Use them to diagnose
13804 // the function templates, and diagnose the non-template candidates
13805 // normally.
13806 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13807 IEnd = OvlExpr->decls_end();
13808 I != IEnd; ++I)
13809 if (FunctionDecl *Fun =
13810 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
13811 if (!functionHasPassObjectSizeParams(FD: Fun))
13812 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
13813 /*TakingAddress=*/true);
13814 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
13815 }
13816 }
13817
13818 bool IsInvalidFormOfPointerToMemberFunction() const {
13819 return TargetTypeIsNonStaticMemberFunction &&
13820 !OvlExprInfo.HasFormOfMemberPointer;
13821 }
13822
13823 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13824 // TODO: Should we condition this on whether any functions might
13825 // have matched, or is it more appropriate to do that in callers?
13826 // TODO: a fixit wouldn't hurt.
13827 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
13828 << TargetType << OvlExpr->getSourceRange();
13829 }
13830
13831 bool IsStaticMemberFunctionFromBoundPointer() const {
13832 return StaticMemberFunctionFromBoundPointer;
13833 }
13834
13835 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13836 S.Diag(Loc: OvlExpr->getBeginLoc(),
13837 DiagID: diag::err_invalid_form_pointer_member_function)
13838 << OvlExpr->getSourceRange();
13839 }
13840
13841 void ComplainOfInvalidConversion() const {
13842 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
13843 << OvlExpr->getName() << TargetType;
13844 }
13845
13846 void ComplainMultipleMatchesFound() const {
13847 assert(Matches.size() > 1);
13848 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
13849 << OvlExpr->getName() << OvlExpr->getSourceRange();
13850 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13851 /*TakingAddress=*/true);
13852 }
13853
13854 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13855
13856 int getNumMatches() const { return Matches.size(); }
13857
13858 FunctionDecl* getMatchingFunctionDecl() const {
13859 if (Matches.size() != 1) return nullptr;
13860 return Matches[0].second;
13861 }
13862
13863 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13864 if (Matches.size() != 1) return nullptr;
13865 return &Matches[0].first;
13866 }
13867};
13868}
13869
13870FunctionDecl *
13871Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13872 QualType TargetType,
13873 bool Complain,
13874 DeclAccessPair &FoundResult,
13875 bool *pHadMultipleCandidates) {
13876 assert(AddressOfExpr->getType() == Context.OverloadTy);
13877
13878 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13879 Complain);
13880 int NumMatches = Resolver.getNumMatches();
13881 FunctionDecl *Fn = nullptr;
13882 bool ShouldComplain = Complain && !Resolver.hasComplained();
13883 if (NumMatches == 0 && ShouldComplain) {
13884 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13885 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13886 else
13887 Resolver.ComplainNoMatchesFound();
13888 }
13889 else if (NumMatches > 1 && ShouldComplain)
13890 Resolver.ComplainMultipleMatchesFound();
13891 else if (NumMatches == 1) {
13892 Fn = Resolver.getMatchingFunctionDecl();
13893 assert(Fn);
13894 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13895 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
13896 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13897 if (Complain) {
13898 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13899 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13900 else
13901 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
13902 }
13903 }
13904
13905 if (pHadMultipleCandidates)
13906 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13907 return Fn;
13908}
13909
13910FunctionDecl *
13911Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13912 OverloadExpr::FindResult R = OverloadExpr::find(E);
13913 OverloadExpr *Ovl = R.Expression;
13914 bool IsResultAmbiguous = false;
13915 FunctionDecl *Result = nullptr;
13916 DeclAccessPair DAP;
13917 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13918
13919 // Return positive for better, negative for worse, 0 for equal preference.
13920 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13921 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13922 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
13923 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
13924 };
13925
13926 // Don't use the AddressOfResolver because we're specifically looking for
13927 // cases where we have one overload candidate that lacks
13928 // enable_if/pass_object_size/...
13929 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13930 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
13931 if (!FD)
13932 return nullptr;
13933
13934 if (!checkAddressOfFunctionIsAvailable(Function: FD))
13935 continue;
13936
13937 // If we found a better result, update Result.
13938 auto FoundBetter = [&]() {
13939 IsResultAmbiguous = false;
13940 DAP = I.getPair();
13941 Result = FD;
13942 };
13943
13944 // We have more than one result - see if it is more
13945 // partial-ordering-constrained than the previous one.
13946 if (Result) {
13947 // Check CUDA preference first. If the candidates have differennt CUDA
13948 // preference, choose the one with higher CUDA preference. Otherwise,
13949 // choose the one with more constraints.
13950 if (getLangOpts().CUDA) {
13951 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13952 // FD has different preference than Result.
13953 if (PreferenceByCUDA != 0) {
13954 // FD is more preferable than Result.
13955 if (PreferenceByCUDA > 0)
13956 FoundBetter();
13957 continue;
13958 }
13959 }
13960 // FD has the same CUDA preference than Result. Continue to check
13961 // constraints.
13962
13963 // C++ [over.over]p5:
13964 // [...] Any given non-template function F0 is eliminated if the set
13965 // contains a second non-template function that is more
13966 // partial-ordering-constrained than F0 [...]
13967 FunctionDecl *MoreConstrained =
13968 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
13969 /*IsFn1Reversed=*/false,
13970 /*IsFn2Reversed=*/false);
13971 if (MoreConstrained != FD) {
13972 if (!MoreConstrained) {
13973 IsResultAmbiguous = true;
13974 AmbiguousDecls.push_back(Elt: FD);
13975 }
13976 continue;
13977 }
13978 // FD is more constrained - replace Result with it.
13979 }
13980 FoundBetter();
13981 }
13982
13983 if (IsResultAmbiguous)
13984 return nullptr;
13985
13986 if (Result) {
13987 // We skipped over some ambiguous declarations which might be ambiguous with
13988 // the selected result.
13989 for (FunctionDecl *Skipped : AmbiguousDecls) {
13990 // If skipped candidate has different CUDA preference than the result,
13991 // there is no ambiguity. Otherwise check whether they have different
13992 // constraints.
13993 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13994 continue;
13995 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
13996 return nullptr;
13997 }
13998 Pair = DAP;
13999 }
14000 return Result;
14001}
14002
14003bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14004 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14005 Expr *E = SrcExpr.get();
14006 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14007
14008 DeclAccessPair DAP;
14009 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14010 if (!Found || Found->isCPUDispatchMultiVersion() ||
14011 Found->isCPUSpecificMultiVersion())
14012 return false;
14013
14014 // Emitting multiple diagnostics for a function that is both inaccessible and
14015 // unavailable is consistent with our behavior elsewhere. So, always check
14016 // for both.
14017 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14018 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14019 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14020 if (Res.isInvalid())
14021 return false;
14022 Expr *Fixed = Res.get();
14023 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14024 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14025 else
14026 SrcExpr = Fixed;
14027 return true;
14028}
14029
14030FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14031 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14032 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14033 // C++ [over.over]p1:
14034 // [...] [Note: any redundant set of parentheses surrounding the
14035 // overloaded function name is ignored (5.1). ]
14036 // C++ [over.over]p1:
14037 // [...] The overloaded function name can be preceded by the &
14038 // operator.
14039
14040 // If we didn't actually find any template-ids, we're done.
14041 if (!ovl->hasExplicitTemplateArgs())
14042 return nullptr;
14043
14044 TemplateArgumentListInfo ExplicitTemplateArgs;
14045 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14046
14047 // Look through all of the overloaded functions, searching for one
14048 // whose type matches exactly.
14049 FunctionDecl *Matched = nullptr;
14050 for (UnresolvedSetIterator I = ovl->decls_begin(),
14051 E = ovl->decls_end(); I != E; ++I) {
14052 // C++0x [temp.arg.explicit]p3:
14053 // [...] In contexts where deduction is done and fails, or in contexts
14054 // where deduction is not done, if a template argument list is
14055 // specified and it, along with any default template arguments,
14056 // identifies a single function template specialization, then the
14057 // template-id is an lvalue for the function template specialization.
14058 FunctionTemplateDecl *FunctionTemplate =
14059 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14060 if (!FunctionTemplate)
14061 continue;
14062
14063 // C++ [over.over]p2:
14064 // If the name is a function template, template argument deduction is
14065 // done (14.8.2.2), and if the argument deduction succeeds, the
14066 // resulting template argument list is used to generate a single
14067 // function template specialization, which is added to the set of
14068 // overloaded functions considered.
14069 FunctionDecl *Specialization = nullptr;
14070 TemplateDeductionInfo Info(ovl->getNameLoc());
14071 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14072 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14073 /*IsAddressOfFunction*/ true);
14074 Result != TemplateDeductionResult::Success) {
14075 // Make a note of the failed deduction for diagnostics.
14076 if (FailedTSC)
14077 FailedTSC->addCandidate().set(
14078 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14079 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14080 continue;
14081 }
14082
14083 assert(Specialization && "no specialization and no error?");
14084
14085 // C++ [temp.deduct.call]p6:
14086 // [...] If all successful deductions yield the same deduced A, that
14087 // deduced A is the result of deduction; otherwise, the parameter is
14088 // treated as a non-deduced context.
14089 if (Matched) {
14090 if (ForTypeDeduction &&
14091 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14092 Arg: Specialization->getType()))
14093 continue;
14094 // Multiple matches; we can't resolve to a single declaration.
14095 if (Complain) {
14096 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14097 << ovl->getName();
14098 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14099 }
14100 return nullptr;
14101 }
14102
14103 Matched = Specialization;
14104 if (FoundResult) *FoundResult = I.getPair();
14105 }
14106
14107 if (Matched &&
14108 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14109 return nullptr;
14110
14111 return Matched;
14112}
14113
14114bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14115 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14116 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14117 unsigned DiagIDForComplaining) {
14118 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14119
14120 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14121
14122 DeclAccessPair found;
14123 ExprResult SingleFunctionExpression;
14124 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14125 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14126 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14127 SrcExpr = ExprError();
14128 return true;
14129 }
14130
14131 // It is only correct to resolve to an instance method if we're
14132 // resolving a form that's permitted to be a pointer to member.
14133 // Otherwise we'll end up making a bound member expression, which
14134 // is illegal in all the contexts we resolve like this.
14135 if (!ovl.HasFormOfMemberPointer &&
14136 isa<CXXMethodDecl>(Val: fn) &&
14137 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14138 if (!complain) return false;
14139
14140 Diag(Loc: ovl.Expression->getExprLoc(),
14141 DiagID: diag::err_bound_member_function)
14142 << 0 << ovl.Expression->getSourceRange();
14143
14144 // TODO: I believe we only end up here if there's a mix of
14145 // static and non-static candidates (otherwise the expression
14146 // would have 'bound member' type, not 'overload' type).
14147 // Ideally we would note which candidate was chosen and why
14148 // the static candidates were rejected.
14149 SrcExpr = ExprError();
14150 return true;
14151 }
14152
14153 // Fix the expression to refer to 'fn'.
14154 SingleFunctionExpression =
14155 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14156
14157 // If desired, do function-to-pointer decay.
14158 if (doFunctionPointerConversion) {
14159 SingleFunctionExpression =
14160 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14161 if (SingleFunctionExpression.isInvalid()) {
14162 SrcExpr = ExprError();
14163 return true;
14164 }
14165 }
14166 }
14167
14168 if (!SingleFunctionExpression.isUsable()) {
14169 if (complain) {
14170 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14171 << ovl.Expression->getName()
14172 << DestTypeForComplaining
14173 << OpRangeForComplaining
14174 << ovl.Expression->getQualifierLoc().getSourceRange();
14175 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14176
14177 SrcExpr = ExprError();
14178 return true;
14179 }
14180
14181 return false;
14182 }
14183
14184 SrcExpr = SingleFunctionExpression;
14185 return true;
14186}
14187
14188/// Add a single candidate to the overload set.
14189static void AddOverloadedCallCandidate(Sema &S,
14190 DeclAccessPair FoundDecl,
14191 TemplateArgumentListInfo *ExplicitTemplateArgs,
14192 ArrayRef<Expr *> Args,
14193 OverloadCandidateSet &CandidateSet,
14194 bool PartialOverloading,
14195 bool KnownValid) {
14196 NamedDecl *Callee = FoundDecl.getDecl();
14197 if (isa<UsingShadowDecl>(Val: Callee))
14198 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14199
14200 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14201 if (ExplicitTemplateArgs) {
14202 assert(!KnownValid && "Explicit template arguments?");
14203 return;
14204 }
14205 // Prevent ill-formed function decls to be added as overload candidates.
14206 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14207 return;
14208
14209 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14210 /*SuppressUserConversions=*/false,
14211 PartialOverloading);
14212 return;
14213 }
14214
14215 if (FunctionTemplateDecl *FuncTemplate
14216 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14217 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14218 ExplicitTemplateArgs, Args, CandidateSet,
14219 /*SuppressUserConversions=*/false,
14220 PartialOverloading);
14221 return;
14222 }
14223
14224 assert(!KnownValid && "unhandled case in overloaded call candidate");
14225}
14226
14227void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14228 ArrayRef<Expr *> Args,
14229 OverloadCandidateSet &CandidateSet,
14230 bool PartialOverloading) {
14231
14232#ifndef NDEBUG
14233 // Verify that ArgumentDependentLookup is consistent with the rules
14234 // in C++0x [basic.lookup.argdep]p3:
14235 //
14236 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14237 // and let Y be the lookup set produced by argument dependent
14238 // lookup (defined as follows). If X contains
14239 //
14240 // -- a declaration of a class member, or
14241 //
14242 // -- a block-scope function declaration that is not a
14243 // using-declaration, or
14244 //
14245 // -- a declaration that is neither a function or a function
14246 // template
14247 //
14248 // then Y is empty.
14249
14250 if (ULE->requiresADL()) {
14251 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14252 E = ULE->decls_end(); I != E; ++I) {
14253 assert(!(*I)->getDeclContext()->isRecord());
14254 assert(isa<UsingShadowDecl>(*I) ||
14255 !(*I)->getDeclContext()->isFunctionOrMethod());
14256 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14257 }
14258 }
14259#endif
14260
14261 // It would be nice to avoid this copy.
14262 TemplateArgumentListInfo TABuffer;
14263 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14264 if (ULE->hasExplicitTemplateArgs()) {
14265 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14266 ExplicitTemplateArgs = &TABuffer;
14267 }
14268
14269 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14270 E = ULE->decls_end(); I != E; ++I)
14271 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14272 CandidateSet, PartialOverloading,
14273 /*KnownValid*/ true);
14274
14275 if (ULE->requiresADL())
14276 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14277 Args, ExplicitTemplateArgs,
14278 CandidateSet, PartialOverloading);
14279}
14280
14281void Sema::AddOverloadedCallCandidates(
14282 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14283 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14284 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14285 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14286 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14287}
14288
14289/// Determine whether a declaration with the specified name could be moved into
14290/// a different namespace.
14291static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14292 switch (Name.getCXXOverloadedOperator()) {
14293 case OO_New: case OO_Array_New:
14294 case OO_Delete: case OO_Array_Delete:
14295 return false;
14296
14297 default:
14298 return true;
14299 }
14300}
14301
14302/// Attempt to recover from an ill-formed use of a non-dependent name in a
14303/// template, where the non-dependent name was declared after the template
14304/// was defined. This is common in code written for a compilers which do not
14305/// correctly implement two-stage name lookup.
14306///
14307/// Returns true if a viable candidate was found and a diagnostic was issued.
14308static bool DiagnoseTwoPhaseLookup(
14309 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14310 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14311 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14312 CXXRecordDecl **FoundInClass = nullptr) {
14313 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14314 return false;
14315
14316 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14317 if (DC->isTransparentContext())
14318 continue;
14319
14320 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14321
14322 if (!R.empty()) {
14323 R.suppressDiagnostics();
14324
14325 OverloadCandidateSet Candidates(FnLoc, CSK);
14326 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14327 CandidateSet&: Candidates);
14328
14329 OverloadCandidateSet::iterator Best;
14330 OverloadingResult OR =
14331 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14332
14333 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14334 // We either found non-function declarations or a best viable function
14335 // at class scope. A class-scope lookup result disables ADL. Don't
14336 // look past this, but let the caller know that we found something that
14337 // either is, or might be, usable in this class.
14338 if (FoundInClass) {
14339 *FoundInClass = RD;
14340 if (OR == OR_Success) {
14341 R.clear();
14342 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14343 R.resolveKind();
14344 }
14345 }
14346 return false;
14347 }
14348
14349 if (OR != OR_Success) {
14350 // There wasn't a unique best function or function template.
14351 return false;
14352 }
14353
14354 // Find the namespaces where ADL would have looked, and suggest
14355 // declaring the function there instead.
14356 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14357 Sema::AssociatedClassSet AssociatedClasses;
14358 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14359 AssociatedNamespaces,
14360 AssociatedClasses);
14361 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14362 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14363 DeclContext *Std = SemaRef.getStdNamespace();
14364 for (Sema::AssociatedNamespaceSet::iterator
14365 it = AssociatedNamespaces.begin(),
14366 end = AssociatedNamespaces.end(); it != end; ++it) {
14367 // Never suggest declaring a function within namespace 'std'.
14368 if (Std && Std->Encloses(DC: *it))
14369 continue;
14370
14371 // Never suggest declaring a function within a namespace with a
14372 // reserved name, like __gnu_cxx.
14373 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14374 if (NS &&
14375 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14376 continue;
14377
14378 SuggestedNamespaces.insert(X: *it);
14379 }
14380 }
14381
14382 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14383 << R.getLookupName();
14384 if (SuggestedNamespaces.empty()) {
14385 SemaRef.Diag(Loc: Best->Function->getLocation(),
14386 DiagID: diag::note_not_found_by_two_phase_lookup)
14387 << R.getLookupName() << 0;
14388 } else if (SuggestedNamespaces.size() == 1) {
14389 SemaRef.Diag(Loc: Best->Function->getLocation(),
14390 DiagID: diag::note_not_found_by_two_phase_lookup)
14391 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14392 } else {
14393 // FIXME: It would be useful to list the associated namespaces here,
14394 // but the diagnostics infrastructure doesn't provide a way to produce
14395 // a localized representation of a list of items.
14396 SemaRef.Diag(Loc: Best->Function->getLocation(),
14397 DiagID: diag::note_not_found_by_two_phase_lookup)
14398 << R.getLookupName() << 2;
14399 }
14400
14401 // Try to recover by calling this function.
14402 return true;
14403 }
14404
14405 R.clear();
14406 }
14407
14408 return false;
14409}
14410
14411/// Attempt to recover from ill-formed use of a non-dependent operator in a
14412/// template, where the non-dependent operator was declared after the template
14413/// was defined.
14414///
14415/// Returns true if a viable candidate was found and a diagnostic was issued.
14416static bool
14417DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14418 SourceLocation OpLoc,
14419 ArrayRef<Expr *> Args) {
14420 DeclarationName OpName =
14421 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14422 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14423 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14424 CSK: OverloadCandidateSet::CSK_Operator,
14425 /*ExplicitTemplateArgs=*/nullptr, Args);
14426}
14427
14428namespace {
14429class BuildRecoveryCallExprRAII {
14430 Sema &SemaRef;
14431 Sema::SatisfactionStackResetRAII SatStack;
14432
14433public:
14434 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14435 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14436 SemaRef.IsBuildingRecoveryCallExpr = true;
14437 }
14438
14439 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14440};
14441}
14442
14443/// Attempts to recover from a call where no functions were found.
14444///
14445/// This function will do one of three things:
14446/// * Diagnose, recover, and return a recovery expression.
14447/// * Diagnose, fail to recover, and return ExprError().
14448/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14449/// expected to diagnose as appropriate.
14450static ExprResult
14451BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14452 UnresolvedLookupExpr *ULE,
14453 SourceLocation LParenLoc,
14454 MutableArrayRef<Expr *> Args,
14455 SourceLocation RParenLoc,
14456 bool EmptyLookup, bool AllowTypoCorrection) {
14457 // Do not try to recover if it is already building a recovery call.
14458 // This stops infinite loops for template instantiations like
14459 //
14460 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14461 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14462 if (SemaRef.IsBuildingRecoveryCallExpr)
14463 return ExprResult();
14464 BuildRecoveryCallExprRAII RCE(SemaRef);
14465
14466 CXXScopeSpec SS;
14467 SS.Adopt(Other: ULE->getQualifierLoc());
14468 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14469
14470 TemplateArgumentListInfo TABuffer;
14471 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14472 if (ULE->hasExplicitTemplateArgs()) {
14473 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14474 ExplicitTemplateArgs = &TABuffer;
14475 }
14476
14477 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14478 Sema::LookupOrdinaryName);
14479 CXXRecordDecl *FoundInClass = nullptr;
14480 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14481 CSK: OverloadCandidateSet::CSK_Normal,
14482 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14483 // OK, diagnosed a two-phase lookup issue.
14484 } else if (EmptyLookup) {
14485 // Try to recover from an empty lookup with typo correction.
14486 R.clear();
14487 NoTypoCorrectionCCC NoTypoValidator{};
14488 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14489 ExplicitTemplateArgs != nullptr,
14490 dyn_cast<MemberExpr>(Val: Fn));
14491 CorrectionCandidateCallback &Validator =
14492 AllowTypoCorrection
14493 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14494 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14495 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14496 Args))
14497 return ExprError();
14498 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14499 // We found a usable declaration of the name in a dependent base of some
14500 // enclosing class.
14501 // FIXME: We should also explain why the candidates found by name lookup
14502 // were not viable.
14503 if (SemaRef.DiagnoseDependentMemberLookup(R))
14504 return ExprError();
14505 } else {
14506 // We had viable candidates and couldn't recover; let the caller diagnose
14507 // this.
14508 return ExprResult();
14509 }
14510
14511 // If we get here, we should have issued a diagnostic and formed a recovery
14512 // lookup result.
14513 assert(!R.empty() && "lookup results empty despite recovery");
14514
14515 // If recovery created an ambiguity, just bail out.
14516 if (R.isAmbiguous()) {
14517 R.suppressDiagnostics();
14518 return ExprError();
14519 }
14520
14521 // Build an implicit member call if appropriate. Just drop the
14522 // casts and such from the call, we don't really care.
14523 ExprResult NewFn = ExprError();
14524 if ((*R.begin())->isCXXClassMember())
14525 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14526 TemplateArgs: ExplicitTemplateArgs, S);
14527 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14528 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14529 TemplateArgs: ExplicitTemplateArgs);
14530 else
14531 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14532
14533 if (NewFn.isInvalid())
14534 return ExprError();
14535
14536 // This shouldn't cause an infinite loop because we're giving it
14537 // an expression with viable lookup results, which should never
14538 // end up here.
14539 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14540 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14541 RParenLoc);
14542}
14543
14544bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14545 UnresolvedLookupExpr *ULE,
14546 MultiExprArg Args,
14547 SourceLocation RParenLoc,
14548 OverloadCandidateSet *CandidateSet,
14549 ExprResult *Result) {
14550#ifndef NDEBUG
14551 if (ULE->requiresADL()) {
14552 // To do ADL, we must have found an unqualified name.
14553 assert(!ULE->getQualifier() && "qualified name with ADL");
14554
14555 // We don't perform ADL for implicit declarations of builtins.
14556 // Verify that this was correctly set up.
14557 FunctionDecl *F;
14558 if (ULE->decls_begin() != ULE->decls_end() &&
14559 ULE->decls_begin() + 1 == ULE->decls_end() &&
14560 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14561 F->getBuiltinID() && F->isImplicit())
14562 llvm_unreachable("performing ADL for builtin");
14563
14564 // We don't perform ADL in C.
14565 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14566 }
14567#endif
14568
14569 UnbridgedCastsSet UnbridgedCasts;
14570 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14571 *Result = ExprError();
14572 return true;
14573 }
14574
14575 // Add the functions denoted by the callee to the set of candidate
14576 // functions, including those from argument-dependent lookup.
14577 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14578
14579 if (getLangOpts().MSVCCompat &&
14580 CurContext->isDependentContext() && !isSFINAEContext() &&
14581 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14582
14583 OverloadCandidateSet::iterator Best;
14584 if (CandidateSet->empty() ||
14585 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14586 OR_No_Viable_Function) {
14587 // In Microsoft mode, if we are inside a template class member function
14588 // then create a type dependent CallExpr. The goal is to postpone name
14589 // lookup to instantiation time to be able to search into type dependent
14590 // base classes.
14591 CallExpr *CE =
14592 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14593 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14594 CE->markDependentForPostponedNameLookup();
14595 *Result = CE;
14596 return true;
14597 }
14598 }
14599
14600 if (CandidateSet->empty())
14601 return false;
14602
14603 UnbridgedCasts.restore();
14604 return false;
14605}
14606
14607// Guess at what the return type for an unresolvable overload should be.
14608static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14609 OverloadCandidateSet::iterator *Best) {
14610 std::optional<QualType> Result;
14611 // Adjust Type after seeing a candidate.
14612 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14613 if (!Candidate.Function)
14614 return;
14615 if (Candidate.Function->isInvalidDecl())
14616 return;
14617 QualType T = Candidate.Function->getReturnType();
14618 if (T.isNull())
14619 return;
14620 if (!Result)
14621 Result = T;
14622 else if (Result != T)
14623 Result = QualType();
14624 };
14625
14626 // Look for an unambiguous type from a progressively larger subset.
14627 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14628 //
14629 // First, consider only the best candidate.
14630 if (Best && *Best != CS.end())
14631 ConsiderCandidate(**Best);
14632 // Next, consider only viable candidates.
14633 if (!Result)
14634 for (const auto &C : CS)
14635 if (C.Viable)
14636 ConsiderCandidate(C);
14637 // Finally, consider all candidates.
14638 if (!Result)
14639 for (const auto &C : CS)
14640 ConsiderCandidate(C);
14641
14642 if (!Result)
14643 return QualType();
14644 auto Value = *Result;
14645 if (Value.isNull() || Value->isUndeducedType())
14646 return QualType();
14647 return Value;
14648}
14649
14650/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14651/// the completed call expression. If overload resolution fails, emits
14652/// diagnostics and returns ExprError()
14653static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14654 UnresolvedLookupExpr *ULE,
14655 SourceLocation LParenLoc,
14656 MultiExprArg Args,
14657 SourceLocation RParenLoc,
14658 Expr *ExecConfig,
14659 OverloadCandidateSet *CandidateSet,
14660 OverloadCandidateSet::iterator *Best,
14661 OverloadingResult OverloadResult,
14662 bool AllowTypoCorrection) {
14663 switch (OverloadResult) {
14664 case OR_Success: {
14665 FunctionDecl *FDecl = (*Best)->Function;
14666 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14667 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14668 return ExprError();
14669 ExprResult Res =
14670 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14671 if (Res.isInvalid())
14672 return ExprError();
14673 return SemaRef.BuildResolvedCallExpr(
14674 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14675 /*IsExecConfig=*/false,
14676 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14677 }
14678
14679 case OR_No_Viable_Function: {
14680 if (*Best != CandidateSet->end() &&
14681 CandidateSet->getKind() ==
14682 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14683 if (CXXMethodDecl *M =
14684 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14685 M && M->isImplicitObjectMemberFunction()) {
14686 CandidateSet->NoteCandidates(
14687 PD: PartialDiagnosticAt(
14688 Fn->getBeginLoc(),
14689 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14690 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14691 return ExprError();
14692 }
14693 }
14694
14695 // Try to recover by looking for viable functions which the user might
14696 // have meant to call.
14697 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14698 Args, RParenLoc,
14699 EmptyLookup: CandidateSet->empty(),
14700 AllowTypoCorrection);
14701 if (Recovery.isInvalid() || Recovery.isUsable())
14702 return Recovery;
14703
14704 // If the user passes in a function that we can't take the address of, we
14705 // generally end up emitting really bad error messages. Here, we attempt to
14706 // emit better ones.
14707 for (const Expr *Arg : Args) {
14708 if (!Arg->getType()->isFunctionType())
14709 continue;
14710 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14711 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14712 if (FD &&
14713 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14714 Loc: Arg->getExprLoc()))
14715 return ExprError();
14716 }
14717 }
14718
14719 CandidateSet->NoteCandidates(
14720 PD: PartialDiagnosticAt(
14721 Fn->getBeginLoc(),
14722 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
14723 << ULE->getName() << Fn->getSourceRange()),
14724 S&: SemaRef, OCD: OCD_AllCandidates, Args);
14725 break;
14726 }
14727
14728 case OR_Ambiguous:
14729 CandidateSet->NoteCandidates(
14730 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
14731 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
14732 << ULE->getName() << Fn->getSourceRange()),
14733 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14734 break;
14735
14736 case OR_Deleted: {
14737 FunctionDecl *FDecl = (*Best)->Function;
14738 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14739 Range: Fn->getSourceRange(), Name: ULE->getName(),
14740 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14741
14742 // We emitted an error for the unavailable/deleted function call but keep
14743 // the call in the AST.
14744 ExprResult Res =
14745 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14746 if (Res.isInvalid())
14747 return ExprError();
14748 return SemaRef.BuildResolvedCallExpr(
14749 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14750 /*IsExecConfig=*/false,
14751 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14752 }
14753 }
14754
14755 // Overload resolution failed, try to recover.
14756 SmallVector<Expr *, 8> SubExprs = {Fn};
14757 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14758 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14759 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14760}
14761
14762static void markUnaddressableCandidatesUnviable(Sema &S,
14763 OverloadCandidateSet &CS) {
14764 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14765 if (I->Viable &&
14766 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14767 I->Viable = false;
14768 I->FailureKind = ovl_fail_addr_not_available;
14769 }
14770 }
14771}
14772
14773ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14774 UnresolvedLookupExpr *ULE,
14775 SourceLocation LParenLoc,
14776 MultiExprArg Args,
14777 SourceLocation RParenLoc,
14778 Expr *ExecConfig,
14779 bool AllowTypoCorrection,
14780 bool CalleesAddressIsTaken) {
14781
14782 OverloadCandidateSet::CandidateSetKind CSK =
14783 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14784 : OverloadCandidateSet::CSK_Normal;
14785
14786 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14787 ExprResult result;
14788
14789 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
14790 Result: &result))
14791 return result;
14792
14793 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14794 // functions that aren't addressible are considered unviable.
14795 if (CalleesAddressIsTaken)
14796 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
14797
14798 OverloadCandidateSet::iterator Best;
14799 OverloadingResult OverloadResult =
14800 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
14801
14802 // [C++23][over.call.func]
14803 // if overload resolution selects a non-static member function,
14804 // the call is ill-formed;
14805 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
14806 Best != CandidateSet.end()) {
14807 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
14808 M && M->isImplicitObjectMemberFunction()) {
14809 OverloadResult = OR_No_Viable_Function;
14810 }
14811 }
14812
14813 // Model the case with a call to a templated function whose definition
14814 // encloses the call and whose return type contains a placeholder type as if
14815 // the UnresolvedLookupExpr was type-dependent.
14816 if (OverloadResult == OR_Success) {
14817 const FunctionDecl *FDecl = Best->Function;
14818 if (LangOpts.CUDA)
14819 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14820 if (FDecl && FDecl->isTemplateInstantiation() &&
14821 FDecl->getReturnType()->isUndeducedType()) {
14822
14823 // Creating dependent CallExpr is not okay if the enclosing context itself
14824 // is not dependent. This situation notably arises if a non-dependent
14825 // member function calls the later-defined overloaded static function.
14826 //
14827 // For example, in
14828 // class A {
14829 // void c() { callee(1); }
14830 // static auto callee(auto x) { }
14831 // };
14832 //
14833 // Here callee(1) is unresolved at the call site, but is not inside a
14834 // dependent context. There will be no further attempt to resolve this
14835 // call if it is made dependent.
14836
14837 if (const auto *TP =
14838 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14839 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14840 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
14841 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
14842 }
14843 }
14844 }
14845
14846 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14847 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
14848 OverloadResult, AllowTypoCorrection);
14849}
14850
14851ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14852 NestedNameSpecifierLoc NNSLoc,
14853 DeclarationNameInfo DNI,
14854 const UnresolvedSetImpl &Fns,
14855 bool PerformADL) {
14856 return UnresolvedLookupExpr::Create(
14857 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
14858 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14859}
14860
14861ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14862 CXXConversionDecl *Method,
14863 bool HadMultipleCandidates) {
14864 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14865 // the FoundDecl as it impedes TransformMemberExpr.
14866 // We go a bit further here: if there's no difference in UnderlyingDecl,
14867 // then using FoundDecl vs Method shouldn't make a difference either.
14868 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14869 FoundDecl = Method;
14870 // Convert the expression to match the conversion function's implicit object
14871 // parameter.
14872 ExprResult Exp;
14873 if (Method->isExplicitObjectMemberFunction())
14874 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
14875 else
14876 Exp = PerformImplicitObjectArgumentInitialization(From: E, /*Qualifier=*/nullptr,
14877 FoundDecl, Method);
14878 if (Exp.isInvalid())
14879 return true;
14880
14881 if (Method->getParent()->isLambda() &&
14882 Method->getConversionType()->isBlockPointerType()) {
14883 // This is a lambda conversion to block pointer; check if the argument
14884 // was a LambdaExpr.
14885 Expr *SubE = E;
14886 auto *CE = dyn_cast<CastExpr>(Val: SubE);
14887 if (CE && CE->getCastKind() == CK_NoOp)
14888 SubE = CE->getSubExpr();
14889 SubE = SubE->IgnoreParens();
14890 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
14891 SubE = BE->getSubExpr();
14892 if (isa<LambdaExpr>(Val: SubE)) {
14893 // For the conversion to block pointer on a lambda expression, we
14894 // construct a special BlockLiteral instead; this doesn't really make
14895 // a difference in ARC, but outside of ARC the resulting block literal
14896 // follows the normal lifetime rules for block literals instead of being
14897 // autoreleased.
14898 PushExpressionEvaluationContext(
14899 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
14900 ExprResult BlockExp = BuildBlockForLambdaConversion(
14901 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
14902 PopExpressionEvaluationContext();
14903
14904 // FIXME: This note should be produced by a CodeSynthesisContext.
14905 if (BlockExp.isInvalid())
14906 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
14907 return BlockExp;
14908 }
14909 }
14910 CallExpr *CE;
14911 QualType ResultType = Method->getReturnType();
14912 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
14913 ResultType = ResultType.getNonLValueExprType(Context);
14914 if (Method->isExplicitObjectMemberFunction()) {
14915 ExprResult FnExpr =
14916 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
14917 HadMultipleCandidates, Loc: E->getBeginLoc());
14918 if (FnExpr.isInvalid())
14919 return ExprError();
14920 Expr *ObjectParam = Exp.get();
14921 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
14922 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
14923 FPFeatures: CurFPFeatureOverrides());
14924 CE->setUsesMemberSyntax(true);
14925 } else {
14926 MemberExpr *ME =
14927 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
14928 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
14929 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
14930 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
14931 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
14932
14933 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
14934 RP: Exp.get()->getEndLoc(),
14935 FPFeatures: CurFPFeatureOverrides());
14936 }
14937
14938 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
14939 Proto: Method->getType()->castAs<FunctionProtoType>()))
14940 return ExprError();
14941
14942 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
14943}
14944
14945ExprResult
14946Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14947 const UnresolvedSetImpl &Fns,
14948 Expr *Input, bool PerformADL) {
14949 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14950 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14951 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14952 // TODO: provide better source location info.
14953 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14954
14955 if (checkPlaceholderForOverload(S&: *this, E&: Input))
14956 return ExprError();
14957
14958 Expr *Args[2] = { Input, nullptr };
14959 unsigned NumArgs = 1;
14960
14961 // For post-increment and post-decrement, add the implicit '0' as
14962 // the second argument, so that we know this is a post-increment or
14963 // post-decrement.
14964 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14965 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
14966 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
14967 l: SourceLocation());
14968 NumArgs = 2;
14969 }
14970
14971 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14972
14973 if (Input->isTypeDependent()) {
14974 ExprValueKind VK = ExprValueKind::VK_PRValue;
14975 // [C++26][expr.unary.op][expr.pre.incr]
14976 // The * operator yields an lvalue of type
14977 // The pre/post increment operators yied an lvalue.
14978 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14979 VK = VK_LValue;
14980
14981 if (Fns.empty())
14982 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
14983 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
14984 FPFeatures: CurFPFeatureOverrides());
14985
14986 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14987 ExprResult Fn = CreateUnresolvedLookupExpr(
14988 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
14989 if (Fn.isInvalid())
14990 return ExprError();
14991 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
14992 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
14993 FPFeatures: CurFPFeatureOverrides());
14994 }
14995
14996 // Build an empty overload set.
14997 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14998
14999 // Add the candidates from the given function set.
15000 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
15001
15002 // Add operator candidates that are member functions.
15003 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15004
15005 // Add candidates from ADL.
15006 if (PerformADL) {
15007 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15008 /*ExplicitTemplateArgs*/nullptr,
15009 CandidateSet);
15010 }
15011
15012 // Add builtin operator candidates.
15013 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15014
15015 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15016
15017 // Perform overload resolution.
15018 OverloadCandidateSet::iterator Best;
15019 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15020 case OR_Success: {
15021 // We found a built-in operator or an overloaded operator.
15022 FunctionDecl *FnDecl = Best->Function;
15023
15024 if (FnDecl) {
15025 Expr *Base = nullptr;
15026 // We matched an overloaded operator. Build a call to that
15027 // operator.
15028
15029 // Convert the arguments.
15030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15031 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15032
15033 ExprResult InputInit;
15034 if (Method->isExplicitObjectMemberFunction())
15035 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15036 else
15037 InputInit = PerformImplicitObjectArgumentInitialization(
15038 From: Input, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15039 if (InputInit.isInvalid())
15040 return ExprError();
15041 Base = Input = InputInit.get();
15042 } else {
15043 // Convert the arguments.
15044 ExprResult InputInit
15045 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15046 Context,
15047 Parm: FnDecl->getParamDecl(i: 0)),
15048 EqualLoc: SourceLocation(),
15049 Init: Input);
15050 if (InputInit.isInvalid())
15051 return ExprError();
15052 Input = InputInit.get();
15053 }
15054
15055 // Build the actual expression node.
15056 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15057 Base, HadMultipleCandidates,
15058 Loc: OpLoc);
15059 if (FnExpr.isInvalid())
15060 return ExprError();
15061
15062 // Determine the result type.
15063 QualType ResultTy = FnDecl->getReturnType();
15064 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15065 ResultTy = ResultTy.getNonLValueExprType(Context);
15066
15067 Args[0] = Input;
15068 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15069 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15070 FPFeatures: CurFPFeatureOverrides(),
15071 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15072
15073 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15074 return ExprError();
15075
15076 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15077 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15078 return ExprError();
15079 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15080 } else {
15081 // We matched a built-in operator. Convert the arguments, then
15082 // break out so that we will build the appropriate built-in
15083 // operator node.
15084 ExprResult InputRes = PerformImplicitConversion(
15085 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15086 Action: AssignmentAction::Passing,
15087 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15088 if (InputRes.isInvalid())
15089 return ExprError();
15090 Input = InputRes.get();
15091 break;
15092 }
15093 }
15094
15095 case OR_No_Viable_Function:
15096 // This is an erroneous use of an operator which can be overloaded by
15097 // a non-member function. Check for non-member operators which were
15098 // defined too late to be candidates.
15099 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15100 // FIXME: Recover by calling the found function.
15101 return ExprError();
15102
15103 // No viable function; fall through to handling this as a
15104 // built-in operator, which will produce an error message for us.
15105 break;
15106
15107 case OR_Ambiguous:
15108 CandidateSet.NoteCandidates(
15109 PD: PartialDiagnosticAt(OpLoc,
15110 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15111 << UnaryOperator::getOpcodeStr(Op: Opc)
15112 << Input->getType() << Input->getSourceRange()),
15113 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15114 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15115 return ExprError();
15116
15117 case OR_Deleted: {
15118 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15119 // object whose method was called. Later in NoteCandidates size of ArgsArray
15120 // is passed further and it eventually ends up compared to number of
15121 // function candidate parameters which never includes the object parameter,
15122 // so slice ArgsArray to make sure apples are compared to apples.
15123 StringLiteral *Msg = Best->Function->getDeletedMessage();
15124 CandidateSet.NoteCandidates(
15125 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15126 << UnaryOperator::getOpcodeStr(Op: Opc)
15127 << (Msg != nullptr)
15128 << (Msg ? Msg->getString() : StringRef())
15129 << Input->getSourceRange()),
15130 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15131 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15132 return ExprError();
15133 }
15134 }
15135
15136 // Either we found no viable overloaded operator or we matched a
15137 // built-in operator. In either case, fall through to trying to
15138 // build a built-in operation.
15139 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15140}
15141
15142void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15143 OverloadedOperatorKind Op,
15144 const UnresolvedSetImpl &Fns,
15145 ArrayRef<Expr *> Args, bool PerformADL) {
15146 SourceLocation OpLoc = CandidateSet.getLocation();
15147
15148 OverloadedOperatorKind ExtraOp =
15149 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15150 ? getRewrittenOverloadedOperator(Kind: Op)
15151 : OO_None;
15152
15153 // Add the candidates from the given function set. This also adds the
15154 // rewritten candidates using these functions if necessary.
15155 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15156
15157 // As template candidates are not deduced immediately,
15158 // persist the array in the overload set.
15159 ArrayRef<Expr *> ReversedArgs;
15160 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15161 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15162 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15163
15164 // Add operator candidates that are member functions.
15165 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15166 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15167 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15168 PO: OverloadCandidateParamOrder::Reversed);
15169
15170 // In C++20, also add any rewritten member candidates.
15171 if (ExtraOp) {
15172 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15173 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15174 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15175 PO: OverloadCandidateParamOrder::Reversed);
15176 }
15177
15178 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15179 // performed for an assignment operator (nor for operator[] nor operator->,
15180 // which don't get here).
15181 if (Op != OO_Equal && PerformADL) {
15182 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15183 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15184 /*ExplicitTemplateArgs*/ nullptr,
15185 CandidateSet);
15186 if (ExtraOp) {
15187 DeclarationName ExtraOpName =
15188 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15189 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15190 /*ExplicitTemplateArgs*/ nullptr,
15191 CandidateSet);
15192 }
15193 }
15194
15195 // Add builtin operator candidates.
15196 //
15197 // FIXME: We don't add any rewritten candidates here. This is strictly
15198 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15199 // resulting in our selecting a rewritten builtin candidate. For example:
15200 //
15201 // enum class E { e };
15202 // bool operator!=(E, E) requires false;
15203 // bool k = E::e != E::e;
15204 //
15205 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15206 // it seems unreasonable to consider rewritten builtin candidates. A core
15207 // issue has been filed proposing to removed this requirement.
15208 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15209}
15210
15211ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15212 BinaryOperatorKind Opc,
15213 const UnresolvedSetImpl &Fns, Expr *LHS,
15214 Expr *RHS, bool PerformADL,
15215 bool AllowRewrittenCandidates,
15216 FunctionDecl *DefaultedFn) {
15217 Expr *Args[2] = { LHS, RHS };
15218 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15219
15220 if (!getLangOpts().CPlusPlus20)
15221 AllowRewrittenCandidates = false;
15222
15223 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15224
15225 // If either side is type-dependent, create an appropriate dependent
15226 // expression.
15227 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15228 if (Fns.empty()) {
15229 // If there are no functions to store, just build a dependent
15230 // BinaryOperator or CompoundAssignment.
15231 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15232 return CompoundAssignOperator::Create(
15233 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15234 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15235 CompResultType: Context.DependentTy);
15236 return BinaryOperator::Create(
15237 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15238 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15239 }
15240
15241 // FIXME: save results of ADL from here?
15242 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15243 // TODO: provide better source location info in DNLoc component.
15244 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15245 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15246 ExprResult Fn = CreateUnresolvedLookupExpr(
15247 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15248 if (Fn.isInvalid())
15249 return ExprError();
15250 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15251 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15252 FPFeatures: CurFPFeatureOverrides());
15253 }
15254
15255 // If this is the .* operator, which is not overloadable, just
15256 // create a built-in binary operator.
15257 if (Opc == BO_PtrMemD) {
15258 auto CheckPlaceholder = [&](Expr *&Arg) {
15259 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15260 if (Res.isUsable())
15261 Arg = Res.get();
15262 return !Res.isUsable();
15263 };
15264
15265 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15266 // expression that contains placeholders (in either the LHS or RHS).
15267 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15268 return ExprError();
15269 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15270 }
15271
15272 // Always do placeholder-like conversions on the RHS.
15273 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15274 return ExprError();
15275
15276 // Do placeholder-like conversion on the LHS; note that we should
15277 // not get here with a PseudoObject LHS.
15278 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15279 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15280 return ExprError();
15281
15282 // If this is the assignment operator, we only perform overload resolution
15283 // if the left-hand side is a class or enumeration type. This is actually
15284 // a hack. The standard requires that we do overload resolution between the
15285 // various built-in candidates, but as DR507 points out, this can lead to
15286 // problems. So we do it this way, which pretty much follows what GCC does.
15287 // Note that we go the traditional code path for compound assignment forms.
15288 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15289 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15290
15291 // Build the overload set.
15292 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15293 OverloadCandidateSet::OperatorRewriteInfo(
15294 Op, OpLoc, AllowRewrittenCandidates));
15295 if (DefaultedFn)
15296 CandidateSet.exclude(F: DefaultedFn);
15297 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15298
15299 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15300
15301 // Perform overload resolution.
15302 OverloadCandidateSet::iterator Best;
15303 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15304 case OR_Success: {
15305 // We found a built-in operator or an overloaded operator.
15306 FunctionDecl *FnDecl = Best->Function;
15307
15308 bool IsReversed = Best->isReversed();
15309 if (IsReversed)
15310 std::swap(a&: Args[0], b&: Args[1]);
15311
15312 if (FnDecl) {
15313
15314 if (FnDecl->isInvalidDecl())
15315 return ExprError();
15316
15317 Expr *Base = nullptr;
15318 // We matched an overloaded operator. Build a call to that
15319 // operator.
15320
15321 OverloadedOperatorKind ChosenOp =
15322 FnDecl->getDeclName().getCXXOverloadedOperator();
15323
15324 // C++2a [over.match.oper]p9:
15325 // If a rewritten operator== candidate is selected by overload
15326 // resolution for an operator@, its return type shall be cv bool
15327 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15328 !FnDecl->getReturnType()->isBooleanType()) {
15329 bool IsExtension =
15330 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15331 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15332 : diag::err_ovl_rewrite_equalequal_not_bool)
15333 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15334 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15335 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15336 if (!IsExtension)
15337 return ExprError();
15338 }
15339
15340 if (AllowRewrittenCandidates && !IsReversed &&
15341 CandidateSet.getRewriteInfo().isReversible()) {
15342 // We could have reversed this operator, but didn't. Check if some
15343 // reversed form was a viable candidate, and if so, if it had a
15344 // better conversion for either parameter. If so, this call is
15345 // formally ambiguous, and allowing it is an extension.
15346 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15347 for (OverloadCandidate &Cand : CandidateSet) {
15348 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15349 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15350 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15351 if (CompareImplicitConversionSequences(
15352 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15353 ICS2: Best->Conversions[ArgIdx]) ==
15354 ImplicitConversionSequence::Better) {
15355 AmbiguousWith.push_back(Elt: Cand.Function);
15356 break;
15357 }
15358 }
15359 }
15360 }
15361
15362 if (!AmbiguousWith.empty()) {
15363 bool AmbiguousWithSelf =
15364 AmbiguousWith.size() == 1 &&
15365 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15366 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15367 << BinaryOperator::getOpcodeStr(Op: Opc)
15368 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15369 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15370 if (AmbiguousWithSelf) {
15371 Diag(Loc: FnDecl->getLocation(),
15372 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15373 // Mark member== const or provide matching != to disallow reversed
15374 // args. Eg.
15375 // struct S { bool operator==(const S&); };
15376 // S()==S();
15377 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15378 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15379 !MD->isConst() &&
15380 !MD->hasCXXExplicitFunctionObjectParameter() &&
15381 Context.hasSameUnqualifiedType(
15382 T1: MD->getFunctionObjectParameterType(),
15383 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15384 Context.hasSameUnqualifiedType(
15385 T1: MD->getFunctionObjectParameterType(),
15386 T2: Args[0]->getType()) &&
15387 Context.hasSameUnqualifiedType(
15388 T1: MD->getFunctionObjectParameterType(),
15389 T2: Args[1]->getType()))
15390 Diag(Loc: FnDecl->getLocation(),
15391 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15392 } else {
15393 Diag(Loc: FnDecl->getLocation(),
15394 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15395 for (auto *F : AmbiguousWith)
15396 Diag(Loc: F->getLocation(),
15397 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15398 }
15399 }
15400 }
15401
15402 // Check for nonnull = nullable.
15403 // This won't be caught in the arg's initialization: the parameter to
15404 // the assignment operator is not marked nonnull.
15405 if (Op == OO_Equal)
15406 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15407 SrcType: Args[1]->getType(), Loc: OpLoc);
15408
15409 // Convert the arguments.
15410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15411 // Best->Access is only meaningful for class members.
15412 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15413
15414 ExprResult Arg0, Arg1;
15415 unsigned ParamIdx = 0;
15416 if (Method->isExplicitObjectMemberFunction()) {
15417 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15418 ParamIdx = 1;
15419 } else {
15420 Arg0 = PerformImplicitObjectArgumentInitialization(
15421 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15422 }
15423 Arg1 = PerformCopyInitialization(
15424 Entity: InitializedEntity::InitializeParameter(
15425 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15426 EqualLoc: SourceLocation(), Init: Args[1]);
15427 if (Arg0.isInvalid() || Arg1.isInvalid())
15428 return ExprError();
15429
15430 Base = Args[0] = Arg0.getAs<Expr>();
15431 Args[1] = RHS = Arg1.getAs<Expr>();
15432 } else {
15433 // Convert the arguments.
15434 ExprResult Arg0 = PerformCopyInitialization(
15435 Entity: InitializedEntity::InitializeParameter(Context,
15436 Parm: FnDecl->getParamDecl(i: 0)),
15437 EqualLoc: SourceLocation(), Init: Args[0]);
15438 if (Arg0.isInvalid())
15439 return ExprError();
15440
15441 ExprResult Arg1 =
15442 PerformCopyInitialization(
15443 Entity: InitializedEntity::InitializeParameter(Context,
15444 Parm: FnDecl->getParamDecl(i: 1)),
15445 EqualLoc: SourceLocation(), Init: Args[1]);
15446 if (Arg1.isInvalid())
15447 return ExprError();
15448 Args[0] = LHS = Arg0.getAs<Expr>();
15449 Args[1] = RHS = Arg1.getAs<Expr>();
15450 }
15451
15452 // Build the actual expression node.
15453 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15454 FoundDecl: Best->FoundDecl, Base,
15455 HadMultipleCandidates, Loc: OpLoc);
15456 if (FnExpr.isInvalid())
15457 return ExprError();
15458
15459 // Determine the result type.
15460 QualType ResultTy = FnDecl->getReturnType();
15461 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15462 ResultTy = ResultTy.getNonLValueExprType(Context);
15463
15464 CallExpr *TheCall;
15465 ArrayRef<const Expr *> ArgsArray(Args, 2);
15466 const Expr *ImplicitThis = nullptr;
15467
15468 // We always create a CXXOperatorCallExpr, even for explicit object
15469 // members; CodeGen should take care not to emit the this pointer.
15470 TheCall = CXXOperatorCallExpr::Create(
15471 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15472 FPFeatures: CurFPFeatureOverrides(),
15473 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15474
15475 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15476 Method && Method->isImplicitObjectMemberFunction()) {
15477 // Cut off the implicit 'this'.
15478 ImplicitThis = ArgsArray[0];
15479 ArgsArray = ArgsArray.slice(N: 1);
15480 }
15481
15482 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15483 FD: FnDecl))
15484 return ExprError();
15485
15486 if (Op == OO_Equal) {
15487 // Check for a self move.
15488 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15489 // lifetime check.
15490 checkAssignmentLifetime(
15491 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15492 Init: Args[1]);
15493 }
15494 if (ImplicitThis) {
15495 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15496 QualType ThisTypeFromDecl = Context.getPointerType(
15497 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15498
15499 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15500 ParamTy: ThisTypeFromDecl);
15501 }
15502
15503 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15504 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15505 CallType: VariadicCallType::DoesNotApply);
15506
15507 ExprResult R = MaybeBindToTemporary(E: TheCall);
15508 if (R.isInvalid())
15509 return ExprError();
15510
15511 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15512 if (R.isInvalid())
15513 return ExprError();
15514
15515 // For a rewritten candidate, we've already reversed the arguments
15516 // if needed. Perform the rest of the rewrite now.
15517 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15518 (Op == OO_Spaceship && IsReversed)) {
15519 if (Op == OO_ExclaimEqual) {
15520 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15521 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15522 } else {
15523 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15524 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15525 Expr *ZeroLiteral =
15526 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15527
15528 Sema::CodeSynthesisContext Ctx;
15529 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15530 Ctx.Entity = FnDecl;
15531 pushCodeSynthesisContext(Ctx);
15532
15533 R = CreateOverloadedBinOp(
15534 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15535 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15536 /*AllowRewrittenCandidates=*/false);
15537
15538 popCodeSynthesisContext();
15539 }
15540 if (R.isInvalid())
15541 return ExprError();
15542 } else {
15543 assert(ChosenOp == Op && "unexpected operator name");
15544 }
15545
15546 // Make a note in the AST if we did any rewriting.
15547 if (Best->RewriteKind != CRK_None)
15548 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15549
15550 return R;
15551 } else {
15552 // We matched a built-in operator. Convert the arguments, then
15553 // break out so that we will build the appropriate built-in
15554 // operator node.
15555 ExprResult ArgsRes0 = PerformImplicitConversion(
15556 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15557 Action: AssignmentAction::Passing,
15558 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15559 if (ArgsRes0.isInvalid())
15560 return ExprError();
15561 Args[0] = ArgsRes0.get();
15562
15563 ExprResult ArgsRes1 = PerformImplicitConversion(
15564 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15565 Action: AssignmentAction::Passing,
15566 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15567 if (ArgsRes1.isInvalid())
15568 return ExprError();
15569 Args[1] = ArgsRes1.get();
15570 break;
15571 }
15572 }
15573
15574 case OR_No_Viable_Function: {
15575 // C++ [over.match.oper]p9:
15576 // If the operator is the operator , [...] and there are no
15577 // viable functions, then the operator is assumed to be the
15578 // built-in operator and interpreted according to clause 5.
15579 if (Opc == BO_Comma)
15580 break;
15581
15582 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15583 // compare result using '==' and '<'.
15584 if (DefaultedFn && Opc == BO_Cmp) {
15585 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15586 RHS: Args[1], DefaultedFn);
15587 if (E.isInvalid() || E.isUsable())
15588 return E;
15589 }
15590
15591 // For class as left operand for assignment or compound assignment
15592 // operator do not fall through to handling in built-in, but report that
15593 // no overloaded assignment operator found
15594 ExprResult Result = ExprError();
15595 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15596 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15597 Args, OpLoc);
15598 DeferDiagsRAII DDR(*this,
15599 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15600 if (Args[0]->getType()->isRecordType() &&
15601 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15602 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15603 << BinaryOperator::getOpcodeStr(Op: Opc)
15604 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15605 if (Args[0]->getType()->isIncompleteType()) {
15606 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15607 << Args[0]->getType()
15608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15609 }
15610 } else {
15611 // This is an erroneous use of an operator which can be overloaded by
15612 // a non-member function. Check for non-member operators which were
15613 // defined too late to be candidates.
15614 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15615 // FIXME: Recover by calling the found function.
15616 return ExprError();
15617
15618 // No viable function; try to create a built-in operation, which will
15619 // produce an error. Then, show the non-viable candidates.
15620 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15621 }
15622 assert(Result.isInvalid() &&
15623 "C++ binary operator overloading is missing candidates!");
15624 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15625 return Result;
15626 }
15627
15628 case OR_Ambiguous:
15629 CandidateSet.NoteCandidates(
15630 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15631 << BinaryOperator::getOpcodeStr(Op: Opc)
15632 << Args[0]->getType()
15633 << Args[1]->getType()
15634 << Args[0]->getSourceRange()
15635 << Args[1]->getSourceRange()),
15636 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15637 OpLoc);
15638 return ExprError();
15639
15640 case OR_Deleted: {
15641 if (isImplicitlyDeleted(FD: Best->Function)) {
15642 FunctionDecl *DeletedFD = Best->Function;
15643 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15644 if (DFK.isSpecialMember()) {
15645 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15646 << Args[0]->getType() << DFK.asSpecialMember();
15647 } else {
15648 assert(DFK.isComparison());
15649 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15650 << Args[0]->getType() << DeletedFD;
15651 }
15652
15653 // The user probably meant to call this special member. Just
15654 // explain why it's deleted.
15655 NoteDeletedFunction(FD: DeletedFD);
15656 return ExprError();
15657 }
15658
15659 StringLiteral *Msg = Best->Function->getDeletedMessage();
15660 CandidateSet.NoteCandidates(
15661 PD: PartialDiagnosticAt(
15662 OpLoc,
15663 PDiag(DiagID: diag::err_ovl_deleted_oper)
15664 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15665 .getCXXOverloadedOperator())
15666 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15667 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15668 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15669 OpLoc);
15670 return ExprError();
15671 }
15672 }
15673
15674 // We matched a built-in operator; build it.
15675 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15676}
15677
15678ExprResult Sema::BuildSynthesizedThreeWayComparison(
15679 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15680 FunctionDecl *DefaultedFn) {
15681 const ComparisonCategoryInfo *Info =
15682 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15683 // If we're not producing a known comparison category type, we can't
15684 // synthesize a three-way comparison. Let the caller diagnose this.
15685 if (!Info)
15686 return ExprResult((Expr*)nullptr);
15687
15688 // If we ever want to perform this synthesis more generally, we will need to
15689 // apply the temporary materialization conversion to the operands.
15690 assert(LHS->isGLValue() && RHS->isGLValue() &&
15691 "cannot use prvalue expressions more than once");
15692 Expr *OrigLHS = LHS;
15693 Expr *OrigRHS = RHS;
15694
15695 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15696 // each of them multiple times below.
15697 LHS = new (Context)
15698 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15699 LHS->getObjectKind(), LHS);
15700 RHS = new (Context)
15701 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15702 RHS->getObjectKind(), RHS);
15703
15704 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15705 DefaultedFn);
15706 if (Eq.isInvalid())
15707 return ExprError();
15708
15709 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15710 AllowRewrittenCandidates: true, DefaultedFn);
15711 if (Less.isInvalid())
15712 return ExprError();
15713
15714 ExprResult Greater;
15715 if (Info->isPartial()) {
15716 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15717 DefaultedFn);
15718 if (Greater.isInvalid())
15719 return ExprError();
15720 }
15721
15722 // Form the list of comparisons we're going to perform.
15723 struct Comparison {
15724 ExprResult Cmp;
15725 ComparisonCategoryResult Result;
15726 } Comparisons[4] =
15727 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15728 : ComparisonCategoryResult::Equivalent},
15729 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15730 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15731 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15732 };
15733
15734 int I = Info->isPartial() ? 3 : 2;
15735
15736 // Combine the comparisons with suitable conditional expressions.
15737 ExprResult Result;
15738 for (; I >= 0; --I) {
15739 // Build a reference to the comparison category constant.
15740 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15741 // FIXME: Missing a constant for a comparison category. Diagnose this?
15742 if (!VI)
15743 return ExprResult((Expr*)nullptr);
15744 ExprResult ThisResult =
15745 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
15746 if (ThisResult.isInvalid())
15747 return ExprError();
15748
15749 // Build a conditional unless this is the final case.
15750 if (Result.get()) {
15751 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15752 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15753 if (Result.isInvalid())
15754 return ExprError();
15755 } else {
15756 Result = ThisResult;
15757 }
15758 }
15759
15760 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15761 // bind the OpaqueValueExprs before they're (repeatedly) used.
15762 Expr *SyntacticForm = BinaryOperator::Create(
15763 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15764 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15765 FPFeatures: CurFPFeatureOverrides());
15766 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15767 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15768}
15769
15770static bool PrepareArgumentsForCallToObjectOfClassType(
15771 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15772 MultiExprArg Args, SourceLocation LParenLoc) {
15773
15774 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15775 unsigned NumParams = Proto->getNumParams();
15776 unsigned NumArgsSlots =
15777 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
15778 // Build the full argument list for the method call (the implicit object
15779 // parameter is placed at the beginning of the list).
15780 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
15781 bool IsError = false;
15782 // Initialize the implicit object parameter.
15783 // Check the argument types.
15784 for (unsigned i = 0; i != NumParams; i++) {
15785 Expr *Arg;
15786 if (i < Args.size()) {
15787 Arg = Args[i];
15788 ExprResult InputInit =
15789 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15790 Context&: S.Context, Parm: Method->getParamDecl(i)),
15791 EqualLoc: SourceLocation(), Init: Arg);
15792 IsError |= InputInit.isInvalid();
15793 Arg = InputInit.getAs<Expr>();
15794 } else {
15795 ExprResult DefArg =
15796 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
15797 if (DefArg.isInvalid()) {
15798 IsError = true;
15799 break;
15800 }
15801 Arg = DefArg.getAs<Expr>();
15802 }
15803
15804 MethodArgs.push_back(Elt: Arg);
15805 }
15806 return IsError;
15807}
15808
15809ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15810 SourceLocation RLoc,
15811 Expr *Base,
15812 MultiExprArg ArgExpr) {
15813 SmallVector<Expr *, 2> Args;
15814 Args.push_back(Elt: Base);
15815 for (auto *e : ArgExpr) {
15816 Args.push_back(Elt: e);
15817 }
15818 DeclarationName OpName =
15819 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
15820
15821 SourceRange Range = ArgExpr.empty()
15822 ? SourceRange{}
15823 : SourceRange(ArgExpr.front()->getBeginLoc(),
15824 ArgExpr.back()->getEndLoc());
15825
15826 // If either side is type-dependent, create an appropriate dependent
15827 // expression.
15828 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
15829
15830 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15831 // CHECKME: no 'operator' keyword?
15832 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15833 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15834 ExprResult Fn = CreateUnresolvedLookupExpr(
15835 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
15836 if (Fn.isInvalid())
15837 return ExprError();
15838 // Can't add any actual overloads yet
15839
15840 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
15841 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
15842 FPFeatures: CurFPFeatureOverrides());
15843 }
15844
15845 // Handle placeholders
15846 UnbridgedCastsSet UnbridgedCasts;
15847 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
15848 return ExprError();
15849 }
15850 // Build an empty overload set.
15851 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15852
15853 // Subscript can only be overloaded as a member function.
15854
15855 // Add operator candidates that are member functions.
15856 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15857
15858 // Add builtin operator candidates.
15859 if (Args.size() == 2)
15860 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15861
15862 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15863
15864 // Perform overload resolution.
15865 OverloadCandidateSet::iterator Best;
15866 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
15867 case OR_Success: {
15868 // We found a built-in operator or an overloaded operator.
15869 FunctionDecl *FnDecl = Best->Function;
15870
15871 if (FnDecl) {
15872 // We matched an overloaded operator. Build a call to that
15873 // operator.
15874
15875 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
15876
15877 // Convert the arguments.
15878 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
15879 SmallVector<Expr *, 2> MethodArgs;
15880
15881 // Initialize the object parameter.
15882 if (Method->isExplicitObjectMemberFunction()) {
15883 ExprResult Res =
15884 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
15885 if (Res.isInvalid())
15886 return ExprError();
15887 Args[0] = Res.get();
15888 ArgExpr = Args;
15889 } else {
15890 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15891 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15892 if (Arg0.isInvalid())
15893 return ExprError();
15894
15895 MethodArgs.push_back(Elt: Arg0.get());
15896 }
15897
15898 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15899 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
15900 if (IsError)
15901 return ExprError();
15902
15903 // Build the actual expression node.
15904 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15905 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15906 ExprResult FnExpr = CreateFunctionRefExpr(
15907 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
15908 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
15909 if (FnExpr.isInvalid())
15910 return ExprError();
15911
15912 // Determine the result type
15913 QualType ResultTy = FnDecl->getReturnType();
15914 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15915 ResultTy = ResultTy.getNonLValueExprType(Context);
15916
15917 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15918 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
15919 FPFeatures: CurFPFeatureOverrides());
15920
15921 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
15922 return ExprError();
15923
15924 if (CheckFunctionCall(FDecl: Method, TheCall,
15925 Proto: Method->getType()->castAs<FunctionProtoType>()))
15926 return ExprError();
15927
15928 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
15929 Decl: FnDecl);
15930 } else {
15931 // We matched a built-in operator. Convert the arguments, then
15932 // break out so that we will build the appropriate built-in
15933 // operator node.
15934 ExprResult ArgsRes0 = PerformImplicitConversion(
15935 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15936 Action: AssignmentAction::Passing,
15937 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15938 if (ArgsRes0.isInvalid())
15939 return ExprError();
15940 Args[0] = ArgsRes0.get();
15941
15942 ExprResult ArgsRes1 = PerformImplicitConversion(
15943 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15944 Action: AssignmentAction::Passing,
15945 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15946 if (ArgsRes1.isInvalid())
15947 return ExprError();
15948 Args[1] = ArgsRes1.get();
15949
15950 break;
15951 }
15952 }
15953
15954 case OR_No_Viable_Function: {
15955 PartialDiagnostic PD =
15956 CandidateSet.empty()
15957 ? (PDiag(DiagID: diag::err_ovl_no_oper)
15958 << Args[0]->getType() << /*subscript*/ 0
15959 << Args[0]->getSourceRange() << Range)
15960 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
15961 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15962 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
15963 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
15964 return ExprError();
15965 }
15966
15967 case OR_Ambiguous:
15968 if (Args.size() == 2) {
15969 CandidateSet.NoteCandidates(
15970 PD: PartialDiagnosticAt(
15971 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15972 << "[]" << Args[0]->getType() << Args[1]->getType()
15973 << Args[0]->getSourceRange() << Range),
15974 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
15975 } else {
15976 CandidateSet.NoteCandidates(
15977 PD: PartialDiagnosticAt(LLoc,
15978 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
15979 << Args[0]->getType()
15980 << Args[0]->getSourceRange() << Range),
15981 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
15982 }
15983 return ExprError();
15984
15985 case OR_Deleted: {
15986 StringLiteral *Msg = Best->Function->getDeletedMessage();
15987 CandidateSet.NoteCandidates(
15988 PD: PartialDiagnosticAt(LLoc,
15989 PDiag(DiagID: diag::err_ovl_deleted_oper)
15990 << "[]" << (Msg != nullptr)
15991 << (Msg ? Msg->getString() : StringRef())
15992 << Args[0]->getSourceRange() << Range),
15993 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
15994 return ExprError();
15995 }
15996 }
15997
15998 // We matched a built-in operator; build it.
15999 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16000}
16001
16002ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16003 SourceLocation LParenLoc,
16004 MultiExprArg Args,
16005 SourceLocation RParenLoc,
16006 Expr *ExecConfig, bool IsExecConfig,
16007 bool AllowRecovery) {
16008 assert(MemExprE->getType() == Context.BoundMemberTy ||
16009 MemExprE->getType() == Context.OverloadTy);
16010
16011 // Dig out the member expression. This holds both the object
16012 // argument and the member function we're referring to.
16013 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16014
16015 // Determine whether this is a call to a pointer-to-member function.
16016 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16017 assert(op->getType() == Context.BoundMemberTy);
16018 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16019
16020 QualType fnType =
16021 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16022
16023 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16024 QualType resultType = proto->getCallResultType(Context);
16025 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16026
16027 // Check that the object type isn't more qualified than the
16028 // member function we're calling.
16029 Qualifiers funcQuals = proto->getMethodQuals();
16030
16031 QualType objectType = op->getLHS()->getType();
16032 if (op->getOpcode() == BO_PtrMemI)
16033 objectType = objectType->castAs<PointerType>()->getPointeeType();
16034 Qualifiers objectQuals = objectType.getQualifiers();
16035
16036 Qualifiers difference = objectQuals - funcQuals;
16037 difference.removeObjCGCAttr();
16038 difference.removeAddressSpace();
16039 if (difference) {
16040 std::string qualsString = difference.getAsString();
16041 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16042 << fnType.getUnqualifiedType()
16043 << qualsString
16044 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16045 }
16046
16047 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16048 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16049 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16050
16051 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16052 CE: call, FD: nullptr))
16053 return ExprError();
16054
16055 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16056 return ExprError();
16057
16058 if (CheckOtherCall(TheCall: call, Proto: proto))
16059 return ExprError();
16060
16061 return MaybeBindToTemporary(E: call);
16062 }
16063
16064 // We only try to build a recovery expr at this level if we can preserve
16065 // the return type, otherwise we return ExprError() and let the caller
16066 // recover.
16067 auto BuildRecoveryExpr = [&](QualType Type) {
16068 if (!AllowRecovery)
16069 return ExprError();
16070 std::vector<Expr *> SubExprs = {MemExprE};
16071 llvm::append_range(C&: SubExprs, R&: Args);
16072 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16073 T: Type);
16074 };
16075 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16076 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16077 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16078
16079 UnbridgedCastsSet UnbridgedCasts;
16080 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16081 return ExprError();
16082
16083 MemberExpr *MemExpr;
16084 CXXMethodDecl *Method = nullptr;
16085 bool HadMultipleCandidates = false;
16086 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16087 NestedNameSpecifier *Qualifier = nullptr;
16088 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16089 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16090 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16091 FoundDecl = MemExpr->getFoundDecl();
16092 Qualifier = MemExpr->getQualifier();
16093 UnbridgedCasts.restore();
16094 } else {
16095 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16096 Qualifier = UnresExpr->getQualifier();
16097
16098 QualType ObjectType = UnresExpr->getBaseType();
16099 Expr::Classification ObjectClassification
16100 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16101 : UnresExpr->getBase()->Classify(Ctx&: Context);
16102
16103 // Add overload candidates
16104 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16105 OverloadCandidateSet::CSK_Normal);
16106
16107 // FIXME: avoid copy.
16108 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16109 if (UnresExpr->hasExplicitTemplateArgs()) {
16110 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16111 TemplateArgs = &TemplateArgsBuffer;
16112 }
16113
16114 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16115 E = UnresExpr->decls_end(); I != E; ++I) {
16116
16117 QualType ExplicitObjectType = ObjectType;
16118
16119 NamedDecl *Func = *I;
16120 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16121 if (isa<UsingShadowDecl>(Val: Func))
16122 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16123
16124 bool HasExplicitParameter = false;
16125 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16126 M && M->hasCXXExplicitFunctionObjectParameter())
16127 HasExplicitParameter = true;
16128 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16129 M &&
16130 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16131 HasExplicitParameter = true;
16132
16133 if (HasExplicitParameter)
16134 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16135
16136 // Microsoft supports direct constructor calls.
16137 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16138 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16139 CandidateSet,
16140 /*SuppressUserConversions*/ false);
16141 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16142 // If explicit template arguments were provided, we can't call a
16143 // non-template member function.
16144 if (TemplateArgs)
16145 continue;
16146
16147 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16148 ObjectClassification, Args, CandidateSet,
16149 /*SuppressUserConversions=*/false);
16150 } else {
16151 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16152 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16153 ObjectType: ExplicitObjectType, ObjectClassification,
16154 Args, CandidateSet,
16155 /*SuppressUserConversions=*/false);
16156 }
16157 }
16158
16159 HadMultipleCandidates = (CandidateSet.size() > 1);
16160
16161 DeclarationName DeclName = UnresExpr->getMemberName();
16162
16163 UnbridgedCasts.restore();
16164
16165 OverloadCandidateSet::iterator Best;
16166 bool Succeeded = false;
16167 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16168 Best)) {
16169 case OR_Success:
16170 Method = cast<CXXMethodDecl>(Val: Best->Function);
16171 FoundDecl = Best->FoundDecl;
16172 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16173 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16174 break;
16175 // If FoundDecl is different from Method (such as if one is a template
16176 // and the other a specialization), make sure DiagnoseUseOfDecl is
16177 // called on both.
16178 // FIXME: This would be more comprehensively addressed by modifying
16179 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16180 // being used.
16181 if (Method != FoundDecl.getDecl() &&
16182 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16183 break;
16184 Succeeded = true;
16185 break;
16186
16187 case OR_No_Viable_Function:
16188 CandidateSet.NoteCandidates(
16189 PD: PartialDiagnosticAt(
16190 UnresExpr->getMemberLoc(),
16191 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16192 << DeclName << MemExprE->getSourceRange()),
16193 S&: *this, OCD: OCD_AllCandidates, Args);
16194 break;
16195 case OR_Ambiguous:
16196 CandidateSet.NoteCandidates(
16197 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16198 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16199 << DeclName << MemExprE->getSourceRange()),
16200 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16201 break;
16202 case OR_Deleted:
16203 DiagnoseUseOfDeletedFunction(
16204 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16205 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16206 break;
16207 }
16208 // Overload resolution fails, try to recover.
16209 if (!Succeeded)
16210 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16211
16212 ExprResult Res =
16213 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16214 if (Res.isInvalid())
16215 return ExprError();
16216 MemExprE = Res.get();
16217
16218 // If overload resolution picked a static member
16219 // build a non-member call based on that function.
16220 if (Method->isStatic()) {
16221 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16222 Config: ExecConfig, IsExecConfig);
16223 }
16224
16225 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16226 }
16227
16228 QualType ResultType = Method->getReturnType();
16229 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16230 ResultType = ResultType.getNonLValueExprType(Context);
16231
16232 assert(Method && "Member call to something that isn't a method?");
16233 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16234
16235 CallExpr *TheCall = nullptr;
16236 llvm::SmallVector<Expr *, 8> NewArgs;
16237 if (Method->isExplicitObjectMemberFunction()) {
16238 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16239 NewArgs))
16240 return ExprError();
16241
16242 // Build the actual expression node.
16243 ExprResult FnExpr =
16244 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16245 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16246 if (FnExpr.isInvalid())
16247 return ExprError();
16248
16249 TheCall =
16250 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16251 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16252 TheCall->setUsesMemberSyntax(true);
16253 } else {
16254 // Convert the object argument (for a non-static member function call).
16255 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16256 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16257 if (ObjectArg.isInvalid())
16258 return ExprError();
16259 MemExpr->setBase(ObjectArg.get());
16260 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16261 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16262 MinNumArgs: Proto->getNumParams());
16263 }
16264
16265 // Check for a valid return type.
16266 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16267 CE: TheCall, FD: Method))
16268 return BuildRecoveryExpr(ResultType);
16269
16270 // Convert the rest of the arguments
16271 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16272 RParenLoc))
16273 return BuildRecoveryExpr(ResultType);
16274
16275 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16276
16277 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16278 return ExprError();
16279
16280 // In the case the method to call was not selected by the overloading
16281 // resolution process, we still need to handle the enable_if attribute. Do
16282 // that here, so it will not hide previous -- and more relevant -- errors.
16283 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16284 if (const EnableIfAttr *Attr =
16285 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16286 Diag(Loc: MemE->getMemberLoc(),
16287 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16288 << Method << Method->getSourceRange();
16289 Diag(Loc: Method->getLocation(),
16290 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16291 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16292 return ExprError();
16293 }
16294 }
16295
16296 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16297 TheCall->getDirectCallee()->isPureVirtual()) {
16298 const FunctionDecl *MD = TheCall->getDirectCallee();
16299
16300 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16301 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16302 Diag(Loc: MemExpr->getBeginLoc(),
16303 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16304 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16305 << MD->getParent();
16306
16307 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16308 if (getLangOpts().AppleKext)
16309 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16310 << MD->getParent() << MD->getDeclName();
16311 }
16312 }
16313
16314 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16315 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16316 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16317 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16318 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16319 DtorLoc: MemExpr->getMemberLoc());
16320 }
16321
16322 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16323 Decl: TheCall->getDirectCallee());
16324}
16325
16326ExprResult
16327Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16328 SourceLocation LParenLoc,
16329 MultiExprArg Args,
16330 SourceLocation RParenLoc) {
16331 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16332 return ExprError();
16333 ExprResult Object = Obj;
16334
16335 UnbridgedCastsSet UnbridgedCasts;
16336 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16337 return ExprError();
16338
16339 assert(Object.get()->getType()->isRecordType() &&
16340 "Requires object type argument");
16341
16342 // C++ [over.call.object]p1:
16343 // If the primary-expression E in the function call syntax
16344 // evaluates to a class object of type "cv T", then the set of
16345 // candidate functions includes at least the function call
16346 // operators of T. The function call operators of T are obtained by
16347 // ordinary lookup of the name operator() in the context of
16348 // (E).operator().
16349 OverloadCandidateSet CandidateSet(LParenLoc,
16350 OverloadCandidateSet::CSK_Operator);
16351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16352
16353 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16354 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16355 return true;
16356
16357 const auto *Record = Object.get()->getType()->castAs<RecordType>();
16358 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16359 LookupQualifiedName(R, LookupCtx: Record->getDecl());
16360 R.suppressAccessDiagnostics();
16361
16362 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16363 Oper != OperEnd; ++Oper) {
16364 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16365 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16366 /*SuppressUserConversion=*/SuppressUserConversions: false);
16367 }
16368
16369 // When calling a lambda, both the call operator, and
16370 // the conversion operator to function pointer
16371 // are considered. But when constraint checking
16372 // on the call operator fails, it will also fail on the
16373 // conversion operator as the constraints are always the same.
16374 // As the user probably does not intend to perform a surrogate call,
16375 // we filter them out to produce better error diagnostics, ie to avoid
16376 // showing 2 failed overloads instead of one.
16377 bool IgnoreSurrogateFunctions = false;
16378 if (CandidateSet.nonDeferredCandidatesCount() == 1 &&
16379 Record->getAsCXXRecordDecl()->isLambda()) {
16380 const OverloadCandidate &Candidate = *CandidateSet.begin();
16381 if (!Candidate.Viable &&
16382 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16383 IgnoreSurrogateFunctions = true;
16384 }
16385
16386 // C++ [over.call.object]p2:
16387 // In addition, for each (non-explicit in C++0x) conversion function
16388 // declared in T of the form
16389 //
16390 // operator conversion-type-id () cv-qualifier;
16391 //
16392 // where cv-qualifier is the same cv-qualification as, or a
16393 // greater cv-qualification than, cv, and where conversion-type-id
16394 // denotes the type "pointer to function of (P1,...,Pn) returning
16395 // R", or the type "reference to pointer to function of
16396 // (P1,...,Pn) returning R", or the type "reference to function
16397 // of (P1,...,Pn) returning R", a surrogate call function [...]
16398 // is also considered as a candidate function. Similarly,
16399 // surrogate call functions are added to the set of candidate
16400 // functions for each conversion function declared in an
16401 // accessible base class provided the function is not hidden
16402 // within T by another intervening declaration.
16403 const auto &Conversions =
16404 cast<CXXRecordDecl>(Val: Record->getDecl())->getVisibleConversionFunctions();
16405 for (auto I = Conversions.begin(), E = Conversions.end();
16406 !IgnoreSurrogateFunctions && I != E; ++I) {
16407 NamedDecl *D = *I;
16408 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16409 if (isa<UsingShadowDecl>(Val: D))
16410 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16411
16412 // Skip over templated conversion functions; they aren't
16413 // surrogates.
16414 if (isa<FunctionTemplateDecl>(Val: D))
16415 continue;
16416
16417 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16418 if (!Conv->isExplicit()) {
16419 // Strip the reference type (if any) and then the pointer type (if
16420 // any) to get down to what might be a function type.
16421 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16422 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16423 ConvType = ConvPtrType->getPointeeType();
16424
16425 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16426 {
16427 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16428 Object: Object.get(), Args, CandidateSet);
16429 }
16430 }
16431 }
16432
16433 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16434
16435 // Perform overload resolution.
16436 OverloadCandidateSet::iterator Best;
16437 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16438 Best)) {
16439 case OR_Success:
16440 // Overload resolution succeeded; we'll build the appropriate call
16441 // below.
16442 break;
16443
16444 case OR_No_Viable_Function: {
16445 PartialDiagnostic PD =
16446 CandidateSet.empty()
16447 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16448 << Object.get()->getType() << /*call*/ 1
16449 << Object.get()->getSourceRange())
16450 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16451 << Object.get()->getType() << Object.get()->getSourceRange());
16452 CandidateSet.NoteCandidates(
16453 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16454 OCD: OCD_AllCandidates, Args);
16455 break;
16456 }
16457 case OR_Ambiguous:
16458 if (!R.isAmbiguous())
16459 CandidateSet.NoteCandidates(
16460 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16461 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16462 << Object.get()->getType()
16463 << Object.get()->getSourceRange()),
16464 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16465 break;
16466
16467 case OR_Deleted: {
16468 // FIXME: Is this diagnostic here really necessary? It seems that
16469 // 1. we don't have any tests for this diagnostic, and
16470 // 2. we already issue err_deleted_function_use for this later on anyway.
16471 StringLiteral *Msg = Best->Function->getDeletedMessage();
16472 CandidateSet.NoteCandidates(
16473 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16474 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16475 << Object.get()->getType() << (Msg != nullptr)
16476 << (Msg ? Msg->getString() : StringRef())
16477 << Object.get()->getSourceRange()),
16478 S&: *this, OCD: OCD_AllCandidates, Args);
16479 break;
16480 }
16481 }
16482
16483 if (Best == CandidateSet.end())
16484 return true;
16485
16486 UnbridgedCasts.restore();
16487
16488 if (Best->Function == nullptr) {
16489 // Since there is no function declaration, this is one of the
16490 // surrogate candidates. Dig out the conversion function.
16491 CXXConversionDecl *Conv
16492 = cast<CXXConversionDecl>(
16493 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16494
16495 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16496 FoundDecl: Best->FoundDecl);
16497 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16498 return ExprError();
16499 assert(Conv == Best->FoundDecl.getDecl() &&
16500 "Found Decl & conversion-to-functionptr should be same, right?!");
16501 // We selected one of the surrogate functions that converts the
16502 // object parameter to a function pointer. Perform the conversion
16503 // on the object argument, then let BuildCallExpr finish the job.
16504
16505 // Create an implicit member expr to refer to the conversion operator.
16506 // and then call it.
16507 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16508 Method: Conv, HadMultipleCandidates);
16509 if (Call.isInvalid())
16510 return ExprError();
16511 // Record usage of conversion in an implicit cast.
16512 Call = ImplicitCastExpr::Create(
16513 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16514 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16515
16516 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16517 }
16518
16519 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16520
16521 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16522 // that calls this method, using Object for the implicit object
16523 // parameter and passing along the remaining arguments.
16524 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16525
16526 // An error diagnostic has already been printed when parsing the declaration.
16527 if (Method->isInvalidDecl())
16528 return ExprError();
16529
16530 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16531 unsigned NumParams = Proto->getNumParams();
16532
16533 DeclarationNameInfo OpLocInfo(
16534 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16535 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16536 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16537 Base: Obj, HadMultipleCandidates,
16538 Loc: OpLocInfo.getLoc(),
16539 LocInfo: OpLocInfo.getInfo());
16540 if (NewFn.isInvalid())
16541 return true;
16542
16543 SmallVector<Expr *, 8> MethodArgs;
16544 MethodArgs.reserve(N: NumParams + 1);
16545
16546 bool IsError = false;
16547
16548 // Initialize the object parameter.
16549 llvm::SmallVector<Expr *, 8> NewArgs;
16550 if (Method->isExplicitObjectMemberFunction()) {
16551 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16552 } else {
16553 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16554 From: Object.get(), /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
16555 if (ObjRes.isInvalid())
16556 IsError = true;
16557 else
16558 Object = ObjRes;
16559 MethodArgs.push_back(Elt: Object.get());
16560 }
16561
16562 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16563 S&: *this, MethodArgs, Method, Args, LParenLoc);
16564
16565 // If this is a variadic call, handle args passed through "...".
16566 if (Proto->isVariadic()) {
16567 // Promote the arguments (C99 6.5.2.2p7).
16568 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16569 ExprResult Arg = DefaultVariadicArgumentPromotion(
16570 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16571 IsError |= Arg.isInvalid();
16572 MethodArgs.push_back(Elt: Arg.get());
16573 }
16574 }
16575
16576 if (IsError)
16577 return true;
16578
16579 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16580
16581 // Once we've built TheCall, all of the expressions are properly owned.
16582 QualType ResultTy = Method->getReturnType();
16583 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16584 ResultTy = ResultTy.getNonLValueExprType(Context);
16585
16586 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16587 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16588 FPFeatures: CurFPFeatureOverrides());
16589
16590 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16591 return true;
16592
16593 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16594 return true;
16595
16596 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16597}
16598
16599ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16600 SourceLocation OpLoc,
16601 bool *NoArrowOperatorFound) {
16602 assert(Base->getType()->isRecordType() &&
16603 "left-hand side must have class type");
16604
16605 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16606 return ExprError();
16607
16608 SourceLocation Loc = Base->getExprLoc();
16609
16610 // C++ [over.ref]p1:
16611 //
16612 // [...] An expression x->m is interpreted as (x.operator->())->m
16613 // for a class object x of type T if T::operator->() exists and if
16614 // the operator is selected as the best match function by the
16615 // overload resolution mechanism (13.3).
16616 DeclarationName OpName =
16617 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16618 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16619
16620 if (RequireCompleteType(Loc, T: Base->getType(),
16621 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16622 return ExprError();
16623
16624 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16625 LookupQualifiedName(R, LookupCtx: Base->getType()->castAs<RecordType>()->getDecl());
16626 R.suppressAccessDiagnostics();
16627
16628 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16629 Oper != OperEnd; ++Oper) {
16630 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16631 Args: {}, CandidateSet,
16632 /*SuppressUserConversion=*/SuppressUserConversions: false);
16633 }
16634
16635 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16636
16637 // Perform overload resolution.
16638 OverloadCandidateSet::iterator Best;
16639 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16640 case OR_Success:
16641 // Overload resolution succeeded; we'll build the call below.
16642 break;
16643
16644 case OR_No_Viable_Function: {
16645 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16646 if (CandidateSet.empty()) {
16647 QualType BaseType = Base->getType();
16648 if (NoArrowOperatorFound) {
16649 // Report this specific error to the caller instead of emitting a
16650 // diagnostic, as requested.
16651 *NoArrowOperatorFound = true;
16652 return ExprError();
16653 }
16654 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16655 << BaseType << Base->getSourceRange();
16656 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16657 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16658 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16659 }
16660 } else
16661 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16662 << "operator->" << Base->getSourceRange();
16663 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16664 return ExprError();
16665 }
16666 case OR_Ambiguous:
16667 if (!R.isAmbiguous())
16668 CandidateSet.NoteCandidates(
16669 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16670 << "->" << Base->getType()
16671 << Base->getSourceRange()),
16672 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16673 return ExprError();
16674
16675 case OR_Deleted: {
16676 StringLiteral *Msg = Best->Function->getDeletedMessage();
16677 CandidateSet.NoteCandidates(
16678 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16679 << "->" << (Msg != nullptr)
16680 << (Msg ? Msg->getString() : StringRef())
16681 << Base->getSourceRange()),
16682 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16683 return ExprError();
16684 }
16685 }
16686
16687 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16688
16689 // Convert the object parameter.
16690 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16691
16692 if (Method->isExplicitObjectMemberFunction()) {
16693 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16694 if (R.isInvalid())
16695 return ExprError();
16696 Base = R.get();
16697 } else {
16698 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16699 From: Base, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
16700 if (BaseResult.isInvalid())
16701 return ExprError();
16702 Base = BaseResult.get();
16703 }
16704
16705 // Build the operator call.
16706 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16707 Base, HadMultipleCandidates, Loc: OpLoc);
16708 if (FnExpr.isInvalid())
16709 return ExprError();
16710
16711 QualType ResultTy = Method->getReturnType();
16712 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16713 ResultTy = ResultTy.getNonLValueExprType(Context);
16714
16715 CallExpr *TheCall =
16716 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16717 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16718
16719 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16720 return ExprError();
16721
16722 if (CheckFunctionCall(FDecl: Method, TheCall,
16723 Proto: Method->getType()->castAs<FunctionProtoType>()))
16724 return ExprError();
16725
16726 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16727}
16728
16729ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16730 DeclarationNameInfo &SuffixInfo,
16731 ArrayRef<Expr*> Args,
16732 SourceLocation LitEndLoc,
16733 TemplateArgumentListInfo *TemplateArgs) {
16734 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16735
16736 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16737 OverloadCandidateSet::CSK_Normal);
16738 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16739 ExplicitTemplateArgs: TemplateArgs);
16740
16741 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16742
16743 // Perform overload resolution. This will usually be trivial, but might need
16744 // to perform substitutions for a literal operator template.
16745 OverloadCandidateSet::iterator Best;
16746 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16747 case OR_Success:
16748 case OR_Deleted:
16749 break;
16750
16751 case OR_No_Viable_Function:
16752 CandidateSet.NoteCandidates(
16753 PD: PartialDiagnosticAt(UDSuffixLoc,
16754 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
16755 << R.getLookupName()),
16756 S&: *this, OCD: OCD_AllCandidates, Args);
16757 return ExprError();
16758
16759 case OR_Ambiguous:
16760 CandidateSet.NoteCandidates(
16761 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
16762 << R.getLookupName()),
16763 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16764 return ExprError();
16765 }
16766
16767 FunctionDecl *FD = Best->Function;
16768 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16769 Base: nullptr, HadMultipleCandidates,
16770 Loc: SuffixInfo.getLoc(),
16771 LocInfo: SuffixInfo.getInfo());
16772 if (Fn.isInvalid())
16773 return true;
16774
16775 // Check the argument types. This should almost always be a no-op, except
16776 // that array-to-pointer decay is applied to string literals.
16777 Expr *ConvArgs[2];
16778 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16779 ExprResult InputInit = PerformCopyInitialization(
16780 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
16781 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
16782 if (InputInit.isInvalid())
16783 return true;
16784 ConvArgs[ArgIdx] = InputInit.get();
16785 }
16786
16787 QualType ResultTy = FD->getReturnType();
16788 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16789 ResultTy = ResultTy.getNonLValueExprType(Context);
16790
16791 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16792 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
16793 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
16794
16795 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
16796 return ExprError();
16797
16798 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
16799 return ExprError();
16800
16801 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
16802}
16803
16804Sema::ForRangeStatus
16805Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16806 SourceLocation RangeLoc,
16807 const DeclarationNameInfo &NameInfo,
16808 LookupResult &MemberLookup,
16809 OverloadCandidateSet *CandidateSet,
16810 Expr *Range, ExprResult *CallExpr) {
16811 Scope *S = nullptr;
16812
16813 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
16814 if (!MemberLookup.empty()) {
16815 ExprResult MemberRef =
16816 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
16817 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
16818 /*TemplateKWLoc=*/SourceLocation(),
16819 /*FirstQualifierInScope=*/nullptr,
16820 R&: MemberLookup,
16821 /*TemplateArgs=*/nullptr, S);
16822 if (MemberRef.isInvalid()) {
16823 *CallExpr = ExprError();
16824 return FRS_DiagnosticIssued;
16825 }
16826 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
16827 if (CallExpr->isInvalid()) {
16828 *CallExpr = ExprError();
16829 return FRS_DiagnosticIssued;
16830 }
16831 } else {
16832 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16833 NNSLoc: NestedNameSpecifierLoc(),
16834 DNI: NameInfo, Fns: UnresolvedSet<0>());
16835 if (FnR.isInvalid())
16836 return FRS_DiagnosticIssued;
16837 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
16838
16839 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
16840 CandidateSet, Result: CallExpr);
16841 if (CandidateSet->empty() || CandidateSetError) {
16842 *CallExpr = ExprError();
16843 return FRS_NoViableFunction;
16844 }
16845 OverloadCandidateSet::iterator Best;
16846 OverloadingResult OverloadResult =
16847 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
16848
16849 if (OverloadResult == OR_No_Viable_Function) {
16850 *CallExpr = ExprError();
16851 return FRS_NoViableFunction;
16852 }
16853 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
16854 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
16855 OverloadResult,
16856 /*AllowTypoCorrection=*/false);
16857 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16858 *CallExpr = ExprError();
16859 return FRS_DiagnosticIssued;
16860 }
16861 }
16862 return FRS_Success;
16863}
16864
16865ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16866 FunctionDecl *Fn) {
16867 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
16868 ExprResult SubExpr =
16869 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
16870 if (SubExpr.isInvalid())
16871 return ExprError();
16872 if (SubExpr.get() == PE->getSubExpr())
16873 return PE;
16874
16875 return new (Context)
16876 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16877 }
16878
16879 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
16880 ExprResult SubExpr =
16881 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
16882 if (SubExpr.isInvalid())
16883 return ExprError();
16884 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16885 SubExpr.get()->getType()) &&
16886 "Implicit cast type cannot be determined from overload");
16887 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16888 if (SubExpr.get() == ICE->getSubExpr())
16889 return ICE;
16890
16891 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
16892 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
16893 FPO: CurFPFeatureOverrides());
16894 }
16895
16896 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
16897 if (!GSE->isResultDependent()) {
16898 ExprResult SubExpr =
16899 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
16900 if (SubExpr.isInvalid())
16901 return ExprError();
16902 if (SubExpr.get() == GSE->getResultExpr())
16903 return GSE;
16904
16905 // Replace the resulting type information before rebuilding the generic
16906 // selection expression.
16907 ArrayRef<Expr *> A = GSE->getAssocExprs();
16908 SmallVector<Expr *, 4> AssocExprs(A);
16909 unsigned ResultIdx = GSE->getResultIndex();
16910 AssocExprs[ResultIdx] = SubExpr.get();
16911
16912 if (GSE->isExprPredicate())
16913 return GenericSelectionExpr::Create(
16914 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
16915 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
16916 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
16917 ResultIndex: ResultIdx);
16918 return GenericSelectionExpr::Create(
16919 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
16920 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
16921 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
16922 ResultIndex: ResultIdx);
16923 }
16924 // Rather than fall through to the unreachable, return the original generic
16925 // selection expression.
16926 return GSE;
16927 }
16928
16929 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
16930 assert(UnOp->getOpcode() == UO_AddrOf &&
16931 "Can only take the address of an overloaded function");
16932 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
16933 if (!Method->isImplicitObjectMemberFunction()) {
16934 // Do nothing: the address of static and
16935 // explicit object member functions is a (non-member) function pointer.
16936 } else {
16937 // Fix the subexpression, which really has to be an
16938 // UnresolvedLookupExpr holding an overloaded member function
16939 // or template.
16940 ExprResult SubExpr =
16941 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16942 if (SubExpr.isInvalid())
16943 return ExprError();
16944 if (SubExpr.get() == UnOp->getSubExpr())
16945 return UnOp;
16946
16947 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
16948 Op: SubExpr.get(), MD: Method))
16949 return ExprError();
16950
16951 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16952 "fixed to something other than a decl ref");
16953 NestedNameSpecifier *Qualifier =
16954 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
16955 assert(Qualifier &&
16956 "fixed to a member ref with no nested name qualifier");
16957
16958 // We have taken the address of a pointer to member
16959 // function. Perform the computation here so that we get the
16960 // appropriate pointer to member type.
16961 QualType MemPtrType = Context.getMemberPointerType(
16962 T: Fn->getType(), Qualifier,
16963 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
16964 // Under the MS ABI, lock down the inheritance model now.
16965 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16966 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
16967
16968 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
16969 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
16970 l: UnOp->getOperatorLoc(), CanOverflow: false,
16971 FPFeatures: CurFPFeatureOverrides());
16972 }
16973 }
16974 ExprResult SubExpr =
16975 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16976 if (SubExpr.isInvalid())
16977 return ExprError();
16978 if (SubExpr.get() == UnOp->getSubExpr())
16979 return UnOp;
16980
16981 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
16982 InputExpr: SubExpr.get());
16983 }
16984
16985 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16986 if (Found.getAccess() == AS_none) {
16987 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
16988 }
16989 // FIXME: avoid copy.
16990 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16991 if (ULE->hasExplicitTemplateArgs()) {
16992 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16993 TemplateArgs = &TemplateArgsBuffer;
16994 }
16995
16996 QualType Type = Fn->getType();
16997 ExprValueKind ValueKind =
16998 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16999 ? VK_LValue
17000 : VK_PRValue;
17001
17002 // FIXME: Duplicated from BuildDeclarationNameExpr.
17003 if (unsigned BID = Fn->getBuiltinID()) {
17004 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17005 Type = Context.BuiltinFnTy;
17006 ValueKind = VK_PRValue;
17007 }
17008 }
17009
17010 DeclRefExpr *DRE = BuildDeclRefExpr(
17011 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17012 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17013 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17014 return DRE;
17015 }
17016
17017 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17018 // FIXME: avoid copy.
17019 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17020 if (MemExpr->hasExplicitTemplateArgs()) {
17021 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17022 TemplateArgs = &TemplateArgsBuffer;
17023 }
17024
17025 Expr *Base;
17026
17027 // If we're filling in a static method where we used to have an
17028 // implicit member access, rewrite to a simple decl ref.
17029 if (MemExpr->isImplicitAccess()) {
17030 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17031 DeclRefExpr *DRE = BuildDeclRefExpr(
17032 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17033 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17034 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17035 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17036 return DRE;
17037 } else {
17038 SourceLocation Loc = MemExpr->getMemberLoc();
17039 if (MemExpr->getQualifier())
17040 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17041 Base =
17042 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17043 }
17044 } else
17045 Base = MemExpr->getBase();
17046
17047 ExprValueKind valueKind;
17048 QualType type;
17049 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17050 valueKind = VK_LValue;
17051 type = Fn->getType();
17052 } else {
17053 valueKind = VK_PRValue;
17054 type = Context.BoundMemberTy;
17055 }
17056
17057 return BuildMemberExpr(
17058 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17059 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17060 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17061 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17062 }
17063
17064 llvm_unreachable("Invalid reference to overloaded function");
17065}
17066
17067ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17068 DeclAccessPair Found,
17069 FunctionDecl *Fn) {
17070 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17071}
17072
17073bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17074 FunctionDecl *Function) {
17075 if (!PartialOverloading || !Function)
17076 return true;
17077 if (Function->isVariadic())
17078 return false;
17079 if (const auto *Proto =
17080 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17081 if (Proto->isTemplateVariadic())
17082 return false;
17083 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17084 if (const auto *Proto =
17085 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17086 if (Proto->isTemplateVariadic())
17087 return false;
17088 return true;
17089}
17090
17091void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17092 DeclarationName Name,
17093 OverloadCandidateSet &CandidateSet,
17094 FunctionDecl *Fn, MultiExprArg Args,
17095 bool IsMember) {
17096 StringLiteral *Msg = Fn->getDeletedMessage();
17097 CandidateSet.NoteCandidates(
17098 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17099 << IsMember << Name << (Msg != nullptr)
17100 << (Msg ? Msg->getString() : StringRef())
17101 << Range),
17102 S&: *this, OCD: OCD_AllCandidates, Args);
17103}
17104