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_HLSL_Dimension_Reduction,
166 ICR_Conversion,
167 ICR_HLSL_Scalar_Widening,
168 ICR_HLSL_Scalar_Widening,
169 };
170 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
171 return Rank[(int)Kind];
172}
173
174ImplicitConversionRank
175clang::GetDimensionConversionRank(ImplicitConversionRank Base,
176 ImplicitConversionKind Dimension) {
177 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
178 if (Rank == ICR_HLSL_Scalar_Widening) {
179 if (Base == ICR_Promotion)
180 return ICR_HLSL_Scalar_Widening_Promotion;
181 if (Base == ICR_Conversion)
182 return ICR_HLSL_Scalar_Widening_Conversion;
183 }
184 if (Rank == ICR_HLSL_Dimension_Reduction) {
185 if (Base == ICR_Promotion)
186 return ICR_HLSL_Dimension_Reduction_Promotion;
187 if (Base == ICR_Conversion)
188 return ICR_HLSL_Dimension_Reduction_Conversion;
189 }
190 return Rank;
191}
192
193/// GetImplicitConversionName - Return the name of this kind of
194/// implicit conversion.
195static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
196 static const char *const Name[] = {
197 "No conversion",
198 "Lvalue-to-rvalue",
199 "Array-to-pointer",
200 "Function-to-pointer",
201 "Function pointer conversion",
202 "Qualification",
203 "Integral promotion",
204 "Floating point promotion",
205 "Complex promotion",
206 "Integral conversion",
207 "Floating conversion",
208 "Complex conversion",
209 "Floating-integral conversion",
210 "Pointer conversion",
211 "Pointer-to-member conversion",
212 "Boolean conversion",
213 "Compatible-types conversion",
214 "Derived-to-base conversion",
215 "Vector conversion",
216 "SVE Vector conversion",
217 "RVV Vector conversion",
218 "Vector splat",
219 "Complex-real conversion",
220 "Block Pointer conversion",
221 "Transparent Union Conversion",
222 "Writeback conversion",
223 "OpenCL Zero Event Conversion",
224 "OpenCL Zero Queue Conversion",
225 "C specific type conversion",
226 "Incompatible pointer conversion",
227 "Fixed point conversion",
228 "HLSL vector truncation",
229 "HLSL matrix truncation",
230 "Non-decaying array conversion",
231 "HLSL vector splat",
232 "HLSL matrix splat",
233 };
234 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
235 return Name[Kind];
236}
237
238/// StandardConversionSequence - Set the standard conversion
239/// sequence to the identity conversion.
240void StandardConversionSequence::setAsIdentityConversion() {
241 First = ICK_Identity;
242 Second = ICK_Identity;
243 Dimension = ICK_Identity;
244 Third = ICK_Identity;
245 DeprecatedStringLiteralToCharPtr = false;
246 QualificationIncludesObjCLifetime = false;
247 ReferenceBinding = false;
248 DirectBinding = false;
249 IsLvalueReference = true;
250 BindsToFunctionLvalue = false;
251 BindsToRvalue = false;
252 BindsImplicitObjectArgumentWithoutRefQualifier = false;
253 ObjCLifetimeConversionBinding = false;
254 FromBracedInitList = false;
255 CopyConstructor = nullptr;
256}
257
258/// getRank - Retrieve the rank of this standard conversion sequence
259/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260/// implicit conversions.
261ImplicitConversionRank StandardConversionSequence::getRank() const {
262 ImplicitConversionRank Rank = ICR_Exact_Match;
263 if (GetConversionRank(Kind: First) > Rank)
264 Rank = GetConversionRank(Kind: First);
265 if (GetConversionRank(Kind: Second) > Rank)
266 Rank = GetConversionRank(Kind: Second);
267 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
268 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
269 if (GetConversionRank(Kind: Third) > Rank)
270 Rank = GetConversionRank(Kind: Third);
271 return Rank;
272}
273
274/// isPointerConversionToBool - Determines whether this conversion is
275/// a conversion of a pointer or pointer-to-member to bool. This is
276/// used as part of the ranking of standard conversion sequences
277/// (C++ 13.3.3.2p4).
278bool StandardConversionSequence::isPointerConversionToBool() const {
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(Idx: 1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
288 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
289 return true;
290
291 return false;
292}
293
294/// isPointerConversionToVoidPointer - Determines whether this
295/// conversion is a conversion of a pointer to a void pointer. This is
296/// used as part of the ranking of standard conversion sequences (C++
297/// 13.3.3.2p4).
298bool
299StandardConversionSequence::
300isPointerConversionToVoidPointer(ASTContext& Context) const {
301 QualType FromType = getFromType();
302 QualType ToType = getToType(Idx: 1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
307 if (First == ICK_Array_To_Pointer)
308 FromType = Context.getArrayDecayedType(T: FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315}
316
317/// Skip any implicit casts which could be either part of a narrowing conversion
318/// or after one in an implicit conversion.
319static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
326 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
327 objects: EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349}
350
351/// Check if this standard conversion sequence represents a narrowing
352/// conversion, according to C++11 [dcl.init.list]p7.
353///
354/// \param Ctx The AST context.
355/// \param Converted The result of applying this standard conversion sequence.
356/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357/// value of the expression prior to the narrowing conversion.
358/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359/// type of the expression prior to the narrowing conversion.
360/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361/// from floating point types to integral types should be ignored.
362NarrowingKind StandardConversionSequence::getNarrowingKind(
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(Idx: 0);
371 QualType ToType = getToType(Idx: 1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (const auto *ED = ToType->getAsEnumDecl())
377 ToType = ED->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
381 case ICK_Boolean_Conversion:
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
384 if (FromType->isIntegralOrUnscopedEnumerationType())
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
395 case ICK_Floating_Integral:
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
408 return NK_Dependent_Narrowing;
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
414 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
415 RM: llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 llvm::APFloat::opStatus Status = Result.convertToInteger(
420 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
421 // If the converted-back integer has unspecified value, or if the
422 // resulting value is different, this was a narrowing conversion.
423 if (Status == llvm::APFloat::opInvalidOp ||
424 *IntConstantValue != ConvertedValue) {
425 ConstantValue = APValue(*IntConstantValue);
426 ConstantType = Initializer->getType();
427 return NK_Constant_Narrowing;
428 }
429 } else {
430 // Variables are always narrowings.
431 return NK_Variable_Narrowing;
432 }
433 }
434 return NK_Not_Narrowing;
435
436 // -- from long double to double or float, or from double to float, except
437 // where the source is a constant expression and the actual value after
438 // conversion is within the range of values that can be represented (even
439 // if it cannot be represented exactly), or
440 case ICK_Floating_Conversion:
441 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
442 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
443 // FromType is larger than ToType.
444 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
445
446 // If it's value-dependent, we can't tell whether it's narrowing.
447 if (Initializer->isValueDependent())
448 return NK_Dependent_Narrowing;
449
450 Expr::EvalResult R;
451 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
452 ((Ctx.getLangOpts().CPlusPlus &&
453 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)))) {
454 // Constant!
455 if (Ctx.getLangOpts().C23)
456 ConstantValue = R.Val;
457 assert(ConstantValue.isFloat());
458 llvm::APFloat FloatVal = ConstantValue.getFloat();
459 // Convert the source value into the target type.
460 bool ignored;
461 llvm::APFloat Converted = FloatVal;
462 llvm::APFloat::opStatus ConvertStatus =
463 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
464 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
465 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
466 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
467 if (Ctx.getLangOpts().C23) {
468 if (FloatVal.isNaN() && Converted.isNaN() &&
469 !FloatVal.isSignaling() && !Converted.isSignaling()) {
470 // Quiet NaNs are considered the same value, regardless of
471 // payloads.
472 return NK_Not_Narrowing;
473 }
474 // For normal values, check exact equality.
475 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
476 ConstantType = Initializer->getType();
477 return NK_Constant_Narrowing;
478 }
479 } else {
480 // If there was no overflow, the source value is within the range of
481 // values that can be represented.
482 if (ConvertStatus & llvm::APFloat::opOverflow) {
483 ConstantType = Initializer->getType();
484 return NK_Constant_Narrowing;
485 }
486 }
487 } else {
488 return NK_Variable_Narrowing;
489 }
490 }
491 return NK_Not_Narrowing;
492
493 // -- from an integer type or unscoped enumeration type to an integer type
494 // that cannot represent all the values of the original type, except where
495 // (CWG2627) -- the source is a bit-field whose width w is less than that
496 // of its type (or, for an enumeration type, its underlying type) and the
497 // target type can represent all the values of a hypothetical extended
498 // integer type with width w and with the same signedness as the original
499 // type or
500 // -- the source is a constant expression and the actual value after
501 // conversion will fit into the target type and will produce the original
502 // value when converted back to the original type.
503 case ICK_Integral_Conversion:
504 IntegralConversion: {
505 assert(FromType->isIntegralOrUnscopedEnumerationType());
506 assert(ToType->isIntegralOrUnscopedEnumerationType());
507 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
508 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
509 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
510 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
511
512 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
513 bool ToSigned, unsigned ToWidth) {
514 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
515 !(FromSigned && !ToSigned);
516 };
517
518 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
519 return NK_Not_Narrowing;
520
521 // Not all values of FromType can be represented in ToType.
522 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
523
524 bool DependentBitField = false;
525 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
526 if (BitField->getBitWidth()->isValueDependent())
527 DependentBitField = true;
528 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
529 BitFieldWidth < FromWidth) {
530 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // The initializer will be truncated to the bit-field width
534 FromWidth = BitFieldWidth;
535 }
536 }
537
538 // If it's value-dependent, we can't tell whether it's narrowing.
539 if (Initializer->isValueDependent())
540 return NK_Dependent_Narrowing;
541
542 std::optional<llvm::APSInt> OptInitializerValue =
543 Initializer->getIntegerConstantExpr(Ctx);
544 if (!OptInitializerValue) {
545 // If the bit-field width was dependent, it might end up being small
546 // enough to fit in the target type (unless the target type is unsigned
547 // and the source type is signed, in which case it will never fit)
548 if (DependentBitField && !(FromSigned && !ToSigned))
549 return NK_Dependent_Narrowing;
550
551 // Otherwise, such a conversion is always narrowing
552 return NK_Variable_Narrowing;
553 }
554 llvm::APSInt &InitializerValue = *OptInitializerValue;
555 bool Narrowing = false;
556 if (FromWidth < ToWidth) {
557 // Negative -> unsigned is narrowing. Otherwise, more bits is never
558 // narrowing.
559 if (InitializerValue.isSigned() && InitializerValue.isNegative())
560 Narrowing = true;
561 } else {
562 // Add a bit to the InitializerValue so we don't have to worry about
563 // signed vs. unsigned comparisons.
564 InitializerValue =
565 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
566 // Convert the initializer to and from the target width and signed-ness.
567 llvm::APSInt ConvertedValue = InitializerValue;
568 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
569 ConvertedValue.setIsSigned(ToSigned);
570 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
571 ConvertedValue.setIsSigned(InitializerValue.isSigned());
572 // If the result is different, this was a narrowing conversion.
573 if (ConvertedValue != InitializerValue)
574 Narrowing = true;
575 }
576 if (Narrowing) {
577 ConstantType = Initializer->getType();
578 ConstantValue = APValue(InitializerValue);
579 return NK_Constant_Narrowing;
580 }
581
582 return NK_Not_Narrowing;
583 }
584 case ICK_Complex_Real:
585 if (FromType->isComplexType() && !ToType->isComplexType())
586 return NK_Type_Narrowing;
587 return NK_Not_Narrowing;
588
589 case ICK_Floating_Promotion:
590 if (Ctx.getLangOpts().C23) {
591 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
592 Expr::EvalResult R;
593 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
594 ConstantValue = R.Val;
595 assert(ConstantValue.isFloat());
596 llvm::APFloat FloatVal = ConstantValue.getFloat();
597 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
598 // value, the unqualified versions of the type of the initializer and
599 // the corresponding real type of the object declared shall be
600 // compatible.
601 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
602 ConstantType = Initializer->getType();
603 return NK_Constant_Narrowing;
604 }
605 }
606 }
607 return NK_Not_Narrowing;
608 default:
609 // Other kinds of conversions are not narrowings.
610 return NK_Not_Narrowing;
611 }
612}
613
614/// dump - Print this standard conversion sequence to standard
615/// error. Useful for debugging overloading issues.
616LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
617 raw_ostream &OS = llvm::errs();
618 bool PrintedSomething = false;
619 if (First != ICK_Identity) {
620 OS << GetImplicitConversionName(Kind: First);
621 PrintedSomething = true;
622 }
623
624 if (Second != ICK_Identity) {
625 if (PrintedSomething) {
626 OS << " -> ";
627 }
628 OS << GetImplicitConversionName(Kind: Second);
629
630 if (CopyConstructor) {
631 OS << " (by copy constructor)";
632 } else if (DirectBinding) {
633 OS << " (direct reference binding)";
634 } else if (ReferenceBinding) {
635 OS << " (reference binding)";
636 }
637 PrintedSomething = true;
638 }
639
640 if (Third != ICK_Identity) {
641 if (PrintedSomething) {
642 OS << " -> ";
643 }
644 OS << GetImplicitConversionName(Kind: Third);
645 PrintedSomething = true;
646 }
647
648 if (!PrintedSomething) {
649 OS << "No conversions required";
650 }
651}
652
653/// dump - Print this user-defined conversion sequence to standard
654/// error. Useful for debugging overloading issues.
655void UserDefinedConversionSequence::dump() const {
656 raw_ostream &OS = llvm::errs();
657 if (Before.First || Before.Second || Before.Third) {
658 Before.dump();
659 OS << " -> ";
660 }
661 if (ConversionFunction)
662 OS << '\'' << *ConversionFunction << '\'';
663 else
664 OS << "aggregate initialization";
665 if (After.First || After.Second || After.Third) {
666 OS << " -> ";
667 After.dump();
668 }
669}
670
671/// dump - Print this implicit conversion sequence to standard
672/// error. Useful for debugging overloading issues.
673void ImplicitConversionSequence::dump() const {
674 raw_ostream &OS = llvm::errs();
675 if (hasInitializerListContainerType())
676 OS << "Worst list element conversion: ";
677 switch (ConversionKind) {
678 case StandardConversion:
679 OS << "Standard conversion: ";
680 Standard.dump();
681 break;
682 case UserDefinedConversion:
683 OS << "User-defined conversion: ";
684 UserDefined.dump();
685 break;
686 case EllipsisConversion:
687 OS << "Ellipsis conversion";
688 break;
689 case AmbiguousConversion:
690 OS << "Ambiguous conversion";
691 break;
692 case BadConversion:
693 OS << "Bad conversion";
694 break;
695 }
696
697 OS << "\n";
698}
699
700void AmbiguousConversionSequence::construct() {
701 new (&conversions()) ConversionSet();
702}
703
704void AmbiguousConversionSequence::destruct() {
705 conversions().~ConversionSet();
706}
707
708void
709AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
710 FromTypePtr = O.FromTypePtr;
711 ToTypePtr = O.ToTypePtr;
712 new (&conversions()) ConversionSet(O.conversions());
713}
714
715namespace {
716 // Structure used by DeductionFailureInfo to store
717 // template argument information.
718 struct DFIArguments {
719 TemplateArgument FirstArg;
720 TemplateArgument SecondArg;
721 };
722 // Structure used by DeductionFailureInfo to store
723 // template parameter and template argument information.
724 struct DFIParamWithArguments : DFIArguments {
725 TemplateParameter Param;
726 };
727 // Structure used by DeductionFailureInfo to store template argument
728 // information and the index of the problematic call argument.
729 struct DFIDeducedMismatchArgs : DFIArguments {
730 TemplateArgumentList *TemplateArgs;
731 unsigned CallArgIndex;
732 };
733 // Structure used by DeductionFailureInfo to store information about
734 // unsatisfied constraints.
735 struct CNSInfo {
736 TemplateArgumentList *TemplateArgs;
737 ConstraintSatisfaction Satisfaction;
738 };
739}
740
741/// Convert from Sema's representation of template deduction information
742/// to the form used in overload-candidate information.
743DeductionFailureInfo
744clang::MakeDeductionFailureInfo(ASTContext &Context,
745 TemplateDeductionResult TDK,
746 TemplateDeductionInfo &Info) {
747 DeductionFailureInfo Result;
748 Result.Result = static_cast<unsigned>(TDK);
749 Result.HasDiagnostic = false;
750 switch (TDK) {
751 case TemplateDeductionResult::Invalid:
752 case TemplateDeductionResult::InstantiationDepth:
753 case TemplateDeductionResult::TooManyArguments:
754 case TemplateDeductionResult::TooFewArguments:
755 case TemplateDeductionResult::MiscellaneousDeductionFailure:
756 case TemplateDeductionResult::CUDATargetMismatch:
757 Result.Data = nullptr;
758 break;
759
760 case TemplateDeductionResult::Incomplete:
761 case TemplateDeductionResult::InvalidExplicitArguments:
762 Result.Data = Info.Param.getOpaqueValue();
763 break;
764
765 case TemplateDeductionResult::DeducedMismatch:
766 case TemplateDeductionResult::DeducedMismatchNested: {
767 // FIXME: Should allocate from normal heap so that we can free this later.
768 auto *Saved = new (Context) DFIDeducedMismatchArgs;
769 Saved->FirstArg = Info.FirstArg;
770 Saved->SecondArg = Info.SecondArg;
771 Saved->TemplateArgs = Info.takeSugared();
772 Saved->CallArgIndex = Info.CallArgIndex;
773 Result.Data = Saved;
774 break;
775 }
776
777 case TemplateDeductionResult::NonDeducedMismatch: {
778 // FIXME: Should allocate from normal heap so that we can free this later.
779 DFIArguments *Saved = new (Context) DFIArguments;
780 Saved->FirstArg = Info.FirstArg;
781 Saved->SecondArg = Info.SecondArg;
782 Result.Data = Saved;
783 break;
784 }
785
786 case TemplateDeductionResult::IncompletePack:
787 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
788 case TemplateDeductionResult::Inconsistent:
789 case TemplateDeductionResult::Underqualified: {
790 // FIXME: Should allocate from normal heap so that we can free this later.
791 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
792 Saved->Param = Info.Param;
793 Saved->FirstArg = Info.FirstArg;
794 Saved->SecondArg = Info.SecondArg;
795 Result.Data = Saved;
796 break;
797 }
798
799 case TemplateDeductionResult::SubstitutionFailure:
800 Result.Data = Info.takeSugared();
801 if (Info.hasSFINAEDiagnostic()) {
802 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
803 SourceLocation(), PartialDiagnostic::NullDiagnostic());
804 Info.takeSFINAEDiagnostic(PD&: *Diag);
805 Result.HasDiagnostic = true;
806 }
807 break;
808
809 case TemplateDeductionResult::ConstraintsNotSatisfied: {
810 CNSInfo *Saved = new (Context) CNSInfo;
811 Saved->TemplateArgs = Info.takeSugared();
812 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
813 Result.Data = Saved;
814 break;
815 }
816
817 case TemplateDeductionResult::Success:
818 case TemplateDeductionResult::NonDependentConversionFailure:
819 case TemplateDeductionResult::AlreadyDiagnosed:
820 llvm_unreachable("not a deduction failure");
821 }
822
823 return Result;
824}
825
826void DeductionFailureInfo::Destroy() {
827 switch (static_cast<TemplateDeductionResult>(Result)) {
828 case TemplateDeductionResult::Success:
829 case TemplateDeductionResult::Invalid:
830 case TemplateDeductionResult::InstantiationDepth:
831 case TemplateDeductionResult::Incomplete:
832 case TemplateDeductionResult::TooManyArguments:
833 case TemplateDeductionResult::TooFewArguments:
834 case TemplateDeductionResult::InvalidExplicitArguments:
835 case TemplateDeductionResult::CUDATargetMismatch:
836 case TemplateDeductionResult::NonDependentConversionFailure:
837 break;
838
839 case TemplateDeductionResult::IncompletePack:
840 case TemplateDeductionResult::Inconsistent:
841 case TemplateDeductionResult::Underqualified:
842 case TemplateDeductionResult::DeducedMismatch:
843 case TemplateDeductionResult::DeducedMismatchNested:
844 case TemplateDeductionResult::NonDeducedMismatch:
845 // FIXME: Destroy the data?
846 Data = nullptr;
847 break;
848
849 case TemplateDeductionResult::SubstitutionFailure:
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
852 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
858 case TemplateDeductionResult::ConstraintsNotSatisfied:
859 // FIXME: Destroy the template argument list?
860 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
861 Data = nullptr;
862 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
863 Diag->~PartialDiagnosticAt();
864 HasDiagnostic = false;
865 }
866 break;
867
868 // Unhandled
869 case TemplateDeductionResult::MiscellaneousDeductionFailure:
870 case TemplateDeductionResult::AlreadyDiagnosed:
871 break;
872 }
873}
874
875PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
876 if (HasDiagnostic)
877 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
878 return nullptr;
879}
880
881TemplateParameter DeductionFailureInfo::getTemplateParameter() {
882 switch (static_cast<TemplateDeductionResult>(Result)) {
883 case TemplateDeductionResult::Success:
884 case TemplateDeductionResult::Invalid:
885 case TemplateDeductionResult::InstantiationDepth:
886 case TemplateDeductionResult::TooManyArguments:
887 case TemplateDeductionResult::TooFewArguments:
888 case TemplateDeductionResult::SubstitutionFailure:
889 case TemplateDeductionResult::DeducedMismatch:
890 case TemplateDeductionResult::DeducedMismatchNested:
891 case TemplateDeductionResult::NonDeducedMismatch:
892 case TemplateDeductionResult::CUDATargetMismatch:
893 case TemplateDeductionResult::NonDependentConversionFailure:
894 case TemplateDeductionResult::ConstraintsNotSatisfied:
895 return TemplateParameter();
896
897 case TemplateDeductionResult::Incomplete:
898 case TemplateDeductionResult::InvalidExplicitArguments:
899 return TemplateParameter::getFromOpaqueValue(VP: Data);
900
901 case TemplateDeductionResult::IncompletePack:
902 case TemplateDeductionResult::Inconsistent:
903 case TemplateDeductionResult::Underqualified:
904 return static_cast<DFIParamWithArguments*>(Data)->Param;
905
906 // Unhandled
907 case TemplateDeductionResult::MiscellaneousDeductionFailure:
908 case TemplateDeductionResult::AlreadyDiagnosed:
909 break;
910 }
911
912 return TemplateParameter();
913}
914
915TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
916 switch (static_cast<TemplateDeductionResult>(Result)) {
917 case TemplateDeductionResult::Success:
918 case TemplateDeductionResult::Invalid:
919 case TemplateDeductionResult::InstantiationDepth:
920 case TemplateDeductionResult::TooManyArguments:
921 case TemplateDeductionResult::TooFewArguments:
922 case TemplateDeductionResult::Incomplete:
923 case TemplateDeductionResult::IncompletePack:
924 case TemplateDeductionResult::InvalidExplicitArguments:
925 case TemplateDeductionResult::Inconsistent:
926 case TemplateDeductionResult::Underqualified:
927 case TemplateDeductionResult::NonDeducedMismatch:
928 case TemplateDeductionResult::CUDATargetMismatch:
929 case TemplateDeductionResult::NonDependentConversionFailure:
930 return nullptr;
931
932 case TemplateDeductionResult::DeducedMismatch:
933 case TemplateDeductionResult::DeducedMismatchNested:
934 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
935
936 case TemplateDeductionResult::SubstitutionFailure:
937 return static_cast<TemplateArgumentList*>(Data);
938
939 case TemplateDeductionResult::ConstraintsNotSatisfied:
940 return static_cast<CNSInfo*>(Data)->TemplateArgs;
941
942 // Unhandled
943 case TemplateDeductionResult::MiscellaneousDeductionFailure:
944 case TemplateDeductionResult::AlreadyDiagnosed:
945 break;
946 }
947
948 return nullptr;
949}
950
951const TemplateArgument *DeductionFailureInfo::getFirstArg() {
952 switch (static_cast<TemplateDeductionResult>(Result)) {
953 case TemplateDeductionResult::Success:
954 case TemplateDeductionResult::Invalid:
955 case TemplateDeductionResult::InstantiationDepth:
956 case TemplateDeductionResult::Incomplete:
957 case TemplateDeductionResult::TooManyArguments:
958 case TemplateDeductionResult::TooFewArguments:
959 case TemplateDeductionResult::InvalidExplicitArguments:
960 case TemplateDeductionResult::SubstitutionFailure:
961 case TemplateDeductionResult::CUDATargetMismatch:
962 case TemplateDeductionResult::NonDependentConversionFailure:
963 case TemplateDeductionResult::ConstraintsNotSatisfied:
964 return nullptr;
965
966 case TemplateDeductionResult::IncompletePack:
967 case TemplateDeductionResult::Inconsistent:
968 case TemplateDeductionResult::Underqualified:
969 case TemplateDeductionResult::DeducedMismatch:
970 case TemplateDeductionResult::DeducedMismatchNested:
971 case TemplateDeductionResult::NonDeducedMismatch:
972 return &static_cast<DFIArguments*>(Data)->FirstArg;
973
974 // Unhandled
975 case TemplateDeductionResult::MiscellaneousDeductionFailure:
976 case TemplateDeductionResult::AlreadyDiagnosed:
977 break;
978 }
979
980 return nullptr;
981}
982
983const TemplateArgument *DeductionFailureInfo::getSecondArg() {
984 switch (static_cast<TemplateDeductionResult>(Result)) {
985 case TemplateDeductionResult::Success:
986 case TemplateDeductionResult::Invalid:
987 case TemplateDeductionResult::InstantiationDepth:
988 case TemplateDeductionResult::Incomplete:
989 case TemplateDeductionResult::IncompletePack:
990 case TemplateDeductionResult::TooManyArguments:
991 case TemplateDeductionResult::TooFewArguments:
992 case TemplateDeductionResult::InvalidExplicitArguments:
993 case TemplateDeductionResult::SubstitutionFailure:
994 case TemplateDeductionResult::CUDATargetMismatch:
995 case TemplateDeductionResult::NonDependentConversionFailure:
996 case TemplateDeductionResult::ConstraintsNotSatisfied:
997 return nullptr;
998
999 case TemplateDeductionResult::Inconsistent:
1000 case TemplateDeductionResult::Underqualified:
1001 case TemplateDeductionResult::DeducedMismatch:
1002 case TemplateDeductionResult::DeducedMismatchNested:
1003 case TemplateDeductionResult::NonDeducedMismatch:
1004 return &static_cast<DFIArguments*>(Data)->SecondArg;
1005
1006 // Unhandled
1007 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1008 case TemplateDeductionResult::AlreadyDiagnosed:
1009 break;
1010 }
1011
1012 return nullptr;
1013}
1014
1015UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1016 switch (static_cast<TemplateDeductionResult>(Result)) {
1017 case TemplateDeductionResult::DeducedMismatch:
1018 case TemplateDeductionResult::DeducedMismatchNested:
1019 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1020
1021 default:
1022 return std::nullopt;
1023 }
1024}
1025
1026static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1027 const FunctionDecl *Y) {
1028 if (!X || !Y)
1029 return false;
1030 if (X->getNumParams() != Y->getNumParams())
1031 return false;
1032 // FIXME: when do rewritten comparison operators
1033 // with explicit object parameters correspond?
1034 // https://cplusplus.github.io/CWG/issues/2797.html
1035 for (unsigned I = 0; I < X->getNumParams(); ++I)
1036 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1037 T2: Y->getParamDecl(i: I)->getType()))
1038 return false;
1039 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1040 auto *FTY = Y->getDescribedFunctionTemplate();
1041 if (!FTY)
1042 return false;
1043 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1044 Y: FTY->getTemplateParameters()))
1045 return false;
1046 }
1047 return true;
1048}
1049
1050static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1051 Expr *FirstOperand, FunctionDecl *EqFD) {
1052 assert(EqFD->getOverloadedOperator() ==
1053 OverloadedOperatorKind::OO_EqualEqual);
1054 // C++2a [over.match.oper]p4:
1055 // A non-template function or function template F named operator== is a
1056 // rewrite target with first operand o unless a search for the name operator!=
1057 // in the scope S from the instantiation context of the operator expression
1058 // finds a function or function template that would correspond
1059 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1060 // scope of the class type of o if F is a class member, and the namespace
1061 // scope of which F is a member otherwise. A function template specialization
1062 // named operator== is a rewrite target if its function template is a rewrite
1063 // target.
1064 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1065 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1066 if (isa<CXXMethodDecl>(Val: EqFD)) {
1067 // If F is a class member, search scope is class type of first operand.
1068 QualType RHS = FirstOperand->getType();
1069 auto *RHSRec = RHS->getAsCXXRecordDecl();
1070 if (!RHSRec)
1071 return true;
1072 LookupResult Members(S, NotEqOp, OpLoc,
1073 Sema::LookupNameKind::LookupMemberName);
1074 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1075 Members.suppressAccessDiagnostics();
1076 for (NamedDecl *Op : Members)
1077 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1078 return false;
1079 return true;
1080 }
1081 // Otherwise the search scope is the namespace scope of which F is a member.
1082 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1083 auto *NotEqFD = Op->getAsFunction();
1084 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1085 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1086 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1087 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1088 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1089 return false;
1090 }
1091 return true;
1092}
1093
1094bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1095 OverloadedOperatorKind Op) const {
1096 if (!AllowRewrittenCandidates)
1097 return false;
1098 return Op == OO_EqualEqual || Op == OO_Spaceship;
1099}
1100
1101bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1102 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1103 auto Op = FD->getOverloadedOperator();
1104 if (!allowsReversed(Op))
1105 return false;
1106 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1107 assert(OriginalArgs.size() == 2);
1108 if (!shouldAddReversedEqEq(
1109 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1110 return false;
1111 }
1112 // Don't bother adding a reversed candidate that can never be a better
1113 // match than the non-reversed version.
1114 return FD->getNumNonObjectParams() != 2 ||
1115 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1116 T2: FD->getParamDecl(i: 1)->getType()) ||
1117 FD->hasAttr<EnableIfAttr>();
1118}
1119
1120void OverloadCandidateSet::destroyCandidates() {
1121 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1122 for (auto &C : i->Conversions)
1123 C.~ImplicitConversionSequence();
1124 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1125 i->DeductionFailure.Destroy();
1126 }
1127}
1128
1129void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1130 destroyCandidates();
1131 SlabAllocator.Reset();
1132 NumInlineBytesUsed = 0;
1133 Candidates.clear();
1134 Functions.clear();
1135 Kind = CSK;
1136 FirstDeferredCandidate = nullptr;
1137 DeferredCandidatesCount = 0;
1138 HasDeferredTemplateConstructors = false;
1139 ResolutionByPerfectCandidateIsDisabled = false;
1140}
1141
1142namespace {
1143 class UnbridgedCastsSet {
1144 struct Entry {
1145 Expr **Addr;
1146 Expr *Saved;
1147 };
1148 SmallVector<Entry, 2> Entries;
1149
1150 public:
1151 void save(Sema &S, Expr *&E) {
1152 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1153 Entry entry = { .Addr: &E, .Saved: E };
1154 Entries.push_back(Elt: entry);
1155 E = S.ObjC().stripARCUnbridgedCast(e: E);
1156 }
1157
1158 void restore() {
1159 for (SmallVectorImpl<Entry>::iterator
1160 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1161 *i->Addr = i->Saved;
1162 }
1163 };
1164}
1165
1166/// checkPlaceholderForOverload - Do any interesting placeholder-like
1167/// preprocessing on the given expression.
1168///
1169/// \param unbridgedCasts a collection to which to add unbridged casts;
1170/// without this, they will be immediately diagnosed as errors
1171///
1172/// Return true on unrecoverable error.
1173static bool
1174checkPlaceholderForOverload(Sema &S, Expr *&E,
1175 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1176 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1177 // We can't handle overloaded expressions here because overload
1178 // resolution might reasonably tweak them.
1179 if (placeholder->getKind() == BuiltinType::Overload) return false;
1180
1181 // If the context potentially accepts unbridged ARC casts, strip
1182 // the unbridged cast and add it to the collection for later restoration.
1183 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1184 unbridgedCasts) {
1185 unbridgedCasts->save(S, E);
1186 return false;
1187 }
1188
1189 // Go ahead and check everything else.
1190 ExprResult result = S.CheckPlaceholderExpr(E);
1191 if (result.isInvalid())
1192 return true;
1193
1194 E = result.get();
1195 return false;
1196 }
1197
1198 // Nothing to do.
1199 return false;
1200}
1201
1202/// checkArgPlaceholdersForOverload - Check a set of call operands for
1203/// placeholders.
1204static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1205 UnbridgedCastsSet &unbridged) {
1206 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1207 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1208 return true;
1209
1210 return false;
1211}
1212
1213OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1214 const LookupResult &Old, NamedDecl *&Match,
1215 bool NewIsUsingDecl) {
1216 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1217 I != E; ++I) {
1218 NamedDecl *OldD = *I;
1219
1220 bool OldIsUsingDecl = false;
1221 if (isa<UsingShadowDecl>(Val: OldD)) {
1222 OldIsUsingDecl = true;
1223
1224 // We can always introduce two using declarations into the same
1225 // context, even if they have identical signatures.
1226 if (NewIsUsingDecl) continue;
1227
1228 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1229 }
1230
1231 // A using-declaration does not conflict with another declaration
1232 // if one of them is hidden.
1233 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1234 continue;
1235
1236 // If either declaration was introduced by a using declaration,
1237 // we'll need to use slightly different rules for matching.
1238 // Essentially, these rules are the normal rules, except that
1239 // function templates hide function templates with different
1240 // return types or template parameter lists.
1241 bool UseMemberUsingDeclRules =
1242 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1243 !New->getFriendObjectKind();
1244
1245 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1246 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1247 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1248 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1249 continue;
1250 }
1251
1252 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1253 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1254 continue;
1255
1256 Match = *I;
1257 return OverloadKind::Match;
1258 }
1259
1260 // Builtins that have custom typechecking or have a reference should
1261 // not be overloadable or redeclarable.
1262 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1263 Match = *I;
1264 return OverloadKind::NonFunction;
1265 }
1266 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1267 // We can overload with these, which can show up when doing
1268 // redeclaration checks for UsingDecls.
1269 assert(Old.getLookupKind() == LookupUsingDeclName);
1270 } else if (isa<TagDecl>(Val: OldD)) {
1271 // We can always overload with tags by hiding them.
1272 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1273 // Optimistically assume that an unresolved using decl will
1274 // overload; if it doesn't, we'll have to diagnose during
1275 // template instantiation.
1276 //
1277 // Exception: if the scope is dependent and this is not a class
1278 // member, the using declaration can only introduce an enumerator.
1279 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1280 Match = *I;
1281 return OverloadKind::NonFunction;
1282 }
1283 } else {
1284 // (C++ 13p1):
1285 // Only function declarations can be overloaded; object and type
1286 // declarations cannot be overloaded.
1287 Match = *I;
1288 return OverloadKind::NonFunction;
1289 }
1290 }
1291
1292 // C++ [temp.friend]p1:
1293 // For a friend function declaration that is not a template declaration:
1294 // -- if the name of the friend is a qualified or unqualified template-id,
1295 // [...], otherwise
1296 // -- if the name of the friend is a qualified-id and a matching
1297 // non-template function is found in the specified class or namespace,
1298 // the friend declaration refers to that function, otherwise,
1299 // -- if the name of the friend is a qualified-id and a matching function
1300 // template is found in the specified class or namespace, the friend
1301 // declaration refers to the deduced specialization of that function
1302 // template, otherwise
1303 // -- the name shall be an unqualified-id [...]
1304 // If we get here for a qualified friend declaration, we've just reached the
1305 // third bullet. If the type of the friend is dependent, skip this lookup
1306 // until instantiation.
1307 if (New->getFriendObjectKind() && New->getQualifier() &&
1308 !New->getDescribedFunctionTemplate() &&
1309 !New->getDependentSpecializationInfo() &&
1310 !New->getType()->isDependentType()) {
1311 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1312 TemplateSpecResult.addAllDecls(Other: Old);
1313 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1314 /*QualifiedFriend*/true)) {
1315 New->setInvalidDecl();
1316 return OverloadKind::Overload;
1317 }
1318
1319 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1320 return OverloadKind::Match;
1321 }
1322
1323 return OverloadKind::Overload;
1324}
1325
1326template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1327 assert(D && "function decl should not be null");
1328 if (auto *A = D->getAttr<AttrT>())
1329 return !A->isImplicit();
1330 return false;
1331}
1332
1333static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1334 FunctionDecl *Old,
1335 bool UseMemberUsingDeclRules,
1336 bool ConsiderCudaAttrs,
1337 bool UseOverrideRules = false) {
1338 // C++ [basic.start.main]p2: This function shall not be overloaded.
1339 if (New->isMain())
1340 return false;
1341
1342 // MSVCRT user defined entry points cannot be overloaded.
1343 if (New->isMSVCRTEntryPoint())
1344 return false;
1345
1346 NamedDecl *OldDecl = Old;
1347 NamedDecl *NewDecl = New;
1348 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1349 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1350
1351 // C++ [temp.fct]p2:
1352 // A function template can be overloaded with other function templates
1353 // and with normal (non-template) functions.
1354 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1355 return true;
1356
1357 // Is the function New an overload of the function Old?
1358 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1359 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1360
1361 // Compare the signatures (C++ 1.3.10) of the two functions to
1362 // determine whether they are overloads. If we find any mismatch
1363 // in the signature, they are overloads.
1364
1365 // If either of these functions is a K&R-style function (no
1366 // prototype), then we consider them to have matching signatures.
1367 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1368 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1369 return false;
1370
1371 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1372 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1373
1374 // The signature of a function includes the types of its
1375 // parameters (C++ 1.3.10), which includes the presence or absence
1376 // of the ellipsis; see C++ DR 357).
1377 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1378 return true;
1379
1380 // For member-like friends, the enclosing class is part of the signature.
1381 if ((New->isMemberLikeConstrainedFriend() ||
1382 Old->isMemberLikeConstrainedFriend()) &&
1383 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1384 return true;
1385
1386 // Compare the parameter lists.
1387 // This can only be done once we have establish that friend functions
1388 // inhabit the same context, otherwise we might tried to instantiate
1389 // references to non-instantiated entities during constraint substitution.
1390 // GH78101.
1391 if (NewTemplate) {
1392 OldDecl = OldTemplate;
1393 NewDecl = NewTemplate;
1394 // C++ [temp.over.link]p4:
1395 // The signature of a function template consists of its function
1396 // signature, its return type and its template parameter list. The names
1397 // of the template parameters are significant only for establishing the
1398 // relationship between the template parameters and the rest of the
1399 // signature.
1400 //
1401 // We check the return type and template parameter lists for function
1402 // templates first; the remaining checks follow.
1403 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1404 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1405 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1406 bool SameReturnType = SemaRef.Context.hasSameType(
1407 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1408 // FIXME(GH58571): Match template parameter list even for non-constrained
1409 // template heads. This currently ensures that the code prior to C++20 is
1410 // not newly broken.
1411 bool ConstraintsInTemplateHead =
1412 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1413 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1414 // C++ [namespace.udecl]p11:
1415 // The set of declarations named by a using-declarator that inhabits a
1416 // class C does not include member functions and member function
1417 // templates of a base class that "correspond" to (and thus would
1418 // conflict with) a declaration of a function or function template in
1419 // C.
1420 // Comparing return types is not required for the "correspond" check to
1421 // decide whether a member introduced by a shadow declaration is hidden.
1422 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1423 !SameTemplateParameterList)
1424 return true;
1425 if (!UseMemberUsingDeclRules &&
1426 (!SameTemplateParameterList || !SameReturnType))
1427 return true;
1428 }
1429
1430 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1431 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1432
1433 int OldParamsOffset = 0;
1434 int NewParamsOffset = 0;
1435
1436 // When determining if a method is an overload from a base class, act as if
1437 // the implicit object parameter are of the same type.
1438
1439 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1440 if (M->isExplicitObjectMemberFunction()) {
1441 auto ThisType = M->getFunctionObjectParameterReferenceType();
1442 if (ThisType.isConstQualified())
1443 Q.removeConst();
1444 return Q;
1445 }
1446
1447 // We do not allow overloading based off of '__restrict'.
1448 Q.removeRestrict();
1449
1450 // We may not have applied the implicit const for a constexpr member
1451 // function yet (because we haven't yet resolved whether this is a static
1452 // or non-static member function). Add it now, on the assumption that this
1453 // is a redeclaration of OldMethod.
1454 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1455 (M->isConstexpr() || M->isConsteval()) &&
1456 !isa<CXXConstructorDecl>(Val: NewMethod))
1457 Q.addConst();
1458 return Q;
1459 };
1460
1461 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1462 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1463 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1464
1465 if (OldMethod->isExplicitObjectMemberFunction()) {
1466 BS.Quals.removeVolatile();
1467 DS.Quals.removeVolatile();
1468 }
1469
1470 return BS.Quals == DS.Quals;
1471 };
1472
1473 auto CompareType = [&](QualType Base, QualType D) {
1474 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1475 auto DS = D.getNonReferenceType().getCanonicalType().split();
1476
1477 if (!AreQualifiersEqual(BS, DS))
1478 return false;
1479
1480 if (OldMethod->isImplicitObjectMemberFunction() &&
1481 OldMethod->getParent() != NewMethod->getParent()) {
1482 CanQualType ParentType =
1483 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1484 if (ParentType.getTypePtr() != BS.Ty)
1485 return false;
1486 BS.Ty = DS.Ty;
1487 }
1488
1489 // FIXME: should we ignore some type attributes here?
1490 if (BS.Ty != DS.Ty)
1491 return false;
1492
1493 if (Base->isLValueReferenceType())
1494 return D->isLValueReferenceType();
1495 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1496 };
1497
1498 // If the function is a class member, its signature includes the
1499 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1500 auto DiagnoseInconsistentRefQualifiers = [&]() {
1501 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1502 return false;
1503 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1504 return false;
1505 if (OldMethod->isExplicitObjectMemberFunction() ||
1506 NewMethod->isExplicitObjectMemberFunction())
1507 return false;
1508 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1509 NewMethod->getRefQualifier() == RQ_None)) {
1510 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1511 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1512 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1513 return true;
1514 }
1515 return false;
1516 };
1517
1518 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1519 OldParamsOffset++;
1520 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1521 NewParamsOffset++;
1522
1523 if (OldType->getNumParams() - OldParamsOffset !=
1524 NewType->getNumParams() - NewParamsOffset ||
1525 !SemaRef.FunctionParamTypesAreEqual(
1526 Old: {OldType->param_type_begin() + OldParamsOffset,
1527 OldType->param_type_end()},
1528 New: {NewType->param_type_begin() + NewParamsOffset,
1529 NewType->param_type_end()},
1530 ArgPos: nullptr)) {
1531 return true;
1532 }
1533
1534 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1535 !NewMethod->isStatic()) {
1536 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1537 const CXXMethodDecl *New) {
1538 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1539 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1540
1541 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1542 return F->getRefQualifier() == RQ_None &&
1543 !F->isExplicitObjectMemberFunction();
1544 };
1545
1546 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1547 CompareType(OldObjectType.getNonReferenceType(),
1548 NewObjectType.getNonReferenceType()))
1549 return true;
1550 return CompareType(OldObjectType, NewObjectType);
1551 }(OldMethod, NewMethod);
1552
1553 if (!HaveCorrespondingObjectParameters) {
1554 if (DiagnoseInconsistentRefQualifiers())
1555 return true;
1556 // CWG2554
1557 // and, if at least one is an explicit object member function, ignoring
1558 // object parameters
1559 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1560 !OldMethod->isExplicitObjectMemberFunction()))
1561 return true;
1562 }
1563 }
1564
1565 if (!UseOverrideRules &&
1566 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1567 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1568 OldRC = Old->getTrailingRequiresClause();
1569 if (!NewRC != !OldRC)
1570 return true;
1571 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1572 return true;
1573 if (NewRC &&
1574 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1575 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1576 return true;
1577 }
1578
1579 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1580 NewMethod->isImplicitObjectMemberFunction()) {
1581 if (DiagnoseInconsistentRefQualifiers())
1582 return true;
1583 }
1584
1585 // Though pass_object_size is placed on parameters and takes an argument, we
1586 // consider it to be a function-level modifier for the sake of function
1587 // identity. Either the function has one or more parameters with
1588 // pass_object_size or it doesn't.
1589 if (functionHasPassObjectSizeParams(FD: New) !=
1590 functionHasPassObjectSizeParams(FD: Old))
1591 return true;
1592
1593 // enable_if attributes are an order-sensitive part of the signature.
1594 for (specific_attr_iterator<EnableIfAttr>
1595 NewI = New->specific_attr_begin<EnableIfAttr>(),
1596 NewE = New->specific_attr_end<EnableIfAttr>(),
1597 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1598 OldE = Old->specific_attr_end<EnableIfAttr>();
1599 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1600 if (NewI == NewE || OldI == OldE)
1601 return true;
1602 llvm::FoldingSetNodeID NewID, OldID;
1603 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1604 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1605 if (NewID != OldID)
1606 return true;
1607 }
1608
1609 // At this point, it is known that the two functions have the same signature.
1610 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1611 // Don't allow overloading of destructors. (In theory we could, but it
1612 // would be a giant change to clang.)
1613 if (!isa<CXXDestructorDecl>(Val: New)) {
1614 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1615 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1616 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1617 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1618 "Unexpected invalid target.");
1619
1620 // Allow overloading of functions with same signature and different CUDA
1621 // target attributes.
1622 if (NewTarget != OldTarget) {
1623 // Special case: non-constexpr function is allowed to override
1624 // constexpr virtual function
1625 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1626 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1627 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1628 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1629 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1630 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1631 return false;
1632 }
1633 return true;
1634 }
1635 }
1636 }
1637 }
1638
1639 // The signatures match; this is not an overload.
1640 return false;
1641}
1642
1643bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1644 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1645 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1646 ConsiderCudaAttrs);
1647}
1648
1649bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1650 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1651 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1652 /*UseMemberUsingDeclRules=*/false,
1653 /*ConsiderCudaAttrs=*/true,
1654 /*UseOverrideRules=*/true);
1655}
1656
1657/// Tries a user-defined conversion from From to ToType.
1658///
1659/// Produces an implicit conversion sequence for when a standard conversion
1660/// is not an option. See TryImplicitConversion for more information.
1661static ImplicitConversionSequence
1662TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1663 bool SuppressUserConversions,
1664 AllowedExplicit AllowExplicit,
1665 bool InOverloadResolution,
1666 bool CStyle,
1667 bool AllowObjCWritebackConversion,
1668 bool AllowObjCConversionOnExplicit) {
1669 ImplicitConversionSequence ICS;
1670
1671 if (SuppressUserConversions) {
1672 // We're not in the case above, so there is no conversion that
1673 // we can perform.
1674 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1675 return ICS;
1676 }
1677
1678 // Attempt user-defined conversion.
1679 OverloadCandidateSet Conversions(From->getExprLoc(),
1680 OverloadCandidateSet::CSK_Normal);
1681 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1682 Conversions, AllowExplicit,
1683 AllowObjCConversionOnExplicit)) {
1684 case OR_Success:
1685 case OR_Deleted:
1686 ICS.setUserDefined();
1687 // C++ [over.ics.user]p4:
1688 // A conversion of an expression of class type to the same class
1689 // type is given Exact Match rank, and a conversion of an
1690 // expression of class type to a base class of that type is
1691 // given Conversion rank, in spite of the fact that a copy
1692 // constructor (i.e., a user-defined conversion function) is
1693 // called for those cases.
1694 if (CXXConstructorDecl *Constructor
1695 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1696 QualType FromType;
1697 SourceLocation FromLoc;
1698 // C++11 [over.ics.list]p6, per DR2137:
1699 // C++17 [over.ics.list]p6:
1700 // If C is not an initializer-list constructor and the initializer list
1701 // has a single element of type cv U, where U is X or a class derived
1702 // from X, the implicit conversion sequence has Exact Match rank if U is
1703 // X, or Conversion rank if U is derived from X.
1704 bool FromListInit = false;
1705 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1706 InitList && InitList->getNumInits() == 1 &&
1707 !S.isInitListConstructor(Ctor: Constructor)) {
1708 const Expr *SingleInit = InitList->getInit(Init: 0);
1709 FromType = SingleInit->getType();
1710 FromLoc = SingleInit->getBeginLoc();
1711 FromListInit = true;
1712 } else {
1713 FromType = From->getType();
1714 FromLoc = From->getBeginLoc();
1715 }
1716 QualType FromCanon =
1717 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1718 QualType ToCanon
1719 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1720 if ((FromCanon == ToCanon ||
1721 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1722 // Turn this into a "standard" conversion sequence, so that it
1723 // gets ranked with standard conversion sequences.
1724 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1725 ICS.setStandard();
1726 ICS.Standard.setAsIdentityConversion();
1727 ICS.Standard.setFromType(FromType);
1728 ICS.Standard.setAllToTypes(ToType);
1729 ICS.Standard.FromBracedInitList = FromListInit;
1730 ICS.Standard.CopyConstructor = Constructor;
1731 ICS.Standard.FoundCopyConstructor = Found;
1732 if (ToCanon != FromCanon)
1733 ICS.Standard.Second = ICK_Derived_To_Base;
1734 }
1735 }
1736 break;
1737
1738 case OR_Ambiguous:
1739 ICS.setAmbiguous();
1740 ICS.Ambiguous.setFromType(From->getType());
1741 ICS.Ambiguous.setToType(ToType);
1742 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1743 Cand != Conversions.end(); ++Cand)
1744 if (Cand->Best)
1745 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1746 break;
1747
1748 // Fall through.
1749 case OR_No_Viable_Function:
1750 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1751 break;
1752 }
1753
1754 return ICS;
1755}
1756
1757/// TryImplicitConversion - Attempt to perform an implicit conversion
1758/// from the given expression (Expr) to the given type (ToType). This
1759/// function returns an implicit conversion sequence that can be used
1760/// to perform the initialization. Given
1761///
1762/// void f(float f);
1763/// void g(int i) { f(i); }
1764///
1765/// this routine would produce an implicit conversion sequence to
1766/// describe the initialization of f from i, which will be a standard
1767/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1768/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1769//
1770/// Note that this routine only determines how the conversion can be
1771/// performed; it does not actually perform the conversion. As such,
1772/// it will not produce any diagnostics if no conversion is available,
1773/// but will instead return an implicit conversion sequence of kind
1774/// "BadConversion".
1775///
1776/// If @p SuppressUserConversions, then user-defined conversions are
1777/// not permitted.
1778/// If @p AllowExplicit, then explicit user-defined conversions are
1779/// permitted.
1780///
1781/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1782/// writeback conversion, which allows __autoreleasing id* parameters to
1783/// be initialized with __strong id* or __weak id* arguments.
1784static ImplicitConversionSequence
1785TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1786 bool SuppressUserConversions,
1787 AllowedExplicit AllowExplicit,
1788 bool InOverloadResolution,
1789 bool CStyle,
1790 bool AllowObjCWritebackConversion,
1791 bool AllowObjCConversionOnExplicit) {
1792 ImplicitConversionSequence ICS;
1793 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1794 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1795 ICS.setStandard();
1796 return ICS;
1797 }
1798
1799 if (!S.getLangOpts().CPlusPlus) {
1800 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1801 return ICS;
1802 }
1803
1804 // C++ [over.ics.user]p4:
1805 // A conversion of an expression of class type to the same class
1806 // type is given Exact Match rank, and a conversion of an
1807 // expression of class type to a base class of that type is
1808 // given Conversion rank, in spite of the fact that a copy/move
1809 // constructor (i.e., a user-defined conversion function) is
1810 // called for those cases.
1811 QualType FromType = From->getType();
1812 if (ToType->isRecordType() &&
1813 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1814 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1815 ICS.setStandard();
1816 ICS.Standard.setAsIdentityConversion();
1817 ICS.Standard.setFromType(FromType);
1818 ICS.Standard.setAllToTypes(ToType);
1819
1820 // We don't actually check at this point whether there is a valid
1821 // copy/move constructor, since overloading just assumes that it
1822 // exists. When we actually perform initialization, we'll find the
1823 // appropriate constructor to copy the returned object, if needed.
1824 ICS.Standard.CopyConstructor = nullptr;
1825
1826 // Determine whether this is considered a derived-to-base conversion.
1827 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1828 ICS.Standard.Second = ICK_Derived_To_Base;
1829
1830 return ICS;
1831 }
1832
1833 if (S.getLangOpts().HLSL) {
1834 // Handle conversion of the HLSL resource types.
1835 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1836 if (FromTy->isHLSLAttributedResourceType()) {
1837 // Attributed resource types can convert to other attributed
1838 // resource types with the same attributes and contained types,
1839 // or to __hlsl_resource_t without any attributes.
1840 bool CanConvert = false;
1841 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1842 if (ToTy->isHLSLAttributedResourceType()) {
1843 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1844 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1845 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1846 T2: FromResType->getWrappedType()) &&
1847 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1848 T2: FromResType->getContainedType()) &&
1849 ToResType->getAttrs() == FromResType->getAttrs())
1850 CanConvert = true;
1851 } else if (ToTy->isHLSLResourceType()) {
1852 CanConvert = true;
1853 }
1854 if (CanConvert) {
1855 ICS.setStandard();
1856 ICS.Standard.setAsIdentityConversion();
1857 ICS.Standard.setFromType(FromType);
1858 ICS.Standard.setAllToTypes(ToType);
1859 return ICS;
1860 }
1861 }
1862 }
1863
1864 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1865 AllowExplicit, InOverloadResolution, CStyle,
1866 AllowObjCWritebackConversion,
1867 AllowObjCConversionOnExplicit);
1868}
1869
1870ImplicitConversionSequence
1871Sema::TryImplicitConversion(Expr *From, QualType ToType,
1872 bool SuppressUserConversions,
1873 AllowedExplicit AllowExplicit,
1874 bool InOverloadResolution,
1875 bool CStyle,
1876 bool AllowObjCWritebackConversion) {
1877 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1878 AllowExplicit, InOverloadResolution, CStyle,
1879 AllowObjCWritebackConversion,
1880 /*AllowObjCConversionOnExplicit=*/false);
1881}
1882
1883ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1884 AssignmentAction Action,
1885 bool AllowExplicit) {
1886 if (checkPlaceholderForOverload(S&: *this, E&: From))
1887 return ExprError();
1888
1889 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1890 bool AllowObjCWritebackConversion =
1891 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1892 Action == AssignmentAction::Sending);
1893 if (getLangOpts().ObjC)
1894 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1895 SrcType: From->getType(), SrcExpr&: From);
1896 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1897 S&: *this, From, ToType,
1898 /*SuppressUserConversions=*/false,
1899 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1900 /*InOverloadResolution=*/false,
1901 /*CStyle=*/false, AllowObjCWritebackConversion,
1902 /*AllowObjCConversionOnExplicit=*/false);
1903 return PerformImplicitConversion(From, ToType, ICS, Action);
1904}
1905
1906bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1907 QualType &ResultTy) const {
1908 bool Changed = IsFunctionConversion(FromType, ToType);
1909 if (Changed)
1910 ResultTy = ToType;
1911 return Changed;
1912}
1913
1914bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1915 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1916 return false;
1917
1918 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1919 // or F(t noexcept) -> F(t)
1920 // where F adds one of the following at most once:
1921 // - a pointer
1922 // - a member pointer
1923 // - a block pointer
1924 // Changes here need matching changes in FindCompositePointerType.
1925 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1926 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1927 Type::TypeClass TyClass = CanTo->getTypeClass();
1928 if (TyClass != CanFrom->getTypeClass()) return false;
1929 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1930 if (TyClass == Type::Pointer) {
1931 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1932 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1933 } else if (TyClass == Type::BlockPointer) {
1934 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1935 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1936 } else if (TyClass == Type::MemberPointer) {
1937 auto ToMPT = CanTo.castAs<MemberPointerType>();
1938 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1939 // A function pointer conversion cannot change the class of the function.
1940 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1941 D2: FromMPT->getMostRecentCXXRecordDecl()))
1942 return false;
1943 CanTo = ToMPT->getPointeeType();
1944 CanFrom = FromMPT->getPointeeType();
1945 } else {
1946 return false;
1947 }
1948
1949 TyClass = CanTo->getTypeClass();
1950 if (TyClass != CanFrom->getTypeClass()) return false;
1951 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1952 return false;
1953 }
1954
1955 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1956 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1957
1958 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1959 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1960
1961 bool Changed = false;
1962
1963 // Drop 'noreturn' if not present in target type.
1964 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1965 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1966 Changed = true;
1967 }
1968
1969 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1970 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1971
1972 if (FromFPT && ToFPT) {
1973 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1974 QualType NewTy = Context.getFunctionType(
1975 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1976 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1977 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
1978 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1979 FromFn = FromFPT;
1980 Changed = true;
1981 }
1982 }
1983
1984 // Drop 'noexcept' if not present in target type.
1985 if (FromFPT && ToFPT) {
1986 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1987 FromFn = cast<FunctionType>(
1988 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1989 ESI: EST_None)
1990 .getTypePtr());
1991 Changed = true;
1992 }
1993
1994 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1995 // only if the ExtParameterInfo lists of the two function prototypes can be
1996 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1997 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1998 bool CanUseToFPT, CanUseFromFPT;
1999 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2000 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2001 CanUseToFPT && !CanUseFromFPT) {
2002 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2003 ExtInfo.ExtParameterInfos =
2004 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2005 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2006 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2007 FromFn = QT->getAs<FunctionType>();
2008 Changed = true;
2009 }
2010
2011 if (Context.hasAnyFunctionEffects()) {
2012 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2013
2014 // Transparently add/drop effects; here we are concerned with
2015 // language rules/canonicalization. Adding/dropping effects is a warning.
2016 const auto FromFX = FromFPT->getFunctionEffects();
2017 const auto ToFX = ToFPT->getFunctionEffects();
2018 if (FromFX != ToFX) {
2019 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2020 ExtInfo.FunctionEffects = ToFX;
2021 QualType QT = Context.getFunctionType(
2022 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2023 FromFn = QT->getAs<FunctionType>();
2024 Changed = true;
2025 }
2026 }
2027 }
2028
2029 if (!Changed)
2030 return false;
2031
2032 assert(QualType(FromFn, 0).isCanonical());
2033 if (QualType(FromFn, 0) != CanTo) return false;
2034
2035 return true;
2036}
2037
2038/// Determine whether the conversion from FromType to ToType is a valid
2039/// floating point conversion.
2040///
2041static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2042 QualType ToType) {
2043 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2044 return false;
2045 // FIXME: disable conversions between long double, __ibm128 and __float128
2046 // if their representation is different until there is back end support
2047 // We of course allow this conversion if long double is really double.
2048
2049 // Conversions between bfloat16 and float16 are currently not supported.
2050 if ((FromType->isBFloat16Type() &&
2051 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2052 (ToType->isBFloat16Type() &&
2053 (FromType->isFloat16Type() || FromType->isHalfType())))
2054 return false;
2055
2056 // Conversions between IEEE-quad and IBM-extended semantics are not
2057 // permitted.
2058 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2059 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2060 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2061 &ToSem == &llvm::APFloat::IEEEquad()) ||
2062 (&FromSem == &llvm::APFloat::IEEEquad() &&
2063 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2064 return false;
2065 return true;
2066}
2067
2068static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2069 QualType ToType,
2070 ImplicitConversionKind &ICK,
2071 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/// matrix conversion.
2113///
2114/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2115/// conversion.
2116static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2117 ImplicitConversionKind &ICK,
2118 ImplicitConversionKind &ElConv, Expr *From,
2119 bool InOverloadResolution, bool CStyle) {
2120 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2121 if (!S.getLangOpts().HLSL)
2122 return false;
2123
2124 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2125 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2126
2127 // If both arguments are matrix, handle possible matrix truncation and
2128 // element conversion.
2129 if (ToMatrixType && FromMatrixType) {
2130 unsigned FromCols = FromMatrixType->getNumColumns();
2131 unsigned ToCols = ToMatrixType->getNumColumns();
2132 if (FromCols < ToCols)
2133 return false;
2134
2135 unsigned FromRows = FromMatrixType->getNumRows();
2136 unsigned ToRows = ToMatrixType->getNumRows();
2137 if (FromRows < ToRows)
2138 return false;
2139
2140 if (FromRows == ToRows && FromCols == ToCols)
2141 ElConv = ICK_Identity;
2142 else
2143 ElConv = ICK_HLSL_Matrix_Truncation;
2144
2145 QualType FromElTy = FromMatrixType->getElementType();
2146 QualType ToElTy = ToMatrixType->getElementType();
2147 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2148 return true;
2149 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2150 }
2151
2152 // Matrix splat from any arithmetic type to a matrix.
2153 if (ToMatrixType && FromType->isArithmeticType()) {
2154 ElConv = ICK_HLSL_Matrix_Splat;
2155 QualType ToElTy = ToMatrixType->getElementType();
2156 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2157 ICK = ICK_HLSL_Matrix_Splat;
2158 return true;
2159 }
2160 if (FromMatrixType && !ToMatrixType) {
2161 ElConv = ICK_HLSL_Matrix_Truncation;
2162 QualType FromElTy = FromMatrixType->getElementType();
2163 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2164 return true;
2165 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2166 }
2167
2168 return false;
2169}
2170
2171/// Determine whether the conversion from FromType to ToType is a valid
2172/// vector conversion.
2173///
2174/// \param ICK Will be set to the vector conversion kind, if this is a vector
2175/// conversion.
2176static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2177 ImplicitConversionKind &ICK,
2178 ImplicitConversionKind &ElConv, Expr *From,
2179 bool InOverloadResolution, bool CStyle) {
2180 // We need at least one of these types to be a vector type to have a vector
2181 // conversion.
2182 if (!ToType->isVectorType() && !FromType->isVectorType())
2183 return false;
2184
2185 // Identical types require no conversions.
2186 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2187 return false;
2188
2189 // HLSL allows implicit truncation of vector types.
2190 if (S.getLangOpts().HLSL) {
2191 auto *ToExtType = ToType->getAs<ExtVectorType>();
2192 auto *FromExtType = FromType->getAs<ExtVectorType>();
2193
2194 // If both arguments are vectors, handle possible vector truncation and
2195 // element conversion.
2196 if (ToExtType && FromExtType) {
2197 unsigned FromElts = FromExtType->getNumElements();
2198 unsigned ToElts = ToExtType->getNumElements();
2199 if (FromElts < ToElts)
2200 return false;
2201 if (FromElts == ToElts)
2202 ElConv = ICK_Identity;
2203 else
2204 ElConv = ICK_HLSL_Vector_Truncation;
2205
2206 QualType FromElTy = FromExtType->getElementType();
2207 QualType ToElTy = ToExtType->getElementType();
2208 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2209 return true;
2210 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2211 }
2212 if (FromExtType && !ToExtType) {
2213 ElConv = ICK_HLSL_Vector_Truncation;
2214 QualType FromElTy = FromExtType->getElementType();
2215 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2216 return true;
2217 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2218 }
2219 // Fallthrough for the case where ToType is a vector and FromType is not.
2220 }
2221
2222 // There are no conversions between extended vector types, only identity.
2223 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2224 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2225 // Implicit conversions require the same number of elements.
2226 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2227 return false;
2228
2229 // Permit implicit conversions from integral values to boolean vectors.
2230 if (ToType->isExtVectorBoolType() &&
2231 FromExtType->getElementType()->isIntegerType()) {
2232 ICK = ICK_Boolean_Conversion;
2233 return true;
2234 }
2235 // There are no other conversions between extended vector types.
2236 return false;
2237 }
2238
2239 // Vector splat from any arithmetic type to a vector.
2240 if (FromType->isArithmeticType()) {
2241 if (S.getLangOpts().HLSL) {
2242 ElConv = ICK_HLSL_Vector_Splat;
2243 QualType ToElTy = ToExtType->getElementType();
2244 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2245 From);
2246 }
2247 ICK = ICK_Vector_Splat;
2248 return true;
2249 }
2250 }
2251
2252 if (ToType->isSVESizelessBuiltinType() ||
2253 FromType->isSVESizelessBuiltinType())
2254 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2255 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2256 ICK = ICK_SVE_Vector_Conversion;
2257 return true;
2258 }
2259
2260 if (ToType->isRVVSizelessBuiltinType() ||
2261 FromType->isRVVSizelessBuiltinType())
2262 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2263 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2264 ICK = ICK_RVV_Vector_Conversion;
2265 return true;
2266 }
2267
2268 // We can perform the conversion between vector types in the following cases:
2269 // 1)vector types are equivalent AltiVec and GCC vector types
2270 // 2)lax vector conversions are permitted and the vector types are of the
2271 // same size
2272 // 3)the destination type does not have the ARM MVE strict-polymorphism
2273 // attribute, which inhibits lax vector conversion for overload resolution
2274 // only
2275 if (ToType->isVectorType() && FromType->isVectorType()) {
2276 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2277 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2278 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2279 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2280 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2281 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2282 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2283 !InOverloadResolution && !CStyle) {
2284 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2285 << FromType << ToType;
2286 }
2287 ICK = ICK_Vector_Conversion;
2288 return true;
2289 }
2290 }
2291
2292 return false;
2293}
2294
2295static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2296 bool InOverloadResolution,
2297 StandardConversionSequence &SCS,
2298 bool CStyle);
2299
2300/// IsStandardConversion - Determines whether there is a standard
2301/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2302/// expression From to the type ToType. Standard conversion sequences
2303/// only consider non-class types; for conversions that involve class
2304/// types, use TryImplicitConversion. If a conversion exists, SCS will
2305/// contain the standard conversion sequence required to perform this
2306/// conversion and this routine will return true. Otherwise, this
2307/// routine will return false and the value of SCS is unspecified.
2308static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2309 bool InOverloadResolution,
2310 StandardConversionSequence &SCS,
2311 bool CStyle,
2312 bool AllowObjCWritebackConversion) {
2313 QualType FromType = From->getType();
2314
2315 // Standard conversions (C++ [conv])
2316 SCS.setAsIdentityConversion();
2317 SCS.IncompatibleObjC = false;
2318 SCS.setFromType(FromType);
2319 SCS.CopyConstructor = nullptr;
2320
2321 // There are no standard conversions for class types in C++, so
2322 // abort early. When overloading in C, however, we do permit them.
2323 if (S.getLangOpts().CPlusPlus &&
2324 (FromType->isRecordType() || ToType->isRecordType()))
2325 return false;
2326
2327 // The first conversion can be an lvalue-to-rvalue conversion,
2328 // array-to-pointer conversion, or function-to-pointer conversion
2329 // (C++ 4p1).
2330
2331 if (FromType == S.Context.OverloadTy) {
2332 DeclAccessPair AccessPair;
2333 if (FunctionDecl *Fn
2334 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2335 Found&: AccessPair)) {
2336 // We were able to resolve the address of the overloaded function,
2337 // so we can convert to the type of that function.
2338 FromType = Fn->getType();
2339 SCS.setFromType(FromType);
2340
2341 // we can sometimes resolve &foo<int> regardless of ToType, so check
2342 // if the type matches (identity) or we are converting to bool
2343 if (!S.Context.hasSameUnqualifiedType(
2344 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2345 // if the function type matches except for [[noreturn]], it's ok
2346 if (!S.IsFunctionConversion(FromType,
2347 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2348 // otherwise, only a boolean conversion is standard
2349 if (!ToType->isBooleanType())
2350 return false;
2351 }
2352
2353 // Check if the "from" expression is taking the address of an overloaded
2354 // function and recompute the FromType accordingly. Take advantage of the
2355 // fact that non-static member functions *must* have such an address-of
2356 // expression.
2357 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2358 if (Method && !Method->isStatic() &&
2359 !Method->isExplicitObjectMemberFunction()) {
2360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2361 "Non-unary operator on non-static member address");
2362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2363 == UO_AddrOf &&
2364 "Non-address-of operator on non-static member address");
2365 FromType = S.Context.getMemberPointerType(
2366 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2367 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2368 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2369 UO_AddrOf &&
2370 "Non-address-of operator for overloaded function expression");
2371 FromType = S.Context.getPointerType(T: FromType);
2372 }
2373 } else {
2374 return false;
2375 }
2376 }
2377
2378 bool argIsLValue = From->isGLValue();
2379 // To handle conversion from ArrayParameterType to ConstantArrayType
2380 // this block must be above the one below because Array parameters
2381 // do not decay and when handling HLSLOutArgExprs and
2382 // the From expression is an LValue.
2383 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2384 ToType->isConstantArrayType()) {
2385 // HLSL constant array parameters do not decay, so if the argument is a
2386 // constant array and the parameter is an ArrayParameterType we have special
2387 // handling here.
2388 if (ToType->isArrayParameterType()) {
2389 FromType = S.Context.getArrayParameterType(Ty: FromType);
2390 } else if (FromType->isArrayParameterType()) {
2391 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2392 FromType = APT->getConstantArrayType(Ctx: S.Context);
2393 }
2394
2395 SCS.First = ICK_HLSL_Array_RValue;
2396
2397 // Don't consider qualifiers, which include things like address spaces
2398 if (FromType.getCanonicalType().getUnqualifiedType() !=
2399 ToType.getCanonicalType().getUnqualifiedType())
2400 return false;
2401
2402 SCS.setAllToTypes(ToType);
2403 return true;
2404 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2405 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2406 // Lvalue-to-rvalue conversion (C++11 4.1):
2407 // A glvalue (3.10) of a non-function, non-array type T can
2408 // be converted to a prvalue.
2409
2410 SCS.First = ICK_Lvalue_To_Rvalue;
2411
2412 // C11 6.3.2.1p2:
2413 // ... if the lvalue has atomic type, the value has the non-atomic version
2414 // of the type of the lvalue ...
2415 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2416 FromType = Atomic->getValueType();
2417
2418 // If T is a non-class type, the type of the rvalue is the
2419 // cv-unqualified version of T. Otherwise, the type of the rvalue
2420 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2421 // just strip the qualifiers because they don't matter.
2422 FromType = FromType.getUnqualifiedType();
2423 } else if (FromType->isArrayType()) {
2424 // Array-to-pointer conversion (C++ 4.2)
2425 SCS.First = ICK_Array_To_Pointer;
2426
2427 // An lvalue or rvalue of type "array of N T" or "array of unknown
2428 // bound of T" can be converted to an rvalue of type "pointer to
2429 // T" (C++ 4.2p1).
2430 FromType = S.Context.getArrayDecayedType(T: FromType);
2431
2432 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2433 // This conversion is deprecated in C++03 (D.4)
2434 SCS.DeprecatedStringLiteralToCharPtr = true;
2435
2436 // For the purpose of ranking in overload resolution
2437 // (13.3.3.1.1), this conversion is considered an
2438 // array-to-pointer conversion followed by a qualification
2439 // conversion (4.4). (C++ 4.2p2)
2440 SCS.Second = ICK_Identity;
2441 SCS.Third = ICK_Qualification;
2442 SCS.QualificationIncludesObjCLifetime = false;
2443 SCS.setAllToTypes(FromType);
2444 return true;
2445 }
2446 } else if (FromType->isFunctionType() && argIsLValue) {
2447 // Function-to-pointer conversion (C++ 4.3).
2448 SCS.First = ICK_Function_To_Pointer;
2449
2450 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2451 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2452 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2453 return false;
2454
2455 // An lvalue of function type T can be converted to an rvalue of
2456 // type "pointer to T." The result is a pointer to the
2457 // function. (C++ 4.3p1).
2458 FromType = S.Context.getPointerType(T: FromType);
2459 } else {
2460 // We don't require any conversions for the first step.
2461 SCS.First = ICK_Identity;
2462 }
2463 SCS.setToType(Idx: 0, T: FromType);
2464
2465 // The second conversion can be an integral promotion, floating
2466 // point promotion, integral conversion, floating point conversion,
2467 // floating-integral conversion, pointer conversion,
2468 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2469 // For overloading in C, this can also be a "compatible-type"
2470 // conversion.
2471 bool IncompatibleObjC = false;
2472 ImplicitConversionKind SecondICK = ICK_Identity;
2473 ImplicitConversionKind DimensionICK = ICK_Identity;
2474 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2475 // The unqualified versions of the types are the same: there's no
2476 // conversion to do.
2477 SCS.Second = ICK_Identity;
2478 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2479 // Integral promotion (C++ 4.5).
2480 SCS.Second = ICK_Integral_Promotion;
2481 FromType = ToType.getUnqualifiedType();
2482 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2483 // Floating point promotion (C++ 4.6).
2484 SCS.Second = ICK_Floating_Promotion;
2485 FromType = ToType.getUnqualifiedType();
2486 } else if (S.IsComplexPromotion(FromType, ToType)) {
2487 // Complex promotion (Clang extension)
2488 SCS.Second = ICK_Complex_Promotion;
2489 FromType = ToType.getUnqualifiedType();
2490 } else if (ToType->isBooleanType() &&
2491 (FromType->isArithmeticType() ||
2492 FromType->isAnyPointerType() ||
2493 FromType->isBlockPointerType() ||
2494 FromType->isMemberPointerType())) {
2495 // Boolean conversions (C++ 4.12).
2496 SCS.Second = ICK_Boolean_Conversion;
2497 FromType = S.Context.BoolTy;
2498 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2499 ToType->isIntegralType(Ctx: S.Context)) {
2500 // Integral conversions (C++ 4.7).
2501 SCS.Second = ICK_Integral_Conversion;
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2504 // Complex conversions (C99 6.3.1.6)
2505 SCS.Second = ICK_Complex_Conversion;
2506 FromType = ToType.getUnqualifiedType();
2507 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2508 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2509 // Complex-real conversions (C99 6.3.1.7)
2510 SCS.Second = ICK_Complex_Real;
2511 FromType = ToType.getUnqualifiedType();
2512 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2513 // Floating point conversions (C++ 4.8).
2514 SCS.Second = ICK_Floating_Conversion;
2515 FromType = ToType.getUnqualifiedType();
2516 } else if ((FromType->isRealFloatingType() &&
2517 ToType->isIntegralType(Ctx: S.Context)) ||
2518 (FromType->isIntegralOrUnscopedEnumerationType() &&
2519 ToType->isRealFloatingType())) {
2520
2521 // Floating-integral conversions (C++ 4.9).
2522 SCS.Second = ICK_Floating_Integral;
2523 FromType = ToType.getUnqualifiedType();
2524 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2525 SCS.Second = ICK_Block_Pointer_Conversion;
2526 } else if (AllowObjCWritebackConversion &&
2527 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2528 SCS.Second = ICK_Writeback_Conversion;
2529 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2530 ConvertedType&: FromType, IncompatibleObjC)) {
2531 // Pointer conversions (C++ 4.10).
2532 SCS.Second = ICK_Pointer_Conversion;
2533 SCS.IncompatibleObjC = IncompatibleObjC;
2534 FromType = FromType.getUnqualifiedType();
2535 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2536 InOverloadResolution, ConvertedType&: FromType)) {
2537 // Pointer to member conversions (4.11).
2538 SCS.Second = ICK_Pointer_Member;
2539 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2540 From, InOverloadResolution, CStyle)) {
2541 SCS.Second = SecondICK;
2542 SCS.Dimension = DimensionICK;
2543 FromType = ToType.getUnqualifiedType();
2544 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2545 From, InOverloadResolution, CStyle)) {
2546 SCS.Second = SecondICK;
2547 SCS.Dimension = DimensionICK;
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (!S.getLangOpts().CPlusPlus &&
2550 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2551 // Compatible conversions (Clang extension for C function overloading)
2552 SCS.Second = ICK_Compatible_Conversion;
2553 FromType = ToType.getUnqualifiedType();
2554 } else if (IsTransparentUnionStandardConversion(
2555 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2556 SCS.Second = ICK_TransparentUnionConversion;
2557 FromType = ToType;
2558 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2559 CStyle)) {
2560 // tryAtomicConversion has updated the standard conversion sequence
2561 // appropriately.
2562 return true;
2563 } else if (ToType->isEventT() &&
2564 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2565 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2566 SCS.Second = ICK_Zero_Event_Conversion;
2567 FromType = ToType;
2568 } else if (ToType->isQueueT() &&
2569 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2570 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2571 SCS.Second = ICK_Zero_Queue_Conversion;
2572 FromType = ToType;
2573 } else if (ToType->isSamplerT() &&
2574 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2575 SCS.Second = ICK_Compatible_Conversion;
2576 FromType = ToType;
2577 } else if ((ToType->isFixedPointType() &&
2578 FromType->isConvertibleToFixedPointType()) ||
2579 (FromType->isFixedPointType() &&
2580 ToType->isConvertibleToFixedPointType())) {
2581 SCS.Second = ICK_Fixed_Point_Conversion;
2582 FromType = ToType;
2583 } else {
2584 // No second conversion required.
2585 SCS.Second = ICK_Identity;
2586 }
2587 SCS.setToType(Idx: 1, T: FromType);
2588
2589 // The third conversion can be a function pointer conversion or a
2590 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2591 bool ObjCLifetimeConversion;
2592 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2593 // Function pointer conversions (removing 'noexcept') including removal of
2594 // 'noreturn' (Clang extension).
2595 SCS.Third = ICK_Function_Conversion;
2596 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2597 ObjCLifetimeConversion)) {
2598 SCS.Third = ICK_Qualification;
2599 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2600 FromType = ToType;
2601 } else {
2602 // No conversion required
2603 SCS.Third = ICK_Identity;
2604 }
2605
2606 // C++ [over.best.ics]p6:
2607 // [...] Any difference in top-level cv-qualification is
2608 // subsumed by the initialization itself and does not constitute
2609 // a conversion. [...]
2610 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2611 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2612 if (CanonFrom.getLocalUnqualifiedType()
2613 == CanonTo.getLocalUnqualifiedType() &&
2614 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2615 FromType = ToType;
2616 CanonFrom = CanonTo;
2617 }
2618
2619 SCS.setToType(Idx: 2, T: FromType);
2620
2621 if (CanonFrom == CanonTo)
2622 return true;
2623
2624 // If we have not converted the argument type to the parameter type,
2625 // this is a bad conversion sequence, unless we're resolving an overload in C.
2626 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2627 return false;
2628
2629 ExprResult ER = ExprResult{From};
2630 AssignConvertType Conv =
2631 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2632 /*Diagnose=*/false,
2633 /*DiagnoseCFAudited=*/false,
2634 /*ConvertRHS=*/false);
2635 ImplicitConversionKind SecondConv;
2636 switch (Conv) {
2637 case AssignConvertType::Compatible:
2638 case AssignConvertType::
2639 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2640 SecondConv = ICK_C_Only_Conversion;
2641 break;
2642 // For our purposes, discarding qualifiers is just as bad as using an
2643 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2644 // qualifiers, as well.
2645 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2646 case AssignConvertType::IncompatiblePointer:
2647 case AssignConvertType::IncompatiblePointerSign:
2648 SecondConv = ICK_Incompatible_Pointer_Conversion;
2649 break;
2650 default:
2651 return false;
2652 }
2653
2654 // First can only be an lvalue conversion, so we pretend that this was the
2655 // second conversion. First should already be valid from earlier in the
2656 // function.
2657 SCS.Second = SecondConv;
2658 SCS.setToType(Idx: 1, T: ToType);
2659
2660 // Third is Identity, because Second should rank us worse than any other
2661 // conversion. This could also be ICK_Qualification, but it's simpler to just
2662 // lump everything in with the second conversion, and we don't gain anything
2663 // from making this ICK_Qualification.
2664 SCS.Third = ICK_Identity;
2665 SCS.setToType(Idx: 2, T: ToType);
2666 return true;
2667}
2668
2669static bool
2670IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2671 QualType &ToType,
2672 bool InOverloadResolution,
2673 StandardConversionSequence &SCS,
2674 bool CStyle) {
2675
2676 const RecordType *UT = ToType->getAsUnionType();
2677 if (!UT)
2678 return false;
2679 // The field to initialize within the transparent union.
2680 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2681 if (!UD->hasAttr<TransparentUnionAttr>())
2682 return false;
2683 // It's compatible if the expression matches any of the fields.
2684 for (const auto *it : UD->fields()) {
2685 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2686 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2687 ToType = it->getType();
2688 return true;
2689 }
2690 }
2691 return false;
2692}
2693
2694bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2695 const BuiltinType *To = ToType->getAs<BuiltinType>();
2696 // All integers are built-in.
2697 if (!To) {
2698 return false;
2699 }
2700
2701 // An rvalue of type char, signed char, unsigned char, short int, or
2702 // unsigned short int can be converted to an rvalue of type int if
2703 // int can represent all the values of the source type; otherwise,
2704 // the source rvalue can be converted to an rvalue of type unsigned
2705 // int (C++ 4.5p1).
2706 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2707 !FromType->isEnumeralType()) {
2708 if ( // We can promote any signed, promotable integer type to an int
2709 (FromType->isSignedIntegerType() ||
2710 // We can promote any unsigned integer type whose size is
2711 // less than int to an int.
2712 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2713 return To->getKind() == BuiltinType::Int;
2714 }
2715
2716 return To->getKind() == BuiltinType::UInt;
2717 }
2718
2719 // C++11 [conv.prom]p3:
2720 // A prvalue of an unscoped enumeration type whose underlying type is not
2721 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2722 // following types that can represent all the values of the enumeration
2723 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2724 // unsigned int, long int, unsigned long int, long long int, or unsigned
2725 // long long int. If none of the types in that list can represent all the
2726 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2727 // type can be converted to an rvalue a prvalue of the extended integer type
2728 // with lowest integer conversion rank (4.13) greater than the rank of long
2729 // long in which all the values of the enumeration can be represented. If
2730 // there are two such extended types, the signed one is chosen.
2731 // C++11 [conv.prom]p4:
2732 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2733 // can be converted to a prvalue of its underlying type. Moreover, if
2734 // integral promotion can be applied to its underlying type, a prvalue of an
2735 // unscoped enumeration type whose underlying type is fixed can also be
2736 // converted to a prvalue of the promoted underlying type.
2737 if (const auto *FromED = FromType->getAsEnumDecl()) {
2738 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2739 // provided for a scoped enumeration.
2740 if (FromED->isScoped())
2741 return false;
2742
2743 // We can perform an integral promotion to the underlying type of the enum,
2744 // even if that's not the promoted type. Note that the check for promoting
2745 // the underlying type is based on the type alone, and does not consider
2746 // the bitfield-ness of the actual source expression.
2747 if (FromED->isFixed()) {
2748 QualType Underlying = FromED->getIntegerType();
2749 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2750 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2751 }
2752
2753 // We have already pre-calculated the promotion type, so this is trivial.
2754 if (ToType->isIntegerType() &&
2755 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2756 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2757
2758 // C++ [conv.prom]p5:
2759 // If the bit-field has an enumerated type, it is treated as any other
2760 // value of that type for promotion purposes.
2761 //
2762 // ... so do not fall through into the bit-field checks below in C++.
2763 if (getLangOpts().CPlusPlus)
2764 return false;
2765 }
2766
2767 // C++0x [conv.prom]p2:
2768 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2769 // to an rvalue a prvalue of the first of the following types that can
2770 // represent all the values of its underlying type: int, unsigned int,
2771 // long int, unsigned long int, long long int, or unsigned long long int.
2772 // If none of the types in that list can represent all the values of its
2773 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2774 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2775 // type.
2776 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2777 ToType->isIntegerType()) {
2778 // Determine whether the type we're converting from is signed or
2779 // unsigned.
2780 bool FromIsSigned = FromType->isSignedIntegerType();
2781 uint64_t FromSize = Context.getTypeSize(T: FromType);
2782
2783 // The types we'll try to promote to, in the appropriate
2784 // order. Try each of these types.
2785 QualType PromoteTypes[6] = {
2786 Context.IntTy, Context.UnsignedIntTy,
2787 Context.LongTy, Context.UnsignedLongTy ,
2788 Context.LongLongTy, Context.UnsignedLongLongTy
2789 };
2790 for (int Idx = 0; Idx < 6; ++Idx) {
2791 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2792 if (FromSize < ToSize ||
2793 (FromSize == ToSize &&
2794 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2795 // We found the type that we can promote to. If this is the
2796 // type we wanted, we have a promotion. Otherwise, no
2797 // promotion.
2798 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2799 }
2800 }
2801 }
2802
2803 // An rvalue for an integral bit-field (9.6) can be converted to an
2804 // rvalue of type int if int can represent all the values of the
2805 // bit-field; otherwise, it can be converted to unsigned int if
2806 // unsigned int can represent all the values of the bit-field. If
2807 // the bit-field is larger yet, no integral promotion applies to
2808 // it. If the bit-field has an enumerated type, it is treated as any
2809 // other value of that type for promotion purposes (C++ 4.5p3).
2810 // FIXME: We should delay checking of bit-fields until we actually perform the
2811 // conversion.
2812 //
2813 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2814 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2815 // bit-fields and those whose underlying type is larger than int) for GCC
2816 // compatibility.
2817 if (From) {
2818 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2819 std::optional<llvm::APSInt> BitWidth;
2820 if (FromType->isIntegralType(Ctx: Context) &&
2821 (BitWidth =
2822 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2823 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2824 ToSize = Context.getTypeSize(T: ToType);
2825
2826 // Are we promoting to an int from a bitfield that fits in an int?
2827 if (*BitWidth < ToSize ||
2828 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2829 return To->getKind() == BuiltinType::Int;
2830 }
2831
2832 // Are we promoting to an unsigned int from an unsigned bitfield
2833 // that fits into an unsigned int?
2834 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2835 return To->getKind() == BuiltinType::UInt;
2836 }
2837
2838 return false;
2839 }
2840 }
2841 }
2842
2843 // An rvalue of type bool can be converted to an rvalue of type int,
2844 // with false becoming zero and true becoming one (C++ 4.5p4).
2845 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2846 return true;
2847 }
2848
2849 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2850 // integral type.
2851 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2852 ToType->isIntegerType())
2853 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2854
2855 return false;
2856}
2857
2858bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2859 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2860 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2861 /// An rvalue of type float can be converted to an rvalue of type
2862 /// double. (C++ 4.6p1).
2863 if (FromBuiltin->getKind() == BuiltinType::Float &&
2864 ToBuiltin->getKind() == BuiltinType::Double)
2865 return true;
2866
2867 // C99 6.3.1.5p1:
2868 // When a float is promoted to double or long double, or a
2869 // double is promoted to long double [...].
2870 if (!getLangOpts().CPlusPlus &&
2871 (FromBuiltin->getKind() == BuiltinType::Float ||
2872 FromBuiltin->getKind() == BuiltinType::Double) &&
2873 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2874 ToBuiltin->getKind() == BuiltinType::Float128 ||
2875 ToBuiltin->getKind() == BuiltinType::Ibm128))
2876 return true;
2877
2878 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2879 // or not native half types are enabled.
2880 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2881 (ToBuiltin->getKind() == BuiltinType::Float ||
2882 ToBuiltin->getKind() == BuiltinType::Double))
2883 return true;
2884
2885 // Half can be promoted to float.
2886 if (!getLangOpts().NativeHalfType &&
2887 FromBuiltin->getKind() == BuiltinType::Half &&
2888 ToBuiltin->getKind() == BuiltinType::Float)
2889 return true;
2890 }
2891
2892 return false;
2893}
2894
2895bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2897 if (!FromComplex)
2898 return false;
2899
2900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2901 if (!ToComplex)
2902 return false;
2903
2904 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2905 ToType: ToComplex->getElementType()) ||
2906 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2907 ToType: ToComplex->getElementType());
2908}
2909
2910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2911/// the pointer type FromPtr to a pointer to type ToPointee, with the
2912/// same type qualifiers as FromPtr has on its pointee type. ToType,
2913/// if non-empty, will be a pointer to ToType that may or may not have
2914/// the right set of qualifiers on its pointee.
2915///
2916static QualType
2917BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2918 QualType ToPointee, QualType ToType,
2919 ASTContext &Context,
2920 bool StripObjCLifetime = false) {
2921 assert((FromPtr->getTypeClass() == Type::Pointer ||
2922 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2923 "Invalid similarly-qualified pointer type");
2924
2925 /// Conversions to 'id' subsume cv-qualifier conversions.
2926 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2927 return ToType.getUnqualifiedType();
2928
2929 QualType CanonFromPointee
2930 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2931 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2932 Qualifiers Quals = CanonFromPointee.getQualifiers();
2933
2934 if (StripObjCLifetime)
2935 Quals.removeObjCLifetime();
2936
2937 // Exact qualifier match -> return the pointer type we're converting to.
2938 if (CanonToPointee.getLocalQualifiers() == Quals) {
2939 // ToType is exactly what we need. Return it.
2940 if (!ToType.isNull())
2941 return ToType.getUnqualifiedType();
2942
2943 // Build a pointer to ToPointee. It has the right qualifiers
2944 // already.
2945 if (isa<ObjCObjectPointerType>(Val: ToType))
2946 return Context.getObjCObjectPointerType(OIT: ToPointee);
2947 return Context.getPointerType(T: ToPointee);
2948 }
2949
2950 // Just build a canonical type that has the right qualifiers.
2951 QualType QualifiedCanonToPointee
2952 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
2953
2954 if (isa<ObjCObjectPointerType>(Val: ToType))
2955 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
2956 return Context.getPointerType(T: QualifiedCanonToPointee);
2957}
2958
2959static bool isNullPointerConstantForConversion(Expr *Expr,
2960 bool InOverloadResolution,
2961 ASTContext &Context) {
2962 // Handle value-dependent integral null pointer constants correctly.
2963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2965 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2966 return !InOverloadResolution;
2967
2968 return Expr->isNullPointerConstant(Ctx&: Context,
2969 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970 : Expr::NPC_ValueDependentIsNull);
2971}
2972
2973bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2974 bool InOverloadResolution,
2975 QualType& ConvertedType,
2976 bool &IncompatibleObjC) {
2977 IncompatibleObjC = false;
2978 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2979 IncompatibleObjC))
2980 return true;
2981
2982 // Conversion from a null pointer constant to any Objective-C pointer type.
2983 if (ToType->isObjCObjectPointerType() &&
2984 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2985 ConvertedType = ToType;
2986 return true;
2987 }
2988
2989 // Blocks: Block pointers can be converted to void*.
2990 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2991 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2992 ConvertedType = ToType;
2993 return true;
2994 }
2995 // Blocks: A null pointer constant can be converted to a block
2996 // pointer type.
2997 if (ToType->isBlockPointerType() &&
2998 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2999 ConvertedType = ToType;
3000 return true;
3001 }
3002
3003 // If the left-hand-side is nullptr_t, the right side can be a null
3004 // pointer constant.
3005 if (ToType->isNullPtrType() &&
3006 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3007 ConvertedType = ToType;
3008 return true;
3009 }
3010
3011 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3012 if (!ToTypePtr)
3013 return false;
3014
3015 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3016 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3017 ConvertedType = ToType;
3018 return true;
3019 }
3020
3021 // Beyond this point, both types need to be pointers
3022 // , including objective-c pointers.
3023 QualType ToPointeeType = ToTypePtr->getPointeeType();
3024 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3025 !getLangOpts().ObjCAutoRefCount) {
3026 ConvertedType = BuildSimilarlyQualifiedPointerType(
3027 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3028 Context);
3029 return true;
3030 }
3031 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3032 if (!FromTypePtr)
3033 return false;
3034
3035 QualType FromPointeeType = FromTypePtr->getPointeeType();
3036
3037 // If the unqualified pointee types are the same, this can't be a
3038 // pointer conversion, so don't do all of the work below.
3039 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3040 return false;
3041
3042 // An rvalue of type "pointer to cv T," where T is an object type,
3043 // can be converted to an rvalue of type "pointer to cv void" (C++
3044 // 4.10p2).
3045 if (FromPointeeType->isIncompleteOrObjectType() &&
3046 ToPointeeType->isVoidType()) {
3047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3048 ToPointee: ToPointeeType,
3049 ToType, Context,
3050 /*StripObjCLifetime=*/true);
3051 return true;
3052 }
3053
3054 // MSVC allows implicit function to void* type conversion.
3055 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3056 ToPointeeType->isVoidType()) {
3057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3058 ToPointee: ToPointeeType,
3059 ToType, Context);
3060 return true;
3061 }
3062
3063 // When we're overloading in C, we allow a special kind of pointer
3064 // conversion for compatible-but-not-identical pointee types.
3065 if (!getLangOpts().CPlusPlus &&
3066 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3068 ToPointee: ToPointeeType,
3069 ToType, Context);
3070 return true;
3071 }
3072
3073 // C++ [conv.ptr]p3:
3074 //
3075 // An rvalue of type "pointer to cv D," where D is a class type,
3076 // can be converted to an rvalue of type "pointer to cv B," where
3077 // B is a base class (clause 10) of D. If B is an inaccessible
3078 // (clause 11) or ambiguous (10.2) base class of D, a program that
3079 // necessitates this conversion is ill-formed. The result of the
3080 // conversion is a pointer to the base class sub-object of the
3081 // derived class object. The null pointer value is converted to
3082 // the null pointer value of the destination type.
3083 //
3084 // Note that we do not check for ambiguity or inaccessibility
3085 // here. That is handled by CheckPointerConversion.
3086 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3087 ToPointeeType->isRecordType() &&
3088 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3089 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3091 ToPointee: ToPointeeType,
3092 ToType, Context);
3093 return true;
3094 }
3095
3096 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3097 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3098 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3099 ToPointee: ToPointeeType,
3100 ToType, Context);
3101 return true;
3102 }
3103
3104 return false;
3105}
3106
3107/// Adopt the given qualifiers for the given type.
3108static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3109 Qualifiers TQs = T.getQualifiers();
3110
3111 // Check whether qualifiers already match.
3112 if (TQs == Qs)
3113 return T;
3114
3115 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3116 return Context.getQualifiedType(T, Qs);
3117
3118 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3119}
3120
3121bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3122 QualType& ConvertedType,
3123 bool &IncompatibleObjC) {
3124 if (!getLangOpts().ObjC)
3125 return false;
3126
3127 // The set of qualifiers on the type we're converting from.
3128 Qualifiers FromQualifiers = FromType.getQualifiers();
3129
3130 // First, we handle all conversions on ObjC object pointer types.
3131 const ObjCObjectPointerType* ToObjCPtr =
3132 ToType->getAs<ObjCObjectPointerType>();
3133 const ObjCObjectPointerType *FromObjCPtr =
3134 FromType->getAs<ObjCObjectPointerType>();
3135
3136 if (ToObjCPtr && FromObjCPtr) {
3137 // If the pointee types are the same (ignoring qualifications),
3138 // then this is not a pointer conversion.
3139 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3140 T2: FromObjCPtr->getPointeeType()))
3141 return false;
3142
3143 // Conversion between Objective-C pointers.
3144 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3145 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3146 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3147 if (getLangOpts().CPlusPlus && LHS && RHS &&
3148 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3149 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3150 return false;
3151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3152 ToPointee: ToObjCPtr->getPointeeType(),
3153 ToType, Context);
3154 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3155 return true;
3156 }
3157
3158 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3159 // Okay: this is some kind of implicit downcast of Objective-C
3160 // interfaces, which is permitted. However, we're going to
3161 // complain about it.
3162 IncompatibleObjC = true;
3163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3164 ToPointee: ToObjCPtr->getPointeeType(),
3165 ToType, Context);
3166 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3167 return true;
3168 }
3169 }
3170 // Beyond this point, both types need to be C pointers or block pointers.
3171 QualType ToPointeeType;
3172 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3173 ToPointeeType = ToCPtr->getPointeeType();
3174 else if (const BlockPointerType *ToBlockPtr =
3175 ToType->getAs<BlockPointerType>()) {
3176 // Objective C++: We're able to convert from a pointer to any object
3177 // to a block pointer type.
3178 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3179 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3180 return true;
3181 }
3182 ToPointeeType = ToBlockPtr->getPointeeType();
3183 }
3184 else if (FromType->getAs<BlockPointerType>() &&
3185 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3186 // Objective C++: We're able to convert from a block pointer type to a
3187 // pointer to any object.
3188 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3189 return true;
3190 }
3191 else
3192 return false;
3193
3194 QualType FromPointeeType;
3195 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3196 FromPointeeType = FromCPtr->getPointeeType();
3197 else if (const BlockPointerType *FromBlockPtr =
3198 FromType->getAs<BlockPointerType>())
3199 FromPointeeType = FromBlockPtr->getPointeeType();
3200 else
3201 return false;
3202
3203 // If we have pointers to pointers, recursively check whether this
3204 // is an Objective-C conversion.
3205 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3206 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3207 IncompatibleObjC)) {
3208 // We always complain about this conversion.
3209 IncompatibleObjC = true;
3210 ConvertedType = Context.getPointerType(T: ConvertedType);
3211 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3212 return true;
3213 }
3214 // Allow conversion of pointee being objective-c pointer to another one;
3215 // as in I* to id.
3216 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3217 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3218 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3219 IncompatibleObjC)) {
3220
3221 ConvertedType = Context.getPointerType(T: ConvertedType);
3222 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3223 return true;
3224 }
3225
3226 // If we have pointers to functions or blocks, check whether the only
3227 // differences in the argument and result types are in Objective-C
3228 // pointer conversions. If so, we permit the conversion (but
3229 // complain about it).
3230 const FunctionProtoType *FromFunctionType
3231 = FromPointeeType->getAs<FunctionProtoType>();
3232 const FunctionProtoType *ToFunctionType
3233 = ToPointeeType->getAs<FunctionProtoType>();
3234 if (FromFunctionType && ToFunctionType) {
3235 // If the function types are exactly the same, this isn't an
3236 // Objective-C pointer conversion.
3237 if (Context.getCanonicalType(T: FromPointeeType)
3238 == Context.getCanonicalType(T: ToPointeeType))
3239 return false;
3240
3241 // Perform the quick checks that will tell us whether these
3242 // function types are obviously different.
3243 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3244 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3245 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3246 return false;
3247
3248 bool HasObjCConversion = false;
3249 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3250 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3251 // Okay, the types match exactly. Nothing to do.
3252 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3253 ToType: ToFunctionType->getReturnType(),
3254 ConvertedType, IncompatibleObjC)) {
3255 // Okay, we have an Objective-C pointer conversion.
3256 HasObjCConversion = true;
3257 } else {
3258 // Function types are too different. Abort.
3259 return false;
3260 }
3261
3262 // Check argument types.
3263 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3264 ArgIdx != NumArgs; ++ArgIdx) {
3265 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3266 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3267 if (Context.getCanonicalType(T: FromArgType)
3268 == Context.getCanonicalType(T: ToArgType)) {
3269 // Okay, the types match exactly. Nothing to do.
3270 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3271 ConvertedType, IncompatibleObjC)) {
3272 // Okay, we have an Objective-C pointer conversion.
3273 HasObjCConversion = true;
3274 } else {
3275 // Argument types are too different. Abort.
3276 return false;
3277 }
3278 }
3279
3280 if (HasObjCConversion) {
3281 // We had an Objective-C conversion. Allow this pointer
3282 // conversion, but complain about it.
3283 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3284 IncompatibleObjC = true;
3285 return true;
3286 }
3287 }
3288
3289 return false;
3290}
3291
3292bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3293 QualType& ConvertedType) {
3294 QualType ToPointeeType;
3295 if (const BlockPointerType *ToBlockPtr =
3296 ToType->getAs<BlockPointerType>())
3297 ToPointeeType = ToBlockPtr->getPointeeType();
3298 else
3299 return false;
3300
3301 QualType FromPointeeType;
3302 if (const BlockPointerType *FromBlockPtr =
3303 FromType->getAs<BlockPointerType>())
3304 FromPointeeType = FromBlockPtr->getPointeeType();
3305 else
3306 return false;
3307 // We have pointer to blocks, check whether the only
3308 // differences in the argument and result types are in Objective-C
3309 // pointer conversions. If so, we permit the conversion.
3310
3311 const FunctionProtoType *FromFunctionType
3312 = FromPointeeType->getAs<FunctionProtoType>();
3313 const FunctionProtoType *ToFunctionType
3314 = ToPointeeType->getAs<FunctionProtoType>();
3315
3316 if (!FromFunctionType || !ToFunctionType)
3317 return false;
3318
3319 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3320 return true;
3321
3322 // Perform the quick checks that will tell us whether these
3323 // function types are obviously different.
3324 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3325 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3326 return false;
3327
3328 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3329 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3330 if (FromEInfo != ToEInfo)
3331 return false;
3332
3333 bool IncompatibleObjC = false;
3334 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3335 T2: ToFunctionType->getReturnType())) {
3336 // Okay, the types match exactly. Nothing to do.
3337 } else {
3338 QualType RHS = FromFunctionType->getReturnType();
3339 QualType LHS = ToFunctionType->getReturnType();
3340 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3341 !RHS.hasQualifiers() && LHS.hasQualifiers())
3342 LHS = LHS.getUnqualifiedType();
3343
3344 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3345 // OK exact match.
3346 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3347 ConvertedType, IncompatibleObjC)) {
3348 if (IncompatibleObjC)
3349 return false;
3350 // Okay, we have an Objective-C pointer conversion.
3351 }
3352 else
3353 return false;
3354 }
3355
3356 // Check argument types.
3357 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3358 ArgIdx != NumArgs; ++ArgIdx) {
3359 IncompatibleObjC = false;
3360 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3361 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3362 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3363 // Okay, the types match exactly. Nothing to do.
3364 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3365 ConvertedType, IncompatibleObjC)) {
3366 if (IncompatibleObjC)
3367 return false;
3368 // Okay, we have an Objective-C pointer conversion.
3369 } else
3370 // Argument types are too different. Abort.
3371 return false;
3372 }
3373
3374 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3375 bool CanUseToFPT, CanUseFromFPT;
3376 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3377 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3378 NewParamInfos))
3379 return false;
3380
3381 ConvertedType = ToType;
3382 return true;
3383}
3384
3385enum {
3386 ft_default,
3387 ft_different_class,
3388 ft_parameter_arity,
3389 ft_parameter_mismatch,
3390 ft_return_type,
3391 ft_qualifer_mismatch,
3392 ft_noexcept
3393};
3394
3395/// Attempts to get the FunctionProtoType from a Type. Handles
3396/// MemberFunctionPointers properly.
3397static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3398 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3399 return FPT;
3400
3401 if (auto *MPT = FromType->getAs<MemberPointerType>())
3402 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3403
3404 return nullptr;
3405}
3406
3407void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3408 QualType FromType, QualType ToType) {
3409 // If either type is not valid, include no extra info.
3410 if (FromType.isNull() || ToType.isNull()) {
3411 PDiag << ft_default;
3412 return;
3413 }
3414
3415 // Get the function type from the pointers.
3416 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3417 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3418 *ToMember = ToType->castAs<MemberPointerType>();
3419 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3420 D2: ToMember->getMostRecentCXXRecordDecl())) {
3421 PDiag << ft_different_class;
3422 if (ToMember->isSugared())
3423 PDiag << Context.getCanonicalTagType(
3424 TD: ToMember->getMostRecentCXXRecordDecl());
3425 else
3426 PDiag << ToMember->getQualifier();
3427 if (FromMember->isSugared())
3428 PDiag << Context.getCanonicalTagType(
3429 TD: FromMember->getMostRecentCXXRecordDecl());
3430 else
3431 PDiag << FromMember->getQualifier();
3432 return;
3433 }
3434 FromType = FromMember->getPointeeType();
3435 ToType = ToMember->getPointeeType();
3436 }
3437
3438 if (FromType->isPointerType())
3439 FromType = FromType->getPointeeType();
3440 if (ToType->isPointerType())
3441 ToType = ToType->getPointeeType();
3442
3443 // Remove references.
3444 FromType = FromType.getNonReferenceType();
3445 ToType = ToType.getNonReferenceType();
3446
3447 // Don't print extra info for non-specialized template functions.
3448 if (FromType->isInstantiationDependentType() &&
3449 !FromType->getAs<TemplateSpecializationType>()) {
3450 PDiag << ft_default;
3451 return;
3452 }
3453
3454 // No extra info for same types.
3455 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3456 PDiag << ft_default;
3457 return;
3458 }
3459
3460 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3461 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3462
3463 // Both types need to be function types.
3464 if (!FromFunction || !ToFunction) {
3465 PDiag << ft_default;
3466 return;
3467 }
3468
3469 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3470 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3471 << FromFunction->getNumParams();
3472 return;
3473 }
3474
3475 // Handle different parameter types.
3476 unsigned ArgPos;
3477 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3478 PDiag << ft_parameter_mismatch << ArgPos + 1
3479 << ToFunction->getParamType(i: ArgPos)
3480 << FromFunction->getParamType(i: ArgPos);
3481 return;
3482 }
3483
3484 // Handle different return type.
3485 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3486 T2: ToFunction->getReturnType())) {
3487 PDiag << ft_return_type << ToFunction->getReturnType()
3488 << FromFunction->getReturnType();
3489 return;
3490 }
3491
3492 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3493 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3494 << FromFunction->getMethodQuals();
3495 return;
3496 }
3497
3498 // Handle exception specification differences on canonical type (in C++17
3499 // onwards).
3500 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3501 ->isNothrow() !=
3502 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3503 ->isNothrow()) {
3504 PDiag << ft_noexcept;
3505 return;
3506 }
3507
3508 // Unable to find a difference, so add no extra info.
3509 PDiag << ft_default;
3510}
3511
3512bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3513 ArrayRef<QualType> New, unsigned *ArgPos,
3514 bool Reversed) {
3515 assert(llvm::size(Old) == llvm::size(New) &&
3516 "Can't compare parameters of functions with different number of "
3517 "parameters!");
3518
3519 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3520 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3521 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3522
3523 // Ignore address spaces in pointee type. This is to disallow overloading
3524 // on __ptr32/__ptr64 address spaces.
3525 QualType OldType =
3526 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3527 QualType NewType =
3528 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3529
3530 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3531 if (ArgPos)
3532 *ArgPos = Idx;
3533 return false;
3534 }
3535 }
3536 return true;
3537}
3538
3539bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3540 const FunctionProtoType *NewType,
3541 unsigned *ArgPos, bool Reversed) {
3542 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3543 New: NewType->param_types(), ArgPos, Reversed);
3544}
3545
3546bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3547 const FunctionDecl *NewFunction,
3548 unsigned *ArgPos,
3549 bool Reversed) {
3550
3551 if (OldFunction->getNumNonObjectParams() !=
3552 NewFunction->getNumNonObjectParams())
3553 return false;
3554
3555 unsigned OldIgnore =
3556 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3557 unsigned NewIgnore =
3558 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3559
3560 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3561 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3562
3563 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3564 New: NewPT->param_types().slice(N: NewIgnore),
3565 ArgPos, Reversed);
3566}
3567
3568bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3569 CastKind &Kind,
3570 CXXCastPath& BasePath,
3571 bool IgnoreBaseAccess,
3572 bool Diagnose) {
3573 QualType FromType = From->getType();
3574 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3575
3576 Kind = CK_BitCast;
3577
3578 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3579 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3580 Expr::NPCK_ZeroExpression) {
3581 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3582 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3583 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3584 << ToType << From->getSourceRange());
3585 else if (!isUnevaluatedContext())
3586 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3587 << ToType << From->getSourceRange();
3588 }
3589 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3590 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3591 QualType FromPointeeType = FromPtrType->getPointeeType(),
3592 ToPointeeType = ToPtrType->getPointeeType();
3593
3594 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3595 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3596 // We must have a derived-to-base conversion. Check an
3597 // ambiguous or inaccessible conversion.
3598 unsigned InaccessibleID = 0;
3599 unsigned AmbiguousID = 0;
3600 if (Diagnose) {
3601 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3602 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3603 }
3604 if (CheckDerivedToBaseConversion(
3605 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3606 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3607 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3608 return true;
3609
3610 // The conversion was successful.
3611 Kind = CK_DerivedToBase;
3612 }
3613
3614 if (Diagnose && !IsCStyleOrFunctionalCast &&
3615 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3616 assert(getLangOpts().MSVCCompat &&
3617 "this should only be possible with MSVCCompat!");
3618 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3619 << From->getSourceRange();
3620 }
3621 }
3622 } else if (const ObjCObjectPointerType *ToPtrType =
3623 ToType->getAs<ObjCObjectPointerType>()) {
3624 if (const ObjCObjectPointerType *FromPtrType =
3625 FromType->getAs<ObjCObjectPointerType>()) {
3626 // Objective-C++ conversions are always okay.
3627 // FIXME: We should have a different class of conversions for the
3628 // Objective-C++ implicit conversions.
3629 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3630 return false;
3631 } else if (FromType->isBlockPointerType()) {
3632 Kind = CK_BlockPointerToObjCPointerCast;
3633 } else {
3634 Kind = CK_CPointerToObjCPointerCast;
3635 }
3636 } else if (ToType->isBlockPointerType()) {
3637 if (!FromType->isBlockPointerType())
3638 Kind = CK_AnyPointerToBlockPointerCast;
3639 }
3640
3641 // We shouldn't fall into this case unless it's valid for other
3642 // reasons.
3643 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3644 Kind = CK_NullToPointer;
3645
3646 return false;
3647}
3648
3649bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3650 QualType ToType,
3651 bool InOverloadResolution,
3652 QualType &ConvertedType) {
3653 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3654 if (!ToTypePtr)
3655 return false;
3656
3657 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3658 if (From->isNullPointerConstant(Ctx&: Context,
3659 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3660 : Expr::NPC_ValueDependentIsNull)) {
3661 ConvertedType = ToType;
3662 return true;
3663 }
3664
3665 // Otherwise, both types have to be member pointers.
3666 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3667 if (!FromTypePtr)
3668 return false;
3669
3670 // A pointer to member of B can be converted to a pointer to member of D,
3671 // where D is derived from B (C++ 4.11p2).
3672 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3673 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3674
3675 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3676 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3677 ConvertedType = Context.getMemberPointerType(
3678 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3679 return true;
3680 }
3681
3682 return false;
3683}
3684
3685Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3686 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3687 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3688 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3689 // Lock down the inheritance model right now in MS ABI, whether or not the
3690 // pointee types are the same.
3691 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3692 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3693 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3694 }
3695
3696 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3697 if (!FromPtrType) {
3698 // This must be a null pointer to member pointer conversion
3699 Kind = CK_NullToMemberPointer;
3700 return MemberPointerConversionResult::Success;
3701 }
3702
3703 // T == T, modulo cv
3704 if (Direction == MemberPointerConversionDirection::Upcast &&
3705 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3706 T2: ToPtrType->getPointeeType()))
3707 return MemberPointerConversionResult::DifferentPointee;
3708
3709 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3710 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3711
3712 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3713 const CXXRecordDecl *Cls) {
3714 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3715 PD << Qual;
3716 else
3717 PD << Context.getCanonicalTagType(TD: Cls);
3718 };
3719 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3720 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3721 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3722 return PD;
3723 };
3724
3725 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3726 if (Direction == MemberPointerConversionDirection::Upcast)
3727 std::swap(a&: Base, b&: Derived);
3728
3729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3730 /*DetectVirtual=*/true);
3731 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3732 return MemberPointerConversionResult::NotDerived;
3733
3734 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3735 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3736 PD << int(Direction);
3737 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3738 Diag(Loc: CheckLoc, PD);
3739 return MemberPointerConversionResult::Ambiguous;
3740 }
3741
3742 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3743 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3744 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3745 Diag(Loc: CheckLoc, PD);
3746 return MemberPointerConversionResult::Virtual;
3747 }
3748
3749 // Must be a base to derived member conversion.
3750 BuildBasePathArray(Paths, BasePath);
3751 Kind = Direction == MemberPointerConversionDirection::Upcast
3752 ? CK_DerivedToBaseMemberPointer
3753 : CK_BaseToDerivedMemberPointer;
3754
3755 if (!IgnoreBaseAccess)
3756 switch (CheckBaseClassAccess(
3757 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3758 DiagID: Direction == MemberPointerConversionDirection::Upcast
3759 ? diag::err_upcast_to_inaccessible_base
3760 : diag::err_downcast_from_inaccessible_base,
3761 SetupPDiag: [&](PartialDiagnostic &PD) {
3762 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3763 DerivedQual = ToPtrType->getQualifier();
3764 if (Direction == MemberPointerConversionDirection::Upcast)
3765 std::swap(a&: BaseQual, b&: DerivedQual);
3766 DiagCls(PD, DerivedQual, Derived);
3767 DiagCls(PD, BaseQual, Base);
3768 })) {
3769 case Sema::AR_accessible:
3770 case Sema::AR_delayed:
3771 case Sema::AR_dependent:
3772 // Optimistically assume that the delayed and dependent cases
3773 // will work out.
3774 break;
3775
3776 case Sema::AR_inaccessible:
3777 return MemberPointerConversionResult::Inaccessible;
3778 }
3779
3780 return MemberPointerConversionResult::Success;
3781}
3782
3783/// Determine whether the lifetime conversion between the two given
3784/// qualifiers sets is nontrivial.
3785static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3786 Qualifiers ToQuals) {
3787 // Converting anything to const __unsafe_unretained is trivial.
3788 if (ToQuals.hasConst() &&
3789 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3790 return false;
3791
3792 return true;
3793}
3794
3795/// Perform a single iteration of the loop for checking if a qualification
3796/// conversion is valid.
3797///
3798/// Specifically, check whether any change between the qualifiers of \p
3799/// FromType and \p ToType is permissible, given knowledge about whether every
3800/// outer layer is const-qualified.
3801static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3802 bool CStyle, bool IsTopLevel,
3803 bool &PreviousToQualsIncludeConst,
3804 bool &ObjCLifetimeConversion,
3805 const ASTContext &Ctx) {
3806 Qualifiers FromQuals = FromType.getQualifiers();
3807 Qualifiers ToQuals = ToType.getQualifiers();
3808
3809 // Ignore __unaligned qualifier.
3810 FromQuals.removeUnaligned();
3811
3812 // Objective-C ARC:
3813 // Check Objective-C lifetime conversions.
3814 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3815 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3816 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3817 ObjCLifetimeConversion = true;
3818 FromQuals.removeObjCLifetime();
3819 ToQuals.removeObjCLifetime();
3820 } else {
3821 // Qualification conversions cannot cast between different
3822 // Objective-C lifetime qualifiers.
3823 return false;
3824 }
3825 }
3826
3827 // Allow addition/removal of GC attributes but not changing GC attributes.
3828 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3829 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3830 FromQuals.removeObjCGCAttr();
3831 ToQuals.removeObjCGCAttr();
3832 }
3833
3834 // __ptrauth qualifiers must match exactly.
3835 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3836 return false;
3837
3838 // -- for every j > 0, if const is in cv 1,j then const is in cv
3839 // 2,j, and similarly for volatile.
3840 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3841 return false;
3842
3843 // If address spaces mismatch:
3844 // - in top level it is only valid to convert to addr space that is a
3845 // superset in all cases apart from C-style casts where we allow
3846 // conversions between overlapping address spaces.
3847 // - in non-top levels it is not a valid conversion.
3848 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3849 (!IsTopLevel ||
3850 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3851 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3852 return false;
3853
3854 // -- if the cv 1,j and cv 2,j are different, then const is in
3855 // every cv for 0 < k < j.
3856 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3857 !PreviousToQualsIncludeConst)
3858 return false;
3859
3860 // The following wording is from C++20, where the result of the conversion
3861 // is T3, not T2.
3862 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3863 // "array of unknown bound of"
3864 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3865 return false;
3866
3867 // -- if the resulting P3,i is different from P1,i [...], then const is
3868 // added to every cv 3_k for 0 < k < i.
3869 if (!CStyle && FromType->isConstantArrayType() &&
3870 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3871 return false;
3872
3873 // Keep track of whether all prior cv-qualifiers in the "to" type
3874 // include const.
3875 PreviousToQualsIncludeConst =
3876 PreviousToQualsIncludeConst && ToQuals.hasConst();
3877 return true;
3878}
3879
3880bool
3881Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3882 bool CStyle, bool &ObjCLifetimeConversion) {
3883 FromType = Context.getCanonicalType(T: FromType);
3884 ToType = Context.getCanonicalType(T: ToType);
3885 ObjCLifetimeConversion = false;
3886
3887 // If FromType and ToType are the same type, this is not a
3888 // qualification conversion.
3889 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3890 return false;
3891
3892 // (C++ 4.4p4):
3893 // A conversion can add cv-qualifiers at levels other than the first
3894 // in multi-level pointers, subject to the following rules: [...]
3895 bool PreviousToQualsIncludeConst = true;
3896 bool UnwrappedAnyPointer = false;
3897 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3898 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3899 IsTopLevel: !UnwrappedAnyPointer,
3900 PreviousToQualsIncludeConst,
3901 ObjCLifetimeConversion, Ctx: getASTContext()))
3902 return false;
3903 UnwrappedAnyPointer = true;
3904 }
3905
3906 // We are left with FromType and ToType being the pointee types
3907 // after unwrapping the original FromType and ToType the same number
3908 // of times. If we unwrapped any pointers, and if FromType and
3909 // ToType have the same unqualified type (since we checked
3910 // qualifiers above), then this is a qualification conversion.
3911 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3912}
3913
3914/// - Determine whether this is a conversion from a scalar type to an
3915/// atomic type.
3916///
3917/// If successful, updates \c SCS's second and third steps in the conversion
3918/// sequence to finish the conversion.
3919static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3920 bool InOverloadResolution,
3921 StandardConversionSequence &SCS,
3922 bool CStyle) {
3923 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3924 if (!ToAtomic)
3925 return false;
3926
3927 StandardConversionSequence InnerSCS;
3928 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3929 InOverloadResolution, SCS&: InnerSCS,
3930 CStyle, /*AllowObjCWritebackConversion=*/false))
3931 return false;
3932
3933 SCS.Second = InnerSCS.Second;
3934 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3935 SCS.Third = InnerSCS.Third;
3936 SCS.QualificationIncludesObjCLifetime
3937 = InnerSCS.QualificationIncludesObjCLifetime;
3938 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3939 return true;
3940}
3941
3942static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3943 CXXConstructorDecl *Constructor,
3944 QualType Type) {
3945 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3946 if (CtorType->getNumParams() > 0) {
3947 QualType FirstArg = CtorType->getParamType(i: 0);
3948 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
3949 return true;
3950 }
3951 return false;
3952}
3953
3954static OverloadingResult
3955IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3956 CXXRecordDecl *To,
3957 UserDefinedConversionSequence &User,
3958 OverloadCandidateSet &CandidateSet,
3959 bool AllowExplicit) {
3960 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3961 for (auto *D : S.LookupConstructors(Class: To)) {
3962 auto Info = getConstructorInfo(ND: D);
3963 if (!Info)
3964 continue;
3965
3966 bool Usable = !Info.Constructor->isInvalidDecl() &&
3967 S.isInitListConstructor(Ctor: Info.Constructor);
3968 if (Usable) {
3969 bool SuppressUserConversions = false;
3970 if (Info.ConstructorTmpl)
3971 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3972 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
3973 CandidateSet, SuppressUserConversions,
3974 /*PartialOverloading*/ false,
3975 AllowExplicit);
3976 else
3977 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
3978 CandidateSet, SuppressUserConversions,
3979 /*PartialOverloading*/ false, AllowExplicit);
3980 }
3981 }
3982
3983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3984
3985 OverloadCandidateSet::iterator Best;
3986 switch (auto Result =
3987 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
3988 case OR_Deleted:
3989 case OR_Success: {
3990 // Record the standard conversion we used and the conversion function.
3991 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
3992 QualType ThisType = Constructor->getFunctionObjectParameterType();
3993 // Initializer lists don't have conversions as such.
3994 User.Before.setAsIdentityConversion();
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3996 User.ConversionFunction = Constructor;
3997 User.FoundConversionFunction = Best->FoundDecl;
3998 User.After.setAsIdentityConversion();
3999 User.After.setFromType(ThisType);
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003
4004 case OR_No_Viable_Function:
4005 return OR_No_Viable_Function;
4006 case OR_Ambiguous:
4007 return OR_Ambiguous;
4008 }
4009
4010 llvm_unreachable("Invalid OverloadResult!");
4011}
4012
4013/// Determines whether there is a user-defined conversion sequence
4014/// (C++ [over.ics.user]) that converts expression From to the type
4015/// ToType. If such a conversion exists, User will contain the
4016/// user-defined conversion sequence that performs such a conversion
4017/// and this routine will return true. Otherwise, this routine returns
4018/// false and User is unspecified.
4019///
4020/// \param AllowExplicit true if the conversion should consider C++0x
4021/// "explicit" conversion functions as well as non-explicit conversion
4022/// functions (C++0x [class.conv.fct]p2).
4023///
4024/// \param AllowObjCConversionOnExplicit true if the conversion should
4025/// allow an extra Objective-C pointer conversion on uses of explicit
4026/// constructors. Requires \c AllowExplicit to also be set.
4027static OverloadingResult
4028IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4029 UserDefinedConversionSequence &User,
4030 OverloadCandidateSet &CandidateSet,
4031 AllowedExplicit AllowExplicit,
4032 bool AllowObjCConversionOnExplicit) {
4033 assert(AllowExplicit != AllowedExplicit::None ||
4034 !AllowObjCConversionOnExplicit);
4035 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4036
4037 // Whether we will only visit constructors.
4038 bool ConstructorsOnly = false;
4039
4040 // If the type we are conversion to is a class type, enumerate its
4041 // constructors.
4042 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4043 // C++ [over.match.ctor]p1:
4044 // When objects of class type are direct-initialized (8.5), or
4045 // copy-initialized from an expression of the same or a
4046 // derived class type (8.5), overload resolution selects the
4047 // constructor. [...] For copy-initialization, the candidate
4048 // functions are all the converting constructors (12.3.1) of
4049 // that class. The argument list is the expression-list within
4050 // the parentheses of the initializer.
4051 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4052 (From->getType()->isRecordType() &&
4053 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4054 ConstructorsOnly = true;
4055
4056 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4057 // We're not going to find any constructors.
4058 } else if (auto *ToRecordDecl =
4059 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4060 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4061
4062 Expr **Args = &From;
4063 unsigned NumArgs = 1;
4064 bool ListInitializing = false;
4065 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4066 // But first, see if there is an init-list-constructor that will work.
4067 OverloadingResult Result = IsInitializerListConstructorConversion(
4068 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4069 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4070 if (Result != OR_No_Viable_Function)
4071 return Result;
4072 // Never mind.
4073 CandidateSet.clear(
4074 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4075
4076 // If we're list-initializing, we pass the individual elements as
4077 // arguments, not the entire list.
4078 Args = InitList->getInits();
4079 NumArgs = InitList->getNumInits();
4080 ListInitializing = true;
4081 }
4082
4083 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4084 auto Info = getConstructorInfo(ND: D);
4085 if (!Info)
4086 continue;
4087
4088 bool Usable = !Info.Constructor->isInvalidDecl();
4089 if (!ListInitializing)
4090 Usable = Usable && Info.Constructor->isConvertingConstructor(
4091 /*AllowExplicit*/ true);
4092 if (Usable) {
4093 bool SuppressUserConversions = !ConstructorsOnly;
4094 // C++20 [over.best.ics.general]/4.5:
4095 // if the target is the first parameter of a constructor [of class
4096 // X] and the constructor [...] is a candidate by [...] the second
4097 // phase of [over.match.list] when the initializer list has exactly
4098 // one element that is itself an initializer list, [...] and the
4099 // conversion is to X or reference to cv X, user-defined conversion
4100 // sequences are not considered.
4101 if (SuppressUserConversions && ListInitializing) {
4102 SuppressUserConversions =
4103 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4104 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4105 Type: ToType);
4106 }
4107 if (Info.ConstructorTmpl)
4108 S.AddTemplateOverloadCandidate(
4109 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4110 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4111 CandidateSet, SuppressUserConversions,
4112 /*PartialOverloading*/ false,
4113 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4114 else
4115 // Allow one user-defined conversion when user specifies a
4116 // From->ToType conversion via an static cast (c-style, etc).
4117 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4118 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4119 SuppressUserConversions,
4120 /*PartialOverloading*/ false,
4121 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4122 }
4123 }
4124 }
4125 }
4126
4127 // Enumerate conversion functions, if we're allowed to.
4128 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4129 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4130 // No conversion functions from incomplete types.
4131 } else if (const RecordType *FromRecordType =
4132 From->getType()->getAsCanonical<RecordType>()) {
4133 if (auto *FromRecordDecl =
4134 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4135 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4136 // Add all of the conversion functions as candidates.
4137 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4138 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4139 DeclAccessPair FoundDecl = I.getPair();
4140 NamedDecl *D = FoundDecl.getDecl();
4141 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4142 if (isa<UsingShadowDecl>(Val: D))
4143 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4144
4145 CXXConversionDecl *Conv;
4146 FunctionTemplateDecl *ConvTemplate;
4147 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4148 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4149 else
4150 Conv = cast<CXXConversionDecl>(Val: D);
4151
4152 if (ConvTemplate)
4153 S.AddTemplateConversionCandidate(
4154 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4155 CandidateSet, AllowObjCConversionOnExplicit,
4156 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4157 else
4158 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4159 CandidateSet, AllowObjCConversionOnExplicit,
4160 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4161 }
4162 }
4163 }
4164
4165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4166
4167 OverloadCandidateSet::iterator Best;
4168 switch (auto Result =
4169 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4170 case OR_Success:
4171 case OR_Deleted:
4172 // Record the standard conversion we used and the conversion function.
4173 if (CXXConstructorDecl *Constructor
4174 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4175 // C++ [over.ics.user]p1:
4176 // If the user-defined conversion is specified by a
4177 // constructor (12.3.1), the initial standard conversion
4178 // sequence converts the source type to the type required by
4179 // the argument of the constructor.
4180 //
4181 if (isa<InitListExpr>(Val: From)) {
4182 // Initializer lists don't have conversions as such.
4183 User.Before.setAsIdentityConversion();
4184 User.Before.FromBracedInitList = true;
4185 } else {
4186 if (Best->Conversions[0].isEllipsis())
4187 User.EllipsisConversion = true;
4188 else {
4189 User.Before = Best->Conversions[0].Standard;
4190 User.EllipsisConversion = false;
4191 }
4192 }
4193 User.HadMultipleCandidates = HadMultipleCandidates;
4194 User.ConversionFunction = Constructor;
4195 User.FoundConversionFunction = Best->FoundDecl;
4196 User.After.setAsIdentityConversion();
4197 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4198 User.After.setAllToTypes(ToType);
4199 return Result;
4200 }
4201 if (CXXConversionDecl *Conversion
4202 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4203
4204 assert(Best->HasFinalConversion);
4205
4206 // C++ [over.ics.user]p1:
4207 //
4208 // [...] If the user-defined conversion is specified by a
4209 // conversion function (12.3.2), the initial standard
4210 // conversion sequence converts the source type to the
4211 // implicit object parameter of the conversion function.
4212 User.Before = Best->Conversions[0].Standard;
4213 User.HadMultipleCandidates = HadMultipleCandidates;
4214 User.ConversionFunction = Conversion;
4215 User.FoundConversionFunction = Best->FoundDecl;
4216 User.EllipsisConversion = false;
4217
4218 // C++ [over.ics.user]p2:
4219 // The second standard conversion sequence converts the
4220 // result of the user-defined conversion to the target type
4221 // for the sequence. Since an implicit conversion sequence
4222 // is an initialization, the special rules for
4223 // initialization by user-defined conversion apply when
4224 // selecting the best user-defined conversion for a
4225 // user-defined conversion sequence (see 13.3.3 and
4226 // 13.3.3.1).
4227 User.After = Best->FinalConversion;
4228 return Result;
4229 }
4230 llvm_unreachable("Not a constructor or conversion function?");
4231
4232 case OR_No_Viable_Function:
4233 return OR_No_Viable_Function;
4234
4235 case OR_Ambiguous:
4236 return OR_Ambiguous;
4237 }
4238
4239 llvm_unreachable("Invalid OverloadResult!");
4240}
4241
4242bool
4243Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4244 ImplicitConversionSequence ICS;
4245 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4246 OverloadCandidateSet::CSK_Normal);
4247 OverloadingResult OvResult =
4248 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4249 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4250
4251 if (!(OvResult == OR_Ambiguous ||
4252 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4253 return false;
4254
4255 auto Cands = CandidateSet.CompleteCandidates(
4256 S&: *this,
4257 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4258 Args: From);
4259 if (OvResult == OR_Ambiguous)
4260 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4261 << From->getType() << ToType << From->getSourceRange();
4262 else { // OR_No_Viable_Function && !CandidateSet.empty()
4263 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4264 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4265 Args: From->getType(), Args: From->getSourceRange()))
4266 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4267 << false << From->getType() << From->getSourceRange() << ToType;
4268 }
4269
4270 CandidateSet.NoteCandidates(
4271 S&: *this, Args: From, Cands);
4272 return true;
4273}
4274
4275// Helper for compareConversionFunctions that gets the FunctionType that the
4276// conversion-operator return value 'points' to, or nullptr.
4277static const FunctionType *
4278getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4279 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4280 const PointerType *RetPtrTy =
4281 ConvFuncTy->getReturnType()->getAs<PointerType>();
4282
4283 if (!RetPtrTy)
4284 return nullptr;
4285
4286 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4287}
4288
4289/// Compare the user-defined conversion functions or constructors
4290/// of two user-defined conversion sequences to determine whether any ordering
4291/// is possible.
4292static ImplicitConversionSequence::CompareKind
4293compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4294 FunctionDecl *Function2) {
4295 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4296 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4297 if (!Conv1 || !Conv2)
4298 return ImplicitConversionSequence::Indistinguishable;
4299
4300 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4301 return ImplicitConversionSequence::Indistinguishable;
4302
4303 // Objective-C++:
4304 // If both conversion functions are implicitly-declared conversions from
4305 // a lambda closure type to a function pointer and a block pointer,
4306 // respectively, always prefer the conversion to a function pointer,
4307 // because the function pointer is more lightweight and is more likely
4308 // to keep code working.
4309 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4310 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4311 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4312 if (Block1 != Block2)
4313 return Block1 ? ImplicitConversionSequence::Worse
4314 : ImplicitConversionSequence::Better;
4315 }
4316
4317 // In order to support multiple calling conventions for the lambda conversion
4318 // operator (such as when the free and member function calling convention is
4319 // different), prefer the 'free' mechanism, followed by the calling-convention
4320 // of operator(). The latter is in place to support the MSVC-like solution of
4321 // defining ALL of the possible conversions in regards to calling-convention.
4322 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4323 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4324
4325 if (Conv1FuncRet && Conv2FuncRet &&
4326 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4327 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4328 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4329
4330 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4331 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4332
4333 CallingConv CallOpCC =
4334 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4335 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4336 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4337 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4338 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4339
4340 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4341 for (CallingConv CC : PrefOrder) {
4342 if (Conv1CC == CC)
4343 return ImplicitConversionSequence::Better;
4344 if (Conv2CC == CC)
4345 return ImplicitConversionSequence::Worse;
4346 }
4347 }
4348
4349 return ImplicitConversionSequence::Indistinguishable;
4350}
4351
4352static bool hasDeprecatedStringLiteralToCharPtrConversion(
4353 const ImplicitConversionSequence &ICS) {
4354 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4355 (ICS.isUserDefined() &&
4356 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4357}
4358
4359/// CompareImplicitConversionSequences - Compare two implicit
4360/// conversion sequences to determine whether one is better than the
4361/// other or if they are indistinguishable (C++ 13.3.3.2).
4362static ImplicitConversionSequence::CompareKind
4363CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4364 const ImplicitConversionSequence& ICS1,
4365 const ImplicitConversionSequence& ICS2)
4366{
4367 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4368 // conversion sequences (as defined in 13.3.3.1)
4369 // -- a standard conversion sequence (13.3.3.1.1) is a better
4370 // conversion sequence than a user-defined conversion sequence or
4371 // an ellipsis conversion sequence, and
4372 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4373 // conversion sequence than an ellipsis conversion sequence
4374 // (13.3.3.1.3).
4375 //
4376 // C++0x [over.best.ics]p10:
4377 // For the purpose of ranking implicit conversion sequences as
4378 // described in 13.3.3.2, the ambiguous conversion sequence is
4379 // treated as a user-defined sequence that is indistinguishable
4380 // from any other user-defined conversion sequence.
4381
4382 // String literal to 'char *' conversion has been deprecated in C++03. It has
4383 // been removed from C++11. We still accept this conversion, if it happens at
4384 // the best viable function. Otherwise, this conversion is considered worse
4385 // than ellipsis conversion. Consider this as an extension; this is not in the
4386 // standard. For example:
4387 //
4388 // int &f(...); // #1
4389 // void f(char*); // #2
4390 // void g() { int &r = f("foo"); }
4391 //
4392 // In C++03, we pick #2 as the best viable function.
4393 // In C++11, we pick #1 as the best viable function, because ellipsis
4394 // conversion is better than string-literal to char* conversion (since there
4395 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4396 // convert arguments, #2 would be the best viable function in C++11.
4397 // If the best viable function has this conversion, a warning will be issued
4398 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4399
4400 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4401 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4402 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4403 // Ill-formedness must not differ
4404 ICS1.isBad() == ICS2.isBad())
4405 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4406 ? ImplicitConversionSequence::Worse
4407 : ImplicitConversionSequence::Better;
4408
4409 if (ICS1.getKindRank() < ICS2.getKindRank())
4410 return ImplicitConversionSequence::Better;
4411 if (ICS2.getKindRank() < ICS1.getKindRank())
4412 return ImplicitConversionSequence::Worse;
4413
4414 // The following checks require both conversion sequences to be of
4415 // the same kind.
4416 if (ICS1.getKind() != ICS2.getKind())
4417 return ImplicitConversionSequence::Indistinguishable;
4418
4419 ImplicitConversionSequence::CompareKind Result =
4420 ImplicitConversionSequence::Indistinguishable;
4421
4422 // Two implicit conversion sequences of the same form are
4423 // indistinguishable conversion sequences unless one of the
4424 // following rules apply: (C++ 13.3.3.2p3):
4425
4426 // List-initialization sequence L1 is a better conversion sequence than
4427 // list-initialization sequence L2 if:
4428 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4429 // if not that,
4430 // — L1 and L2 convert to arrays of the same element type, and either the
4431 // number of elements n_1 initialized by L1 is less than the number of
4432 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4433 // an array of unknown bound and L1 does not,
4434 // even if one of the other rules in this paragraph would otherwise apply.
4435 if (!ICS1.isBad()) {
4436 bool StdInit1 = false, StdInit2 = false;
4437 if (ICS1.hasInitializerListContainerType())
4438 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4439 Element: nullptr);
4440 if (ICS2.hasInitializerListContainerType())
4441 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4442 Element: nullptr);
4443 if (StdInit1 != StdInit2)
4444 return StdInit1 ? ImplicitConversionSequence::Better
4445 : ImplicitConversionSequence::Worse;
4446
4447 if (ICS1.hasInitializerListContainerType() &&
4448 ICS2.hasInitializerListContainerType())
4449 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4450 T: ICS1.getInitializerListContainerType()))
4451 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4452 T: ICS2.getInitializerListContainerType())) {
4453 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4454 T2: CAT2->getElementType())) {
4455 // Both to arrays of the same element type
4456 if (CAT1->getSize() != CAT2->getSize())
4457 // Different sized, the smaller wins
4458 return CAT1->getSize().ult(RHS: CAT2->getSize())
4459 ? ImplicitConversionSequence::Better
4460 : ImplicitConversionSequence::Worse;
4461 if (ICS1.isInitializerListOfIncompleteArray() !=
4462 ICS2.isInitializerListOfIncompleteArray())
4463 // One is incomplete, it loses
4464 return ICS2.isInitializerListOfIncompleteArray()
4465 ? ImplicitConversionSequence::Better
4466 : ImplicitConversionSequence::Worse;
4467 }
4468 }
4469 }
4470
4471 if (ICS1.isStandard())
4472 // Standard conversion sequence S1 is a better conversion sequence than
4473 // standard conversion sequence S2 if [...]
4474 Result = CompareStandardConversionSequences(S, Loc,
4475 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4476 else if (ICS1.isUserDefined()) {
4477 // With lazy template loading, it is possible to find non-canonical
4478 // FunctionDecls, depending on when redecl chains are completed. Make sure
4479 // to compare the canonical decls of conversion functions. This avoids
4480 // ambiguity problems for templated conversion operators.
4481 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4482 if (ConvFunc1)
4483 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4484 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4485 if (ConvFunc2)
4486 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4487 // User-defined conversion sequence U1 is a better conversion
4488 // sequence than another user-defined conversion sequence U2 if
4489 // they contain the same user-defined conversion function or
4490 // constructor and if the second standard conversion sequence of
4491 // U1 is better than the second standard conversion sequence of
4492 // U2 (C++ 13.3.3.2p3).
4493 if (ConvFunc1 == ConvFunc2)
4494 Result = CompareStandardConversionSequences(S, Loc,
4495 SCS1: ICS1.UserDefined.After,
4496 SCS2: ICS2.UserDefined.After);
4497 else
4498 Result = compareConversionFunctions(S,
4499 Function1: ICS1.UserDefined.ConversionFunction,
4500 Function2: ICS2.UserDefined.ConversionFunction);
4501 }
4502
4503 return Result;
4504}
4505
4506// Per 13.3.3.2p3, compare the given standard conversion sequences to
4507// determine if one is a proper subset of the other.
4508static ImplicitConversionSequence::CompareKind
4509compareStandardConversionSubsets(ASTContext &Context,
4510 const StandardConversionSequence& SCS1,
4511 const StandardConversionSequence& SCS2) {
4512 ImplicitConversionSequence::CompareKind Result
4513 = ImplicitConversionSequence::Indistinguishable;
4514
4515 // the identity conversion sequence is considered to be a subsequence of
4516 // any non-identity conversion sequence
4517 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4518 return ImplicitConversionSequence::Better;
4519 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4520 return ImplicitConversionSequence::Worse;
4521
4522 if (SCS1.Second != SCS2.Second) {
4523 if (SCS1.Second == ICK_Identity)
4524 Result = ImplicitConversionSequence::Better;
4525 else if (SCS2.Second == ICK_Identity)
4526 Result = ImplicitConversionSequence::Worse;
4527 else
4528 return ImplicitConversionSequence::Indistinguishable;
4529 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4530 return ImplicitConversionSequence::Indistinguishable;
4531
4532 if (SCS1.Third == SCS2.Third) {
4533 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4534 : ImplicitConversionSequence::Indistinguishable;
4535 }
4536
4537 if (SCS1.Third == ICK_Identity)
4538 return Result == ImplicitConversionSequence::Worse
4539 ? ImplicitConversionSequence::Indistinguishable
4540 : ImplicitConversionSequence::Better;
4541
4542 if (SCS2.Third == ICK_Identity)
4543 return Result == ImplicitConversionSequence::Better
4544 ? ImplicitConversionSequence::Indistinguishable
4545 : ImplicitConversionSequence::Worse;
4546
4547 return ImplicitConversionSequence::Indistinguishable;
4548}
4549
4550/// Determine whether one of the given reference bindings is better
4551/// than the other based on what kind of bindings they are.
4552static bool
4553isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4554 const StandardConversionSequence &SCS2) {
4555 // C++0x [over.ics.rank]p3b4:
4556 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4557 // implicit object parameter of a non-static member function declared
4558 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4559 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4560 // lvalue reference to a function lvalue and S2 binds an rvalue
4561 // reference*.
4562 //
4563 // FIXME: Rvalue references. We're going rogue with the above edits,
4564 // because the semantics in the current C++0x working paper (N3225 at the
4565 // time of this writing) break the standard definition of std::forward
4566 // and std::reference_wrapper when dealing with references to functions.
4567 // Proposed wording changes submitted to CWG for consideration.
4568 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4569 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4570 return false;
4571
4572 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4573 SCS2.IsLvalueReference) ||
4574 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4575 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4576}
4577
4578enum class FixedEnumPromotion {
4579 None,
4580 ToUnderlyingType,
4581 ToPromotedUnderlyingType
4582};
4583
4584/// Returns kind of fixed enum promotion the \a SCS uses.
4585static FixedEnumPromotion
4586getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4587
4588 if (SCS.Second != ICK_Integral_Promotion)
4589 return FixedEnumPromotion::None;
4590
4591 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4592 if (!Enum)
4593 return FixedEnumPromotion::None;
4594
4595 if (!Enum->isFixed())
4596 return FixedEnumPromotion::None;
4597
4598 QualType UnderlyingType = Enum->getIntegerType();
4599 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4600 return FixedEnumPromotion::ToUnderlyingType;
4601
4602 return FixedEnumPromotion::ToPromotedUnderlyingType;
4603}
4604
4605/// CompareStandardConversionSequences - Compare two standard
4606/// conversion sequences to determine whether one is better than the
4607/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4608static ImplicitConversionSequence::CompareKind
4609CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4610 const StandardConversionSequence& SCS1,
4611 const StandardConversionSequence& SCS2)
4612{
4613 // Standard conversion sequence S1 is a better conversion sequence
4614 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4615
4616 // -- S1 is a proper subsequence of S2 (comparing the conversion
4617 // sequences in the canonical form defined by 13.3.3.1.1,
4618 // excluding any Lvalue Transformation; the identity conversion
4619 // sequence is considered to be a subsequence of any
4620 // non-identity conversion sequence) or, if not that,
4621 if (ImplicitConversionSequence::CompareKind CK
4622 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4623 return CK;
4624
4625 // -- the rank of S1 is better than the rank of S2 (by the rules
4626 // defined below), or, if not that,
4627 ImplicitConversionRank Rank1 = SCS1.getRank();
4628 ImplicitConversionRank Rank2 = SCS2.getRank();
4629 if (Rank1 < Rank2)
4630 return ImplicitConversionSequence::Better;
4631 else if (Rank2 < Rank1)
4632 return ImplicitConversionSequence::Worse;
4633
4634 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4635 // are indistinguishable unless one of the following rules
4636 // applies:
4637
4638 // A conversion that is not a conversion of a pointer, or
4639 // pointer to member, to bool is better than another conversion
4640 // that is such a conversion.
4641 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4642 return SCS2.isPointerConversionToBool()
4643 ? ImplicitConversionSequence::Better
4644 : ImplicitConversionSequence::Worse;
4645
4646 // C++14 [over.ics.rank]p4b2:
4647 // This is retroactively applied to C++11 by CWG 1601.
4648 //
4649 // A conversion that promotes an enumeration whose underlying type is fixed
4650 // to its underlying type is better than one that promotes to the promoted
4651 // underlying type, if the two are different.
4652 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4653 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4654 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4655 FEP1 != FEP2)
4656 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4657 ? ImplicitConversionSequence::Better
4658 : ImplicitConversionSequence::Worse;
4659
4660 // C++ [over.ics.rank]p4b2:
4661 //
4662 // If class B is derived directly or indirectly from class A,
4663 // conversion of B* to A* is better than conversion of B* to
4664 // void*, and conversion of A* to void* is better than conversion
4665 // of B* to void*.
4666 bool SCS1ConvertsToVoid
4667 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4668 bool SCS2ConvertsToVoid
4669 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4670 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4671 // Exactly one of the conversion sequences is a conversion to
4672 // a void pointer; it's the worse conversion.
4673 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4674 : ImplicitConversionSequence::Worse;
4675 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4676 // Neither conversion sequence converts to a void pointer; compare
4677 // their derived-to-base conversions.
4678 if (ImplicitConversionSequence::CompareKind DerivedCK
4679 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4680 return DerivedCK;
4681 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4682 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4683 // Both conversion sequences are conversions to void
4684 // pointers. Compare the source types to determine if there's an
4685 // inheritance relationship in their sources.
4686 QualType FromType1 = SCS1.getFromType();
4687 QualType FromType2 = SCS2.getFromType();
4688
4689 // Adjust the types we're converting from via the array-to-pointer
4690 // conversion, if we need to.
4691 if (SCS1.First == ICK_Array_To_Pointer)
4692 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4693 if (SCS2.First == ICK_Array_To_Pointer)
4694 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4695
4696 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4697 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4698
4699 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4700 return ImplicitConversionSequence::Better;
4701 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4702 return ImplicitConversionSequence::Worse;
4703
4704 // Objective-C++: If one interface is more specific than the
4705 // other, it is the better one.
4706 const ObjCObjectPointerType* FromObjCPtr1
4707 = FromType1->getAs<ObjCObjectPointerType>();
4708 const ObjCObjectPointerType* FromObjCPtr2
4709 = FromType2->getAs<ObjCObjectPointerType>();
4710 if (FromObjCPtr1 && FromObjCPtr2) {
4711 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4712 RHSOPT: FromObjCPtr2);
4713 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4714 RHSOPT: FromObjCPtr1);
4715 if (AssignLeft != AssignRight) {
4716 return AssignLeft? ImplicitConversionSequence::Better
4717 : ImplicitConversionSequence::Worse;
4718 }
4719 }
4720 }
4721
4722 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4723 // Check for a better reference binding based on the kind of bindings.
4724 if (isBetterReferenceBindingKind(SCS1, SCS2))
4725 return ImplicitConversionSequence::Better;
4726 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4727 return ImplicitConversionSequence::Worse;
4728 }
4729
4730 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4731 // bullet 3).
4732 if (ImplicitConversionSequence::CompareKind QualCK
4733 = CompareQualificationConversions(S, SCS1, SCS2))
4734 return QualCK;
4735
4736 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4737 // C++ [over.ics.rank]p3b4:
4738 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4739 // which the references refer are the same type except for
4740 // top-level cv-qualifiers, and the type to which the reference
4741 // initialized by S2 refers is more cv-qualified than the type
4742 // to which the reference initialized by S1 refers.
4743 QualType T1 = SCS1.getToType(Idx: 2);
4744 QualType T2 = SCS2.getToType(Idx: 2);
4745 T1 = S.Context.getCanonicalType(T: T1);
4746 T2 = S.Context.getCanonicalType(T: T2);
4747 Qualifiers T1Quals, T2Quals;
4748 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4749 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4750 if (UnqualT1 == UnqualT2) {
4751 // Objective-C++ ARC: If the references refer to objects with different
4752 // lifetimes, prefer bindings that don't change lifetime.
4753 if (SCS1.ObjCLifetimeConversionBinding !=
4754 SCS2.ObjCLifetimeConversionBinding) {
4755 return SCS1.ObjCLifetimeConversionBinding
4756 ? ImplicitConversionSequence::Worse
4757 : ImplicitConversionSequence::Better;
4758 }
4759
4760 // If the type is an array type, promote the element qualifiers to the
4761 // type for comparison.
4762 if (isa<ArrayType>(Val: T1) && T1Quals)
4763 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4764 if (isa<ArrayType>(Val: T2) && T2Quals)
4765 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4766 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4767 return ImplicitConversionSequence::Better;
4768 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4769 return ImplicitConversionSequence::Worse;
4770 }
4771 }
4772
4773 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4774 // floating-to-integral conversion if the integral conversion
4775 // is between types of the same size.
4776 // For example:
4777 // void f(float);
4778 // void f(int);
4779 // int main {
4780 // long a;
4781 // f(a);
4782 // }
4783 // Here, MSVC will call f(int) instead of generating a compile error
4784 // as clang will do in standard mode.
4785 if (S.getLangOpts().MSVCCompat &&
4786 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4787 SCS1.Second == ICK_Integral_Conversion &&
4788 SCS2.Second == ICK_Floating_Integral &&
4789 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4790 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4791 return ImplicitConversionSequence::Better;
4792
4793 // Prefer a compatible vector conversion over a lax vector conversion
4794 // For example:
4795 //
4796 // typedef float __v4sf __attribute__((__vector_size__(16)));
4797 // void f(vector float);
4798 // void f(vector signed int);
4799 // int main() {
4800 // __v4sf a;
4801 // f(a);
4802 // }
4803 // Here, we'd like to choose f(vector float) and not
4804 // report an ambiguous call error
4805 if (SCS1.Second == ICK_Vector_Conversion &&
4806 SCS2.Second == ICK_Vector_Conversion) {
4807 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4808 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4809 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4810 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4811
4812 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4813 return SCS1IsCompatibleVectorConversion
4814 ? ImplicitConversionSequence::Better
4815 : ImplicitConversionSequence::Worse;
4816 }
4817
4818 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4819 SCS2.Second == ICK_SVE_Vector_Conversion) {
4820 bool SCS1IsCompatibleSVEVectorConversion =
4821 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4822 bool SCS2IsCompatibleSVEVectorConversion =
4823 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4824
4825 if (SCS1IsCompatibleSVEVectorConversion !=
4826 SCS2IsCompatibleSVEVectorConversion)
4827 return SCS1IsCompatibleSVEVectorConversion
4828 ? ImplicitConversionSequence::Better
4829 : ImplicitConversionSequence::Worse;
4830 }
4831
4832 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4833 SCS2.Second == ICK_RVV_Vector_Conversion) {
4834 bool SCS1IsCompatibleRVVVectorConversion =
4835 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4836 bool SCS2IsCompatibleRVVVectorConversion =
4837 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4838
4839 if (SCS1IsCompatibleRVVVectorConversion !=
4840 SCS2IsCompatibleRVVVectorConversion)
4841 return SCS1IsCompatibleRVVVectorConversion
4842 ? ImplicitConversionSequence::Better
4843 : ImplicitConversionSequence::Worse;
4844 }
4845 return ImplicitConversionSequence::Indistinguishable;
4846}
4847
4848/// CompareQualificationConversions - Compares two standard conversion
4849/// sequences to determine whether they can be ranked based on their
4850/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4851static ImplicitConversionSequence::CompareKind
4852CompareQualificationConversions(Sema &S,
4853 const StandardConversionSequence& SCS1,
4854 const StandardConversionSequence& SCS2) {
4855 // C++ [over.ics.rank]p3:
4856 // -- S1 and S2 differ only in their qualification conversion and
4857 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4858 // [C++98]
4859 // [...] and the cv-qualification signature of type T1 is a proper subset
4860 // of the cv-qualification signature of type T2, and S1 is not the
4861 // deprecated string literal array-to-pointer conversion (4.2).
4862 // [C++2a]
4863 // [...] where T1 can be converted to T2 by a qualification conversion.
4864 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4865 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4866 return ImplicitConversionSequence::Indistinguishable;
4867
4868 // FIXME: the example in the standard doesn't use a qualification
4869 // conversion (!)
4870 QualType T1 = SCS1.getToType(Idx: 2);
4871 QualType T2 = SCS2.getToType(Idx: 2);
4872 T1 = S.Context.getCanonicalType(T: T1);
4873 T2 = S.Context.getCanonicalType(T: T2);
4874 assert(!T1->isReferenceType() && !T2->isReferenceType());
4875 Qualifiers T1Quals, T2Quals;
4876 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4877 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4878
4879 // If the types are the same, we won't learn anything by unwrapping
4880 // them.
4881 if (UnqualT1 == UnqualT2)
4882 return ImplicitConversionSequence::Indistinguishable;
4883
4884 // Don't ever prefer a standard conversion sequence that uses the deprecated
4885 // string literal array to pointer conversion.
4886 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4887 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4888
4889 // Objective-C++ ARC:
4890 // Prefer qualification conversions not involving a change in lifetime
4891 // to qualification conversions that do change lifetime.
4892 if (SCS1.QualificationIncludesObjCLifetime &&
4893 !SCS2.QualificationIncludesObjCLifetime)
4894 CanPick1 = false;
4895 if (SCS2.QualificationIncludesObjCLifetime &&
4896 !SCS1.QualificationIncludesObjCLifetime)
4897 CanPick2 = false;
4898
4899 bool ObjCLifetimeConversion;
4900 if (CanPick1 &&
4901 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
4902 CanPick1 = false;
4903 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4904 // directions, so we can't short-cut this second check in general.
4905 if (CanPick2 &&
4906 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
4907 CanPick2 = false;
4908
4909 if (CanPick1 != CanPick2)
4910 return CanPick1 ? ImplicitConversionSequence::Better
4911 : ImplicitConversionSequence::Worse;
4912 return ImplicitConversionSequence::Indistinguishable;
4913}
4914
4915/// CompareDerivedToBaseConversions - Compares two standard conversion
4916/// sequences to determine whether they can be ranked based on their
4917/// various kinds of derived-to-base conversions (C++
4918/// [over.ics.rank]p4b3). As part of these checks, we also look at
4919/// conversions between Objective-C interface types.
4920static ImplicitConversionSequence::CompareKind
4921CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4922 const StandardConversionSequence& SCS1,
4923 const StandardConversionSequence& SCS2) {
4924 QualType FromType1 = SCS1.getFromType();
4925 QualType ToType1 = SCS1.getToType(Idx: 1);
4926 QualType FromType2 = SCS2.getFromType();
4927 QualType ToType2 = SCS2.getToType(Idx: 1);
4928
4929 // Adjust the types we're converting from via the array-to-pointer
4930 // conversion, if we need to.
4931 if (SCS1.First == ICK_Array_To_Pointer)
4932 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4933 if (SCS2.First == ICK_Array_To_Pointer)
4934 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4935
4936 // Canonicalize all of the types.
4937 FromType1 = S.Context.getCanonicalType(T: FromType1);
4938 ToType1 = S.Context.getCanonicalType(T: ToType1);
4939 FromType2 = S.Context.getCanonicalType(T: FromType2);
4940 ToType2 = S.Context.getCanonicalType(T: ToType2);
4941
4942 // C++ [over.ics.rank]p4b3:
4943 //
4944 // If class B is derived directly or indirectly from class A and
4945 // class C is derived directly or indirectly from B,
4946 //
4947 // Compare based on pointer conversions.
4948 if (SCS1.Second == ICK_Pointer_Conversion &&
4949 SCS2.Second == ICK_Pointer_Conversion &&
4950 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4951 FromType1->isPointerType() && FromType2->isPointerType() &&
4952 ToType1->isPointerType() && ToType2->isPointerType()) {
4953 QualType FromPointee1 =
4954 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4955 QualType ToPointee1 =
4956 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4957 QualType FromPointee2 =
4958 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4959 QualType ToPointee2 =
4960 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4961
4962 // -- conversion of C* to B* is better than conversion of C* to A*,
4963 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4964 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4965 return ImplicitConversionSequence::Better;
4966 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4967 return ImplicitConversionSequence::Worse;
4968 }
4969
4970 // -- conversion of B* to A* is better than conversion of C* to A*,
4971 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4972 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4973 return ImplicitConversionSequence::Better;
4974 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4975 return ImplicitConversionSequence::Worse;
4976 }
4977 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4978 SCS2.Second == ICK_Pointer_Conversion) {
4979 const ObjCObjectPointerType *FromPtr1
4980 = FromType1->getAs<ObjCObjectPointerType>();
4981 const ObjCObjectPointerType *FromPtr2
4982 = FromType2->getAs<ObjCObjectPointerType>();
4983 const ObjCObjectPointerType *ToPtr1
4984 = ToType1->getAs<ObjCObjectPointerType>();
4985 const ObjCObjectPointerType *ToPtr2
4986 = ToType2->getAs<ObjCObjectPointerType>();
4987
4988 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4989 // Apply the same conversion ranking rules for Objective-C pointer types
4990 // that we do for C++ pointers to class types. However, we employ the
4991 // Objective-C pseudo-subtyping relationship used for assignment of
4992 // Objective-C pointer types.
4993 bool FromAssignLeft
4994 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
4995 bool FromAssignRight
4996 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
4997 bool ToAssignLeft
4998 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
4999 bool ToAssignRight
5000 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5001
5002 // A conversion to an a non-id object pointer type or qualified 'id'
5003 // type is better than a conversion to 'id'.
5004 if (ToPtr1->isObjCIdType() &&
5005 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5006 return ImplicitConversionSequence::Worse;
5007 if (ToPtr2->isObjCIdType() &&
5008 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5009 return ImplicitConversionSequence::Better;
5010
5011 // A conversion to a non-id object pointer type is better than a
5012 // conversion to a qualified 'id' type
5013 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5014 return ImplicitConversionSequence::Worse;
5015 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5016 return ImplicitConversionSequence::Better;
5017
5018 // A conversion to an a non-Class object pointer type or qualified 'Class'
5019 // type is better than a conversion to 'Class'.
5020 if (ToPtr1->isObjCClassType() &&
5021 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5022 return ImplicitConversionSequence::Worse;
5023 if (ToPtr2->isObjCClassType() &&
5024 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5025 return ImplicitConversionSequence::Better;
5026
5027 // A conversion to a non-Class object pointer type is better than a
5028 // conversion to a qualified 'Class' type.
5029 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5030 return ImplicitConversionSequence::Worse;
5031 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5032 return ImplicitConversionSequence::Better;
5033
5034 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5035 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5036 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5037 (ToAssignLeft != ToAssignRight)) {
5038 if (FromPtr1->isSpecialized()) {
5039 // "conversion of B<A> * to B * is better than conversion of B * to
5040 // C *.
5041 bool IsFirstSame =
5042 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5043 bool IsSecondSame =
5044 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5045 if (IsFirstSame) {
5046 if (!IsSecondSame)
5047 return ImplicitConversionSequence::Better;
5048 } else if (IsSecondSame)
5049 return ImplicitConversionSequence::Worse;
5050 }
5051 return ToAssignLeft? ImplicitConversionSequence::Worse
5052 : ImplicitConversionSequence::Better;
5053 }
5054
5055 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5056 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5057 (FromAssignLeft != FromAssignRight))
5058 return FromAssignLeft? ImplicitConversionSequence::Better
5059 : ImplicitConversionSequence::Worse;
5060 }
5061 }
5062
5063 // Ranking of member-pointer types.
5064 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5065 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5066 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5067 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5068 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5069 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5070 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5071 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5072 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5073 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5074 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5075 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5076 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5077 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5078 return ImplicitConversionSequence::Worse;
5079 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5080 return ImplicitConversionSequence::Better;
5081 }
5082 // conversion of B::* to C::* is better than conversion of A::* to C::*
5083 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5084 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5085 return ImplicitConversionSequence::Better;
5086 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5087 return ImplicitConversionSequence::Worse;
5088 }
5089 }
5090
5091 if (SCS1.Second == ICK_Derived_To_Base) {
5092 // -- conversion of C to B is better than conversion of C to A,
5093 // -- binding of an expression of type C to a reference of type
5094 // B& is better than binding an expression of type C to a
5095 // reference of type A&,
5096 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5097 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5098 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5099 return ImplicitConversionSequence::Better;
5100 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5101 return ImplicitConversionSequence::Worse;
5102 }
5103
5104 // -- conversion of B to A is better than conversion of C to A.
5105 // -- binding of an expression of type B to a reference of type
5106 // A& is better than binding an expression of type C to a
5107 // reference of type A&,
5108 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5109 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5110 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5111 return ImplicitConversionSequence::Better;
5112 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5113 return ImplicitConversionSequence::Worse;
5114 }
5115 }
5116
5117 return ImplicitConversionSequence::Indistinguishable;
5118}
5119
5120static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5121 if (!T.getQualifiers().hasUnaligned())
5122 return T;
5123
5124 Qualifiers Q;
5125 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5126 Q.removeUnaligned();
5127 return Ctx.getQualifiedType(T, Qs: Q);
5128}
5129
5130Sema::ReferenceCompareResult
5131Sema::CompareReferenceRelationship(SourceLocation Loc,
5132 QualType OrigT1, QualType OrigT2,
5133 ReferenceConversions *ConvOut) {
5134 assert(!OrigT1->isReferenceType() &&
5135 "T1 must be the pointee type of the reference type");
5136 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5137
5138 QualType T1 = Context.getCanonicalType(T: OrigT1);
5139 QualType T2 = Context.getCanonicalType(T: OrigT2);
5140 Qualifiers T1Quals, T2Quals;
5141 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5142 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5143
5144 ReferenceConversions ConvTmp;
5145 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5146 Conv = ReferenceConversions();
5147
5148 // C++2a [dcl.init.ref]p4:
5149 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5150 // reference-related to "cv2 T2" if T1 is similar to T2, or
5151 // T1 is a base class of T2.
5152 // "cv1 T1" is reference-compatible with "cv2 T2" if
5153 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5154 // "pointer to cv1 T1" via a standard conversion sequence.
5155
5156 // Check for standard conversions we can apply to pointers: derived-to-base
5157 // conversions, ObjC pointer conversions, and function pointer conversions.
5158 // (Qualification conversions are checked last.)
5159 if (UnqualT1 == UnqualT2) {
5160 // Nothing to do.
5161 } else if (isCompleteType(Loc, T: OrigT2) &&
5162 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5163 Conv |= ReferenceConversions::DerivedToBase;
5164 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5165 UnqualT2->isObjCObjectOrInterfaceType() &&
5166 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5167 Conv |= ReferenceConversions::ObjC;
5168 else if (UnqualT2->isFunctionType() &&
5169 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5170 Conv |= ReferenceConversions::Function;
5171 // No need to check qualifiers; function types don't have them.
5172 return Ref_Compatible;
5173 }
5174 bool ConvertedReferent = Conv != 0;
5175
5176 // We can have a qualification conversion. Compute whether the types are
5177 // similar at the same time.
5178 bool PreviousToQualsIncludeConst = true;
5179 bool TopLevel = true;
5180 do {
5181 if (T1 == T2)
5182 break;
5183
5184 // We will need a qualification conversion.
5185 Conv |= ReferenceConversions::Qualification;
5186
5187 // Track whether we performed a qualification conversion anywhere other
5188 // than the top level. This matters for ranking reference bindings in
5189 // overload resolution.
5190 if (!TopLevel)
5191 Conv |= ReferenceConversions::NestedQualification;
5192
5193 // MS compiler ignores __unaligned qualifier for references; do the same.
5194 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5195 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5196
5197 // If we find a qualifier mismatch, the types are not reference-compatible,
5198 // but are still be reference-related if they're similar.
5199 bool ObjCLifetimeConversion = false;
5200 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5201 PreviousToQualsIncludeConst,
5202 ObjCLifetimeConversion, Ctx: getASTContext()))
5203 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5204 ? Ref_Related
5205 : Ref_Incompatible;
5206
5207 // FIXME: Should we track this for any level other than the first?
5208 if (ObjCLifetimeConversion)
5209 Conv |= ReferenceConversions::ObjCLifetime;
5210
5211 TopLevel = false;
5212 } while (Context.UnwrapSimilarTypes(T1, T2));
5213
5214 // At this point, if the types are reference-related, we must either have the
5215 // same inner type (ignoring qualifiers), or must have already worked out how
5216 // to convert the referent.
5217 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5218 ? Ref_Compatible
5219 : Ref_Incompatible;
5220}
5221
5222/// Look for a user-defined conversion to a value reference-compatible
5223/// with DeclType. Return true if something definite is found.
5224static bool
5225FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5226 QualType DeclType, SourceLocation DeclLoc,
5227 Expr *Init, QualType T2, bool AllowRvalues,
5228 bool AllowExplicit) {
5229 assert(T2->isRecordType() && "Can only find conversions of record types.");
5230 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5231 OverloadCandidateSet CandidateSet(
5232 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5233 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5234 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5235 NamedDecl *D = *I;
5236 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5237 if (isa<UsingShadowDecl>(Val: D))
5238 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5239
5240 FunctionTemplateDecl *ConvTemplate
5241 = dyn_cast<FunctionTemplateDecl>(Val: D);
5242 CXXConversionDecl *Conv;
5243 if (ConvTemplate)
5244 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5245 else
5246 Conv = cast<CXXConversionDecl>(Val: D);
5247
5248 if (AllowRvalues) {
5249 // If we are initializing an rvalue reference, don't permit conversion
5250 // functions that return lvalues.
5251 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5252 const ReferenceType *RefType
5253 = Conv->getConversionType()->getAs<LValueReferenceType>();
5254 if (RefType && !RefType->getPointeeType()->isFunctionType())
5255 continue;
5256 }
5257
5258 if (!ConvTemplate &&
5259 S.CompareReferenceRelationship(
5260 Loc: DeclLoc,
5261 OrigT1: Conv->getConversionType()
5262 .getNonReferenceType()
5263 .getUnqualifiedType(),
5264 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5265 Sema::Ref_Incompatible)
5266 continue;
5267 } else {
5268 // If the conversion function doesn't return a reference type,
5269 // it can't be considered for this conversion. An rvalue reference
5270 // is only acceptable if its referencee is a function type.
5271
5272 const ReferenceType *RefType =
5273 Conv->getConversionType()->getAs<ReferenceType>();
5274 if (!RefType ||
5275 (!RefType->isLValueReferenceType() &&
5276 !RefType->getPointeeType()->isFunctionType()))
5277 continue;
5278 }
5279
5280 if (ConvTemplate)
5281 S.AddTemplateConversionCandidate(
5282 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5283 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5284 else
5285 S.AddConversionCandidate(
5286 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5287 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5288 }
5289
5290 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5291
5292 OverloadCandidateSet::iterator Best;
5293 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5294 case OR_Success:
5295
5296 assert(Best->HasFinalConversion);
5297
5298 // C++ [over.ics.ref]p1:
5299 //
5300 // [...] If the parameter binds directly to the result of
5301 // applying a conversion function to the argument
5302 // expression, the implicit conversion sequence is a
5303 // user-defined conversion sequence (13.3.3.1.2), with the
5304 // second standard conversion sequence either an identity
5305 // conversion or, if the conversion function returns an
5306 // entity of a type that is a derived class of the parameter
5307 // type, a derived-to-base Conversion.
5308 if (!Best->FinalConversion.DirectBinding)
5309 return false;
5310
5311 ICS.setUserDefined();
5312 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5313 ICS.UserDefined.After = Best->FinalConversion;
5314 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5315 ICS.UserDefined.ConversionFunction = Best->Function;
5316 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5317 ICS.UserDefined.EllipsisConversion = false;
5318 assert(ICS.UserDefined.After.ReferenceBinding &&
5319 ICS.UserDefined.After.DirectBinding &&
5320 "Expected a direct reference binding!");
5321 return true;
5322
5323 case OR_Ambiguous:
5324 ICS.setAmbiguous();
5325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5326 Cand != CandidateSet.end(); ++Cand)
5327 if (Cand->Best)
5328 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5329 return true;
5330
5331 case OR_No_Viable_Function:
5332 case OR_Deleted:
5333 // There was no suitable conversion, or we found a deleted
5334 // conversion; continue with other checks.
5335 return false;
5336 }
5337
5338 llvm_unreachable("Invalid OverloadResult!");
5339}
5340
5341/// Compute an implicit conversion sequence for reference
5342/// initialization.
5343static ImplicitConversionSequence
5344TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5345 SourceLocation DeclLoc,
5346 bool SuppressUserConversions,
5347 bool AllowExplicit) {
5348 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5349
5350 // Most paths end in a failed conversion.
5351 ImplicitConversionSequence ICS;
5352 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5353
5354 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5355 QualType T2 = Init->getType();
5356
5357 // If the initializer is the address of an overloaded function, try
5358 // to resolve the overloaded function. If all goes well, T2 is the
5359 // type of the resulting function.
5360 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5361 DeclAccessPair Found;
5362 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5363 Complain: false, Found))
5364 T2 = Fn->getType();
5365 }
5366
5367 // Compute some basic properties of the types and the initializer.
5368 bool isRValRef = DeclType->isRValueReferenceType();
5369 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5370
5371 Sema::ReferenceConversions RefConv;
5372 Sema::ReferenceCompareResult RefRelationship =
5373 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5374
5375 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5376 ICS.setStandard();
5377 ICS.Standard.First = ICK_Identity;
5378 // FIXME: A reference binding can be a function conversion too. We should
5379 // consider that when ordering reference-to-function bindings.
5380 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5381 ? ICK_Derived_To_Base
5382 : (RefConv & Sema::ReferenceConversions::ObjC)
5383 ? ICK_Compatible_Conversion
5384 : ICK_Identity;
5385 ICS.Standard.Dimension = ICK_Identity;
5386 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5387 // a reference binding that performs a non-top-level qualification
5388 // conversion as a qualification conversion, not as an identity conversion.
5389 ICS.Standard.Third = (RefConv &
5390 Sema::ReferenceConversions::NestedQualification)
5391 ? ICK_Qualification
5392 : ICK_Identity;
5393 ICS.Standard.setFromType(T2);
5394 ICS.Standard.setToType(Idx: 0, T: T2);
5395 ICS.Standard.setToType(Idx: 1, T: T1);
5396 ICS.Standard.setToType(Idx: 2, T: T1);
5397 ICS.Standard.ReferenceBinding = true;
5398 ICS.Standard.DirectBinding = BindsDirectly;
5399 ICS.Standard.IsLvalueReference = !isRValRef;
5400 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5401 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5402 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5403 ICS.Standard.ObjCLifetimeConversionBinding =
5404 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5405 ICS.Standard.FromBracedInitList = false;
5406 ICS.Standard.CopyConstructor = nullptr;
5407 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5408 };
5409
5410 // C++0x [dcl.init.ref]p5:
5411 // A reference to type "cv1 T1" is initialized by an expression
5412 // of type "cv2 T2" as follows:
5413
5414 // -- If reference is an lvalue reference and the initializer expression
5415 if (!isRValRef) {
5416 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5417 // reference-compatible with "cv2 T2," or
5418 //
5419 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5420 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5421 // C++ [over.ics.ref]p1:
5422 // When a parameter of reference type binds directly (8.5.3)
5423 // to an argument expression, the implicit conversion sequence
5424 // is the identity conversion, unless the argument expression
5425 // has a type that is a derived class of the parameter type,
5426 // in which case the implicit conversion sequence is a
5427 // derived-to-base Conversion (13.3.3.1).
5428 SetAsReferenceBinding(/*BindsDirectly=*/true);
5429
5430 // Nothing more to do: the inaccessibility/ambiguity check for
5431 // derived-to-base conversions is suppressed when we're
5432 // computing the implicit conversion sequence (C++
5433 // [over.best.ics]p2).
5434 return ICS;
5435 }
5436
5437 // -- has a class type (i.e., T2 is a class type), where T1 is
5438 // not reference-related to T2, and can be implicitly
5439 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5440 // is reference-compatible with "cv3 T3" 92) (this
5441 // conversion is selected by enumerating the applicable
5442 // conversion functions (13.3.1.6) and choosing the best
5443 // one through overload resolution (13.3)),
5444 if (!SuppressUserConversions && T2->isRecordType() &&
5445 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5446 RefRelationship == Sema::Ref_Incompatible) {
5447 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5448 Init, T2, /*AllowRvalues=*/false,
5449 AllowExplicit))
5450 return ICS;
5451 }
5452 }
5453
5454 // -- Otherwise, the reference shall be an lvalue reference to a
5455 // non-volatile const type (i.e., cv1 shall be const), or the reference
5456 // shall be an rvalue reference.
5457 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5458 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5459 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5460 return ICS;
5461 }
5462
5463 // -- If the initializer expression
5464 //
5465 // -- is an xvalue, class prvalue, array prvalue or function
5466 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5467 if (RefRelationship == Sema::Ref_Compatible &&
5468 (InitCategory.isXValue() ||
5469 (InitCategory.isPRValue() &&
5470 (T2->isRecordType() || T2->isArrayType())) ||
5471 (InitCategory.isLValue() && T2->isFunctionType()))) {
5472 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5473 // binding unless we're binding to a class prvalue.
5474 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5475 // allow the use of rvalue references in C++98/03 for the benefit of
5476 // standard library implementors; therefore, we need the xvalue check here.
5477 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5478 !(InitCategory.isPRValue() || T2->isRecordType()));
5479 return ICS;
5480 }
5481
5482 // -- has a class type (i.e., T2 is a class type), where T1 is not
5483 // reference-related to T2, and can be implicitly converted to
5484 // an xvalue, class prvalue, or function lvalue of type
5485 // "cv3 T3", where "cv1 T1" is reference-compatible with
5486 // "cv3 T3",
5487 //
5488 // then the reference is bound to the value of the initializer
5489 // expression in the first case and to the result of the conversion
5490 // in the second case (or, in either case, to an appropriate base
5491 // class subobject).
5492 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5493 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5494 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5495 Init, T2, /*AllowRvalues=*/true,
5496 AllowExplicit)) {
5497 // In the second case, if the reference is an rvalue reference
5498 // and the second standard conversion sequence of the
5499 // user-defined conversion sequence includes an lvalue-to-rvalue
5500 // conversion, the program is ill-formed.
5501 if (ICS.isUserDefined() && isRValRef &&
5502 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5503 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5504
5505 return ICS;
5506 }
5507
5508 // A temporary of function type cannot be created; don't even try.
5509 if (T1->isFunctionType())
5510 return ICS;
5511
5512 // -- Otherwise, a temporary of type "cv1 T1" is created and
5513 // initialized from the initializer expression using the
5514 // rules for a non-reference copy initialization (8.5). The
5515 // reference is then bound to the temporary. If T1 is
5516 // reference-related to T2, cv1 must be the same
5517 // cv-qualification as, or greater cv-qualification than,
5518 // cv2; otherwise, the program is ill-formed.
5519 if (RefRelationship == Sema::Ref_Related) {
5520 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5521 // we would be reference-compatible or reference-compatible with
5522 // added qualification. But that wasn't the case, so the reference
5523 // initialization fails.
5524 //
5525 // Note that we only want to check address spaces and cvr-qualifiers here.
5526 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5527 Qualifiers T1Quals = T1.getQualifiers();
5528 Qualifiers T2Quals = T2.getQualifiers();
5529 T1Quals.removeObjCGCAttr();
5530 T1Quals.removeObjCLifetime();
5531 T2Quals.removeObjCGCAttr();
5532 T2Quals.removeObjCLifetime();
5533 // MS compiler ignores __unaligned qualifier for references; do the same.
5534 T1Quals.removeUnaligned();
5535 T2Quals.removeUnaligned();
5536 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5537 return ICS;
5538 }
5539
5540 // If at least one of the types is a class type, the types are not
5541 // related, and we aren't allowed any user conversions, the
5542 // reference binding fails. This case is important for breaking
5543 // recursion, since TryImplicitConversion below will attempt to
5544 // create a temporary through the use of a copy constructor.
5545 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5546 (T1->isRecordType() || T2->isRecordType()))
5547 return ICS;
5548
5549 // If T1 is reference-related to T2 and the reference is an rvalue
5550 // reference, the initializer expression shall not be an lvalue.
5551 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5552 Init->Classify(Ctx&: S.Context).isLValue()) {
5553 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5554 return ICS;
5555 }
5556
5557 // C++ [over.ics.ref]p2:
5558 // When a parameter of reference type is not bound directly to
5559 // an argument expression, the conversion sequence is the one
5560 // required to convert the argument expression to the
5561 // underlying type of the reference according to
5562 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5563 // to copy-initializing a temporary of the underlying type with
5564 // the argument expression. Any difference in top-level
5565 // cv-qualification is subsumed by the initialization itself
5566 // and does not constitute a conversion.
5567 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5568 AllowExplicit: AllowedExplicit::None,
5569 /*InOverloadResolution=*/false,
5570 /*CStyle=*/false,
5571 /*AllowObjCWritebackConversion=*/false,
5572 /*AllowObjCConversionOnExplicit=*/false);
5573
5574 // Of course, that's still a reference binding.
5575 if (ICS.isStandard()) {
5576 ICS.Standard.ReferenceBinding = true;
5577 ICS.Standard.IsLvalueReference = !isRValRef;
5578 ICS.Standard.BindsToFunctionLvalue = false;
5579 ICS.Standard.BindsToRvalue = true;
5580 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5581 ICS.Standard.ObjCLifetimeConversionBinding = false;
5582 } else if (ICS.isUserDefined()) {
5583 const ReferenceType *LValRefType =
5584 ICS.UserDefined.ConversionFunction->getReturnType()
5585 ->getAs<LValueReferenceType>();
5586
5587 // C++ [over.ics.ref]p3:
5588 // Except for an implicit object parameter, for which see 13.3.1, a
5589 // standard conversion sequence cannot be formed if it requires [...]
5590 // binding an rvalue reference to an lvalue other than a function
5591 // lvalue.
5592 // Note that the function case is not possible here.
5593 if (isRValRef && LValRefType) {
5594 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5595 return ICS;
5596 }
5597
5598 ICS.UserDefined.After.ReferenceBinding = true;
5599 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5600 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5601 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5602 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5603 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5604 ICS.UserDefined.After.FromBracedInitList = false;
5605 }
5606
5607 return ICS;
5608}
5609
5610static ImplicitConversionSequence
5611TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5612 bool SuppressUserConversions,
5613 bool InOverloadResolution,
5614 bool AllowObjCWritebackConversion,
5615 bool AllowExplicit = false);
5616
5617/// TryListConversion - Try to copy-initialize a value of type ToType from the
5618/// initializer list From.
5619static ImplicitConversionSequence
5620TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5621 bool SuppressUserConversions,
5622 bool InOverloadResolution,
5623 bool AllowObjCWritebackConversion) {
5624 // C++11 [over.ics.list]p1:
5625 // When an argument is an initializer list, it is not an expression and
5626 // special rules apply for converting it to a parameter type.
5627
5628 ImplicitConversionSequence Result;
5629 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5630
5631 // We need a complete type for what follows. With one C++20 exception,
5632 // incomplete types can never be initialized from init lists.
5633 QualType InitTy = ToType;
5634 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5635 if (AT && S.getLangOpts().CPlusPlus20)
5636 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5637 // C++20 allows list initialization of an incomplete array type.
5638 InitTy = IAT->getElementType();
5639 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5640 return Result;
5641
5642 // C++20 [over.ics.list]/2:
5643 // If the initializer list is a designated-initializer-list, a conversion
5644 // is only possible if the parameter has an aggregate type
5645 //
5646 // FIXME: The exception for reference initialization here is not part of the
5647 // language rules, but follow other compilers in adding it as a tentative DR
5648 // resolution.
5649 bool IsDesignatedInit = From->hasDesignatedInit();
5650 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5651 IsDesignatedInit)
5652 return Result;
5653
5654 // Per DR1467 and DR2137:
5655 // If the parameter type is an aggregate class X and the initializer list
5656 // has a single element of type cv U, where U is X or a class derived from
5657 // X, the implicit conversion sequence is the one required to convert the
5658 // element to the parameter type.
5659 //
5660 // Otherwise, if the parameter type is a character array [... ]
5661 // and the initializer list has a single element that is an
5662 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5663 // implicit conversion sequence is the identity conversion.
5664 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5665 if (ToType->isRecordType() && ToType->isAggregateType()) {
5666 QualType InitType = From->getInit(Init: 0)->getType();
5667 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5668 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5669 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5670 SuppressUserConversions,
5671 InOverloadResolution,
5672 AllowObjCWritebackConversion);
5673 }
5674
5675 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5676 InitializedEntity Entity =
5677 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5678 /*Consumed=*/false);
5679 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5680 Result.setStandard();
5681 Result.Standard.setAsIdentityConversion();
5682 Result.Standard.setFromType(ToType);
5683 Result.Standard.setAllToTypes(ToType);
5684 return Result;
5685 }
5686 }
5687 }
5688
5689 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5690 // C++11 [over.ics.list]p2:
5691 // If the parameter type is std::initializer_list<X> or "array of X" and
5692 // all the elements can be implicitly converted to X, the implicit
5693 // conversion sequence is the worst conversion necessary to convert an
5694 // element of the list to X.
5695 //
5696 // C++14 [over.ics.list]p3:
5697 // Otherwise, if the parameter type is "array of N X", if the initializer
5698 // list has exactly N elements or if it has fewer than N elements and X is
5699 // default-constructible, and if all the elements of the initializer list
5700 // can be implicitly converted to X, the implicit conversion sequence is
5701 // the worst conversion necessary to convert an element of the list to X.
5702 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5703 unsigned e = From->getNumInits();
5704 ImplicitConversionSequence DfltElt;
5705 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5706 ToType: QualType());
5707 QualType ContTy = ToType;
5708 bool IsUnbounded = false;
5709 if (AT) {
5710 InitTy = AT->getElementType();
5711 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5712 if (CT->getSize().ult(RHS: e)) {
5713 // Too many inits, fatally bad
5714 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5715 ToType);
5716 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5717 return Result;
5718 }
5719 if (CT->getSize().ugt(RHS: e)) {
5720 // Need an init from empty {}, is there one?
5721 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5722 From->getEndLoc());
5723 EmptyList.setType(S.Context.VoidTy);
5724 DfltElt = TryListConversion(
5725 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5726 InOverloadResolution, AllowObjCWritebackConversion);
5727 if (DfltElt.isBad()) {
5728 // No {} init, fatally bad
5729 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5730 ToType);
5731 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5732 return Result;
5733 }
5734 }
5735 } else {
5736 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5737 IsUnbounded = true;
5738 if (!e) {
5739 // Cannot convert to zero-sized.
5740 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5741 ToType);
5742 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5743 return Result;
5744 }
5745 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5746 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5747 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5748 }
5749 }
5750
5751 Result.setStandard();
5752 Result.Standard.setAsIdentityConversion();
5753 Result.Standard.setFromType(InitTy);
5754 Result.Standard.setAllToTypes(InitTy);
5755 for (unsigned i = 0; i < e; ++i) {
5756 Expr *Init = From->getInit(Init: i);
5757 ImplicitConversionSequence ICS = TryCopyInitialization(
5758 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5759 AllowObjCWritebackConversion);
5760
5761 // Keep the worse conversion seen so far.
5762 // FIXME: Sequences are not totally ordered, so 'worse' can be
5763 // ambiguous. CWG has been informed.
5764 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5765 ICS2: Result) ==
5766 ImplicitConversionSequence::Worse) {
5767 Result = ICS;
5768 // Bail as soon as we find something unconvertible.
5769 if (Result.isBad()) {
5770 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5771 return Result;
5772 }
5773 }
5774 }
5775
5776 // If we needed any implicit {} initialization, compare that now.
5777 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5778 // has been informed that this might not be the best thing.
5779 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5780 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5781 ImplicitConversionSequence::Worse)
5782 Result = DfltElt;
5783 // Record the type being initialized so that we may compare sequences
5784 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5785 return Result;
5786 }
5787
5788 // C++14 [over.ics.list]p4:
5789 // C++11 [over.ics.list]p3:
5790 // Otherwise, if the parameter is a non-aggregate class X and overload
5791 // resolution chooses a single best constructor [...] the implicit
5792 // conversion sequence is a user-defined conversion sequence. If multiple
5793 // constructors are viable but none is better than the others, the
5794 // implicit conversion sequence is a user-defined conversion sequence.
5795 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5796 // This function can deal with initializer lists.
5797 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5798 AllowExplicit: AllowedExplicit::None,
5799 InOverloadResolution, /*CStyle=*/false,
5800 AllowObjCWritebackConversion,
5801 /*AllowObjCConversionOnExplicit=*/false);
5802 }
5803
5804 // C++14 [over.ics.list]p5:
5805 // C++11 [over.ics.list]p4:
5806 // Otherwise, if the parameter has an aggregate type which can be
5807 // initialized from the initializer list [...] the implicit conversion
5808 // sequence is a user-defined conversion sequence.
5809 if (ToType->isAggregateType()) {
5810 // Type is an aggregate, argument is an init list. At this point it comes
5811 // down to checking whether the initialization works.
5812 // FIXME: Find out whether this parameter is consumed or not.
5813 InitializedEntity Entity =
5814 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5815 /*Consumed=*/false);
5816 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5817 From)) {
5818 Result.setUserDefined();
5819 Result.UserDefined.Before.setAsIdentityConversion();
5820 // Initializer lists don't have a type.
5821 Result.UserDefined.Before.setFromType(QualType());
5822 Result.UserDefined.Before.setAllToTypes(QualType());
5823
5824 Result.UserDefined.After.setAsIdentityConversion();
5825 Result.UserDefined.After.setFromType(ToType);
5826 Result.UserDefined.After.setAllToTypes(ToType);
5827 Result.UserDefined.ConversionFunction = nullptr;
5828 }
5829 return Result;
5830 }
5831
5832 // C++14 [over.ics.list]p6:
5833 // C++11 [over.ics.list]p5:
5834 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5835 if (ToType->isReferenceType()) {
5836 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5837 // mention initializer lists in any way. So we go by what list-
5838 // initialization would do and try to extrapolate from that.
5839
5840 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5841
5842 // If the initializer list has a single element that is reference-related
5843 // to the parameter type, we initialize the reference from that.
5844 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5845 Expr *Init = From->getInit(Init: 0);
5846
5847 QualType T2 = Init->getType();
5848
5849 // If the initializer is the address of an overloaded function, try
5850 // to resolve the overloaded function. If all goes well, T2 is the
5851 // type of the resulting function.
5852 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5853 DeclAccessPair Found;
5854 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5855 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5856 T2 = Fn->getType();
5857 }
5858
5859 // Compute some basic properties of the types and the initializer.
5860 Sema::ReferenceCompareResult RefRelationship =
5861 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5862
5863 if (RefRelationship >= Sema::Ref_Related) {
5864 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5865 SuppressUserConversions,
5866 /*AllowExplicit=*/false);
5867 }
5868 }
5869
5870 // Otherwise, we bind the reference to a temporary created from the
5871 // initializer list.
5872 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5873 InOverloadResolution,
5874 AllowObjCWritebackConversion);
5875 if (Result.isFailure())
5876 return Result;
5877 assert(!Result.isEllipsis() &&
5878 "Sub-initialization cannot result in ellipsis conversion.");
5879
5880 // Can we even bind to a temporary?
5881 if (ToType->isRValueReferenceType() ||
5882 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5883 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5884 Result.UserDefined.After;
5885 SCS.ReferenceBinding = true;
5886 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5887 SCS.BindsToRvalue = true;
5888 SCS.BindsToFunctionLvalue = false;
5889 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5890 SCS.ObjCLifetimeConversionBinding = false;
5891 SCS.FromBracedInitList = false;
5892
5893 } else
5894 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
5895 FromExpr: From, ToType);
5896 return Result;
5897 }
5898
5899 // C++14 [over.ics.list]p7:
5900 // C++11 [over.ics.list]p6:
5901 // Otherwise, if the parameter type is not a class:
5902 if (!ToType->isRecordType()) {
5903 // - if the initializer list has one element that is not itself an
5904 // initializer list, the implicit conversion sequence is the one
5905 // required to convert the element to the parameter type.
5906 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5907 // single integer.
5908 unsigned NumInits = From->getNumInits();
5909 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
5910 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
5911 Result = TryCopyInitialization(
5912 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
5913 InOverloadResolution, AllowObjCWritebackConversion);
5914 if (Result.isStandard())
5915 Result.Standard.FromBracedInitList = true;
5916 }
5917 // - if the initializer list has no elements, the implicit conversion
5918 // sequence is the identity conversion.
5919 else if (NumInits == 0) {
5920 Result.setStandard();
5921 Result.Standard.setAsIdentityConversion();
5922 Result.Standard.setFromType(ToType);
5923 Result.Standard.setAllToTypes(ToType);
5924 }
5925 return Result;
5926 }
5927
5928 // C++14 [over.ics.list]p8:
5929 // C++11 [over.ics.list]p7:
5930 // In all cases other than those enumerated above, no conversion is possible
5931 return Result;
5932}
5933
5934/// TryCopyInitialization - Try to copy-initialize a value of type
5935/// ToType from the expression From. Return the implicit conversion
5936/// sequence required to pass this argument, which may be a bad
5937/// conversion sequence (meaning that the argument cannot be passed to
5938/// a parameter of this type). If @p SuppressUserConversions, then we
5939/// do not permit any user-defined conversion sequences.
5940static ImplicitConversionSequence
5941TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5942 bool SuppressUserConversions,
5943 bool InOverloadResolution,
5944 bool AllowObjCWritebackConversion,
5945 bool AllowExplicit) {
5946 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
5947 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
5948 InOverloadResolution,AllowObjCWritebackConversion);
5949
5950 if (ToType->isReferenceType())
5951 return TryReferenceInit(S, Init: From, DeclType: ToType,
5952 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
5953 SuppressUserConversions, AllowExplicit);
5954
5955 return TryImplicitConversion(S, From, ToType,
5956 SuppressUserConversions,
5957 AllowExplicit: AllowedExplicit::None,
5958 InOverloadResolution,
5959 /*CStyle=*/false,
5960 AllowObjCWritebackConversion,
5961 /*AllowObjCConversionOnExplicit=*/false);
5962}
5963
5964static bool TryCopyInitialization(const CanQualType FromQTy,
5965 const CanQualType ToQTy,
5966 Sema &S,
5967 SourceLocation Loc,
5968 ExprValueKind FromVK) {
5969 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5970 ImplicitConversionSequence ICS =
5971 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
5972
5973 return !ICS.isBad();
5974}
5975
5976/// TryObjectArgumentInitialization - Try to initialize the object
5977/// parameter of the given member function (@c Method) from the
5978/// expression @p From.
5979static ImplicitConversionSequence TryObjectArgumentInitialization(
5980 Sema &S, SourceLocation Loc, QualType FromType,
5981 Expr::Classification FromClassification, CXXMethodDecl *Method,
5982 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5983 QualType ExplicitParameterType = QualType(),
5984 bool SuppressUserConversion = false) {
5985
5986 // We need to have an object of class type.
5987 if (const auto *PT = FromType->getAs<PointerType>()) {
5988 FromType = PT->getPointeeType();
5989
5990 // When we had a pointer, it's implicitly dereferenced, so we
5991 // better have an lvalue.
5992 assert(FromClassification.isLValue());
5993 }
5994
5995 auto ValueKindFromClassification = [](Expr::Classification C) {
5996 if (C.isPRValue())
5997 return clang::VK_PRValue;
5998 if (C.isXValue())
5999 return VK_XValue;
6000 return clang::VK_LValue;
6001 };
6002
6003 if (Method->isExplicitObjectMemberFunction()) {
6004 if (ExplicitParameterType.isNull())
6005 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6006 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6007 ValueKindFromClassification(FromClassification));
6008 ImplicitConversionSequence ICS = TryCopyInitialization(
6009 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6010 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6011 if (ICS.isBad())
6012 ICS.Bad.FromExpr = nullptr;
6013 return ICS;
6014 }
6015
6016 assert(FromType->isRecordType());
6017
6018 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6019 // C++98 [class.dtor]p2:
6020 // A destructor can be invoked for a const, volatile or const volatile
6021 // object.
6022 // C++98 [over.match.funcs]p4:
6023 // For static member functions, the implicit object parameter is considered
6024 // to match any object (since if the function is selected, the object is
6025 // discarded).
6026 Qualifiers Quals = Method->getMethodQualifiers();
6027 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6028 Quals.addConst();
6029 Quals.addVolatile();
6030 }
6031
6032 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6033
6034 // Set up the conversion sequence as a "bad" conversion, to allow us
6035 // to exit early.
6036 ImplicitConversionSequence ICS;
6037
6038 // C++0x [over.match.funcs]p4:
6039 // For non-static member functions, the type of the implicit object
6040 // parameter is
6041 //
6042 // - "lvalue reference to cv X" for functions declared without a
6043 // ref-qualifier or with the & ref-qualifier
6044 // - "rvalue reference to cv X" for functions declared with the &&
6045 // ref-qualifier
6046 //
6047 // where X is the class of which the function is a member and cv is the
6048 // cv-qualification on the member function declaration.
6049 //
6050 // However, when finding an implicit conversion sequence for the argument, we
6051 // are not allowed to perform user-defined conversions
6052 // (C++ [over.match.funcs]p5). We perform a simplified version of
6053 // reference binding here, that allows class rvalues to bind to
6054 // non-constant references.
6055
6056 // First check the qualifiers.
6057 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6058 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6059 if (ImplicitParamType.getCVRQualifiers() !=
6060 FromTypeCanon.getLocalCVRQualifiers() &&
6061 !ImplicitParamType.isAtLeastAsQualifiedAs(
6062 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6063 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6064 FromType, ToType: ImplicitParamType);
6065 return ICS;
6066 }
6067
6068 if (FromTypeCanon.hasAddressSpace()) {
6069 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6070 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6071 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6072 Ctx: S.getASTContext())) {
6073 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6074 FromType, ToType: ImplicitParamType);
6075 return ICS;
6076 }
6077 }
6078
6079 // Check that we have either the same type or a derived type. It
6080 // affects the conversion rank.
6081 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6082 ImplicitConversionKind SecondKind;
6083 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6084 SecondKind = ICK_Identity;
6085 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6086 SecondKind = ICK_Derived_To_Base;
6087 } else if (!Method->isExplicitObjectMemberFunction()) {
6088 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6089 FromType, ToType: ImplicitParamType);
6090 return ICS;
6091 }
6092
6093 // Check the ref-qualifier.
6094 switch (Method->getRefQualifier()) {
6095 case RQ_None:
6096 // Do nothing; we don't care about lvalueness or rvalueness.
6097 break;
6098
6099 case RQ_LValue:
6100 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6101 // non-const lvalue reference cannot bind to an rvalue
6102 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6103 ToType: ImplicitParamType);
6104 return ICS;
6105 }
6106 break;
6107
6108 case RQ_RValue:
6109 if (!FromClassification.isRValue()) {
6110 // rvalue reference cannot bind to an lvalue
6111 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6112 ToType: ImplicitParamType);
6113 return ICS;
6114 }
6115 break;
6116 }
6117
6118 // Success. Mark this as a reference binding.
6119 ICS.setStandard();
6120 ICS.Standard.setAsIdentityConversion();
6121 ICS.Standard.Second = SecondKind;
6122 ICS.Standard.setFromType(FromType);
6123 ICS.Standard.setAllToTypes(ImplicitParamType);
6124 ICS.Standard.ReferenceBinding = true;
6125 ICS.Standard.DirectBinding = true;
6126 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6127 ICS.Standard.BindsToFunctionLvalue = false;
6128 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6129 ICS.Standard.FromBracedInitList = false;
6130 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6131 = (Method->getRefQualifier() == RQ_None);
6132 return ICS;
6133}
6134
6135/// PerformObjectArgumentInitialization - Perform initialization of
6136/// the implicit object parameter for the given Method with the given
6137/// expression.
6138ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6139 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6140 CXXMethodDecl *Method) {
6141 QualType FromRecordType, DestType;
6142 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6143
6144 Expr::Classification FromClassification;
6145 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6146 FromRecordType = PT->getPointeeType();
6147 DestType = Method->getThisType();
6148 FromClassification = Expr::Classification::makeSimpleLValue();
6149 } else {
6150 FromRecordType = From->getType();
6151 DestType = ImplicitParamRecordType;
6152 FromClassification = From->Classify(Ctx&: Context);
6153
6154 // CWG2813 [expr.call]p6:
6155 // If the function is an implicit object member function, the object
6156 // expression of the class member access shall be a glvalue [...]
6157 if (From->isPRValue()) {
6158 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6159 BoundToLvalueReference: Method->getRefQualifier() !=
6160 RefQualifierKind::RQ_RValue);
6161 }
6162 }
6163
6164 // Note that we always use the true parent context when performing
6165 // the actual argument initialization.
6166 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6167 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6168 ActingContext: Method->getParent());
6169 if (ICS.isBad()) {
6170 switch (ICS.Bad.Kind) {
6171 case BadConversionSequence::bad_qualifiers: {
6172 Qualifiers FromQs = FromRecordType.getQualifiers();
6173 Qualifiers ToQs = DestType.getQualifiers();
6174 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6175 if (CVR) {
6176 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6177 << Method->getDeclName() << FromRecordType << (CVR - 1)
6178 << From->getSourceRange();
6179 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6180 << Method->getDeclName();
6181 return ExprError();
6182 }
6183 break;
6184 }
6185
6186 case BadConversionSequence::lvalue_ref_to_rvalue:
6187 case BadConversionSequence::rvalue_ref_to_lvalue: {
6188 bool IsRValueQualified =
6189 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6190 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6191 << Method->getDeclName() << FromClassification.isRValue()
6192 << IsRValueQualified;
6193 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6194 << Method->getDeclName();
6195 return ExprError();
6196 }
6197
6198 case BadConversionSequence::no_conversion:
6199 case BadConversionSequence::unrelated_class:
6200 break;
6201
6202 case BadConversionSequence::too_few_initializers:
6203 case BadConversionSequence::too_many_initializers:
6204 llvm_unreachable("Lists are not objects");
6205 }
6206
6207 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6208 << ImplicitParamRecordType << FromRecordType
6209 << From->getSourceRange();
6210 }
6211
6212 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6213 ExprResult FromRes =
6214 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6215 if (FromRes.isInvalid())
6216 return ExprError();
6217 From = FromRes.get();
6218 }
6219
6220 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6221 CastKind CK;
6222 QualType PteeTy = DestType->getPointeeType();
6223 LangAS DestAS =
6224 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6225 if (FromRecordType.getAddressSpace() != DestAS)
6226 CK = CK_AddressSpaceConversion;
6227 else
6228 CK = CK_NoOp;
6229 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6230 }
6231 return From;
6232}
6233
6234/// TryContextuallyConvertToBool - Attempt to contextually convert the
6235/// expression From to bool (C++0x [conv]p3).
6236static ImplicitConversionSequence
6237TryContextuallyConvertToBool(Sema &S, Expr *From) {
6238 // C++ [dcl.init]/17.8:
6239 // - Otherwise, if the initialization is direct-initialization, the source
6240 // type is std::nullptr_t, and the destination type is bool, the initial
6241 // value of the object being initialized is false.
6242 if (From->getType()->isNullPtrType())
6243 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6244 DestType: S.Context.BoolTy,
6245 NeedLValToRVal: From->isGLValue());
6246
6247 // All other direct-initialization of bool is equivalent to an implicit
6248 // conversion to bool in which explicit conversions are permitted.
6249 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6250 /*SuppressUserConversions=*/false,
6251 AllowExplicit: AllowedExplicit::Conversions,
6252 /*InOverloadResolution=*/false,
6253 /*CStyle=*/false,
6254 /*AllowObjCWritebackConversion=*/false,
6255 /*AllowObjCConversionOnExplicit=*/false);
6256}
6257
6258ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6259 if (checkPlaceholderForOverload(S&: *this, E&: From))
6260 return ExprError();
6261
6262 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6263 if (!ICS.isBad())
6264 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6265 Action: AssignmentAction::Converting);
6266
6267 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6268 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6269 << From->getType() << From->getSourceRange();
6270 return ExprError();
6271}
6272
6273/// Check that the specified conversion is permitted in a converted constant
6274/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6275/// is acceptable.
6276static bool CheckConvertedConstantConversions(Sema &S,
6277 StandardConversionSequence &SCS) {
6278 // Since we know that the target type is an integral or unscoped enumeration
6279 // type, most conversion kinds are impossible. All possible First and Third
6280 // conversions are fine.
6281 switch (SCS.Second) {
6282 case ICK_Identity:
6283 case ICK_Integral_Promotion:
6284 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6285 case ICK_Zero_Queue_Conversion:
6286 return true;
6287
6288 case ICK_Boolean_Conversion:
6289 // Conversion from an integral or unscoped enumeration type to bool is
6290 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6291 // conversion, so we allow it in a converted constant expression.
6292 //
6293 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6294 // a lot of popular code. We should at least add a warning for this
6295 // (non-conforming) extension.
6296 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6297 SCS.getToType(Idx: 2)->isBooleanType();
6298
6299 case ICK_Pointer_Conversion:
6300 case ICK_Pointer_Member:
6301 // C++1z: null pointer conversions and null member pointer conversions are
6302 // only permitted if the source type is std::nullptr_t.
6303 return SCS.getFromType()->isNullPtrType();
6304
6305 case ICK_Floating_Promotion:
6306 case ICK_Complex_Promotion:
6307 case ICK_Floating_Conversion:
6308 case ICK_Complex_Conversion:
6309 case ICK_Floating_Integral:
6310 case ICK_Compatible_Conversion:
6311 case ICK_Derived_To_Base:
6312 case ICK_Vector_Conversion:
6313 case ICK_SVE_Vector_Conversion:
6314 case ICK_RVV_Vector_Conversion:
6315 case ICK_HLSL_Vector_Splat:
6316 case ICK_HLSL_Matrix_Splat:
6317 case ICK_Vector_Splat:
6318 case ICK_Complex_Real:
6319 case ICK_Block_Pointer_Conversion:
6320 case ICK_TransparentUnionConversion:
6321 case ICK_Writeback_Conversion:
6322 case ICK_Zero_Event_Conversion:
6323 case ICK_C_Only_Conversion:
6324 case ICK_Incompatible_Pointer_Conversion:
6325 case ICK_Fixed_Point_Conversion:
6326 case ICK_HLSL_Vector_Truncation:
6327 case ICK_HLSL_Matrix_Truncation:
6328 return false;
6329
6330 case ICK_Lvalue_To_Rvalue:
6331 case ICK_Array_To_Pointer:
6332 case ICK_Function_To_Pointer:
6333 case ICK_HLSL_Array_RValue:
6334 llvm_unreachable("found a first conversion kind in Second");
6335
6336 case ICK_Function_Conversion:
6337 case ICK_Qualification:
6338 llvm_unreachable("found a third conversion kind in Second");
6339
6340 case ICK_Num_Conversion_Kinds:
6341 break;
6342 }
6343
6344 llvm_unreachable("unknown conversion kind");
6345}
6346
6347/// BuildConvertedConstantExpression - Check that the expression From is a
6348/// converted constant expression of type T, perform the conversion but
6349/// does not evaluate the expression
6350static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6351 QualType T, CCEKind CCE,
6352 NamedDecl *Dest,
6353 APValue &PreNarrowingValue) {
6354 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6355 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6356 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6357 "converted constant expression outside C++11 or TTP matching");
6358
6359 if (checkPlaceholderForOverload(S, E&: From))
6360 return ExprError();
6361
6362 // C++1z [expr.const]p3:
6363 // A converted constant expression of type T is an expression,
6364 // implicitly converted to type T, where the converted
6365 // expression is a constant expression and the implicit conversion
6366 // sequence contains only [... list of conversions ...].
6367 ImplicitConversionSequence ICS =
6368 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6369 ? TryContextuallyConvertToBool(S, From)
6370 : TryCopyInitialization(S, From, ToType: T,
6371 /*SuppressUserConversions=*/false,
6372 /*InOverloadResolution=*/false,
6373 /*AllowObjCWritebackConversion=*/false,
6374 /*AllowExplicit=*/false);
6375 StandardConversionSequence *SCS = nullptr;
6376 switch (ICS.getKind()) {
6377 case ImplicitConversionSequence::StandardConversion:
6378 SCS = &ICS.Standard;
6379 break;
6380 case ImplicitConversionSequence::UserDefinedConversion:
6381 if (T->isRecordType())
6382 SCS = &ICS.UserDefined.Before;
6383 else
6384 SCS = &ICS.UserDefined.After;
6385 break;
6386 case ImplicitConversionSequence::AmbiguousConversion:
6387 case ImplicitConversionSequence::BadConversion:
6388 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6389 return S.Diag(Loc: From->getBeginLoc(),
6390 DiagID: diag::err_typecheck_converted_constant_expression)
6391 << From->getType() << From->getSourceRange() << T;
6392 return ExprError();
6393
6394 case ImplicitConversionSequence::EllipsisConversion:
6395 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6396 llvm_unreachable("bad conversion in converted constant expression");
6397 }
6398
6399 // Check that we would only use permitted conversions.
6400 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6401 return S.Diag(Loc: From->getBeginLoc(),
6402 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6403 << From->getType() << From->getSourceRange() << T;
6404 }
6405 // [...] and where the reference binding (if any) binds directly.
6406 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6407 return S.Diag(Loc: From->getBeginLoc(),
6408 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6409 << From->getType() << From->getSourceRange() << T;
6410 }
6411 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6412 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6413 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6414 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6415 // case explicitly.
6416 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6417 return S.Diag(Loc: From->getBeginLoc(),
6418 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6419 << From->getSourceRange();
6420 }
6421
6422 // Usually we can simply apply the ImplicitConversionSequence we formed
6423 // earlier, but that's not guaranteed to work when initializing an object of
6424 // class type.
6425 ExprResult Result;
6426 bool IsTemplateArgument =
6427 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6428 if (T->isRecordType()) {
6429 assert(IsTemplateArgument &&
6430 "unexpected class type converted constant expr");
6431 Result = S.PerformCopyInitialization(
6432 Entity: InitializedEntity::InitializeTemplateParameter(
6433 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6434 EqualLoc: SourceLocation(), Init: From);
6435 } else {
6436 Result =
6437 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6438 }
6439 if (Result.isInvalid())
6440 return Result;
6441
6442 // C++2a [intro.execution]p5:
6443 // A full-expression is [...] a constant-expression [...]
6444 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6445 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6446 IsTemplateArgument);
6447 if (Result.isInvalid())
6448 return Result;
6449
6450 // Check for a narrowing implicit conversion.
6451 bool ReturnPreNarrowingValue = false;
6452 QualType PreNarrowingType;
6453 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6454 ConstantType&: PreNarrowingType)) {
6455 case NK_Variable_Narrowing:
6456 // Implicit conversion to a narrower type, and the value is not a constant
6457 // expression. We'll diagnose this in a moment.
6458 case NK_Not_Narrowing:
6459 break;
6460
6461 case NK_Constant_Narrowing:
6462 if (CCE == CCEKind::ArrayBound &&
6463 PreNarrowingType->isIntegralOrEnumerationType() &&
6464 PreNarrowingValue.isInt()) {
6465 // Don't diagnose array bound narrowing here; we produce more precise
6466 // errors by allowing the un-narrowed value through.
6467 ReturnPreNarrowingValue = true;
6468 break;
6469 }
6470 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6471 << CCE << /*Constant*/ 1
6472 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6473 break;
6474
6475 case NK_Dependent_Narrowing:
6476 // Implicit conversion to a narrower type, but the expression is
6477 // value-dependent so we can't tell whether it's actually narrowing.
6478 // For matching the parameters of a TTP, the conversion is ill-formed
6479 // if it may narrow.
6480 if (CCE != CCEKind::TempArgStrict)
6481 break;
6482 [[fallthrough]];
6483 case NK_Type_Narrowing:
6484 // FIXME: It would be better to diagnose that the expression is not a
6485 // constant expression.
6486 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6487 << CCE << /*Constant*/ 0 << From->getType() << T;
6488 break;
6489 }
6490 if (!ReturnPreNarrowingValue)
6491 PreNarrowingValue = {};
6492
6493 return Result;
6494}
6495
6496/// CheckConvertedConstantExpression - Check that the expression From is a
6497/// converted constant expression of type T, perform the conversion and produce
6498/// the converted expression, per C++11 [expr.const]p3.
6499static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6500 QualType T, APValue &Value,
6501 CCEKind CCE, bool RequireInt,
6502 NamedDecl *Dest) {
6503
6504 APValue PreNarrowingValue;
6505 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6506 PreNarrowingValue);
6507 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6508 Value = APValue();
6509 return Result;
6510 }
6511 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6512 RequireInt, PreNarrowingValue);
6513}
6514
6515ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6516 CCEKind CCE,
6517 NamedDecl *Dest) {
6518 APValue PreNarrowingValue;
6519 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6520 PreNarrowingValue);
6521}
6522
6523ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6524 APValue &Value, CCEKind CCE,
6525 NamedDecl *Dest) {
6526 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6527 Dest);
6528}
6529
6530ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6531 llvm::APSInt &Value,
6532 CCEKind CCE) {
6533 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6534
6535 APValue V;
6536 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6537 /*Dest=*/nullptr);
6538 if (!R.isInvalid() && !R.get()->isValueDependent())
6539 Value = V.getInt();
6540 return R;
6541}
6542
6543ExprResult
6544Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6545 CCEKind CCE, bool RequireInt,
6546 const APValue &PreNarrowingValue) {
6547
6548 ExprResult Result = E;
6549 // Check the expression is a constant expression.
6550 SmallVector<PartialDiagnosticAt, 8> Notes;
6551 Expr::EvalResult Eval;
6552 Eval.Diag = &Notes;
6553
6554 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6555
6556 ConstantExprKind Kind;
6557 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6558 Kind = ConstantExprKind::ClassTemplateArgument;
6559 else if (CCE == CCEKind::TemplateArg)
6560 Kind = ConstantExprKind::NonClassTemplateArgument;
6561 else
6562 Kind = ConstantExprKind::Normal;
6563
6564 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6565 (RequireInt && !Eval.Val.isInt())) {
6566 // The expression can't be folded, so we can't keep it at this position in
6567 // the AST.
6568 Result = ExprError();
6569 } else {
6570 Value = Eval.Val;
6571
6572 if (Notes.empty()) {
6573 // It's a constant expression.
6574 Expr *E = Result.get();
6575 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6576 // We expect a ConstantExpr to have a value associated with it
6577 // by this point.
6578 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6579 "ConstantExpr has no value associated with it");
6580 (void)CE;
6581 } else {
6582 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6583 }
6584 if (!PreNarrowingValue.isAbsent())
6585 Value = std::move(PreNarrowingValue);
6586 return E;
6587 }
6588 }
6589
6590 // It's not a constant expression. Produce an appropriate diagnostic.
6591 if (Notes.size() == 1 &&
6592 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6593 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6594 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6595 diag::note_constexpr_invalid_template_arg) {
6596 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6597 for (unsigned I = 0; I < Notes.size(); ++I)
6598 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6599 } else {
6600 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6601 << CCE << E->getSourceRange();
6602 for (unsigned I = 0; I < Notes.size(); ++I)
6603 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6604 }
6605 return ExprError();
6606}
6607
6608/// dropPointerConversions - If the given standard conversion sequence
6609/// involves any pointer conversions, remove them. This may change
6610/// the result type of the conversion sequence.
6611static void dropPointerConversion(StandardConversionSequence &SCS) {
6612 if (SCS.Second == ICK_Pointer_Conversion) {
6613 SCS.Second = ICK_Identity;
6614 SCS.Dimension = ICK_Identity;
6615 SCS.Third = ICK_Identity;
6616 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6617 }
6618}
6619
6620/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6621/// convert the expression From to an Objective-C pointer type.
6622static ImplicitConversionSequence
6623TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6624 // Do an implicit conversion to 'id'.
6625 QualType Ty = S.Context.getObjCIdType();
6626 ImplicitConversionSequence ICS
6627 = TryImplicitConversion(S, From, ToType: Ty,
6628 // FIXME: Are these flags correct?
6629 /*SuppressUserConversions=*/false,
6630 AllowExplicit: AllowedExplicit::Conversions,
6631 /*InOverloadResolution=*/false,
6632 /*CStyle=*/false,
6633 /*AllowObjCWritebackConversion=*/false,
6634 /*AllowObjCConversionOnExplicit=*/true);
6635
6636 // Strip off any final conversions to 'id'.
6637 switch (ICS.getKind()) {
6638 case ImplicitConversionSequence::BadConversion:
6639 case ImplicitConversionSequence::AmbiguousConversion:
6640 case ImplicitConversionSequence::EllipsisConversion:
6641 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6642 break;
6643
6644 case ImplicitConversionSequence::UserDefinedConversion:
6645 dropPointerConversion(SCS&: ICS.UserDefined.After);
6646 break;
6647
6648 case ImplicitConversionSequence::StandardConversion:
6649 dropPointerConversion(SCS&: ICS.Standard);
6650 break;
6651 }
6652
6653 return ICS;
6654}
6655
6656ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6657 if (checkPlaceholderForOverload(S&: *this, E&: From))
6658 return ExprError();
6659
6660 QualType Ty = Context.getObjCIdType();
6661 ImplicitConversionSequence ICS =
6662 TryContextuallyConvertToObjCPointer(S&: *this, From);
6663 if (!ICS.isBad())
6664 return PerformImplicitConversion(From, ToType: Ty, ICS,
6665 Action: AssignmentAction::Converting);
6666 return ExprResult();
6667}
6668
6669static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6670 const Expr *Base = nullptr;
6671 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6672 "expected a member expression");
6673
6674 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6675 M && !M->isImplicitAccess())
6676 Base = M->getBase();
6677 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6678 M && !M->isImplicitAccess())
6679 Base = M->getBase();
6680
6681 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6682
6683 if (T->isPointerType())
6684 T = T->getPointeeType();
6685
6686 return T;
6687}
6688
6689static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6690 const FunctionDecl *Fun) {
6691 QualType ObjType = Obj->getType();
6692 if (ObjType->isPointerType()) {
6693 ObjType = ObjType->getPointeeType();
6694 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6695 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6696 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6697 }
6698 return Obj;
6699}
6700
6701ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6702 FunctionDecl *Fun) {
6703 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6704 return S.PerformCopyInitialization(
6705 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6706 EqualLoc: Obj->getExprLoc(), Init: Obj);
6707}
6708
6709static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6710 Expr *Object, MultiExprArg &Args,
6711 SmallVectorImpl<Expr *> &NewArgs) {
6712 assert(Method->isExplicitObjectMemberFunction() &&
6713 "Method is not an explicit member function");
6714 assert(NewArgs.empty() && "NewArgs should be empty");
6715
6716 NewArgs.reserve(N: Args.size() + 1);
6717 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6718 NewArgs.push_back(Elt: This);
6719 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6720 Args = NewArgs;
6721 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6722 Method, CallLoc: Object->getBeginLoc());
6723}
6724
6725/// Determine whether the provided type is an integral type, or an enumeration
6726/// type of a permitted flavor.
6727bool Sema::ICEConvertDiagnoser::match(QualType T) {
6728 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6729 : T->isIntegralOrUnscopedEnumerationType();
6730}
6731
6732static ExprResult
6733diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6734 Sema::ContextualImplicitConverter &Converter,
6735 QualType T, UnresolvedSetImpl &ViableConversions) {
6736
6737 if (Converter.Suppress)
6738 return ExprError();
6739
6740 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6741 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6742 CXXConversionDecl *Conv =
6743 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6744 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6745 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6746 }
6747 return From;
6748}
6749
6750static bool
6751diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6752 Sema::ContextualImplicitConverter &Converter,
6753 QualType T, bool HadMultipleCandidates,
6754 UnresolvedSetImpl &ExplicitConversions) {
6755 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6756 DeclAccessPair Found = ExplicitConversions[0];
6757 CXXConversionDecl *Conversion =
6758 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6759
6760 // The user probably meant to invoke the given explicit
6761 // conversion; use it.
6762 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6763 std::string TypeStr;
6764 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6765
6766 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6767 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6768 Code: "static_cast<" + TypeStr + ">(")
6769 << FixItHint::CreateInsertion(
6770 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6771 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6772
6773 // If we aren't in a SFINAE context, build a call to the
6774 // explicit conversion function.
6775 if (SemaRef.isSFINAEContext())
6776 return true;
6777
6778 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6779 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6780 HadMultipleCandidates);
6781 if (Result.isInvalid())
6782 return true;
6783
6784 // Replace the conversion with a RecoveryExpr, so we don't try to
6785 // instantiate it later, but can further diagnose here.
6786 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6787 SubExprs: From, T: Result.get()->getType());
6788 if (Result.isInvalid())
6789 return true;
6790 From = Result.get();
6791 }
6792 return false;
6793}
6794
6795static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6796 Sema::ContextualImplicitConverter &Converter,
6797 QualType T, bool HadMultipleCandidates,
6798 DeclAccessPair &Found) {
6799 CXXConversionDecl *Conversion =
6800 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6801 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6802
6803 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6804 if (!Converter.SuppressConversion) {
6805 if (SemaRef.isSFINAEContext())
6806 return true;
6807
6808 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6809 << From->getSourceRange();
6810 }
6811
6812 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6813 HadMultipleCandidates);
6814 if (Result.isInvalid())
6815 return true;
6816 // Record usage of conversion in an implicit cast.
6817 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6818 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6819 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6820 FPO: SemaRef.CurFPFeatureOverrides());
6821 return false;
6822}
6823
6824static ExprResult finishContextualImplicitConversion(
6825 Sema &SemaRef, SourceLocation Loc, Expr *From,
6826 Sema::ContextualImplicitConverter &Converter) {
6827 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6828 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6829 << From->getSourceRange();
6830
6831 return SemaRef.DefaultLvalueConversion(E: From);
6832}
6833
6834static void
6835collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6836 UnresolvedSetImpl &ViableConversions,
6837 OverloadCandidateSet &CandidateSet) {
6838 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6839 NamedDecl *D = FoundDecl.getDecl();
6840 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6841 if (isa<UsingShadowDecl>(Val: D))
6842 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6843
6844 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6845 SemaRef.AddTemplateConversionCandidate(
6846 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6847 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6848 continue;
6849 }
6850 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6851 SemaRef.AddConversionCandidate(
6852 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6853 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6854 }
6855}
6856
6857/// Attempt to convert the given expression to a type which is accepted
6858/// by the given converter.
6859///
6860/// This routine will attempt to convert an expression of class type to a
6861/// type accepted by the specified converter. In C++11 and before, the class
6862/// must have a single non-explicit conversion function converting to a matching
6863/// type. In C++1y, there can be multiple such conversion functions, but only
6864/// one target type.
6865///
6866/// \param Loc The source location of the construct that requires the
6867/// conversion.
6868///
6869/// \param From The expression we're converting from.
6870///
6871/// \param Converter Used to control and diagnose the conversion process.
6872///
6873/// \returns The expression, converted to an integral or enumeration type if
6874/// successful.
6875ExprResult Sema::PerformContextualImplicitConversion(
6876 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6877 // We can't perform any more checking for type-dependent expressions.
6878 if (From->isTypeDependent())
6879 return From;
6880
6881 // Process placeholders immediately.
6882 if (From->hasPlaceholderType()) {
6883 ExprResult result = CheckPlaceholderExpr(E: From);
6884 if (result.isInvalid())
6885 return result;
6886 From = result.get();
6887 }
6888
6889 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6890 ExprResult Converted = DefaultLvalueConversion(E: From);
6891 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6892 // If the expression already has a matching type, we're golden.
6893 if (Converter.match(T))
6894 return Converted;
6895
6896 // FIXME: Check for missing '()' if T is a function type?
6897
6898 // We can only perform contextual implicit conversions on objects of class
6899 // type.
6900 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6901 if (!RecordTy || !getLangOpts().CPlusPlus) {
6902 if (!Converter.Suppress)
6903 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
6904 return From;
6905 }
6906
6907 // We must have a complete class type.
6908 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6909 ContextualImplicitConverter &Converter;
6910 Expr *From;
6911
6912 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6913 : Converter(Converter), From(From) {}
6914
6915 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6916 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6917 }
6918 } IncompleteDiagnoser(Converter, From);
6919
6920 if (Converter.Suppress ? !isCompleteType(Loc, T)
6921 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
6922 return From;
6923
6924 // Look for a conversion to an integral or enumeration type.
6925 UnresolvedSet<4>
6926 ViableConversions; // These are *potentially* viable in C++1y.
6927 UnresolvedSet<4> ExplicitConversions;
6928 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
6929 ->getDefinitionOrSelf()
6930 ->getVisibleConversionFunctions();
6931
6932 bool HadMultipleCandidates =
6933 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
6934
6935 // To check that there is only one target type, in C++1y:
6936 QualType ToType;
6937 bool HasUniqueTargetType = true;
6938
6939 // Collect explicit or viable (potentially in C++1y) conversions.
6940 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6941 NamedDecl *D = (*I)->getUnderlyingDecl();
6942 CXXConversionDecl *Conversion;
6943 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6944 if (ConvTemplate) {
6945 if (getLangOpts().CPlusPlus14)
6946 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6947 else
6948 continue; // C++11 does not consider conversion operator templates(?).
6949 } else
6950 Conversion = cast<CXXConversionDecl>(Val: D);
6951
6952 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6953 "Conversion operator templates are considered potentially "
6954 "viable in C++1y");
6955
6956 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6957 if (Converter.match(T: CurToType) || ConvTemplate) {
6958
6959 if (Conversion->isExplicit()) {
6960 // FIXME: For C++1y, do we need this restriction?
6961 // cf. diagnoseNoViableConversion()
6962 if (!ConvTemplate)
6963 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6964 } else {
6965 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6966 if (ToType.isNull())
6967 ToType = CurToType.getUnqualifiedType();
6968 else if (HasUniqueTargetType &&
6969 (CurToType.getUnqualifiedType() != ToType))
6970 HasUniqueTargetType = false;
6971 }
6972 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6973 }
6974 }
6975 }
6976
6977 if (getLangOpts().CPlusPlus14) {
6978 // C++1y [conv]p6:
6979 // ... An expression e of class type E appearing in such a context
6980 // is said to be contextually implicitly converted to a specified
6981 // type T and is well-formed if and only if e can be implicitly
6982 // converted to a type T that is determined as follows: E is searched
6983 // for conversion functions whose return type is cv T or reference to
6984 // cv T such that T is allowed by the context. There shall be
6985 // exactly one such T.
6986
6987 // If no unique T is found:
6988 if (ToType.isNull()) {
6989 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6990 HadMultipleCandidates,
6991 ExplicitConversions))
6992 return ExprError();
6993 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6994 }
6995
6996 // If more than one unique Ts are found:
6997 if (!HasUniqueTargetType)
6998 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6999 ViableConversions);
7000
7001 // If one unique T is found:
7002 // First, build a candidate set from the previously recorded
7003 // potentially viable conversions.
7004 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7005 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7006 CandidateSet);
7007
7008 // Then, perform overload resolution over the candidate set.
7009 OverloadCandidateSet::iterator Best;
7010 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7011 case OR_Success: {
7012 // Apply this conversion.
7013 DeclAccessPair Found =
7014 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7015 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7016 HadMultipleCandidates, Found))
7017 return ExprError();
7018 break;
7019 }
7020 case OR_Ambiguous:
7021 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7022 ViableConversions);
7023 case OR_No_Viable_Function:
7024 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7025 HadMultipleCandidates,
7026 ExplicitConversions))
7027 return ExprError();
7028 [[fallthrough]];
7029 case OR_Deleted:
7030 // We'll complain below about a non-integral condition type.
7031 break;
7032 }
7033 } else {
7034 switch (ViableConversions.size()) {
7035 case 0: {
7036 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7037 HadMultipleCandidates,
7038 ExplicitConversions))
7039 return ExprError();
7040
7041 // We'll complain below about a non-integral condition type.
7042 break;
7043 }
7044 case 1: {
7045 // Apply this conversion.
7046 DeclAccessPair Found = ViableConversions[0];
7047 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7048 HadMultipleCandidates, Found))
7049 return ExprError();
7050 break;
7051 }
7052 default:
7053 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7054 ViableConversions);
7055 }
7056 }
7057
7058 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7059}
7060
7061/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7062/// an acceptable non-member overloaded operator for a call whose
7063/// arguments have types T1 (and, if non-empty, T2). This routine
7064/// implements the check in C++ [over.match.oper]p3b2 concerning
7065/// enumeration types.
7066static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7067 FunctionDecl *Fn,
7068 ArrayRef<Expr *> Args) {
7069 QualType T1 = Args[0]->getType();
7070 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7071
7072 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7073 return true;
7074
7075 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7076 return true;
7077
7078 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7079 if (Proto->getNumParams() < 1)
7080 return false;
7081
7082 if (T1->isEnumeralType()) {
7083 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7084 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7085 return true;
7086 }
7087
7088 if (Proto->getNumParams() < 2)
7089 return false;
7090
7091 if (!T2.isNull() && T2->isEnumeralType()) {
7092 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7093 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7094 return true;
7095 }
7096
7097 return false;
7098}
7099
7100static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7101 if (FD->isTargetMultiVersionDefault())
7102 return false;
7103
7104 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7105 return FD->isTargetMultiVersion();
7106
7107 if (!FD->isMultiVersion())
7108 return false;
7109
7110 // Among multiple target versions consider either the default,
7111 // or the first non-default in the absence of default version.
7112 unsigned SeenAt = 0;
7113 unsigned I = 0;
7114 bool HasDefault = false;
7115 FD->getASTContext().forEachMultiversionedFunctionVersion(
7116 FD, Pred: [&](const FunctionDecl *CurFD) {
7117 if (FD == CurFD)
7118 SeenAt = I;
7119 else if (CurFD->isTargetMultiVersionDefault())
7120 HasDefault = true;
7121 ++I;
7122 });
7123 return HasDefault || SeenAt != 0;
7124}
7125
7126void Sema::AddOverloadCandidate(
7127 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7128 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7129 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7130 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7131 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7132 bool StrictPackMatch) {
7133 const FunctionProtoType *Proto
7134 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7135 assert(Proto && "Functions without a prototype cannot be overloaded");
7136 assert(!Function->getDescribedFunctionTemplate() &&
7137 "Use AddTemplateOverloadCandidate for function templates");
7138
7139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7140 if (!isa<CXXConstructorDecl>(Val: Method)) {
7141 // If we get here, it's because we're calling a member function
7142 // that is named without a member access expression (e.g.,
7143 // "this->f") that was either written explicitly or created
7144 // implicitly. This can happen with a qualified call to a member
7145 // function, e.g., X::f(). We use an empty type for the implied
7146 // object argument (C++ [over.call.func]p3), and the acting context
7147 // is irrelevant.
7148 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7149 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7150 CandidateSet, SuppressUserConversions,
7151 PartialOverloading, EarlyConversions, PO,
7152 StrictPackMatch);
7153 return;
7154 }
7155 // We treat a constructor like a non-member function, since its object
7156 // argument doesn't participate in overload resolution.
7157 }
7158
7159 if (!CandidateSet.isNewCandidate(F: Function, PO))
7160 return;
7161
7162 // C++11 [class.copy]p11: [DR1402]
7163 // A defaulted move constructor that is defined as deleted is ignored by
7164 // overload resolution.
7165 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7166 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7167 Constructor->isMoveConstructor())
7168 return;
7169
7170 // Overload resolution is always an unevaluated context.
7171 EnterExpressionEvaluationContext Unevaluated(
7172 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7173
7174 // C++ [over.match.oper]p3:
7175 // if no operand has a class type, only those non-member functions in the
7176 // lookup set that have a first parameter of type T1 or "reference to
7177 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7178 // is a right operand) a second parameter of type T2 or "reference to
7179 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7180 // candidate functions.
7181 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7182 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7183 return;
7184
7185 // Add this candidate
7186 OverloadCandidate &Candidate =
7187 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7188 Candidate.FoundDecl = FoundDecl;
7189 Candidate.Function = Function;
7190 Candidate.Viable = true;
7191 Candidate.RewriteKind =
7192 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7193 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7194 Candidate.ExplicitCallArguments = Args.size();
7195 Candidate.StrictPackMatch = StrictPackMatch;
7196
7197 // Explicit functions are not actually candidates at all if we're not
7198 // allowing them in this context, but keep them around so we can point
7199 // to them in diagnostics.
7200 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7201 Candidate.Viable = false;
7202 Candidate.FailureKind = ovl_fail_explicit;
7203 return;
7204 }
7205
7206 // Functions with internal linkage are only viable in the same module unit.
7207 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7208 /// FIXME: Currently, the semantics of linkage in clang is slightly
7209 /// different from the semantics in C++ spec. In C++ spec, only names
7210 /// have linkage. So that all entities of the same should share one
7211 /// linkage. But in clang, different entities of the same could have
7212 /// different linkage.
7213 const NamedDecl *ND = Function;
7214 bool IsImplicitlyInstantiated = false;
7215 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7216 ND = SpecInfo->getTemplate();
7217 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7218 TSK_ImplicitInstantiation;
7219 }
7220
7221 /// Don't remove inline functions with internal linkage from the overload
7222 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7223 /// However:
7224 /// - Inline functions with internal linkage are a common pattern in
7225 /// headers to avoid ODR issues.
7226 /// - The global module is meant to be a transition mechanism for C and C++
7227 /// headers, and the current rules as written work against that goal.
7228 const bool IsInlineFunctionInGMF =
7229 Function->isFromGlobalModule() &&
7230 (IsImplicitlyInstantiated || Function->isInlined());
7231
7232 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7233 Candidate.Viable = false;
7234 Candidate.FailureKind = ovl_fail_module_mismatched;
7235 return;
7236 }
7237 }
7238
7239 if (isNonViableMultiVersionOverload(FD: Function)) {
7240 Candidate.Viable = false;
7241 Candidate.FailureKind = ovl_non_default_multiversion_function;
7242 return;
7243 }
7244
7245 if (Constructor) {
7246 // C++ [class.copy]p3:
7247 // A member function template is never instantiated to perform the copy
7248 // of a class object to an object of its class type.
7249 CanQualType ClassType =
7250 Context.getCanonicalTagType(TD: Constructor->getParent());
7251 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7252 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7253 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7254 Base: ClassType))) {
7255 Candidate.Viable = false;
7256 Candidate.FailureKind = ovl_fail_illegal_constructor;
7257 return;
7258 }
7259
7260 // C++ [over.match.funcs]p8: (proposed DR resolution)
7261 // A constructor inherited from class type C that has a first parameter
7262 // of type "reference to P" (including such a constructor instantiated
7263 // from a template) is excluded from the set of candidate functions when
7264 // constructing an object of type cv D if the argument list has exactly
7265 // one argument and D is reference-related to P and P is reference-related
7266 // to C.
7267 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7268 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7269 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7270 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7271 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7272 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7273 SourceLocation Loc = Args.front()->getExprLoc();
7274 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7275 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7276 Candidate.Viable = false;
7277 Candidate.FailureKind = ovl_fail_inhctor_slice;
7278 return;
7279 }
7280 }
7281
7282 // Check that the constructor is capable of constructing an object in the
7283 // destination address space.
7284 if (!Qualifiers::isAddressSpaceSupersetOf(
7285 A: Constructor->getMethodQualifiers().getAddressSpace(),
7286 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7287 Candidate.Viable = false;
7288 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7289 }
7290 }
7291
7292 unsigned NumParams = Proto->getNumParams();
7293
7294 // (C++ 13.3.2p2): A candidate function having fewer than m
7295 // parameters is viable only if it has an ellipsis in its parameter
7296 // list (8.3.5).
7297 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7298 !Proto->isVariadic() &&
7299 shouldEnforceArgLimit(PartialOverloading, Function)) {
7300 Candidate.Viable = false;
7301 Candidate.FailureKind = ovl_fail_too_many_arguments;
7302 return;
7303 }
7304
7305 // (C++ 13.3.2p2): A candidate function having more than m parameters
7306 // is viable only if the (m+1)st parameter has a default argument
7307 // (8.3.6). For the purposes of overload resolution, the
7308 // parameter list is truncated on the right, so that there are
7309 // exactly m parameters.
7310 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7311 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7312 !PartialOverloading) {
7313 // Not enough arguments.
7314 Candidate.Viable = false;
7315 Candidate.FailureKind = ovl_fail_too_few_arguments;
7316 return;
7317 }
7318
7319 // (CUDA B.1): Check for invalid calls between targets.
7320 if (getLangOpts().CUDA) {
7321 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7322 // Skip the check for callers that are implicit members, because in this
7323 // case we may not yet know what the member's target is; the target is
7324 // inferred for the member automatically, based on the bases and fields of
7325 // the class.
7326 if (!(Caller && Caller->isImplicit()) &&
7327 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7328 Candidate.Viable = false;
7329 Candidate.FailureKind = ovl_fail_bad_target;
7330 return;
7331 }
7332 }
7333
7334 if (Function->getTrailingRequiresClause()) {
7335 ConstraintSatisfaction Satisfaction;
7336 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7337 /*ForOverloadResolution*/ true) ||
7338 !Satisfaction.IsSatisfied) {
7339 Candidate.Viable = false;
7340 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7341 return;
7342 }
7343 }
7344
7345 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7346 // Determine the implicit conversion sequences for each of the
7347 // arguments.
7348 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7349 unsigned ConvIdx =
7350 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7351 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7352 // We already formed a conversion sequence for this parameter during
7353 // template argument deduction.
7354 } else if (ArgIdx < NumParams) {
7355 // (C++ 13.3.2p3): for F to be a viable function, there shall
7356 // exist for each argument an implicit conversion sequence
7357 // (13.3.3.1) that converts that argument to the corresponding
7358 // parameter of F.
7359 QualType ParamType = Proto->getParamType(i: ArgIdx);
7360 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7361 if (ParamABI == ParameterABI::HLSLOut ||
7362 ParamABI == ParameterABI::HLSLInOut)
7363 ParamType = ParamType.getNonReferenceType();
7364 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7365 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7366 /*InOverloadResolution=*/true,
7367 /*AllowObjCWritebackConversion=*/
7368 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7369 if (Candidate.Conversions[ConvIdx].isBad()) {
7370 Candidate.Viable = false;
7371 Candidate.FailureKind = ovl_fail_bad_conversion;
7372 return;
7373 }
7374 } else {
7375 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7376 // argument for which there is no corresponding parameter is
7377 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7378 Candidate.Conversions[ConvIdx].setEllipsis();
7379 }
7380 }
7381
7382 if (EnableIfAttr *FailedAttr =
7383 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7384 Candidate.Viable = false;
7385 Candidate.FailureKind = ovl_fail_enable_if;
7386 Candidate.DeductionFailure.Data = FailedAttr;
7387 return;
7388 }
7389}
7390
7391ObjCMethodDecl *
7392Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7393 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7394 if (Methods.size() <= 1)
7395 return nullptr;
7396
7397 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7398 bool Match = true;
7399 ObjCMethodDecl *Method = Methods[b];
7400 unsigned NumNamedArgs = Sel.getNumArgs();
7401 // Method might have more arguments than selector indicates. This is due
7402 // to addition of c-style arguments in method.
7403 if (Method->param_size() > NumNamedArgs)
7404 NumNamedArgs = Method->param_size();
7405 if (Args.size() < NumNamedArgs)
7406 continue;
7407
7408 for (unsigned i = 0; i < NumNamedArgs; i++) {
7409 // We can't do any type-checking on a type-dependent argument.
7410 if (Args[i]->isTypeDependent()) {
7411 Match = false;
7412 break;
7413 }
7414
7415 ParmVarDecl *param = Method->parameters()[i];
7416 Expr *argExpr = Args[i];
7417 assert(argExpr && "SelectBestMethod(): missing expression");
7418
7419 // Strip the unbridged-cast placeholder expression off unless it's
7420 // a consumed argument.
7421 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7422 !param->hasAttr<CFConsumedAttr>())
7423 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7424
7425 // If the parameter is __unknown_anytype, move on to the next method.
7426 if (param->getType() == Context.UnknownAnyTy) {
7427 Match = false;
7428 break;
7429 }
7430
7431 ImplicitConversionSequence ConversionState
7432 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7433 /*SuppressUserConversions*/false,
7434 /*InOverloadResolution=*/true,
7435 /*AllowObjCWritebackConversion=*/
7436 getLangOpts().ObjCAutoRefCount,
7437 /*AllowExplicit*/false);
7438 // This function looks for a reasonably-exact match, so we consider
7439 // incompatible pointer conversions to be a failure here.
7440 if (ConversionState.isBad() ||
7441 (ConversionState.isStandard() &&
7442 ConversionState.Standard.Second ==
7443 ICK_Incompatible_Pointer_Conversion)) {
7444 Match = false;
7445 break;
7446 }
7447 }
7448 // Promote additional arguments to variadic methods.
7449 if (Match && Method->isVariadic()) {
7450 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7451 if (Args[i]->isTypeDependent()) {
7452 Match = false;
7453 break;
7454 }
7455 ExprResult Arg = DefaultVariadicArgumentPromotion(
7456 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7457 if (Arg.isInvalid()) {
7458 Match = false;
7459 break;
7460 }
7461 }
7462 } else {
7463 // Check for extra arguments to non-variadic methods.
7464 if (Args.size() != NumNamedArgs)
7465 Match = false;
7466 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7467 // Special case when selectors have no argument. In this case, select
7468 // one with the most general result type of 'id'.
7469 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7470 QualType ReturnT = Methods[b]->getReturnType();
7471 if (ReturnT->isObjCIdType())
7472 return Methods[b];
7473 }
7474 }
7475 }
7476
7477 if (Match)
7478 return Method;
7479 }
7480 return nullptr;
7481}
7482
7483static bool convertArgsForAvailabilityChecks(
7484 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7485 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7486 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7487 if (ThisArg) {
7488 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7489 assert(!isa<CXXConstructorDecl>(Method) &&
7490 "Shouldn't have `this` for ctors!");
7491 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7492 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7493 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7494 if (R.isInvalid())
7495 return false;
7496 ConvertedThis = R.get();
7497 } else {
7498 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7499 (void)MD;
7500 assert((MissingImplicitThis || MD->isStatic() ||
7501 isa<CXXConstructorDecl>(MD)) &&
7502 "Expected `this` for non-ctor instance methods");
7503 }
7504 ConvertedThis = nullptr;
7505 }
7506
7507 // Ignore any variadic arguments. Converting them is pointless, since the
7508 // user can't refer to them in the function condition.
7509 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7510
7511 // Convert the arguments.
7512 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7513 ExprResult R;
7514 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7515 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7516 EqualLoc: SourceLocation(), Init: Args[I]);
7517
7518 if (R.isInvalid())
7519 return false;
7520
7521 ConvertedArgs.push_back(Elt: R.get());
7522 }
7523
7524 if (Trap.hasErrorOccurred())
7525 return false;
7526
7527 // Push default arguments if needed.
7528 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7529 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7530 ParmVarDecl *P = Function->getParamDecl(i);
7531 if (!P->hasDefaultArg())
7532 return false;
7533 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7534 if (R.isInvalid())
7535 return false;
7536 ConvertedArgs.push_back(Elt: R.get());
7537 }
7538
7539 if (Trap.hasErrorOccurred())
7540 return false;
7541 }
7542 return true;
7543}
7544
7545EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7546 SourceLocation CallLoc,
7547 ArrayRef<Expr *> Args,
7548 bool MissingImplicitThis) {
7549 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7550 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7551 return nullptr;
7552
7553 SFINAETrap Trap(*this);
7554 // Perform the access checking immediately so any access diagnostics are
7555 // caught by the SFINAE trap.
7556 llvm::scope_exit UndelayDiags(
7557 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7558 DelayedDiagnostics.popUndelayed(state: CurrentState);
7559 });
7560 SmallVector<Expr *, 16> ConvertedArgs;
7561 // FIXME: We should look into making enable_if late-parsed.
7562 Expr *DiscardedThis;
7563 if (!convertArgsForAvailabilityChecks(
7564 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7565 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7566 return *EnableIfAttrs.begin();
7567
7568 for (auto *EIA : EnableIfAttrs) {
7569 APValue Result;
7570 // FIXME: This doesn't consider value-dependent cases, because doing so is
7571 // very difficult. Ideally, we should handle them more gracefully.
7572 if (EIA->getCond()->isValueDependent() ||
7573 !EIA->getCond()->EvaluateWithSubstitution(
7574 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7575 return EIA;
7576
7577 if (!Result.isInt() || !Result.getInt().getBoolValue())
7578 return EIA;
7579 }
7580 return nullptr;
7581}
7582
7583template <typename CheckFn>
7584static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7585 bool ArgDependent, SourceLocation Loc,
7586 CheckFn &&IsSuccessful) {
7587 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7588 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7589 if (ArgDependent == DIA->getArgDependent())
7590 Attrs.push_back(Elt: DIA);
7591 }
7592
7593 // Common case: No diagnose_if attributes, so we can quit early.
7594 if (Attrs.empty())
7595 return false;
7596
7597 auto WarningBegin = std::stable_partition(
7598 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7599 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7600 DIA->getWarningGroup().empty();
7601 });
7602
7603 // Note that diagnose_if attributes are late-parsed, so they appear in the
7604 // correct order (unlike enable_if attributes).
7605 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7606 IsSuccessful);
7607 if (ErrAttr != WarningBegin) {
7608 const DiagnoseIfAttr *DIA = *ErrAttr;
7609 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7610 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7611 << DIA->getParent() << DIA->getCond()->getSourceRange();
7612 return true;
7613 }
7614
7615 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7616 switch (Sev) {
7617 case DiagnoseIfAttr::DS_warning:
7618 return diag::Severity::Warning;
7619 case DiagnoseIfAttr::DS_error:
7620 return diag::Severity::Error;
7621 }
7622 llvm_unreachable("Fully covered switch above!");
7623 };
7624
7625 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7626 if (IsSuccessful(DIA)) {
7627 if (DIA->getWarningGroup().empty() &&
7628 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7629 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7630 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7631 << DIA->getParent() << DIA->getCond()->getSourceRange();
7632 } else {
7633 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7634 DIA->getWarningGroup());
7635 assert(DiagGroup);
7636 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7637 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7638 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7639 S.Diag(Loc, DiagID) << DIA->getMessage();
7640 }
7641 }
7642
7643 return false;
7644}
7645
7646bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7647 const Expr *ThisArg,
7648 ArrayRef<const Expr *> Args,
7649 SourceLocation Loc) {
7650 return diagnoseDiagnoseIfAttrsWith(
7651 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7652 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7653 APValue Result;
7654 // It's sane to use the same Args for any redecl of this function, since
7655 // EvaluateWithSubstitution only cares about the position of each
7656 // argument in the arg list, not the ParmVarDecl* it maps to.
7657 if (!DIA->getCond()->EvaluateWithSubstitution(
7658 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7659 return false;
7660 return Result.isInt() && Result.getInt().getBoolValue();
7661 });
7662}
7663
7664bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7665 SourceLocation Loc) {
7666 return diagnoseDiagnoseIfAttrsWith(
7667 S&: *this, ND, /*ArgDependent=*/false, Loc,
7668 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7669 bool Result;
7670 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7671 Result;
7672 });
7673}
7674
7675void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7676 ArrayRef<Expr *> Args,
7677 OverloadCandidateSet &CandidateSet,
7678 TemplateArgumentListInfo *ExplicitTemplateArgs,
7679 bool SuppressUserConversions,
7680 bool PartialOverloading,
7681 bool FirstArgumentIsBase) {
7682 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7683 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7684 ArrayRef<Expr *> FunctionArgs = Args;
7685
7686 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7687 FunctionDecl *FD =
7688 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7689
7690 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7691 QualType ObjectType;
7692 Expr::Classification ObjectClassification;
7693 if (Args.size() > 0) {
7694 if (Expr *E = Args[0]) {
7695 // Use the explicit base to restrict the lookup:
7696 ObjectType = E->getType();
7697 // Pointers in the object arguments are implicitly dereferenced, so we
7698 // always classify them as l-values.
7699 if (!ObjectType.isNull() && ObjectType->isPointerType())
7700 ObjectClassification = Expr::Classification::makeSimpleLValue();
7701 else
7702 ObjectClassification = E->Classify(Ctx&: Context);
7703 } // .. else there is an implicit base.
7704 FunctionArgs = Args.slice(N: 1);
7705 }
7706 if (FunTmpl) {
7707 AddMethodTemplateCandidate(
7708 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7709 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7710 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7711 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7712 PartialOverloading);
7713 } else {
7714 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7715 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7716 ObjectClassification, Args: FunctionArgs, CandidateSet,
7717 SuppressUserConversions, PartialOverloading);
7718 }
7719 } else {
7720 // This branch handles both standalone functions and static methods.
7721
7722 // Slice the first argument (which is the base) when we access
7723 // static method as non-static.
7724 if (Args.size() > 0 &&
7725 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7726 !isa<CXXConstructorDecl>(Val: FD)))) {
7727 assert(cast<CXXMethodDecl>(FD)->isStatic());
7728 FunctionArgs = Args.slice(N: 1);
7729 }
7730 if (FunTmpl) {
7731 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7732 ExplicitTemplateArgs, Args: FunctionArgs,
7733 CandidateSet, SuppressUserConversions,
7734 PartialOverloading);
7735 } else {
7736 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7737 SuppressUserConversions, PartialOverloading);
7738 }
7739 }
7740 }
7741}
7742
7743void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7744 Expr::Classification ObjectClassification,
7745 ArrayRef<Expr *> Args,
7746 OverloadCandidateSet &CandidateSet,
7747 bool SuppressUserConversions,
7748 OverloadCandidateParamOrder PO) {
7749 NamedDecl *Decl = FoundDecl.getDecl();
7750 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7751
7752 if (isa<UsingShadowDecl>(Val: Decl))
7753 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7754
7755 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7756 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7757 "Expected a member function template");
7758 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7759 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7760 ObjectClassification, Args, CandidateSet,
7761 SuppressUserConversions, PartialOverloading: false, PO);
7762 } else {
7763 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7764 ObjectType, ObjectClassification, Args, CandidateSet,
7765 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7766 }
7767}
7768
7769void Sema::AddMethodCandidate(
7770 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7771 CXXRecordDecl *ActingContext, QualType ObjectType,
7772 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7773 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7774 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7775 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7776 const FunctionProtoType *Proto
7777 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7778 assert(Proto && "Methods without a prototype cannot be overloaded");
7779 assert(!isa<CXXConstructorDecl>(Method) &&
7780 "Use AddOverloadCandidate for constructors");
7781
7782 if (!CandidateSet.isNewCandidate(F: Method, PO))
7783 return;
7784
7785 // C++11 [class.copy]p23: [DR1402]
7786 // A defaulted move assignment operator that is defined as deleted is
7787 // ignored by overload resolution.
7788 if (Method->isDefaulted() && Method->isDeleted() &&
7789 Method->isMoveAssignmentOperator())
7790 return;
7791
7792 // Overload resolution is always an unevaluated context.
7793 EnterExpressionEvaluationContext Unevaluated(
7794 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7795
7796 bool IgnoreExplicitObject =
7797 (Method->isExplicitObjectMemberFunction() &&
7798 CandidateSet.getKind() ==
7799 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7800 bool ImplicitObjectMethodTreatedAsStatic =
7801 CandidateSet.getKind() ==
7802 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7803 Method->isImplicitObjectMemberFunction();
7804
7805 unsigned ExplicitOffset =
7806 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7807
7808 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7809 int(ImplicitObjectMethodTreatedAsStatic);
7810
7811 unsigned ExtraArgs =
7812 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7813 ? 0
7814 : 1;
7815
7816 // Add this candidate
7817 OverloadCandidate &Candidate =
7818 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
7819 Candidate.FoundDecl = FoundDecl;
7820 Candidate.Function = Method;
7821 Candidate.RewriteKind =
7822 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7823 Candidate.TookAddressOfOverload =
7824 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7825 Candidate.ExplicitCallArguments = Args.size();
7826 Candidate.StrictPackMatch = StrictPackMatch;
7827
7828 // (C++ 13.3.2p2): A candidate function having fewer than m
7829 // parameters is viable only if it has an ellipsis in its parameter
7830 // list (8.3.5).
7831 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7832 !Proto->isVariadic() &&
7833 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7834 Candidate.Viable = false;
7835 Candidate.FailureKind = ovl_fail_too_many_arguments;
7836 return;
7837 }
7838
7839 // (C++ 13.3.2p2): A candidate function having more than m parameters
7840 // is viable only if the (m+1)st parameter has a default argument
7841 // (8.3.6). For the purposes of overload resolution, the
7842 // parameter list is truncated on the right, so that there are
7843 // exactly m parameters.
7844 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7845 ExplicitOffset +
7846 int(ImplicitObjectMethodTreatedAsStatic);
7847
7848 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7849 // Not enough arguments.
7850 Candidate.Viable = false;
7851 Candidate.FailureKind = ovl_fail_too_few_arguments;
7852 return;
7853 }
7854
7855 Candidate.Viable = true;
7856
7857 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7858 if (!IgnoreExplicitObject) {
7859 if (ObjectType.isNull())
7860 Candidate.IgnoreObjectArgument = true;
7861 else if (Method->isStatic()) {
7862 // [over.best.ics.general]p8
7863 // When the parameter is the implicit object parameter of a static member
7864 // function, the implicit conversion sequence is a standard conversion
7865 // sequence that is neither better nor worse than any other standard
7866 // conversion sequence.
7867 //
7868 // This is a rule that was introduced in C++23 to support static lambdas.
7869 // We apply it retroactively because we want to support static lambdas as
7870 // an extension and it doesn't hurt previous code.
7871 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7872 } else {
7873 // Determine the implicit conversion sequence for the object
7874 // parameter.
7875 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7876 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7877 Method, ActingContext, /*InOverloadResolution=*/true);
7878 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7879 Candidate.Viable = false;
7880 Candidate.FailureKind = ovl_fail_bad_conversion;
7881 return;
7882 }
7883 }
7884 }
7885
7886 // (CUDA B.1): Check for invalid calls between targets.
7887 if (getLangOpts().CUDA)
7888 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
7889 Callee: Method)) {
7890 Candidate.Viable = false;
7891 Candidate.FailureKind = ovl_fail_bad_target;
7892 return;
7893 }
7894
7895 if (Method->getTrailingRequiresClause()) {
7896 ConstraintSatisfaction Satisfaction;
7897 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
7898 /*ForOverloadResolution*/ true) ||
7899 !Satisfaction.IsSatisfied) {
7900 Candidate.Viable = false;
7901 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7902 return;
7903 }
7904 }
7905
7906 // Determine the implicit conversion sequences for each of the
7907 // arguments.
7908 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7909 unsigned ConvIdx =
7910 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7911 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7912 // We already formed a conversion sequence for this parameter during
7913 // template argument deduction.
7914 } else if (ArgIdx < NumParams) {
7915 // (C++ 13.3.2p3): for F to be a viable function, there shall
7916 // exist for each argument an implicit conversion sequence
7917 // (13.3.3.1) that converts that argument to the corresponding
7918 // parameter of F.
7919 QualType ParamType;
7920 if (ImplicitObjectMethodTreatedAsStatic) {
7921 ParamType = ArgIdx == 0
7922 ? Method->getFunctionObjectParameterReferenceType()
7923 : Proto->getParamType(i: ArgIdx - 1);
7924 } else {
7925 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
7926 }
7927 Candidate.Conversions[ConvIdx]
7928 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
7929 SuppressUserConversions,
7930 /*InOverloadResolution=*/true,
7931 /*AllowObjCWritebackConversion=*/
7932 getLangOpts().ObjCAutoRefCount);
7933 if (Candidate.Conversions[ConvIdx].isBad()) {
7934 Candidate.Viable = false;
7935 Candidate.FailureKind = ovl_fail_bad_conversion;
7936 return;
7937 }
7938 } else {
7939 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7940 // argument for which there is no corresponding parameter is
7941 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7942 Candidate.Conversions[ConvIdx].setEllipsis();
7943 }
7944 }
7945
7946 if (EnableIfAttr *FailedAttr =
7947 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
7948 Candidate.Viable = false;
7949 Candidate.FailureKind = ovl_fail_enable_if;
7950 Candidate.DeductionFailure.Data = FailedAttr;
7951 return;
7952 }
7953
7954 if (isNonViableMultiVersionOverload(FD: Method)) {
7955 Candidate.Viable = false;
7956 Candidate.FailureKind = ovl_non_default_multiversion_function;
7957 }
7958}
7959
7960static void AddMethodTemplateCandidateImmediately(
7961 Sema &S, OverloadCandidateSet &CandidateSet,
7962 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7963 CXXRecordDecl *ActingContext,
7964 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7965 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7966 bool SuppressUserConversions, bool PartialOverloading,
7967 OverloadCandidateParamOrder PO) {
7968
7969 // C++ [over.match.funcs]p7:
7970 // In each case where a candidate is a function template, candidate
7971 // function template specializations are generated using template argument
7972 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7973 // candidate functions in the usual way.113) A given name can refer to one
7974 // or more function templates and also to a set of overloaded non-template
7975 // functions. In such a case, the candidate functions generated from each
7976 // function template are combined with the set of non-template candidate
7977 // functions.
7978 TemplateDeductionInfo Info(CandidateSet.getLocation());
7979 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
7980 FunctionDecl *Specialization = nullptr;
7981 ConversionSequenceList Conversions;
7982 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7983 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7984 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7985 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7986 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
7987 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
7988 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
7989 bool OnlyInitializeNonUserDefinedConversions) {
7990 return S.CheckNonDependentConversions(
7991 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7992 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
7993 SuppressUserConversions,
7994 OnlyInitializeNonUserDefinedConversions),
7995 ActingContext, ObjectType, ObjectClassification, PO);
7996 });
7997 Result != TemplateDeductionResult::Success) {
7998 OverloadCandidate &Candidate =
7999 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8000 Candidate.FoundDecl = FoundDecl;
8001 Candidate.Function = Method;
8002 Candidate.Viable = false;
8003 Candidate.RewriteKind =
8004 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8005 Candidate.IsSurrogate = false;
8006 Candidate.TookAddressOfOverload =
8007 CandidateSet.getKind() ==
8008 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8009
8010 Candidate.IgnoreObjectArgument =
8011 Method->isStatic() ||
8012 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8013 Candidate.ExplicitCallArguments = Args.size();
8014 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8015 Candidate.FailureKind = ovl_fail_bad_conversion;
8016 else {
8017 Candidate.FailureKind = ovl_fail_bad_deduction;
8018 Candidate.DeductionFailure =
8019 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8020 }
8021 return;
8022 }
8023
8024 // Add the function template specialization produced by template argument
8025 // deduction as a candidate.
8026 assert(Specialization && "Missing member function template specialization?");
8027 assert(isa<CXXMethodDecl>(Specialization) &&
8028 "Specialization is not a member function?");
8029 S.AddMethodCandidate(
8030 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8031 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8032 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8033}
8034
8035void Sema::AddMethodTemplateCandidate(
8036 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8037 CXXRecordDecl *ActingContext,
8038 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8039 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8040 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8041 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8042 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8043 return;
8044
8045 if (ExplicitTemplateArgs ||
8046 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts())) {
8047 AddMethodTemplateCandidateImmediately(
8048 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8049 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8050 SuppressUserConversions, PartialOverloading, PO);
8051 return;
8052 }
8053
8054 CandidateSet.AddDeferredMethodTemplateCandidate(
8055 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8056 Args, SuppressUserConversions, PartialOverloading, PO);
8057}
8058
8059/// Determine whether a given function template has a simple explicit specifier
8060/// or a non-value-dependent explicit-specification that evaluates to true.
8061static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8062 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8063}
8064
8065static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8066 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8067 ExplicitSpecKind::Unresolved;
8068}
8069
8070static void AddTemplateOverloadCandidateImmediately(
8071 Sema &S, OverloadCandidateSet &CandidateSet,
8072 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8073 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8074 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8075 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8076 bool AggregateCandidateDeduction) {
8077
8078 // If the function template has a non-dependent explicit specification,
8079 // exclude it now if appropriate; we are not permitted to perform deduction
8080 // and substitution in this case.
8081 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8082 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8083 Candidate.FoundDecl = FoundDecl;
8084 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8085 Candidate.Viable = false;
8086 Candidate.FailureKind = ovl_fail_explicit;
8087 return;
8088 }
8089
8090 // C++ [over.match.funcs]p7:
8091 // In each case where a candidate is a function template, candidate
8092 // function template specializations are generated using template argument
8093 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8094 // candidate functions in the usual way.113) A given name can refer to one
8095 // or more function templates and also to a set of overloaded non-template
8096 // functions. In such a case, the candidate functions generated from each
8097 // function template are combined with the set of non-template candidate
8098 // functions.
8099 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8100 FunctionTemplate->getTemplateDepth());
8101 FunctionDecl *Specialization = nullptr;
8102 ConversionSequenceList Conversions;
8103 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8104 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8105 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8106 /*PartialOrdering=*/false,
8107 /*ObjectType=*/QualType(),
8108 /*ObjectClassification=*/Expr::Classification(),
8109 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8110 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8111 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8112 bool OnlyInitializeNonUserDefinedConversions) {
8113 return S.CheckNonDependentConversions(
8114 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8115 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8116 SuppressUserConversions,
8117 OnlyInitializeNonUserDefinedConversions),
8118 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8119 });
8120 Result != TemplateDeductionResult::Success) {
8121 OverloadCandidate &Candidate =
8122 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8123 Candidate.FoundDecl = FoundDecl;
8124 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8125 Candidate.Viable = false;
8126 Candidate.RewriteKind =
8127 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8128 Candidate.IsSurrogate = false;
8129 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8130 // Ignore the object argument if there is one, since we don't have an object
8131 // type.
8132 Candidate.TookAddressOfOverload =
8133 CandidateSet.getKind() ==
8134 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8135
8136 Candidate.IgnoreObjectArgument =
8137 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8138 !cast<CXXMethodDecl>(Val: Candidate.Function)
8139 ->isExplicitObjectMemberFunction() &&
8140 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8141
8142 Candidate.ExplicitCallArguments = Args.size();
8143 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8144 Candidate.FailureKind = ovl_fail_bad_conversion;
8145 else {
8146 Candidate.FailureKind = ovl_fail_bad_deduction;
8147 Candidate.DeductionFailure =
8148 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8149 }
8150 return;
8151 }
8152
8153 // Add the function template specialization produced by template argument
8154 // deduction as a candidate.
8155 assert(Specialization && "Missing function template specialization?");
8156 S.AddOverloadCandidate(
8157 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8158 PartialOverloading, AllowExplicit,
8159 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8160 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8161 StrictPackMatch: Info.hasStrictPackMatch());
8162}
8163
8164void Sema::AddTemplateOverloadCandidate(
8165 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8166 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8167 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8168 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8169 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8170 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8171 return;
8172
8173 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8174
8175 if (ExplicitTemplateArgs ||
8176 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8177 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8178 DependentExplicitSpecifier)) {
8179
8180 AddTemplateOverloadCandidateImmediately(
8181 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8182 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8183 IsADLCandidate, PO, AggregateCandidateDeduction);
8184
8185 if (DependentExplicitSpecifier)
8186 CandidateSet.DisableResolutionByPerfectCandidate();
8187 return;
8188 }
8189
8190 CandidateSet.AddDeferredTemplateCandidate(
8191 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8192 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8193 AggregateCandidateDeduction);
8194}
8195
8196bool Sema::CheckNonDependentConversions(
8197 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8198 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8199 ConversionSequenceList &Conversions,
8200 CheckNonDependentConversionsFlag UserConversionFlag,
8201 CXXRecordDecl *ActingContext, QualType ObjectType,
8202 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8203 // FIXME: The cases in which we allow explicit conversions for constructor
8204 // arguments never consider calling a constructor template. It's not clear
8205 // that is correct.
8206 const bool AllowExplicit = false;
8207
8208 bool ForOverloadSetAddressResolution =
8209 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8210 auto *FD = FunctionTemplate->getTemplatedDecl();
8211 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8212 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8213 !isa<CXXConstructorDecl>(Val: Method);
8214 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8215
8216 if (Conversions.empty())
8217 Conversions =
8218 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8219
8220 // Overload resolution is always an unevaluated context.
8221 EnterExpressionEvaluationContext Unevaluated(
8222 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8223
8224 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8225 // require that, but this check should never result in a hard error, and
8226 // overload resolution is permitted to sidestep instantiations.
8227 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8228 !ObjectType.isNull()) {
8229 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8230 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8231 !ParamTypes[0]->isDependentType()) {
8232 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8233 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8234 Method, ActingContext, /*InOverloadResolution=*/true,
8235 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8236 : QualType());
8237 if (Conversions[ConvIdx].isBad())
8238 return true;
8239 }
8240 }
8241
8242 // A speculative workaround for self-dependent constraint bugs that manifest
8243 // after CWG2369.
8244 // FIXME: Add references to the standard once P3606 is adopted.
8245 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8246 QualType ArgType) {
8247 ParamType = ParamType.getNonReferenceType();
8248 ArgType = ArgType.getNonReferenceType();
8249 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8250 if (PointerConv) {
8251 ParamType = ParamType->getPointeeType();
8252 ArgType = ArgType->getPointeeType();
8253 }
8254
8255 if (auto *RD = ParamType->getAsCXXRecordDecl();
8256 RD && RD->hasDefinition() &&
8257 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8258 auto Info = getConstructorInfo(ND);
8259 if (!Info)
8260 return false;
8261 CXXConstructorDecl *Ctor = Info.Constructor;
8262 /// isConvertingConstructor takes copy/move constructors into
8263 /// account!
8264 return !Ctor->isCopyOrMoveConstructor() &&
8265 Ctor->isConvertingConstructor(
8266 /*AllowExplicit=*/true);
8267 }))
8268 return true;
8269 if (auto *RD = ArgType->getAsCXXRecordDecl();
8270 RD && RD->hasDefinition() &&
8271 !RD->getVisibleConversionFunctions().empty())
8272 return true;
8273
8274 return false;
8275 };
8276
8277 unsigned Offset =
8278 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8279 : 0;
8280
8281 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8282 I != N; ++I) {
8283 QualType ParamType = ParamTypes[I + Offset];
8284 if (!ParamType->isDependentType()) {
8285 unsigned ConvIdx;
8286 if (PO == OverloadCandidateParamOrder::Reversed) {
8287 ConvIdx = Args.size() - 1 - I;
8288 assert(Args.size() + ThisConversions == 2 &&
8289 "number of args (including 'this') must be exactly 2 for "
8290 "reversed order");
8291 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8292 // would also be 0. 'this' got ConvIdx = 1 previously.
8293 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8294 } else {
8295 // For members, 'this' got ConvIdx = 0 previously.
8296 ConvIdx = ThisConversions + I;
8297 }
8298 if (Conversions[ConvIdx].isInitialized())
8299 continue;
8300 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8301 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8302 continue;
8303 Conversions[ConvIdx] = TryCopyInitialization(
8304 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8305 /*InOverloadResolution=*/true,
8306 /*AllowObjCWritebackConversion=*/
8307 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8308 if (Conversions[ConvIdx].isBad())
8309 return true;
8310 }
8311 }
8312
8313 return false;
8314}
8315
8316/// Determine whether this is an allowable conversion from the result
8317/// of an explicit conversion operator to the expected type, per C++
8318/// [over.match.conv]p1 and [over.match.ref]p1.
8319///
8320/// \param ConvType The return type of the conversion function.
8321///
8322/// \param ToType The type we are converting to.
8323///
8324/// \param AllowObjCPointerConversion Allow a conversion from one
8325/// Objective-C pointer to another.
8326///
8327/// \returns true if the conversion is allowable, false otherwise.
8328static bool isAllowableExplicitConversion(Sema &S,
8329 QualType ConvType, QualType ToType,
8330 bool AllowObjCPointerConversion) {
8331 QualType ToNonRefType = ToType.getNonReferenceType();
8332
8333 // Easy case: the types are the same.
8334 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8335 return true;
8336
8337 // Allow qualification conversions.
8338 bool ObjCLifetimeConversion;
8339 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8340 ObjCLifetimeConversion))
8341 return true;
8342
8343 // If we're not allowed to consider Objective-C pointer conversions,
8344 // we're done.
8345 if (!AllowObjCPointerConversion)
8346 return false;
8347
8348 // Is this an Objective-C pointer conversion?
8349 bool IncompatibleObjC = false;
8350 QualType ConvertedType;
8351 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8352 IncompatibleObjC);
8353}
8354
8355void Sema::AddConversionCandidate(
8356 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8357 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8358 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8359 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8360 assert(!Conversion->getDescribedFunctionTemplate() &&
8361 "Conversion function templates use AddTemplateConversionCandidate");
8362 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8363 if (!CandidateSet.isNewCandidate(F: Conversion))
8364 return;
8365
8366 // If the conversion function has an undeduced return type, trigger its
8367 // deduction now.
8368 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8369 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8370 return;
8371 ConvType = Conversion->getConversionType().getNonReferenceType();
8372 }
8373
8374 // If we don't allow any conversion of the result type, ignore conversion
8375 // functions that don't convert to exactly (possibly cv-qualified) T.
8376 if (!AllowResultConversion &&
8377 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8378 return;
8379
8380 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8381 // operator is only a candidate if its return type is the target type or
8382 // can be converted to the target type with a qualification conversion.
8383 //
8384 // FIXME: Include such functions in the candidate list and explain why we
8385 // can't select them.
8386 if (Conversion->isExplicit() &&
8387 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8388 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8389 return;
8390
8391 // Overload resolution is always an unevaluated context.
8392 EnterExpressionEvaluationContext Unevaluated(
8393 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8394
8395 // Add this candidate
8396 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8397 Candidate.FoundDecl = FoundDecl;
8398 Candidate.Function = Conversion;
8399 Candidate.FinalConversion.setAsIdentityConversion();
8400 Candidate.FinalConversion.setFromType(ConvType);
8401 Candidate.FinalConversion.setAllToTypes(ToType);
8402 Candidate.HasFinalConversion = true;
8403 Candidate.Viable = true;
8404 Candidate.ExplicitCallArguments = 1;
8405 Candidate.StrictPackMatch = StrictPackMatch;
8406
8407 // Explicit functions are not actually candidates at all if we're not
8408 // allowing them in this context, but keep them around so we can point
8409 // to them in diagnostics.
8410 if (!AllowExplicit && Conversion->isExplicit()) {
8411 Candidate.Viable = false;
8412 Candidate.FailureKind = ovl_fail_explicit;
8413 return;
8414 }
8415
8416 // C++ [over.match.funcs]p4:
8417 // For conversion functions, the function is considered to be a member of
8418 // the class of the implicit implied object argument for the purpose of
8419 // defining the type of the implicit object parameter.
8420 //
8421 // Determine the implicit conversion sequence for the implicit
8422 // object parameter.
8423 QualType ObjectType = From->getType();
8424 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8425 ObjectType = FromPtrType->getPointeeType();
8426 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8427 // C++23 [over.best.ics.general]
8428 // However, if the target is [...]
8429 // - the object parameter of a user-defined conversion function
8430 // [...] user-defined conversion sequences are not considered.
8431 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8432 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8433 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8434 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8435 /*SuppressUserConversion*/ true);
8436
8437 if (Candidate.Conversions[0].isBad()) {
8438 Candidate.Viable = false;
8439 Candidate.FailureKind = ovl_fail_bad_conversion;
8440 return;
8441 }
8442
8443 if (Conversion->getTrailingRequiresClause()) {
8444 ConstraintSatisfaction Satisfaction;
8445 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8446 !Satisfaction.IsSatisfied) {
8447 Candidate.Viable = false;
8448 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8449 return;
8450 }
8451 }
8452
8453 // We won't go through a user-defined type conversion function to convert a
8454 // derived to base as such conversions are given Conversion Rank. They only
8455 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8456 QualType FromCanon
8457 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8458 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8459 if (FromCanon == ToCanon ||
8460 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8461 Candidate.Viable = false;
8462 Candidate.FailureKind = ovl_fail_trivial_conversion;
8463 return;
8464 }
8465
8466 // To determine what the conversion from the result of calling the
8467 // conversion function to the type we're eventually trying to
8468 // convert to (ToType), we need to synthesize a call to the
8469 // conversion function and attempt copy initialization from it. This
8470 // makes sure that we get the right semantics with respect to
8471 // lvalues/rvalues and the type. Fortunately, we can allocate this
8472 // call on the stack and we don't need its arguments to be
8473 // well-formed.
8474 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8475 VK_LValue, From->getBeginLoc());
8476 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8477 Context.getPointerType(T: Conversion->getType()),
8478 CK_FunctionToPointerDecay, &ConversionRef,
8479 VK_PRValue, FPOptionsOverride());
8480
8481 QualType ConversionType = Conversion->getConversionType();
8482 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8483 Candidate.Viable = false;
8484 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8485 return;
8486 }
8487
8488 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8489
8490 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8491
8492 // Introduce a temporary expression with the right type and value category
8493 // that we can use for deduction purposes.
8494 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8495
8496 ImplicitConversionSequence ICS =
8497 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8498 /*SuppressUserConversions=*/true,
8499 /*InOverloadResolution=*/false,
8500 /*AllowObjCWritebackConversion=*/false);
8501
8502 switch (ICS.getKind()) {
8503 case ImplicitConversionSequence::StandardConversion:
8504 Candidate.FinalConversion = ICS.Standard;
8505 Candidate.HasFinalConversion = true;
8506
8507 // C++ [over.ics.user]p3:
8508 // If the user-defined conversion is specified by a specialization of a
8509 // conversion function template, the second standard conversion sequence
8510 // shall have exact match rank.
8511 if (Conversion->getPrimaryTemplate() &&
8512 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8513 Candidate.Viable = false;
8514 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8515 return;
8516 }
8517
8518 // C++0x [dcl.init.ref]p5:
8519 // In the second case, if the reference is an rvalue reference and
8520 // the second standard conversion sequence of the user-defined
8521 // conversion sequence includes an lvalue-to-rvalue conversion, the
8522 // program is ill-formed.
8523 if (ToType->isRValueReferenceType() &&
8524 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8525 Candidate.Viable = false;
8526 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8527 return;
8528 }
8529 break;
8530
8531 case ImplicitConversionSequence::BadConversion:
8532 Candidate.Viable = false;
8533 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8534 return;
8535
8536 default:
8537 llvm_unreachable(
8538 "Can only end up with a standard conversion sequence or failure");
8539 }
8540
8541 if (EnableIfAttr *FailedAttr =
8542 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8543 Candidate.Viable = false;
8544 Candidate.FailureKind = ovl_fail_enable_if;
8545 Candidate.DeductionFailure.Data = FailedAttr;
8546 return;
8547 }
8548
8549 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8550 Candidate.Viable = false;
8551 Candidate.FailureKind = ovl_non_default_multiversion_function;
8552 }
8553}
8554
8555static void AddTemplateConversionCandidateImmediately(
8556 Sema &S, OverloadCandidateSet &CandidateSet,
8557 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8558 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8559 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8560 bool AllowResultConversion) {
8561
8562 // If the function template has a non-dependent explicit specification,
8563 // exclude it now if appropriate; we are not permitted to perform deduction
8564 // and substitution in this case.
8565 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8566 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8567 Candidate.FoundDecl = FoundDecl;
8568 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8569 Candidate.Viable = false;
8570 Candidate.FailureKind = ovl_fail_explicit;
8571 return;
8572 }
8573
8574 QualType ObjectType = From->getType();
8575 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8576
8577 TemplateDeductionInfo Info(CandidateSet.getLocation());
8578 CXXConversionDecl *Specialization = nullptr;
8579 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8580 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8581 Specialization, Info);
8582 Result != TemplateDeductionResult::Success) {
8583 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8584 Candidate.FoundDecl = FoundDecl;
8585 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8586 Candidate.Viable = false;
8587 Candidate.FailureKind = ovl_fail_bad_deduction;
8588 Candidate.ExplicitCallArguments = 1;
8589 Candidate.DeductionFailure =
8590 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8591 return;
8592 }
8593
8594 // Add the conversion function template specialization produced by
8595 // template argument deduction as a candidate.
8596 assert(Specialization && "Missing function template specialization?");
8597 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8598 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8599 AllowExplicit, AllowResultConversion,
8600 StrictPackMatch: Info.hasStrictPackMatch());
8601}
8602
8603void Sema::AddTemplateConversionCandidate(
8604 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8605 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8606 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8607 bool AllowExplicit, bool AllowResultConversion) {
8608 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8609 "Only conversion function templates permitted here");
8610
8611 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8612 return;
8613
8614 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8615 CandidateSet.getKind() ==
8616 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8617 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8618 AddTemplateConversionCandidateImmediately(
8619 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8620 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8621 AllowResultConversion);
8622
8623 CandidateSet.DisableResolutionByPerfectCandidate();
8624 return;
8625 }
8626
8627 CandidateSet.AddDeferredConversionTemplateCandidate(
8628 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8629 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8630}
8631
8632void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8633 DeclAccessPair FoundDecl,
8634 CXXRecordDecl *ActingContext,
8635 const FunctionProtoType *Proto,
8636 Expr *Object,
8637 ArrayRef<Expr *> Args,
8638 OverloadCandidateSet& CandidateSet) {
8639 if (!CandidateSet.isNewCandidate(F: Conversion))
8640 return;
8641
8642 // Overload resolution is always an unevaluated context.
8643 EnterExpressionEvaluationContext Unevaluated(
8644 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8645
8646 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8647 Candidate.FoundDecl = FoundDecl;
8648 Candidate.Function = nullptr;
8649 Candidate.Surrogate = Conversion;
8650 Candidate.IsSurrogate = true;
8651 Candidate.Viable = true;
8652 Candidate.ExplicitCallArguments = Args.size();
8653
8654 // Determine the implicit conversion sequence for the implicit
8655 // object parameter.
8656 ImplicitConversionSequence ObjectInit;
8657 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8658 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8659 ToType: Conversion->getParamDecl(i: 0)->getType(),
8660 /*SuppressUserConversions=*/false,
8661 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8662 } else {
8663 ObjectInit = TryObjectArgumentInitialization(
8664 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8665 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8666 }
8667
8668 if (ObjectInit.isBad()) {
8669 Candidate.Viable = false;
8670 Candidate.FailureKind = ovl_fail_bad_conversion;
8671 Candidate.Conversions[0] = ObjectInit;
8672 return;
8673 }
8674
8675 // The first conversion is actually a user-defined conversion whose
8676 // first conversion is ObjectInit's standard conversion (which is
8677 // effectively a reference binding). Record it as such.
8678 Candidate.Conversions[0].setUserDefined();
8679 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8680 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8681 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8682 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8683 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8684 Candidate.Conversions[0].UserDefined.After
8685 = Candidate.Conversions[0].UserDefined.Before;
8686 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8687
8688 // Find the
8689 unsigned NumParams = Proto->getNumParams();
8690
8691 // (C++ 13.3.2p2): A candidate function having fewer than m
8692 // parameters is viable only if it has an ellipsis in its parameter
8693 // list (8.3.5).
8694 if (Args.size() > NumParams && !Proto->isVariadic()) {
8695 Candidate.Viable = false;
8696 Candidate.FailureKind = ovl_fail_too_many_arguments;
8697 return;
8698 }
8699
8700 // Function types don't have any default arguments, so just check if
8701 // we have enough arguments.
8702 if (Args.size() < NumParams) {
8703 // Not enough arguments.
8704 Candidate.Viable = false;
8705 Candidate.FailureKind = ovl_fail_too_few_arguments;
8706 return;
8707 }
8708
8709 // Determine the implicit conversion sequences for each of the
8710 // arguments.
8711 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8712 if (ArgIdx < NumParams) {
8713 // (C++ 13.3.2p3): for F to be a viable function, there shall
8714 // exist for each argument an implicit conversion sequence
8715 // (13.3.3.1) that converts that argument to the corresponding
8716 // parameter of F.
8717 QualType ParamType = Proto->getParamType(i: ArgIdx);
8718 Candidate.Conversions[ArgIdx + 1]
8719 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8720 /*SuppressUserConversions=*/false,
8721 /*InOverloadResolution=*/false,
8722 /*AllowObjCWritebackConversion=*/
8723 getLangOpts().ObjCAutoRefCount);
8724 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8725 Candidate.Viable = false;
8726 Candidate.FailureKind = ovl_fail_bad_conversion;
8727 return;
8728 }
8729 } else {
8730 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8731 // argument for which there is no corresponding parameter is
8732 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8733 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8734 }
8735 }
8736
8737 if (Conversion->getTrailingRequiresClause()) {
8738 ConstraintSatisfaction Satisfaction;
8739 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8740 /*ForOverloadResolution*/ true) ||
8741 !Satisfaction.IsSatisfied) {
8742 Candidate.Viable = false;
8743 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8744 return;
8745 }
8746 }
8747
8748 if (EnableIfAttr *FailedAttr =
8749 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8750 Candidate.Viable = false;
8751 Candidate.FailureKind = ovl_fail_enable_if;
8752 Candidate.DeductionFailure.Data = FailedAttr;
8753 return;
8754 }
8755}
8756
8757void Sema::AddNonMemberOperatorCandidates(
8758 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8759 OverloadCandidateSet &CandidateSet,
8760 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8761 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8762 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8763 ArrayRef<Expr *> FunctionArgs = Args;
8764
8765 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8766 FunctionDecl *FD =
8767 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8768
8769 // Don't consider rewritten functions if we're not rewriting.
8770 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8771 continue;
8772
8773 assert(!isa<CXXMethodDecl>(FD) &&
8774 "unqualified operator lookup found a member function");
8775
8776 if (FunTmpl) {
8777 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8778 Args: FunctionArgs, CandidateSet);
8779 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8780
8781 // As template candidates are not deduced immediately,
8782 // persist the array in the overload set.
8783 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8784 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8785 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8786 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8787 IsADLCandidate: ADLCallKind::NotADL,
8788 PO: OverloadCandidateParamOrder::Reversed);
8789 }
8790 } else {
8791 if (ExplicitTemplateArgs)
8792 continue;
8793 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8794 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8795 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8796 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8797 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8798 PO: OverloadCandidateParamOrder::Reversed);
8799 }
8800 }
8801}
8802
8803void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8804 SourceLocation OpLoc,
8805 ArrayRef<Expr *> Args,
8806 OverloadCandidateSet &CandidateSet,
8807 OverloadCandidateParamOrder PO) {
8808 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8809
8810 // C++ [over.match.oper]p3:
8811 // For a unary operator @ with an operand of a type whose
8812 // cv-unqualified version is T1, and for a binary operator @ with
8813 // a left operand of a type whose cv-unqualified version is T1 and
8814 // a right operand of a type whose cv-unqualified version is T2,
8815 // three sets of candidate functions, designated member
8816 // candidates, non-member candidates and built-in candidates, are
8817 // constructed as follows:
8818 QualType T1 = Args[0]->getType();
8819
8820 // -- If T1 is a complete class type or a class currently being
8821 // defined, the set of member candidates is the result of the
8822 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8823 // the set of member candidates is empty.
8824 if (T1->isRecordType()) {
8825 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
8826 auto *T1RD = T1->getAsCXXRecordDecl();
8827 // Complete the type if it can be completed.
8828 // If the type is neither complete nor being defined, bail out now.
8829 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8830 return;
8831
8832 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8833 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
8834 Operators.suppressAccessDiagnostics();
8835
8836 for (LookupResult::iterator Oper = Operators.begin(),
8837 OperEnd = Operators.end();
8838 Oper != OperEnd; ++Oper) {
8839 if (Oper->getAsFunction() &&
8840 PO == OverloadCandidateParamOrder::Reversed &&
8841 !CandidateSet.getRewriteInfo().shouldAddReversed(
8842 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8843 continue;
8844 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8845 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8846 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8847 }
8848 }
8849}
8850
8851void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8852 OverloadCandidateSet& CandidateSet,
8853 bool IsAssignmentOperator,
8854 unsigned NumContextualBoolArguments) {
8855 // Overload resolution is always an unevaluated context.
8856 EnterExpressionEvaluationContext Unevaluated(
8857 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8858
8859 // Add this candidate
8860 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8861 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8862 Candidate.Function = nullptr;
8863 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
8864
8865 // Determine the implicit conversion sequences for each of the
8866 // arguments.
8867 Candidate.Viable = true;
8868 Candidate.ExplicitCallArguments = Args.size();
8869 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8870 // C++ [over.match.oper]p4:
8871 // For the built-in assignment operators, conversions of the
8872 // left operand are restricted as follows:
8873 // -- no temporaries are introduced to hold the left operand, and
8874 // -- no user-defined conversions are applied to the left
8875 // operand to achieve a type match with the left-most
8876 // parameter of a built-in candidate.
8877 //
8878 // We block these conversions by turning off user-defined
8879 // conversions, since that is the only way that initialization of
8880 // a reference to a non-class type can occur from something that
8881 // is not of the same type.
8882 if (ArgIdx < NumContextualBoolArguments) {
8883 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8884 "Contextual conversion to bool requires bool type");
8885 Candidate.Conversions[ArgIdx]
8886 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
8887 } else {
8888 Candidate.Conversions[ArgIdx]
8889 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
8890 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
8891 /*InOverloadResolution=*/false,
8892 /*AllowObjCWritebackConversion=*/
8893 getLangOpts().ObjCAutoRefCount);
8894 }
8895 if (Candidate.Conversions[ArgIdx].isBad()) {
8896 Candidate.Viable = false;
8897 Candidate.FailureKind = ovl_fail_bad_conversion;
8898 break;
8899 }
8900 }
8901}
8902
8903namespace {
8904
8905/// BuiltinCandidateTypeSet - A set of types that will be used for the
8906/// candidate operator functions for built-in operators (C++
8907/// [over.built]). The types are separated into pointer types and
8908/// enumeration types.
8909class BuiltinCandidateTypeSet {
8910 /// TypeSet - A set of types.
8911 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8912
8913 /// PointerTypes - The set of pointer types that will be used in the
8914 /// built-in candidates.
8915 TypeSet PointerTypes;
8916
8917 /// MemberPointerTypes - The set of member pointer types that will be
8918 /// used in the built-in candidates.
8919 TypeSet MemberPointerTypes;
8920
8921 /// EnumerationTypes - The set of enumeration types that will be
8922 /// used in the built-in candidates.
8923 TypeSet EnumerationTypes;
8924
8925 /// The set of vector types that will be used in the built-in
8926 /// candidates.
8927 TypeSet VectorTypes;
8928
8929 /// The set of matrix types that will be used in the built-in
8930 /// candidates.
8931 TypeSet MatrixTypes;
8932
8933 /// The set of _BitInt types that will be used in the built-in candidates.
8934 TypeSet BitIntTypes;
8935
8936 /// A flag indicating non-record types are viable candidates
8937 bool HasNonRecordTypes;
8938
8939 /// A flag indicating whether either arithmetic or enumeration types
8940 /// were present in the candidate set.
8941 bool HasArithmeticOrEnumeralTypes;
8942
8943 /// A flag indicating whether the nullptr type was present in the
8944 /// candidate set.
8945 bool HasNullPtrType;
8946
8947 /// Sema - The semantic analysis instance where we are building the
8948 /// candidate type set.
8949 Sema &SemaRef;
8950
8951 /// Context - The AST context in which we will build the type sets.
8952 ASTContext &Context;
8953
8954 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8955 const Qualifiers &VisibleQuals);
8956 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8957
8958public:
8959 /// iterator - Iterates through the types that are part of the set.
8960 typedef TypeSet::iterator iterator;
8961
8962 BuiltinCandidateTypeSet(Sema &SemaRef)
8963 : HasNonRecordTypes(false),
8964 HasArithmeticOrEnumeralTypes(false),
8965 HasNullPtrType(false),
8966 SemaRef(SemaRef),
8967 Context(SemaRef.Context) { }
8968
8969 void AddTypesConvertedFrom(QualType Ty,
8970 SourceLocation Loc,
8971 bool AllowUserConversions,
8972 bool AllowExplicitConversions,
8973 const Qualifiers &VisibleTypeConversionsQuals);
8974
8975 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8976 llvm::iterator_range<iterator> member_pointer_types() {
8977 return MemberPointerTypes;
8978 }
8979 llvm::iterator_range<iterator> enumeration_types() {
8980 return EnumerationTypes;
8981 }
8982 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8983 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8984 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8985
8986 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
8987 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8988 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8989 bool hasNullPtrType() const { return HasNullPtrType; }
8990};
8991
8992} // end anonymous namespace
8993
8994/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8995/// the set of pointer types along with any more-qualified variants of
8996/// that type. For example, if @p Ty is "int const *", this routine
8997/// will add "int const *", "int const volatile *", "int const
8998/// restrict *", and "int const volatile restrict *" to the set of
8999/// pointer types. Returns true if the add of @p Ty itself succeeded,
9000/// false otherwise.
9001///
9002/// FIXME: what to do about extended qualifiers?
9003bool
9004BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9005 const Qualifiers &VisibleQuals) {
9006
9007 // Insert this type.
9008 if (!PointerTypes.insert(X: Ty))
9009 return false;
9010
9011 QualType PointeeTy;
9012 const PointerType *PointerTy = Ty->getAs<PointerType>();
9013 bool buildObjCPtr = false;
9014 if (!PointerTy) {
9015 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9016 PointeeTy = PTy->getPointeeType();
9017 buildObjCPtr = true;
9018 } else {
9019 PointeeTy = PointerTy->getPointeeType();
9020 }
9021
9022 // Don't add qualified variants of arrays. For one, they're not allowed
9023 // (the qualifier would sink to the element type), and for another, the
9024 // only overload situation where it matters is subscript or pointer +- int,
9025 // and those shouldn't have qualifier variants anyway.
9026 if (PointeeTy->isArrayType())
9027 return true;
9028
9029 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9030 bool hasVolatile = VisibleQuals.hasVolatile();
9031 bool hasRestrict = VisibleQuals.hasRestrict();
9032
9033 // Iterate through all strict supersets of BaseCVR.
9034 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9035 if ((CVR | BaseCVR) != CVR) continue;
9036 // Skip over volatile if no volatile found anywhere in the types.
9037 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9038
9039 // Skip over restrict if no restrict found anywhere in the types, or if
9040 // the type cannot be restrict-qualified.
9041 if ((CVR & Qualifiers::Restrict) &&
9042 (!hasRestrict ||
9043 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9044 continue;
9045
9046 // Build qualified pointee type.
9047 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9048
9049 // Build qualified pointer type.
9050 QualType QPointerTy;
9051 if (!buildObjCPtr)
9052 QPointerTy = Context.getPointerType(T: QPointeeTy);
9053 else
9054 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9055
9056 // Insert qualified pointer type.
9057 PointerTypes.insert(X: QPointerTy);
9058 }
9059
9060 return true;
9061}
9062
9063/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9064/// to the set of pointer types along with any more-qualified variants of
9065/// that type. For example, if @p Ty is "int const *", this routine
9066/// will add "int const *", "int const volatile *", "int const
9067/// restrict *", and "int const volatile restrict *" to the set of
9068/// pointer types. Returns true if the add of @p Ty itself succeeded,
9069/// false otherwise.
9070///
9071/// FIXME: what to do about extended qualifiers?
9072bool
9073BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9074 QualType Ty) {
9075 // Insert this type.
9076 if (!MemberPointerTypes.insert(X: Ty))
9077 return false;
9078
9079 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9080 assert(PointerTy && "type was not a member pointer type!");
9081
9082 QualType PointeeTy = PointerTy->getPointeeType();
9083 // Don't add qualified variants of arrays. For one, they're not allowed
9084 // (the qualifier would sink to the element type), and for another, the
9085 // only overload situation where it matters is subscript or pointer +- int,
9086 // and those shouldn't have qualifier variants anyway.
9087 if (PointeeTy->isArrayType())
9088 return true;
9089 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9090
9091 // Iterate through all strict supersets of the pointee type's CVR
9092 // qualifiers.
9093 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9094 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9095 if ((CVR | BaseCVR) != CVR) continue;
9096
9097 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9098 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9099 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9100 }
9101
9102 return true;
9103}
9104
9105/// AddTypesConvertedFrom - Add each of the types to which the type @p
9106/// Ty can be implicit converted to the given set of @p Types. We're
9107/// primarily interested in pointer types and enumeration types. We also
9108/// take member pointer types, for the conditional operator.
9109/// AllowUserConversions is true if we should look at the conversion
9110/// functions of a class type, and AllowExplicitConversions if we
9111/// should also include the explicit conversion functions of a class
9112/// type.
9113void
9114BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9115 SourceLocation Loc,
9116 bool AllowUserConversions,
9117 bool AllowExplicitConversions,
9118 const Qualifiers &VisibleQuals) {
9119 // Only deal with canonical types.
9120 Ty = Context.getCanonicalType(T: Ty);
9121
9122 // Look through reference types; they aren't part of the type of an
9123 // expression for the purposes of conversions.
9124 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9125 Ty = RefTy->getPointeeType();
9126
9127 // If we're dealing with an array type, decay to the pointer.
9128 if (Ty->isArrayType())
9129 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9130
9131 // Otherwise, we don't care about qualifiers on the type.
9132 Ty = Ty.getLocalUnqualifiedType();
9133
9134 // Flag if we ever add a non-record type.
9135 bool TyIsRec = Ty->isRecordType();
9136 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9137
9138 // Flag if we encounter an arithmetic type.
9139 HasArithmeticOrEnumeralTypes =
9140 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9141
9142 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9143 PointerTypes.insert(X: Ty);
9144 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9145 // Insert our type, and its more-qualified variants, into the set
9146 // of types.
9147 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9148 return;
9149 } else if (Ty->isMemberPointerType()) {
9150 // Member pointers are far easier, since the pointee can't be converted.
9151 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9152 return;
9153 } else if (Ty->isEnumeralType()) {
9154 HasArithmeticOrEnumeralTypes = true;
9155 EnumerationTypes.insert(X: Ty);
9156 } else if (Ty->isBitIntType()) {
9157 HasArithmeticOrEnumeralTypes = true;
9158 BitIntTypes.insert(X: Ty);
9159 } else if (Ty->isVectorType()) {
9160 // We treat vector types as arithmetic types in many contexts as an
9161 // extension.
9162 HasArithmeticOrEnumeralTypes = true;
9163 VectorTypes.insert(X: Ty);
9164 } else if (Ty->isMatrixType()) {
9165 // Similar to vector types, we treat vector types as arithmetic types in
9166 // many contexts as an extension.
9167 HasArithmeticOrEnumeralTypes = true;
9168 MatrixTypes.insert(X: Ty);
9169 } else if (Ty->isNullPtrType()) {
9170 HasNullPtrType = true;
9171 } else if (AllowUserConversions && TyIsRec) {
9172 // No conversion functions in incomplete types.
9173 if (!SemaRef.isCompleteType(Loc, T: Ty))
9174 return;
9175
9176 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9177 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9178 if (isa<UsingShadowDecl>(Val: D))
9179 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9180
9181 // Skip conversion function templates; they don't tell us anything
9182 // about which builtin types we can convert to.
9183 if (isa<FunctionTemplateDecl>(Val: D))
9184 continue;
9185
9186 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9187 if (AllowExplicitConversions || !Conv->isExplicit()) {
9188 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9189 VisibleQuals);
9190 }
9191 }
9192 }
9193}
9194/// Helper function for adjusting address spaces for the pointer or reference
9195/// operands of builtin operators depending on the argument.
9196static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9197 Expr *Arg) {
9198 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9199}
9200
9201/// Helper function for AddBuiltinOperatorCandidates() that adds
9202/// the volatile- and non-volatile-qualified assignment operators for the
9203/// given type to the candidate set.
9204static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9205 QualType T,
9206 ArrayRef<Expr *> Args,
9207 OverloadCandidateSet &CandidateSet) {
9208 QualType ParamTypes[2];
9209
9210 // T& operator=(T&, T)
9211 ParamTypes[0] = S.Context.getLValueReferenceType(
9212 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9213 ParamTypes[1] = T;
9214 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9215 /*IsAssignmentOperator=*/true);
9216
9217 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9218 // volatile T& operator=(volatile T&, T)
9219 ParamTypes[0] = S.Context.getLValueReferenceType(
9220 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9221 Arg: Args[0]));
9222 ParamTypes[1] = T;
9223 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9224 /*IsAssignmentOperator=*/true);
9225 }
9226}
9227
9228/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9229/// if any, found in visible type conversion functions found in ArgExpr's type.
9230static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9231 Qualifiers VRQuals;
9232 CXXRecordDecl *ClassDecl;
9233 if (const MemberPointerType *RHSMPType =
9234 ArgExpr->getType()->getAs<MemberPointerType>())
9235 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9236 else
9237 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9238 if (!ClassDecl) {
9239 // Just to be safe, assume the worst case.
9240 VRQuals.addVolatile();
9241 VRQuals.addRestrict();
9242 return VRQuals;
9243 }
9244 if (!ClassDecl->hasDefinition())
9245 return VRQuals;
9246
9247 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9248 if (isa<UsingShadowDecl>(Val: D))
9249 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9250 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9251 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9252 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9253 CanTy = ResTypeRef->getPointeeType();
9254 // Need to go down the pointer/mempointer chain and add qualifiers
9255 // as see them.
9256 bool done = false;
9257 while (!done) {
9258 if (CanTy.isRestrictQualified())
9259 VRQuals.addRestrict();
9260 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9261 CanTy = ResTypePtr->getPointeeType();
9262 else if (const MemberPointerType *ResTypeMPtr =
9263 CanTy->getAs<MemberPointerType>())
9264 CanTy = ResTypeMPtr->getPointeeType();
9265 else
9266 done = true;
9267 if (CanTy.isVolatileQualified())
9268 VRQuals.addVolatile();
9269 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9270 return VRQuals;
9271 }
9272 }
9273 }
9274 return VRQuals;
9275}
9276
9277// Note: We're currently only handling qualifiers that are meaningful for the
9278// LHS of compound assignment overloading.
9279static void forAllQualifierCombinationsImpl(
9280 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9281 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9282 // _Atomic
9283 if (Available.hasAtomic()) {
9284 Available.removeAtomic();
9285 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9286 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9287 return;
9288 }
9289
9290 // volatile
9291 if (Available.hasVolatile()) {
9292 Available.removeVolatile();
9293 assert(!Applied.hasVolatile());
9294 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9295 Callback);
9296 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9297 return;
9298 }
9299
9300 Callback(Applied);
9301}
9302
9303static void forAllQualifierCombinations(
9304 QualifiersAndAtomic Quals,
9305 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9306 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9307 Callback);
9308}
9309
9310static QualType makeQualifiedLValueReferenceType(QualType Base,
9311 QualifiersAndAtomic Quals,
9312 Sema &S) {
9313 if (Quals.hasAtomic())
9314 Base = S.Context.getAtomicType(T: Base);
9315 if (Quals.hasVolatile())
9316 Base = S.Context.getVolatileType(T: Base);
9317 return S.Context.getLValueReferenceType(T: Base);
9318}
9319
9320namespace {
9321
9322/// Helper class to manage the addition of builtin operator overload
9323/// candidates. It provides shared state and utility methods used throughout
9324/// the process, as well as a helper method to add each group of builtin
9325/// operator overloads from the standard to a candidate set.
9326class BuiltinOperatorOverloadBuilder {
9327 // Common instance state available to all overload candidate addition methods.
9328 Sema &S;
9329 ArrayRef<Expr *> Args;
9330 QualifiersAndAtomic VisibleTypeConversionsQuals;
9331 bool HasArithmeticOrEnumeralCandidateType;
9332 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9333 OverloadCandidateSet &CandidateSet;
9334
9335 static constexpr int ArithmeticTypesCap = 26;
9336 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9337
9338 // Define some indices used to iterate over the arithmetic types in
9339 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9340 // types are that preserved by promotion (C++ [over.built]p2).
9341 unsigned FirstIntegralType,
9342 LastIntegralType;
9343 unsigned FirstPromotedIntegralType,
9344 LastPromotedIntegralType;
9345 unsigned FirstPromotedArithmeticType,
9346 LastPromotedArithmeticType;
9347 unsigned NumArithmeticTypes;
9348
9349 void InitArithmeticTypes() {
9350 // Start of promoted types.
9351 FirstPromotedArithmeticType = 0;
9352 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9353 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9354 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9355 if (S.Context.getTargetInfo().hasFloat128Type())
9356 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9357 if (S.Context.getTargetInfo().hasIbm128Type())
9358 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9359
9360 // Start of integral types.
9361 FirstIntegralType = ArithmeticTypes.size();
9362 FirstPromotedIntegralType = ArithmeticTypes.size();
9363 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9364 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9365 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9366 if (S.Context.getTargetInfo().hasInt128Type() ||
9367 (S.Context.getAuxTargetInfo() &&
9368 S.Context.getAuxTargetInfo()->hasInt128Type()))
9369 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9370 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9371 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9372 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9373 if (S.Context.getTargetInfo().hasInt128Type() ||
9374 (S.Context.getAuxTargetInfo() &&
9375 S.Context.getAuxTargetInfo()->hasInt128Type()))
9376 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9377
9378 /// We add candidates for the unique, unqualified _BitInt types present in
9379 /// the candidate type set. The candidate set already handled ensuring the
9380 /// type is unqualified and canonical, but because we're adding from N
9381 /// different sets, we need to do some extra work to unique things. Insert
9382 /// the candidates into a unique set, then move from that set into the list
9383 /// of arithmetic types.
9384 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9385 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9386 for (QualType BitTy : Candidate.bitint_types())
9387 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9388 }
9389 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9390 LastPromotedIntegralType = ArithmeticTypes.size();
9391 LastPromotedArithmeticType = ArithmeticTypes.size();
9392 // End of promoted types.
9393
9394 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9395 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9396 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9397 if (S.Context.getLangOpts().Char8)
9398 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9399 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9400 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9401 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9402 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9403 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9404 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9405 LastIntegralType = ArithmeticTypes.size();
9406 NumArithmeticTypes = ArithmeticTypes.size();
9407 // End of integral types.
9408 // FIXME: What about complex? What about half?
9409
9410 // We don't know for sure how many bit-precise candidates were involved, so
9411 // we subtract those from the total when testing whether we're under the
9412 // cap or not.
9413 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9414 ArithmeticTypesCap &&
9415 "Enough inline storage for all arithmetic types.");
9416 }
9417
9418 /// Helper method to factor out the common pattern of adding overloads
9419 /// for '++' and '--' builtin operators.
9420 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9421 bool HasVolatile,
9422 bool HasRestrict) {
9423 QualType ParamTypes[2] = {
9424 S.Context.getLValueReferenceType(T: CandidateTy),
9425 S.Context.IntTy
9426 };
9427
9428 // Non-volatile version.
9429 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9430
9431 // Use a heuristic to reduce number of builtin candidates in the set:
9432 // add volatile version only if there are conversions to a volatile type.
9433 if (HasVolatile) {
9434 ParamTypes[0] =
9435 S.Context.getLValueReferenceType(
9436 T: S.Context.getVolatileType(T: CandidateTy));
9437 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9438 }
9439
9440 // Add restrict version only if there are conversions to a restrict type
9441 // and our candidate type is a non-restrict-qualified pointer.
9442 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9443 !CandidateTy.isRestrictQualified()) {
9444 ParamTypes[0]
9445 = S.Context.getLValueReferenceType(
9446 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9447 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9448
9449 if (HasVolatile) {
9450 ParamTypes[0]
9451 = S.Context.getLValueReferenceType(
9452 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9453 CVR: (Qualifiers::Volatile |
9454 Qualifiers::Restrict)));
9455 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9456 }
9457 }
9458
9459 }
9460
9461 /// Helper to add an overload candidate for a binary builtin with types \p L
9462 /// and \p R.
9463 void AddCandidate(QualType L, QualType R) {
9464 QualType LandR[2] = {L, R};
9465 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9466 }
9467
9468public:
9469 BuiltinOperatorOverloadBuilder(
9470 Sema &S, ArrayRef<Expr *> Args,
9471 QualifiersAndAtomic VisibleTypeConversionsQuals,
9472 bool HasArithmeticOrEnumeralCandidateType,
9473 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9474 OverloadCandidateSet &CandidateSet)
9475 : S(S), Args(Args),
9476 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9477 HasArithmeticOrEnumeralCandidateType(
9478 HasArithmeticOrEnumeralCandidateType),
9479 CandidateTypes(CandidateTypes),
9480 CandidateSet(CandidateSet) {
9481
9482 InitArithmeticTypes();
9483 }
9484
9485 // Increment is deprecated for bool since C++17.
9486 //
9487 // C++ [over.built]p3:
9488 //
9489 // For every pair (T, VQ), where T is an arithmetic type other
9490 // than bool, and VQ is either volatile or empty, there exist
9491 // candidate operator functions of the form
9492 //
9493 // VQ T& operator++(VQ T&);
9494 // T operator++(VQ T&, int);
9495 //
9496 // C++ [over.built]p4:
9497 //
9498 // For every pair (T, VQ), where T is an arithmetic type other
9499 // than bool, and VQ is either volatile or empty, there exist
9500 // candidate operator functions of the form
9501 //
9502 // VQ T& operator--(VQ T&);
9503 // T operator--(VQ T&, int);
9504 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9505 if (!HasArithmeticOrEnumeralCandidateType)
9506 return;
9507
9508 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9509 const auto TypeOfT = ArithmeticTypes[Arith];
9510 if (TypeOfT == S.Context.BoolTy) {
9511 if (Op == OO_MinusMinus)
9512 continue;
9513 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9514 continue;
9515 }
9516 addPlusPlusMinusMinusStyleOverloads(
9517 CandidateTy: TypeOfT,
9518 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9519 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9520 }
9521 }
9522
9523 // C++ [over.built]p5:
9524 //
9525 // For every pair (T, VQ), where T is a cv-qualified or
9526 // cv-unqualified object type, and VQ is either volatile or
9527 // empty, there exist candidate operator functions of the form
9528 //
9529 // T*VQ& operator++(T*VQ&);
9530 // T*VQ& operator--(T*VQ&);
9531 // T* operator++(T*VQ&, int);
9532 // T* operator--(T*VQ&, int);
9533 void addPlusPlusMinusMinusPointerOverloads() {
9534 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9535 // Skip pointer types that aren't pointers to object types.
9536 if (!PtrTy->getPointeeType()->isObjectType())
9537 continue;
9538
9539 addPlusPlusMinusMinusStyleOverloads(
9540 CandidateTy: PtrTy,
9541 HasVolatile: (!PtrTy.isVolatileQualified() &&
9542 VisibleTypeConversionsQuals.hasVolatile()),
9543 HasRestrict: (!PtrTy.isRestrictQualified() &&
9544 VisibleTypeConversionsQuals.hasRestrict()));
9545 }
9546 }
9547
9548 // C++ [over.built]p6:
9549 // For every cv-qualified or cv-unqualified object type T, there
9550 // exist candidate operator functions of the form
9551 //
9552 // T& operator*(T*);
9553 //
9554 // C++ [over.built]p7:
9555 // For every function type T that does not have cv-qualifiers or a
9556 // ref-qualifier, there exist candidate operator functions of the form
9557 // T& operator*(T*);
9558 void addUnaryStarPointerOverloads() {
9559 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9560 QualType PointeeTy = ParamTy->getPointeeType();
9561 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9562 continue;
9563
9564 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9565 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9566 continue;
9567
9568 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9569 }
9570 }
9571
9572 // C++ [over.built]p9:
9573 // For every promoted arithmetic type T, there exist candidate
9574 // operator functions of the form
9575 //
9576 // T operator+(T);
9577 // T operator-(T);
9578 void addUnaryPlusOrMinusArithmeticOverloads() {
9579 if (!HasArithmeticOrEnumeralCandidateType)
9580 return;
9581
9582 for (unsigned Arith = FirstPromotedArithmeticType;
9583 Arith < LastPromotedArithmeticType; ++Arith) {
9584 QualType ArithTy = ArithmeticTypes[Arith];
9585 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9586 }
9587
9588 // Extension: We also add these operators for vector types.
9589 for (QualType VecTy : CandidateTypes[0].vector_types())
9590 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9591 }
9592
9593 // C++ [over.built]p8:
9594 // For every type T, there exist candidate operator functions of
9595 // the form
9596 //
9597 // T* operator+(T*);
9598 void addUnaryPlusPointerOverloads() {
9599 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9600 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9601 }
9602
9603 // C++ [over.built]p10:
9604 // For every promoted integral type T, there exist candidate
9605 // operator functions of the form
9606 //
9607 // T operator~(T);
9608 void addUnaryTildePromotedIntegralOverloads() {
9609 if (!HasArithmeticOrEnumeralCandidateType)
9610 return;
9611
9612 for (unsigned Int = FirstPromotedIntegralType;
9613 Int < LastPromotedIntegralType; ++Int) {
9614 QualType IntTy = ArithmeticTypes[Int];
9615 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9616 }
9617
9618 // Extension: We also add this operator for vector types.
9619 for (QualType VecTy : CandidateTypes[0].vector_types())
9620 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9621 }
9622
9623 // C++ [over.match.oper]p16:
9624 // For every pointer to member type T or type std::nullptr_t, there
9625 // exist candidate operator functions of the form
9626 //
9627 // bool operator==(T,T);
9628 // bool operator!=(T,T);
9629 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9630 /// Set of (canonical) types that we've already handled.
9631 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9632
9633 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9634 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9635 // Don't add the same builtin candidate twice.
9636 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9637 continue;
9638
9639 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9640 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9641 }
9642
9643 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9644 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9645 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9646 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9647 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9648 }
9649 }
9650 }
9651 }
9652
9653 // C++ [over.built]p15:
9654 //
9655 // For every T, where T is an enumeration type or a pointer type,
9656 // there exist candidate operator functions of the form
9657 //
9658 // bool operator<(T, T);
9659 // bool operator>(T, T);
9660 // bool operator<=(T, T);
9661 // bool operator>=(T, T);
9662 // bool operator==(T, T);
9663 // bool operator!=(T, T);
9664 // R operator<=>(T, T)
9665 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9666 // C++ [over.match.oper]p3:
9667 // [...]the built-in candidates include all of the candidate operator
9668 // functions defined in 13.6 that, compared to the given operator, [...]
9669 // do not have the same parameter-type-list as any non-template non-member
9670 // candidate.
9671 //
9672 // Note that in practice, this only affects enumeration types because there
9673 // aren't any built-in candidates of record type, and a user-defined operator
9674 // must have an operand of record or enumeration type. Also, the only other
9675 // overloaded operator with enumeration arguments, operator=,
9676 // cannot be overloaded for enumeration types, so this is the only place
9677 // where we must suppress candidates like this.
9678 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9679 UserDefinedBinaryOperators;
9680
9681 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9682 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9683 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9684 CEnd = CandidateSet.end();
9685 C != CEnd; ++C) {
9686 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9687 continue;
9688
9689 if (C->Function->isFunctionTemplateSpecialization())
9690 continue;
9691
9692 // We interpret "same parameter-type-list" as applying to the
9693 // "synthesized candidate, with the order of the two parameters
9694 // reversed", not to the original function.
9695 bool Reversed = C->isReversed();
9696 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9697 ->getType()
9698 .getUnqualifiedType();
9699 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9700 ->getType()
9701 .getUnqualifiedType();
9702
9703 // Skip if either parameter isn't of enumeral type.
9704 if (!FirstParamType->isEnumeralType() ||
9705 !SecondParamType->isEnumeralType())
9706 continue;
9707
9708 // Add this operator to the set of known user-defined operators.
9709 UserDefinedBinaryOperators.insert(
9710 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9711 y: S.Context.getCanonicalType(T: SecondParamType)));
9712 }
9713 }
9714 }
9715
9716 /// Set of (canonical) types that we've already handled.
9717 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9718
9719 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9720 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9721 // Don't add the same builtin candidate twice.
9722 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9723 continue;
9724 if (IsSpaceship && PtrTy->isFunctionPointerType())
9725 continue;
9726
9727 QualType ParamTypes[2] = {PtrTy, PtrTy};
9728 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9729 }
9730 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9731 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9732
9733 // Don't add the same builtin candidate twice, or if a user defined
9734 // candidate exists.
9735 if (!AddedTypes.insert(Ptr: CanonType).second ||
9736 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9737 y&: CanonType)))
9738 continue;
9739 QualType ParamTypes[2] = {EnumTy, EnumTy};
9740 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9741 }
9742 }
9743 }
9744
9745 // C++ [over.built]p13:
9746 //
9747 // For every cv-qualified or cv-unqualified object type T
9748 // there exist candidate operator functions of the form
9749 //
9750 // T* operator+(T*, ptrdiff_t);
9751 // T& operator[](T*, ptrdiff_t); [BELOW]
9752 // T* operator-(T*, ptrdiff_t);
9753 // T* operator+(ptrdiff_t, T*);
9754 // T& operator[](ptrdiff_t, T*); [BELOW]
9755 //
9756 // C++ [over.built]p14:
9757 //
9758 // For every T, where T is a pointer to object type, there
9759 // exist candidate operator functions of the form
9760 //
9761 // ptrdiff_t operator-(T, T);
9762 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9763 /// Set of (canonical) types that we've already handled.
9764 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9765
9766 for (int Arg = 0; Arg < 2; ++Arg) {
9767 QualType AsymmetricParamTypes[2] = {
9768 S.Context.getPointerDiffType(),
9769 S.Context.getPointerDiffType(),
9770 };
9771 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9772 QualType PointeeTy = PtrTy->getPointeeType();
9773 if (!PointeeTy->isObjectType())
9774 continue;
9775
9776 AsymmetricParamTypes[Arg] = PtrTy;
9777 if (Arg == 0 || Op == OO_Plus) {
9778 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9779 // T* operator+(ptrdiff_t, T*);
9780 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9781 }
9782 if (Op == OO_Minus) {
9783 // ptrdiff_t operator-(T, T);
9784 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9785 continue;
9786
9787 QualType ParamTypes[2] = {PtrTy, PtrTy};
9788 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9789 }
9790 }
9791 }
9792 }
9793
9794 // C++ [over.built]p12:
9795 //
9796 // For every pair of promoted arithmetic types L and R, there
9797 // exist candidate operator functions of the form
9798 //
9799 // LR operator*(L, R);
9800 // LR operator/(L, R);
9801 // LR operator+(L, R);
9802 // LR operator-(L, R);
9803 // bool operator<(L, R);
9804 // bool operator>(L, R);
9805 // bool operator<=(L, R);
9806 // bool operator>=(L, R);
9807 // bool operator==(L, R);
9808 // bool operator!=(L, R);
9809 //
9810 // where LR is the result of the usual arithmetic conversions
9811 // between types L and R.
9812 //
9813 // C++ [over.built]p24:
9814 //
9815 // For every pair of promoted arithmetic types L and R, there exist
9816 // candidate operator functions of the form
9817 //
9818 // LR operator?(bool, L, R);
9819 //
9820 // where LR is the result of the usual arithmetic conversions
9821 // between types L and R.
9822 // Our candidates ignore the first parameter.
9823 void addGenericBinaryArithmeticOverloads() {
9824 if (!HasArithmeticOrEnumeralCandidateType)
9825 return;
9826
9827 for (unsigned Left = FirstPromotedArithmeticType;
9828 Left < LastPromotedArithmeticType; ++Left) {
9829 for (unsigned Right = FirstPromotedArithmeticType;
9830 Right < LastPromotedArithmeticType; ++Right) {
9831 QualType LandR[2] = { ArithmeticTypes[Left],
9832 ArithmeticTypes[Right] };
9833 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9834 }
9835 }
9836
9837 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9838 // conditional operator for vector types.
9839 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9840 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9841 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9842 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9843 }
9844 }
9845
9846 /// Add binary operator overloads for each candidate matrix type M1, M2:
9847 /// * (M1, M1) -> M1
9848 /// * (M1, M1.getElementType()) -> M1
9849 /// * (M2.getElementType(), M2) -> M2
9850 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9851 void addMatrixBinaryArithmeticOverloads() {
9852 if (!HasArithmeticOrEnumeralCandidateType)
9853 return;
9854
9855 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9856 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9857 AddCandidate(L: M1, R: M1);
9858 }
9859
9860 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9861 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9862 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9863 AddCandidate(L: M2, R: M2);
9864 }
9865 }
9866
9867 // C++2a [over.built]p14:
9868 //
9869 // For every integral type T there exists a candidate operator function
9870 // of the form
9871 //
9872 // std::strong_ordering operator<=>(T, T)
9873 //
9874 // C++2a [over.built]p15:
9875 //
9876 // For every pair of floating-point types L and R, there exists a candidate
9877 // operator function of the form
9878 //
9879 // std::partial_ordering operator<=>(L, R);
9880 //
9881 // FIXME: The current specification for integral types doesn't play nice with
9882 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9883 // comparisons. Under the current spec this can lead to ambiguity during
9884 // overload resolution. For example:
9885 //
9886 // enum A : int {a};
9887 // auto x = (a <=> (long)42);
9888 //
9889 // error: call is ambiguous for arguments 'A' and 'long'.
9890 // note: candidate operator<=>(int, int)
9891 // note: candidate operator<=>(long, long)
9892 //
9893 // To avoid this error, this function deviates from the specification and adds
9894 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9895 // arithmetic types (the same as the generic relational overloads).
9896 //
9897 // For now this function acts as a placeholder.
9898 void addThreeWayArithmeticOverloads() {
9899 addGenericBinaryArithmeticOverloads();
9900 }
9901
9902 // C++ [over.built]p17:
9903 //
9904 // For every pair of promoted integral types L and R, there
9905 // exist candidate operator functions of the form
9906 //
9907 // LR operator%(L, R);
9908 // LR operator&(L, R);
9909 // LR operator^(L, R);
9910 // LR operator|(L, R);
9911 // L operator<<(L, R);
9912 // L operator>>(L, R);
9913 //
9914 // where LR is the result of the usual arithmetic conversions
9915 // between types L and R.
9916 void addBinaryBitwiseArithmeticOverloads() {
9917 if (!HasArithmeticOrEnumeralCandidateType)
9918 return;
9919
9920 for (unsigned Left = FirstPromotedIntegralType;
9921 Left < LastPromotedIntegralType; ++Left) {
9922 for (unsigned Right = FirstPromotedIntegralType;
9923 Right < LastPromotedIntegralType; ++Right) {
9924 QualType LandR[2] = { ArithmeticTypes[Left],
9925 ArithmeticTypes[Right] };
9926 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9927 }
9928 }
9929 }
9930
9931 // C++ [over.built]p20:
9932 //
9933 // For every pair (T, VQ), where T is an enumeration or
9934 // pointer to member type and VQ is either volatile or
9935 // empty, there exist candidate operator functions of the form
9936 //
9937 // VQ T& operator=(VQ T&, T);
9938 void addAssignmentMemberPointerOrEnumeralOverloads() {
9939 /// Set of (canonical) types that we've already handled.
9940 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9941
9942 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9943 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9944 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9945 continue;
9946
9947 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
9948 }
9949
9950 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9951 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9952 continue;
9953
9954 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
9955 }
9956 }
9957 }
9958
9959 // C++ [over.built]p19:
9960 //
9961 // For every pair (T, VQ), where T is any type and VQ is either
9962 // volatile or empty, there exist candidate operator functions
9963 // of the form
9964 //
9965 // T*VQ& operator=(T*VQ&, T*);
9966 //
9967 // C++ [over.built]p21:
9968 //
9969 // For every pair (T, VQ), where T is a cv-qualified or
9970 // cv-unqualified object type and VQ is either volatile or
9971 // empty, there exist candidate operator functions of the form
9972 //
9973 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9974 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9975 void addAssignmentPointerOverloads(bool isEqualOp) {
9976 /// Set of (canonical) types that we've already handled.
9977 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9978
9979 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9980 // If this is operator=, keep track of the builtin candidates we added.
9981 if (isEqualOp)
9982 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
9983 else if (!PtrTy->getPointeeType()->isObjectType())
9984 continue;
9985
9986 // non-volatile version
9987 QualType ParamTypes[2] = {
9988 S.Context.getLValueReferenceType(T: PtrTy),
9989 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9990 };
9991 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9992 /*IsAssignmentOperator=*/ isEqualOp);
9993
9994 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9995 VisibleTypeConversionsQuals.hasVolatile();
9996 if (NeedVolatile) {
9997 // volatile version
9998 ParamTypes[0] =
9999 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10000 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10001 /*IsAssignmentOperator=*/isEqualOp);
10002 }
10003
10004 if (!PtrTy.isRestrictQualified() &&
10005 VisibleTypeConversionsQuals.hasRestrict()) {
10006 // restrict version
10007 ParamTypes[0] =
10008 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10009 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10010 /*IsAssignmentOperator=*/isEqualOp);
10011
10012 if (NeedVolatile) {
10013 // volatile restrict version
10014 ParamTypes[0] =
10015 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10016 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10017 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10018 /*IsAssignmentOperator=*/isEqualOp);
10019 }
10020 }
10021 }
10022
10023 if (isEqualOp) {
10024 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10025 // Make sure we don't add the same candidate twice.
10026 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10027 continue;
10028
10029 QualType ParamTypes[2] = {
10030 S.Context.getLValueReferenceType(T: PtrTy),
10031 PtrTy,
10032 };
10033
10034 // non-volatile version
10035 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10036 /*IsAssignmentOperator=*/true);
10037
10038 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10039 VisibleTypeConversionsQuals.hasVolatile();
10040 if (NeedVolatile) {
10041 // volatile version
10042 ParamTypes[0] = S.Context.getLValueReferenceType(
10043 T: S.Context.getVolatileType(T: PtrTy));
10044 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10045 /*IsAssignmentOperator=*/true);
10046 }
10047
10048 if (!PtrTy.isRestrictQualified() &&
10049 VisibleTypeConversionsQuals.hasRestrict()) {
10050 // restrict version
10051 ParamTypes[0] = S.Context.getLValueReferenceType(
10052 T: S.Context.getRestrictType(T: PtrTy));
10053 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10054 /*IsAssignmentOperator=*/true);
10055
10056 if (NeedVolatile) {
10057 // volatile restrict version
10058 ParamTypes[0] =
10059 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10060 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10061 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10062 /*IsAssignmentOperator=*/true);
10063 }
10064 }
10065 }
10066 }
10067 }
10068
10069 // C++ [over.built]p18:
10070 //
10071 // For every triple (L, VQ, R), where L is an arithmetic type,
10072 // VQ is either volatile or empty, and R is a promoted
10073 // arithmetic type, there exist candidate operator functions of
10074 // the form
10075 //
10076 // VQ L& operator=(VQ L&, R);
10077 // VQ L& operator*=(VQ L&, R);
10078 // VQ L& operator/=(VQ L&, R);
10079 // VQ L& operator+=(VQ L&, R);
10080 // VQ L& operator-=(VQ L&, R);
10081 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10082 if (!HasArithmeticOrEnumeralCandidateType)
10083 return;
10084
10085 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10086 for (unsigned Right = FirstPromotedArithmeticType;
10087 Right < LastPromotedArithmeticType; ++Right) {
10088 QualType ParamTypes[2];
10089 ParamTypes[1] = ArithmeticTypes[Right];
10090 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10091 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10092
10093 forAllQualifierCombinations(
10094 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10095 ParamTypes[0] =
10096 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10097 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10098 /*IsAssignmentOperator=*/isEqualOp);
10099 });
10100 }
10101 }
10102
10103 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10104 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10105 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10106 QualType ParamTypes[2];
10107 ParamTypes[1] = Vec2Ty;
10108 // Add this built-in operator as a candidate (VQ is empty).
10109 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10110 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10111 /*IsAssignmentOperator=*/isEqualOp);
10112
10113 // Add this built-in operator as a candidate (VQ is 'volatile').
10114 if (VisibleTypeConversionsQuals.hasVolatile()) {
10115 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10116 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10117 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10118 /*IsAssignmentOperator=*/isEqualOp);
10119 }
10120 }
10121 }
10122
10123 // C++ [over.built]p22:
10124 //
10125 // For every triple (L, VQ, R), where L is an integral type, VQ
10126 // is either volatile or empty, and R is a promoted integral
10127 // type, there exist candidate operator functions of the form
10128 //
10129 // VQ L& operator%=(VQ L&, R);
10130 // VQ L& operator<<=(VQ L&, R);
10131 // VQ L& operator>>=(VQ L&, R);
10132 // VQ L& operator&=(VQ L&, R);
10133 // VQ L& operator^=(VQ L&, R);
10134 // VQ L& operator|=(VQ L&, R);
10135 void addAssignmentIntegralOverloads() {
10136 if (!HasArithmeticOrEnumeralCandidateType)
10137 return;
10138
10139 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10140 for (unsigned Right = FirstPromotedIntegralType;
10141 Right < LastPromotedIntegralType; ++Right) {
10142 QualType ParamTypes[2];
10143 ParamTypes[1] = ArithmeticTypes[Right];
10144 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10145 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10146
10147 forAllQualifierCombinations(
10148 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10149 ParamTypes[0] =
10150 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10151 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10152 });
10153 }
10154 }
10155 }
10156
10157 // C++ [over.operator]p23:
10158 //
10159 // There also exist candidate operator functions of the form
10160 //
10161 // bool operator!(bool);
10162 // bool operator&&(bool, bool);
10163 // bool operator||(bool, bool);
10164 void addExclaimOverload() {
10165 QualType ParamTy = S.Context.BoolTy;
10166 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10167 /*IsAssignmentOperator=*/false,
10168 /*NumContextualBoolArguments=*/1);
10169 }
10170 void addAmpAmpOrPipePipeOverload() {
10171 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10172 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10173 /*IsAssignmentOperator=*/false,
10174 /*NumContextualBoolArguments=*/2);
10175 }
10176
10177 // C++ [over.built]p13:
10178 //
10179 // For every cv-qualified or cv-unqualified object type T there
10180 // exist candidate operator functions of the form
10181 //
10182 // T* operator+(T*, ptrdiff_t); [ABOVE]
10183 // T& operator[](T*, ptrdiff_t);
10184 // T* operator-(T*, ptrdiff_t); [ABOVE]
10185 // T* operator+(ptrdiff_t, T*); [ABOVE]
10186 // T& operator[](ptrdiff_t, T*);
10187 void addSubscriptOverloads() {
10188 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10189 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10190 QualType PointeeType = PtrTy->getPointeeType();
10191 if (!PointeeType->isObjectType())
10192 continue;
10193
10194 // T& operator[](T*, ptrdiff_t)
10195 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10196 }
10197
10198 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10199 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10200 QualType PointeeType = PtrTy->getPointeeType();
10201 if (!PointeeType->isObjectType())
10202 continue;
10203
10204 // T& operator[](ptrdiff_t, T*)
10205 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10206 }
10207 }
10208
10209 // C++ [over.built]p11:
10210 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10211 // C1 is the same type as C2 or is a derived class of C2, T is an object
10212 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10213 // there exist candidate operator functions of the form
10214 //
10215 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10216 //
10217 // where CV12 is the union of CV1 and CV2.
10218 void addArrowStarOverloads() {
10219 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10220 QualType C1Ty = PtrTy;
10221 QualType C1;
10222 QualifierCollector Q1;
10223 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10224 if (!isa<RecordType>(Val: C1))
10225 continue;
10226 // heuristic to reduce number of builtin candidates in the set.
10227 // Add volatile/restrict version only if there are conversions to a
10228 // volatile/restrict type.
10229 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10230 continue;
10231 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10232 continue;
10233 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10234 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10235 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10236 *D2 = mptr->getMostRecentCXXRecordDecl();
10237 if (!declaresSameEntity(D1, D2) &&
10238 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10239 break;
10240 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10241 // build CV12 T&
10242 QualType T = mptr->getPointeeType();
10243 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10244 T.isVolatileQualified())
10245 continue;
10246 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10247 T.isRestrictQualified())
10248 continue;
10249 T = Q1.apply(Context: S.Context, QT: T);
10250 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10251 }
10252 }
10253 }
10254
10255 // Note that we don't consider the first argument, since it has been
10256 // contextually converted to bool long ago. The candidates below are
10257 // therefore added as binary.
10258 //
10259 // C++ [over.built]p25:
10260 // For every type T, where T is a pointer, pointer-to-member, or scoped
10261 // enumeration type, there exist candidate operator functions of the form
10262 //
10263 // T operator?(bool, T, T);
10264 //
10265 void addConditionalOperatorOverloads() {
10266 /// Set of (canonical) types that we've already handled.
10267 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10268
10269 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10270 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10271 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10272 continue;
10273
10274 QualType ParamTypes[2] = {PtrTy, PtrTy};
10275 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10276 }
10277
10278 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10279 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10280 continue;
10281
10282 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10283 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10284 }
10285
10286 if (S.getLangOpts().CPlusPlus11) {
10287 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10288 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10289 continue;
10290
10291 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10292 continue;
10293
10294 QualType ParamTypes[2] = {EnumTy, EnumTy};
10295 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10296 }
10297 }
10298 }
10299 }
10300};
10301
10302} // end anonymous namespace
10303
10304void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10305 SourceLocation OpLoc,
10306 ArrayRef<Expr *> Args,
10307 OverloadCandidateSet &CandidateSet) {
10308 // Find all of the types that the arguments can convert to, but only
10309 // if the operator we're looking at has built-in operator candidates
10310 // that make use of these types. Also record whether we encounter non-record
10311 // candidate types or either arithmetic or enumeral candidate types.
10312 QualifiersAndAtomic VisibleTypeConversionsQuals;
10313 VisibleTypeConversionsQuals.addConst();
10314 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10315 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10316 if (Args[ArgIdx]->getType()->isAtomicType())
10317 VisibleTypeConversionsQuals.addAtomic();
10318 }
10319
10320 bool HasNonRecordCandidateType = false;
10321 bool HasArithmeticOrEnumeralCandidateType = false;
10322 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10323 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10324 CandidateTypes.emplace_back(Args&: *this);
10325 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10326 Loc: OpLoc,
10327 AllowUserConversions: true,
10328 AllowExplicitConversions: (Op == OO_Exclaim ||
10329 Op == OO_AmpAmp ||
10330 Op == OO_PipePipe),
10331 VisibleQuals: VisibleTypeConversionsQuals);
10332 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10333 CandidateTypes[ArgIdx].hasNonRecordTypes();
10334 HasArithmeticOrEnumeralCandidateType =
10335 HasArithmeticOrEnumeralCandidateType ||
10336 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10337 }
10338
10339 // Exit early when no non-record types have been added to the candidate set
10340 // for any of the arguments to the operator.
10341 //
10342 // We can't exit early for !, ||, or &&, since there we have always have
10343 // 'bool' overloads.
10344 if (!HasNonRecordCandidateType &&
10345 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10346 return;
10347
10348 // Setup an object to manage the common state for building overloads.
10349 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10350 VisibleTypeConversionsQuals,
10351 HasArithmeticOrEnumeralCandidateType,
10352 CandidateTypes, CandidateSet);
10353
10354 // Dispatch over the operation to add in only those overloads which apply.
10355 switch (Op) {
10356 case OO_None:
10357 case NUM_OVERLOADED_OPERATORS:
10358 llvm_unreachable("Expected an overloaded operator");
10359
10360 case OO_New:
10361 case OO_Delete:
10362 case OO_Array_New:
10363 case OO_Array_Delete:
10364 case OO_Call:
10365 llvm_unreachable(
10366 "Special operators don't use AddBuiltinOperatorCandidates");
10367
10368 case OO_Comma:
10369 case OO_Arrow:
10370 case OO_Coawait:
10371 // C++ [over.match.oper]p3:
10372 // -- For the operator ',', the unary operator '&', the
10373 // operator '->', or the operator 'co_await', the
10374 // built-in candidates set is empty.
10375 break;
10376
10377 case OO_Plus: // '+' is either unary or binary
10378 if (Args.size() == 1)
10379 OpBuilder.addUnaryPlusPointerOverloads();
10380 [[fallthrough]];
10381
10382 case OO_Minus: // '-' is either unary or binary
10383 if (Args.size() == 1) {
10384 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10385 } else {
10386 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10387 OpBuilder.addGenericBinaryArithmeticOverloads();
10388 OpBuilder.addMatrixBinaryArithmeticOverloads();
10389 }
10390 break;
10391
10392 case OO_Star: // '*' is either unary or binary
10393 if (Args.size() == 1)
10394 OpBuilder.addUnaryStarPointerOverloads();
10395 else {
10396 OpBuilder.addGenericBinaryArithmeticOverloads();
10397 OpBuilder.addMatrixBinaryArithmeticOverloads();
10398 }
10399 break;
10400
10401 case OO_Slash:
10402 OpBuilder.addGenericBinaryArithmeticOverloads();
10403 break;
10404
10405 case OO_PlusPlus:
10406 case OO_MinusMinus:
10407 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10408 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10409 break;
10410
10411 case OO_EqualEqual:
10412 case OO_ExclaimEqual:
10413 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10414 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10415 OpBuilder.addGenericBinaryArithmeticOverloads();
10416 break;
10417
10418 case OO_Less:
10419 case OO_Greater:
10420 case OO_LessEqual:
10421 case OO_GreaterEqual:
10422 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10423 OpBuilder.addGenericBinaryArithmeticOverloads();
10424 break;
10425
10426 case OO_Spaceship:
10427 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10428 OpBuilder.addThreeWayArithmeticOverloads();
10429 break;
10430
10431 case OO_Percent:
10432 case OO_Caret:
10433 case OO_Pipe:
10434 case OO_LessLess:
10435 case OO_GreaterGreater:
10436 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10437 break;
10438
10439 case OO_Amp: // '&' is either unary or binary
10440 if (Args.size() == 1)
10441 // C++ [over.match.oper]p3:
10442 // -- For the operator ',', the unary operator '&', or the
10443 // operator '->', the built-in candidates set is empty.
10444 break;
10445
10446 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10447 break;
10448
10449 case OO_Tilde:
10450 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10451 break;
10452
10453 case OO_Equal:
10454 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10455 [[fallthrough]];
10456
10457 case OO_PlusEqual:
10458 case OO_MinusEqual:
10459 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10460 [[fallthrough]];
10461
10462 case OO_StarEqual:
10463 case OO_SlashEqual:
10464 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10465 break;
10466
10467 case OO_PercentEqual:
10468 case OO_LessLessEqual:
10469 case OO_GreaterGreaterEqual:
10470 case OO_AmpEqual:
10471 case OO_CaretEqual:
10472 case OO_PipeEqual:
10473 OpBuilder.addAssignmentIntegralOverloads();
10474 break;
10475
10476 case OO_Exclaim:
10477 OpBuilder.addExclaimOverload();
10478 break;
10479
10480 case OO_AmpAmp:
10481 case OO_PipePipe:
10482 OpBuilder.addAmpAmpOrPipePipeOverload();
10483 break;
10484
10485 case OO_Subscript:
10486 if (Args.size() == 2)
10487 OpBuilder.addSubscriptOverloads();
10488 break;
10489
10490 case OO_ArrowStar:
10491 OpBuilder.addArrowStarOverloads();
10492 break;
10493
10494 case OO_Conditional:
10495 OpBuilder.addConditionalOperatorOverloads();
10496 OpBuilder.addGenericBinaryArithmeticOverloads();
10497 break;
10498 }
10499}
10500
10501void
10502Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10503 SourceLocation Loc,
10504 ArrayRef<Expr *> Args,
10505 TemplateArgumentListInfo *ExplicitTemplateArgs,
10506 OverloadCandidateSet& CandidateSet,
10507 bool PartialOverloading) {
10508 ADLResult Fns;
10509
10510 // FIXME: This approach for uniquing ADL results (and removing
10511 // redundant candidates from the set) relies on pointer-equality,
10512 // which means we need to key off the canonical decl. However,
10513 // always going back to the canonical decl might not get us the
10514 // right set of default arguments. What default arguments are
10515 // we supposed to consider on ADL candidates, anyway?
10516
10517 // FIXME: Pass in the explicit template arguments?
10518 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10519
10520 ArrayRef<Expr *> ReversedArgs;
10521
10522 // Erase all of the candidates we already knew about.
10523 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10524 CandEnd = CandidateSet.end();
10525 Cand != CandEnd; ++Cand)
10526 if (Cand->Function) {
10527 FunctionDecl *Fn = Cand->Function;
10528 Fns.erase(D: Fn);
10529 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10530 Fns.erase(D: FunTmpl);
10531 }
10532
10533 // For each of the ADL candidates we found, add it to the overload
10534 // set.
10535 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10536 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10537
10538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10539 if (ExplicitTemplateArgs)
10540 continue;
10541
10542 AddOverloadCandidate(
10543 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10544 PartialOverloading, /*AllowExplicit=*/true,
10545 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10546 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10547 AddOverloadCandidate(
10548 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10549 /*SuppressUserConversions=*/false, PartialOverloading,
10550 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10551 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10552 }
10553 } else {
10554 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10555 AddTemplateOverloadCandidate(
10556 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10557 /*SuppressUserConversions=*/false, PartialOverloading,
10558 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10559 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10560 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10561
10562 // As template candidates are not deduced immediately,
10563 // persist the array in the overload set.
10564 if (ReversedArgs.empty())
10565 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10566
10567 AddTemplateOverloadCandidate(
10568 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10569 /*SuppressUserConversions=*/false, PartialOverloading,
10570 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10571 PO: OverloadCandidateParamOrder::Reversed);
10572 }
10573 }
10574 }
10575}
10576
10577namespace {
10578enum class Comparison { Equal, Better, Worse };
10579}
10580
10581/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10582/// overload resolution.
10583///
10584/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10585/// Cand1's first N enable_if attributes have precisely the same conditions as
10586/// Cand2's first N enable_if attributes (where N = the number of enable_if
10587/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10588///
10589/// Note that you can have a pair of candidates such that Cand1's enable_if
10590/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10591/// worse than Cand1's.
10592static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10593 const FunctionDecl *Cand2) {
10594 // Common case: One (or both) decls don't have enable_if attrs.
10595 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10596 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10597 if (!Cand1Attr || !Cand2Attr) {
10598 if (Cand1Attr == Cand2Attr)
10599 return Comparison::Equal;
10600 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10601 }
10602
10603 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10604 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10605
10606 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10607 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10608 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10609 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10610
10611 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10612 // has fewer enable_if attributes than Cand2, and vice versa.
10613 if (!Cand1A)
10614 return Comparison::Worse;
10615 if (!Cand2A)
10616 return Comparison::Better;
10617
10618 Cand1ID.clear();
10619 Cand2ID.clear();
10620
10621 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10622 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10623 if (Cand1ID != Cand2ID)
10624 return Comparison::Worse;
10625 }
10626
10627 return Comparison::Equal;
10628}
10629
10630static Comparison
10631isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10632 const OverloadCandidate &Cand2) {
10633 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10634 !Cand2.Function->isMultiVersion())
10635 return Comparison::Equal;
10636
10637 // If both are invalid, they are equal. If one of them is invalid, the other
10638 // is better.
10639 if (Cand1.Function->isInvalidDecl()) {
10640 if (Cand2.Function->isInvalidDecl())
10641 return Comparison::Equal;
10642 return Comparison::Worse;
10643 }
10644 if (Cand2.Function->isInvalidDecl())
10645 return Comparison::Better;
10646
10647 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10648 // cpu_dispatch, else arbitrarily based on the identifiers.
10649 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10650 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10651 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10652 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10653
10654 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10655 return Comparison::Equal;
10656
10657 if (Cand1CPUDisp && !Cand2CPUDisp)
10658 return Comparison::Better;
10659 if (Cand2CPUDisp && !Cand1CPUDisp)
10660 return Comparison::Worse;
10661
10662 if (Cand1CPUSpec && Cand2CPUSpec) {
10663 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10664 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10665 ? Comparison::Better
10666 : Comparison::Worse;
10667
10668 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10669 FirstDiff = std::mismatch(
10670 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10671 first2: Cand2CPUSpec->cpus_begin(),
10672 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10673 return LHS->getName() == RHS->getName();
10674 });
10675
10676 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10677 "Two different cpu-specific versions should not have the same "
10678 "identifier list, otherwise they'd be the same decl!");
10679 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10680 ? Comparison::Better
10681 : Comparison::Worse;
10682 }
10683 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10684}
10685
10686/// Compute the type of the implicit object parameter for the given function,
10687/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10688/// null QualType if there is a 'matches anything' implicit object parameter.
10689static std::optional<QualType>
10690getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10691 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10692 return std::nullopt;
10693
10694 auto *M = cast<CXXMethodDecl>(Val: F);
10695 // Static member functions' object parameters match all types.
10696 if (M->isStatic())
10697 return QualType();
10698 return M->getFunctionObjectParameterReferenceType();
10699}
10700
10701// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10702// represent the same entity.
10703static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10704 const FunctionDecl *F2) {
10705 if (declaresSameEntity(D1: F1, D2: F2))
10706 return true;
10707 auto PT1 = F1->getPrimaryTemplate();
10708 auto PT2 = F2->getPrimaryTemplate();
10709 if (PT1 && PT2) {
10710 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10711 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10712 D2: PT2->getInstantiatedFromMemberTemplate()))
10713 return true;
10714 }
10715 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10716 // different functions with same params). Consider removing this (as no test
10717 // fail w/o it).
10718 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10719 if (First) {
10720 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10721 return *T;
10722 }
10723 assert(I < F->getNumParams());
10724 return F->getParamDecl(i: I++)->getType();
10725 };
10726
10727 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10728 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10729
10730 if (F1NumParams != F2NumParams)
10731 return false;
10732
10733 unsigned I1 = 0, I2 = 0;
10734 for (unsigned I = 0; I != F1NumParams; ++I) {
10735 QualType T1 = NextParam(F1, I1, I == 0);
10736 QualType T2 = NextParam(F2, I2, I == 0);
10737 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10738 if (!Context.hasSameUnqualifiedType(T1, T2))
10739 return false;
10740 }
10741 return true;
10742}
10743
10744/// We're allowed to use constraints partial ordering only if the candidates
10745/// have the same parameter types:
10746/// [over.match.best.general]p2.6
10747/// F1 and F2 are non-template functions with the same
10748/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10749static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10750 FunctionDecl *Fn2,
10751 bool IsFn1Reversed,
10752 bool IsFn2Reversed) {
10753 assert(Fn1 && Fn2);
10754 if (Fn1->isVariadic() != Fn2->isVariadic())
10755 return false;
10756
10757 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10758 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10759 return false;
10760
10761 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10762 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10763 if (Mem1 && Mem2) {
10764 // if they are member functions, both are direct members of the same class,
10765 // and
10766 if (Mem1->getParent() != Mem2->getParent())
10767 return false;
10768 // if both are non-static member functions, they have the same types for
10769 // their object parameters
10770 if (Mem1->isInstance() && Mem2->isInstance() &&
10771 !S.getASTContext().hasSameType(
10772 T1: Mem1->getFunctionObjectParameterReferenceType(),
10773 T2: Mem1->getFunctionObjectParameterReferenceType()))
10774 return false;
10775 }
10776 return true;
10777}
10778
10779static FunctionDecl *
10780getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10781 bool IsFn1Reversed, bool IsFn2Reversed) {
10782 if (!Fn1 || !Fn2)
10783 return nullptr;
10784
10785 // C++ [temp.constr.order]:
10786 // A non-template function F1 is more partial-ordering-constrained than a
10787 // non-template function F2 if:
10788 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10789 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10790
10791 if (Cand1IsSpecialization || Cand2IsSpecialization)
10792 return nullptr;
10793
10794 // - they have the same non-object-parameter-type-lists, and [...]
10795 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10796 IsFn2Reversed))
10797 return nullptr;
10798
10799 // - the declaration of F1 is more constrained than the declaration of F2.
10800 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10801}
10802
10803/// isBetterOverloadCandidate - Determines whether the first overload
10804/// candidate is a better candidate than the second (C++ 13.3.3p1).
10805bool clang::isBetterOverloadCandidate(
10806 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10807 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10808 bool PartialOverloading) {
10809 // Define viable functions to be better candidates than non-viable
10810 // functions.
10811 if (!Cand2.Viable)
10812 return Cand1.Viable;
10813 else if (!Cand1.Viable)
10814 return false;
10815
10816 // [CUDA] A function with 'never' preference is marked not viable, therefore
10817 // is never shown up here. The worst preference shown up here is 'wrong side',
10818 // e.g. an H function called by a HD function in device compilation. This is
10819 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10820 // function which is called only by an H function. A deferred diagnostic will
10821 // be triggered if it is emitted. However a wrong-sided function is still
10822 // a viable candidate here.
10823 //
10824 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10825 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10826 // can be emitted, Cand1 is not better than Cand2. This rule should have
10827 // precedence over other rules.
10828 //
10829 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10830 // other rules should be used to determine which is better. This is because
10831 // host/device based overloading resolution is mostly for determining
10832 // viability of a function. If two functions are both viable, other factors
10833 // should take precedence in preference, e.g. the standard-defined preferences
10834 // like argument conversion ranks or enable_if partial-ordering. The
10835 // preference for pass-object-size parameters is probably most similar to a
10836 // type-based-overloading decision and so should take priority.
10837 //
10838 // If other rules cannot determine which is better, CUDA preference will be
10839 // used again to determine which is better.
10840 //
10841 // TODO: Currently IdentifyPreference does not return correct values
10842 // for functions called in global variable initializers due to missing
10843 // correct context about device/host. Therefore we can only enforce this
10844 // rule when there is a caller. We should enforce this rule for functions
10845 // in global variable initializers once proper context is added.
10846 //
10847 // TODO: We can only enable the hostness based overloading resolution when
10848 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10849 // overloading resolution diagnostics.
10850 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10851 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10852 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10853 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10854 bool IsCand1ImplicitHD =
10855 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10856 bool IsCand2ImplicitHD =
10857 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10858 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10859 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10860 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10861 // The implicit HD function may be a function in a system header which
10862 // is forced by pragma. In device compilation, if we prefer HD candidates
10863 // over wrong-sided candidates, overloading resolution may change, which
10864 // may result in non-deferrable diagnostics. As a workaround, we let
10865 // implicit HD candidates take equal preference as wrong-sided candidates.
10866 // This will preserve the overloading resolution.
10867 // TODO: We still need special handling of implicit HD functions since
10868 // they may incur other diagnostics to be deferred. We should make all
10869 // host/device related diagnostics deferrable and remove special handling
10870 // of implicit HD functions.
10871 auto EmitThreshold =
10872 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10873 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10874 ? SemaCUDA::CFP_Never
10875 : SemaCUDA::CFP_WrongSide;
10876 auto Cand1Emittable = P1 > EmitThreshold;
10877 auto Cand2Emittable = P2 > EmitThreshold;
10878 if (Cand1Emittable && !Cand2Emittable)
10879 return true;
10880 if (!Cand1Emittable && Cand2Emittable)
10881 return false;
10882 }
10883 }
10884
10885 // C++ [over.match.best]p1: (Changed in C++23)
10886 //
10887 // -- if F is a static member function, ICS1(F) is defined such
10888 // that ICS1(F) is neither better nor worse than ICS1(G) for
10889 // any function G, and, symmetrically, ICS1(G) is neither
10890 // better nor worse than ICS1(F).
10891 unsigned StartArg = 0;
10892 if (!Cand1.TookAddressOfOverload &&
10893 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
10894 StartArg = 1;
10895
10896 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10897 // We don't allow incompatible pointer conversions in C++.
10898 if (!S.getLangOpts().CPlusPlus)
10899 return ICS.isStandard() &&
10900 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10901
10902 // The only ill-formed conversion we allow in C++ is the string literal to
10903 // char* conversion, which is only considered ill-formed after C++11.
10904 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10905 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10906 };
10907
10908 // Define functions that don't require ill-formed conversions for a given
10909 // argument to be better candidates than functions that do.
10910 unsigned NumArgs = Cand1.Conversions.size();
10911 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10912 bool HasBetterConversion = false;
10913 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10914 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10915 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10916 if (Cand1Bad != Cand2Bad) {
10917 if (Cand1Bad)
10918 return false;
10919 HasBetterConversion = true;
10920 }
10921 }
10922
10923 if (HasBetterConversion)
10924 return true;
10925
10926 // C++ [over.match.best]p1:
10927 // A viable function F1 is defined to be a better function than another
10928 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10929 // conversion sequence than ICSi(F2), and then...
10930 bool HasWorseConversion = false;
10931 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10932 switch (CompareImplicitConversionSequences(S, Loc,
10933 ICS1: Cand1.Conversions[ArgIdx],
10934 ICS2: Cand2.Conversions[ArgIdx])) {
10935 case ImplicitConversionSequence::Better:
10936 // Cand1 has a better conversion sequence.
10937 HasBetterConversion = true;
10938 break;
10939
10940 case ImplicitConversionSequence::Worse:
10941 if (Cand1.Function && Cand2.Function &&
10942 Cand1.isReversed() != Cand2.isReversed() &&
10943 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
10944 // Work around large-scale breakage caused by considering reversed
10945 // forms of operator== in C++20:
10946 //
10947 // When comparing a function against a reversed function, if we have a
10948 // better conversion for one argument and a worse conversion for the
10949 // other, the implicit conversion sequences are treated as being equally
10950 // good.
10951 //
10952 // This prevents a comparison function from being considered ambiguous
10953 // with a reversed form that is written in the same way.
10954 //
10955 // We diagnose this as an extension from CreateOverloadedBinOp.
10956 HasWorseConversion = true;
10957 break;
10958 }
10959
10960 // Cand1 can't be better than Cand2.
10961 return false;
10962
10963 case ImplicitConversionSequence::Indistinguishable:
10964 // Do nothing.
10965 break;
10966 }
10967 }
10968
10969 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10970 // ICSj(F2), or, if not that,
10971 if (HasBetterConversion && !HasWorseConversion)
10972 return true;
10973
10974 // -- the context is an initialization by user-defined conversion
10975 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10976 // from the return type of F1 to the destination type (i.e.,
10977 // the type of the entity being initialized) is a better
10978 // conversion sequence than the standard conversion sequence
10979 // from the return type of F2 to the destination type.
10980 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10981 Cand1.Function && Cand2.Function &&
10982 isa<CXXConversionDecl>(Val: Cand1.Function) &&
10983 isa<CXXConversionDecl>(Val: Cand2.Function)) {
10984
10985 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10986 // First check whether we prefer one of the conversion functions over the
10987 // other. This only distinguishes the results in non-standard, extension
10988 // cases such as the conversion from a lambda closure type to a function
10989 // pointer or block.
10990 ImplicitConversionSequence::CompareKind Result =
10991 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
10992 if (Result == ImplicitConversionSequence::Indistinguishable)
10993 Result = CompareStandardConversionSequences(S, Loc,
10994 SCS1: Cand1.FinalConversion,
10995 SCS2: Cand2.FinalConversion);
10996
10997 if (Result != ImplicitConversionSequence::Indistinguishable)
10998 return Result == ImplicitConversionSequence::Better;
10999
11000 // FIXME: Compare kind of reference binding if conversion functions
11001 // convert to a reference type used in direct reference binding, per
11002 // C++14 [over.match.best]p1 section 2 bullet 3.
11003 }
11004
11005 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11006 // as combined with the resolution to CWG issue 243.
11007 //
11008 // When the context is initialization by constructor ([over.match.ctor] or
11009 // either phase of [over.match.list]), a constructor is preferred over
11010 // a conversion function.
11011 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11012 Cand1.Function && Cand2.Function &&
11013 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11014 isa<CXXConstructorDecl>(Val: Cand2.Function))
11015 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11016
11017 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11018 return Cand2.StrictPackMatch;
11019
11020 // -- F1 is a non-template function and F2 is a function template
11021 // specialization, or, if not that,
11022 bool Cand1IsSpecialization = Cand1.Function &&
11023 Cand1.Function->getPrimaryTemplate();
11024 bool Cand2IsSpecialization = Cand2.Function &&
11025 Cand2.Function->getPrimaryTemplate();
11026 if (Cand1IsSpecialization != Cand2IsSpecialization)
11027 return Cand2IsSpecialization;
11028
11029 // -- F1 and F2 are function template specializations, and the function
11030 // template for F1 is more specialized than the template for F2
11031 // according to the partial ordering rules described in 14.5.5.2, or,
11032 // if not that,
11033 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11034 const auto *Obj1Context =
11035 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11036 const auto *Obj2Context =
11037 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11038 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11039 FT1: Cand1.Function->getPrimaryTemplate(),
11040 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11041 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11042 : TPOC_Call,
11043 NumCallArguments1: Cand1.ExplicitCallArguments,
11044 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11045 : QualType{},
11046 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11047 : QualType{},
11048 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11049 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11050 }
11051 }
11052
11053 // -— F1 and F2 are non-template functions and F1 is more
11054 // partial-ordering-constrained than F2 [...],
11055 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11056 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11057 IsFn2Reversed: Cand2.isReversed());
11058 F && F == Cand1.Function)
11059 return true;
11060
11061 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11062 // class B of D, and for all arguments the corresponding parameters of
11063 // F1 and F2 have the same type.
11064 // FIXME: Implement the "all parameters have the same type" check.
11065 bool Cand1IsInherited =
11066 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11067 bool Cand2IsInherited =
11068 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11069 if (Cand1IsInherited != Cand2IsInherited)
11070 return Cand2IsInherited;
11071 else if (Cand1IsInherited) {
11072 assert(Cand2IsInherited);
11073 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11074 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11075 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11076 return true;
11077 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11078 return false;
11079 // Inherited from sibling base classes: still ambiguous.
11080 }
11081
11082 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11083 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11084 // with reversed order of parameters and F1 is not
11085 //
11086 // We rank reversed + different operator as worse than just reversed, but
11087 // that comparison can never happen, because we only consider reversing for
11088 // the maximally-rewritten operator (== or <=>).
11089 if (Cand1.RewriteKind != Cand2.RewriteKind)
11090 return Cand1.RewriteKind < Cand2.RewriteKind;
11091
11092 // Check C++17 tie-breakers for deduction guides.
11093 {
11094 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11095 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11096 if (Guide1 && Guide2) {
11097 // -- F1 is generated from a deduction-guide and F2 is not
11098 if (Guide1->isImplicit() != Guide2->isImplicit())
11099 return Guide2->isImplicit();
11100
11101 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11102 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11103 return true;
11104 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11105 return false;
11106
11107 // --F1 is generated from a non-template constructor and F2 is generated
11108 // from a constructor template
11109 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11110 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11111 if (Constructor1 && Constructor2) {
11112 bool isC1Templated = Constructor1->getTemplatedKind() !=
11113 FunctionDecl::TemplatedKind::TK_NonTemplate;
11114 bool isC2Templated = Constructor2->getTemplatedKind() !=
11115 FunctionDecl::TemplatedKind::TK_NonTemplate;
11116 if (isC1Templated != isC2Templated)
11117 return isC2Templated;
11118 }
11119 }
11120 }
11121
11122 // Check for enable_if value-based overload resolution.
11123 if (Cand1.Function && Cand2.Function) {
11124 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11125 if (Cmp != Comparison::Equal)
11126 return Cmp == Comparison::Better;
11127 }
11128
11129 bool HasPS1 = Cand1.Function != nullptr &&
11130 functionHasPassObjectSizeParams(FD: Cand1.Function);
11131 bool HasPS2 = Cand2.Function != nullptr &&
11132 functionHasPassObjectSizeParams(FD: Cand2.Function);
11133 if (HasPS1 != HasPS2 && HasPS1)
11134 return true;
11135
11136 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11137 if (MV == Comparison::Better)
11138 return true;
11139 if (MV == Comparison::Worse)
11140 return false;
11141
11142 // If other rules cannot determine which is better, CUDA preference is used
11143 // to determine which is better.
11144 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11145 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11146 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11147 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11148 }
11149
11150 // General member function overloading is handled above, so this only handles
11151 // constructors with address spaces.
11152 // This only handles address spaces since C++ has no other
11153 // qualifier that can be used with constructors.
11154 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11155 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11156 if (CD1 && CD2) {
11157 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11158 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11159 if (AS1 != AS2) {
11160 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11161 return true;
11162 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11163 return false;
11164 }
11165 }
11166
11167 return false;
11168}
11169
11170/// Determine whether two declarations are "equivalent" for the purposes of
11171/// name lookup and overload resolution. This applies when the same internal/no
11172/// linkage entity is defined by two modules (probably by textually including
11173/// the same header). In such a case, we don't consider the declarations to
11174/// declare the same entity, but we also don't want lookups with both
11175/// declarations visible to be ambiguous in some cases (this happens when using
11176/// a modularized libstdc++).
11177bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11178 const NamedDecl *B) {
11179 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11180 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11181 if (!VA || !VB)
11182 return false;
11183
11184 // The declarations must be declaring the same name as an internal linkage
11185 // entity in different modules.
11186 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11187 DC: VB->getDeclContext()->getRedeclContext()) ||
11188 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11189 VA->isExternallyVisible() || VB->isExternallyVisible())
11190 return false;
11191
11192 // Check that the declarations appear to be equivalent.
11193 //
11194 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11195 // For constants and functions, we should check the initializer or body is
11196 // the same. For non-constant variables, we shouldn't allow it at all.
11197 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11198 return true;
11199
11200 // Enum constants within unnamed enumerations will have different types, but
11201 // may still be similar enough to be interchangeable for our purposes.
11202 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11203 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11204 // Only handle anonymous enums. If the enumerations were named and
11205 // equivalent, they would have been merged to the same type.
11206 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11207 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11208 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11209 !Context.hasSameType(T1: EnumA->getIntegerType(),
11210 T2: EnumB->getIntegerType()))
11211 return false;
11212 // Allow this only if the value is the same for both enumerators.
11213 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11214 }
11215 }
11216
11217 // Nothing else is sufficiently similar.
11218 return false;
11219}
11220
11221void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11222 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11223 assert(D && "Unknown declaration");
11224 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11225
11226 Module *M = getOwningModule(Entity: D);
11227 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11228 << !M << (M ? M->getFullModuleName() : "");
11229
11230 for (auto *E : Equiv) {
11231 Module *M = getOwningModule(Entity: E);
11232 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11233 << !M << (M ? M->getFullModuleName() : "");
11234 }
11235}
11236
11237bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11238 return FailureKind == ovl_fail_bad_deduction &&
11239 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11240 TemplateDeductionResult::ConstraintsNotSatisfied &&
11241 static_cast<CNSInfo *>(DeductionFailure.Data)
11242 ->Satisfaction.ContainsErrors;
11243}
11244
11245void OverloadCandidateSet::AddDeferredTemplateCandidate(
11246 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11247 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11248 bool PartialOverloading, bool AllowExplicit,
11249 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11250 bool AggregateCandidateDeduction) {
11251
11252 auto *C =
11253 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11254
11255 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11256 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11257 /*AllowObjCConversionOnExplicit=*/false,
11258 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11259 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11260 .FunctionTemplate: FunctionTemplate,
11261 .FoundDecl: FoundDecl,
11262 .Args: Args,
11263 .IsADLCandidate: IsADLCandidate,
11264 .PO: PO};
11265
11266 HasDeferredTemplateConstructors |=
11267 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11268}
11269
11270void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11271 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11272 CXXRecordDecl *ActingContext, QualType ObjectType,
11273 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11274 bool SuppressUserConversions, bool PartialOverloading,
11275 OverloadCandidateParamOrder PO) {
11276
11277 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11278
11279 auto *C =
11280 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11281
11282 C = new (C) DeferredMethodTemplateOverloadCandidate{
11283 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11284 /*AllowObjCConversionOnExplicit=*/false,
11285 /*AllowResultConversion=*/false,
11286 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11287 /*AggregateCandidateDeduction=*/false},
11288 .FunctionTemplate: MethodTmpl,
11289 .FoundDecl: FoundDecl,
11290 .Args: Args,
11291 .ActingContext: ActingContext,
11292 .ObjectClassification: ObjectClassification,
11293 .ObjectType: ObjectType,
11294 .PO: PO};
11295}
11296
11297void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11298 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11299 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11300 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11301 bool AllowResultConversion) {
11302
11303 auto *C =
11304 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11305
11306 C = new (C) DeferredConversionTemplateOverloadCandidate{
11307 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11308 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11309 /*AllowExplicit=*/false,
11310 /*SuppressUserConversions=*/false,
11311 /*PartialOverloading*/ false,
11312 /*AggregateCandidateDeduction=*/false},
11313 .FunctionTemplate: FunctionTemplate,
11314 .FoundDecl: FoundDecl,
11315 .ActingContext: ActingContext,
11316 .From: From,
11317 .ToType: ToType};
11318}
11319
11320static void
11321AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11322 DeferredMethodTemplateOverloadCandidate &C) {
11323
11324 AddMethodTemplateCandidateImmediately(
11325 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11326 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11327 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11328}
11329
11330static void
11331AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11332 DeferredFunctionTemplateOverloadCandidate &C) {
11333 AddTemplateOverloadCandidateImmediately(
11334 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11335 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11336 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11337 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11338}
11339
11340static void
11341AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11342 DeferredConversionTemplateOverloadCandidate &C) {
11343 return AddTemplateConversionCandidateImmediately(
11344 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11345 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11346 AllowResultConversion: C.AllowResultConversion);
11347}
11348
11349void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11350 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11351 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11352 while (Cand) {
11353 switch (Cand->Kind) {
11354 case DeferredTemplateOverloadCandidate::Function:
11355 AddTemplateOverloadCandidate(
11356 S, CandidateSet&: *this,
11357 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11358 break;
11359 case DeferredTemplateOverloadCandidate::Method:
11360 AddTemplateOverloadCandidate(
11361 S, CandidateSet&: *this,
11362 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11363 break;
11364 case DeferredTemplateOverloadCandidate::Conversion:
11365 AddTemplateOverloadCandidate(
11366 S, CandidateSet&: *this,
11367 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11368 break;
11369 }
11370 Cand = Cand->Next;
11371 }
11372 FirstDeferredCandidate = nullptr;
11373 DeferredCandidatesCount = 0;
11374}
11375
11376OverloadingResult
11377OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11378 Best->Best = true;
11379 if (Best->Function && Best->Function->isDeleted())
11380 return OR_Deleted;
11381 return OR_Success;
11382}
11383
11384void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11385 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11386 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11387 // are accepted by both clang and NVCC. However, during a particular
11388 // compilation mode only one call variant is viable. We need to
11389 // exclude non-viable overload candidates from consideration based
11390 // only on their host/device attributes. Specifically, if one
11391 // candidate call is WrongSide and the other is SameSide, we ignore
11392 // the WrongSide candidate.
11393 // We only need to remove wrong-sided candidates here if
11394 // -fgpu-exclude-wrong-side-overloads is off. When
11395 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11396 // uniformly in isBetterOverloadCandidate.
11397 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11398 return;
11399 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11400
11401 bool ContainsSameSideCandidate =
11402 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11403 // Check viable function only.
11404 return Cand->Viable && Cand->Function &&
11405 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11406 SemaCUDA::CFP_SameSide;
11407 });
11408
11409 if (!ContainsSameSideCandidate)
11410 return;
11411
11412 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11413 // Check viable function only to avoid unnecessary data copying/moving.
11414 return Cand->Viable && Cand->Function &&
11415 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11416 SemaCUDA::CFP_WrongSide;
11417 };
11418 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11419}
11420
11421/// Computes the best viable function (C++ 13.3.3)
11422/// within an overload candidate set.
11423///
11424/// \param Loc The location of the function name (or operator symbol) for
11425/// which overload resolution occurs.
11426///
11427/// \param Best If overload resolution was successful or found a deleted
11428/// function, \p Best points to the candidate function found.
11429///
11430/// \returns The result of overload resolution.
11431OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11432 SourceLocation Loc,
11433 iterator &Best) {
11434
11435 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11436 DeferredCandidatesCount == 0) &&
11437 "Unexpected deferred template candidates");
11438
11439 bool TwoPhaseResolution =
11440 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11441
11442 if (TwoPhaseResolution) {
11443 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11444 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11445 if (!(HasDeferredTemplateConstructors &&
11446 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11447 return Res;
11448 }
11449 }
11450
11451 InjectNonDeducedTemplateCandidates(S);
11452 return BestViableFunctionImpl(S, Loc, Best);
11453}
11454
11455OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11456 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11457
11458 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11459 Candidates.reserve(N: this->Candidates.size());
11460 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11461 result: std::back_inserter(x&: Candidates),
11462 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11463
11464 if (S.getLangOpts().CUDA)
11465 CudaExcludeWrongSideCandidates(S, Candidates);
11466
11467 Best = end();
11468 for (auto *Cand : Candidates) {
11469 Cand->Best = false;
11470 if (Cand->Viable) {
11471 if (Best == end() ||
11472 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11473 Best = Cand;
11474 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11475 // This candidate has constraint that we were unable to evaluate because
11476 // it referenced an expression that contained an error. Rather than fall
11477 // back onto a potentially unintended candidate (made worse by
11478 // subsuming constraints), treat this as 'no viable candidate'.
11479 Best = end();
11480 return OR_No_Viable_Function;
11481 }
11482 }
11483
11484 // If we didn't find any viable functions, abort.
11485 if (Best == end())
11486 return OR_No_Viable_Function;
11487
11488 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11489 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11490 PendingBest.push_back(Elt: &*Best);
11491 Best->Best = true;
11492
11493 // Make sure that this function is better than every other viable
11494 // function. If not, we have an ambiguity.
11495 while (!PendingBest.empty()) {
11496 auto *Curr = PendingBest.pop_back_val();
11497 for (auto *Cand : Candidates) {
11498 if (Cand->Viable && !Cand->Best &&
11499 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11500 PendingBest.push_back(Elt: Cand);
11501 Cand->Best = true;
11502
11503 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11504 B: Curr->Function))
11505 EquivalentCands.push_back(Elt: Cand->Function);
11506 else
11507 Best = end();
11508 }
11509 }
11510 }
11511
11512 if (Best == end())
11513 return OR_Ambiguous;
11514
11515 OverloadingResult R = ResultForBestCandidate(Best);
11516
11517 if (!EquivalentCands.empty())
11518 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11519 Equiv: EquivalentCands);
11520 return R;
11521}
11522
11523namespace {
11524
11525enum OverloadCandidateKind {
11526 oc_function,
11527 oc_method,
11528 oc_reversed_binary_operator,
11529 oc_constructor,
11530 oc_implicit_default_constructor,
11531 oc_implicit_copy_constructor,
11532 oc_implicit_move_constructor,
11533 oc_implicit_copy_assignment,
11534 oc_implicit_move_assignment,
11535 oc_implicit_equality_comparison,
11536 oc_inherited_constructor
11537};
11538
11539enum OverloadCandidateSelect {
11540 ocs_non_template,
11541 ocs_template,
11542 ocs_described_template,
11543};
11544
11545static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11546ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11547 const FunctionDecl *Fn,
11548 OverloadCandidateRewriteKind CRK,
11549 std::string &Description) {
11550
11551 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11552 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11553 isTemplate = true;
11554 Description = S.getTemplateArgumentBindingsText(
11555 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11556 }
11557
11558 OverloadCandidateSelect Select = [&]() {
11559 if (!Description.empty())
11560 return ocs_described_template;
11561 return isTemplate ? ocs_template : ocs_non_template;
11562 }();
11563
11564 OverloadCandidateKind Kind = [&]() {
11565 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11566 return oc_implicit_equality_comparison;
11567
11568 if (CRK & CRK_Reversed)
11569 return oc_reversed_binary_operator;
11570
11571 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11572 if (!Ctor->isImplicit()) {
11573 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11574 return oc_inherited_constructor;
11575 else
11576 return oc_constructor;
11577 }
11578
11579 if (Ctor->isDefaultConstructor())
11580 return oc_implicit_default_constructor;
11581
11582 if (Ctor->isMoveConstructor())
11583 return oc_implicit_move_constructor;
11584
11585 assert(Ctor->isCopyConstructor() &&
11586 "unexpected sort of implicit constructor");
11587 return oc_implicit_copy_constructor;
11588 }
11589
11590 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11591 // This actually gets spelled 'candidate function' for now, but
11592 // it doesn't hurt to split it out.
11593 if (!Meth->isImplicit())
11594 return oc_method;
11595
11596 if (Meth->isMoveAssignmentOperator())
11597 return oc_implicit_move_assignment;
11598
11599 if (Meth->isCopyAssignmentOperator())
11600 return oc_implicit_copy_assignment;
11601
11602 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11603 return oc_method;
11604 }
11605
11606 return oc_function;
11607 }();
11608
11609 return std::make_pair(x&: Kind, y&: Select);
11610}
11611
11612void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11613 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11614 // set.
11615 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11616 S.Diag(Loc: FoundDecl->getLocation(),
11617 DiagID: diag::note_ovl_candidate_inherited_constructor)
11618 << Shadow->getNominatedBaseClass();
11619}
11620
11621} // end anonymous namespace
11622
11623static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11624 const FunctionDecl *FD) {
11625 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11626 bool AlwaysTrue;
11627 if (EnableIf->getCond()->isValueDependent() ||
11628 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11629 return false;
11630 if (!AlwaysTrue)
11631 return false;
11632 }
11633 return true;
11634}
11635
11636/// Returns true if we can take the address of the function.
11637///
11638/// \param Complain - If true, we'll emit a diagnostic
11639/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11640/// we in overload resolution?
11641/// \param Loc - The location of the statement we're complaining about. Ignored
11642/// if we're not complaining, or if we're in overload resolution.
11643static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11644 bool Complain,
11645 bool InOverloadResolution,
11646 SourceLocation Loc) {
11647 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11648 if (Complain) {
11649 if (InOverloadResolution)
11650 S.Diag(Loc: FD->getBeginLoc(),
11651 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11652 else
11653 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11654 }
11655 return false;
11656 }
11657
11658 if (FD->getTrailingRequiresClause()) {
11659 ConstraintSatisfaction Satisfaction;
11660 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11661 return false;
11662 if (!Satisfaction.IsSatisfied) {
11663 if (Complain) {
11664 if (InOverloadResolution) {
11665 SmallString<128> TemplateArgString;
11666 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11667 TemplateArgString += " ";
11668 TemplateArgString += S.getTemplateArgumentBindingsText(
11669 Params: FunTmpl->getTemplateParameters(),
11670 Args: *FD->getTemplateSpecializationArgs());
11671 }
11672
11673 S.Diag(Loc: FD->getBeginLoc(),
11674 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11675 << TemplateArgString;
11676 } else
11677 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11678 << FD;
11679 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11680 }
11681 return false;
11682 }
11683 }
11684
11685 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11686 return P->hasAttr<PassObjectSizeAttr>();
11687 });
11688 if (I == FD->param_end())
11689 return true;
11690
11691 if (Complain) {
11692 // Add one to ParamNo because it's user-facing
11693 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11694 if (InOverloadResolution)
11695 S.Diag(Loc: FD->getLocation(),
11696 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11697 << ParamNo;
11698 else
11699 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11700 << FD << ParamNo;
11701 }
11702 return false;
11703}
11704
11705static bool checkAddressOfCandidateIsAvailable(Sema &S,
11706 const FunctionDecl *FD) {
11707 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11708 /*InOverloadResolution=*/true,
11709 /*Loc=*/SourceLocation());
11710}
11711
11712bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11713 bool Complain,
11714 SourceLocation Loc) {
11715 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11716 /*InOverloadResolution=*/false,
11717 Loc);
11718}
11719
11720// Don't print candidates other than the one that matches the calling
11721// convention of the call operator, since that is guaranteed to exist.
11722static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11723 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11724
11725 if (!ConvD)
11726 return false;
11727 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11728 if (!RD->isLambda())
11729 return false;
11730
11731 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11732 CallingConv CallOpCC =
11733 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11734 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11735 CallingConv ConvToCC =
11736 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11737
11738 return ConvToCC != CallOpCC;
11739}
11740
11741// Notes the location of an overload candidate.
11742void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11743 OverloadCandidateRewriteKind RewriteKind,
11744 QualType DestType, bool TakingAddress) {
11745 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11746 return;
11747 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11748 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11749 return;
11750 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11751 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11752 return;
11753 if (shouldSkipNotingLambdaConversionDecl(Fn))
11754 return;
11755
11756 std::string FnDesc;
11757 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11758 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11759 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11760 << (unsigned)KSPair.first << (unsigned)KSPair.second
11761 << Fn << FnDesc;
11762
11763 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11764 Diag(Loc: Fn->getLocation(), PD);
11765 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11766}
11767
11768static void
11769MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11770 // Perhaps the ambiguity was caused by two atomic constraints that are
11771 // 'identical' but not equivalent:
11772 //
11773 // void foo() requires (sizeof(T) > 4) { } // #1
11774 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11775 //
11776 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11777 // #2 to subsume #1, but these constraint are not considered equivalent
11778 // according to the subsumption rules because they are not the same
11779 // source-level construct. This behavior is quite confusing and we should try
11780 // to help the user figure out what happened.
11781
11782 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11783 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11784 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11785 if (!I->Function)
11786 continue;
11787 SmallVector<AssociatedConstraint, 3> AC;
11788 if (auto *Template = I->Function->getPrimaryTemplate())
11789 Template->getAssociatedConstraints(AC);
11790 else
11791 I->Function->getAssociatedConstraints(ACs&: AC);
11792 if (AC.empty())
11793 continue;
11794 if (FirstCand == nullptr) {
11795 FirstCand = I->Function;
11796 FirstAC = AC;
11797 } else if (SecondCand == nullptr) {
11798 SecondCand = I->Function;
11799 SecondAC = AC;
11800 } else {
11801 // We have more than one pair of constrained functions - this check is
11802 // expensive and we'd rather not try to diagnose it.
11803 return;
11804 }
11805 }
11806 if (!SecondCand)
11807 return;
11808 // The diagnostic can only happen if there are associated constraints on
11809 // both sides (there needs to be some identical atomic constraint).
11810 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11811 D2: SecondCand, AC2: SecondAC))
11812 // Just show the user one diagnostic, they'll probably figure it out
11813 // from here.
11814 return;
11815}
11816
11817// Notes the location of all overload candidates designated through
11818// OverloadedExpr
11819void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11820 bool TakingAddress) {
11821 assert(OverloadedExpr->getType() == Context.OverloadTy);
11822
11823 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11824 OverloadExpr *OvlExpr = Ovl.Expression;
11825
11826 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11827 IEnd = OvlExpr->decls_end();
11828 I != IEnd; ++I) {
11829 if (FunctionTemplateDecl *FunTmpl =
11830 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11831 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11832 TakingAddress);
11833 } else if (FunctionDecl *Fun
11834 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11835 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11836 }
11837 }
11838}
11839
11840/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11841/// "lead" diagnostic; it will be given two arguments, the source and
11842/// target types of the conversion.
11843void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11844 Sema &S,
11845 SourceLocation CaretLoc,
11846 const PartialDiagnostic &PDiag) const {
11847 S.Diag(Loc: CaretLoc, PD: PDiag)
11848 << Ambiguous.getFromType() << Ambiguous.getToType();
11849 unsigned CandsShown = 0;
11850 AmbiguousConversionSequence::const_iterator I, E;
11851 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11852 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11853 break;
11854 ++CandsShown;
11855 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11856 }
11857 S.Diags.overloadCandidatesShown(N: CandsShown);
11858 if (I != E)
11859 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
11860}
11861
11862static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11863 unsigned I, bool TakingCandidateAddress) {
11864 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11865 assert(Conv.isBad());
11866 assert(Cand->Function && "for now, candidate must be a function");
11867 FunctionDecl *Fn = Cand->Function;
11868
11869 // There's a conversion slot for the object argument if this is a
11870 // non-constructor method. Note that 'I' corresponds the
11871 // conversion-slot index.
11872 bool isObjectArgument = false;
11873 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
11874 !isa<CXXConstructorDecl>(Val: Fn)) {
11875 if (I == 0)
11876 isObjectArgument = true;
11877 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
11878 I--;
11879 }
11880
11881 std::string FnDesc;
11882 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11883 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
11884 Description&: FnDesc);
11885
11886 Expr *FromExpr = Conv.Bad.FromExpr;
11887 QualType FromTy = Conv.Bad.getFromType();
11888 QualType ToTy = Conv.Bad.getToType();
11889 SourceRange ToParamRange;
11890
11891 // FIXME: In presence of parameter packs we can't determine parameter range
11892 // reliably, as we don't have access to instantiation.
11893 bool HasParamPack =
11894 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
11895 return Parm->isParameterPack();
11896 });
11897 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
11898 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
11899
11900 if (FromTy == S.Context.OverloadTy) {
11901 assert(FromExpr && "overload set argument came from implicit argument?");
11902 Expr *E = FromExpr->IgnoreParens();
11903 if (isa<UnaryOperator>(Val: E))
11904 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
11905 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
11906
11907 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
11908 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11909 << ToParamRange << ToTy << Name << I + 1;
11910 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11911 return;
11912 }
11913
11914 // Do some hand-waving analysis to see if the non-viability is due
11915 // to a qualifier mismatch.
11916 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
11917 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
11918 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11919 CToTy = RT->getPointeeType();
11920 else {
11921 // TODO: detect and diagnose the full richness of const mismatches.
11922 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11923 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11924 CFromTy = FromPT->getPointeeType();
11925 CToTy = ToPT->getPointeeType();
11926 }
11927 }
11928
11929 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11930 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
11931 Qualifiers FromQs = CFromTy.getQualifiers();
11932 Qualifiers ToQs = CToTy.getQualifiers();
11933
11934 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11935 if (isObjectArgument)
11936 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
11937 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11938 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11939 else
11940 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
11941 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11942 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11943 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11944 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11945 return;
11946 }
11947
11948 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11949 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
11950 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11951 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11952 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11953 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11954 return;
11955 }
11956
11957 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11958 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
11959 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11960 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11961 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11962 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11963 return;
11964 }
11965
11966 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
11967 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
11968 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11969 << FromTy << !!FromQs.getPointerAuth()
11970 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11971 << ToQs.getPointerAuth().getAsString() << I + 1
11972 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11973 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11974 return;
11975 }
11976
11977 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11978 assert(CVR && "expected qualifiers mismatch");
11979
11980 if (isObjectArgument) {
11981 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
11982 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11983 << FromTy << (CVR - 1);
11984 } else {
11985 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
11986 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11987 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11988 }
11989 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
11990 return;
11991 }
11992
11993 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11994 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11995 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
11996 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11997 << (unsigned)isObjectArgument << I + 1
11998 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11999 << ToParamRange;
12000 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12001 return;
12002 }
12003
12004 // Special diagnostic for failure to convert an initializer list, since
12005 // telling the user that it has type void is not useful.
12006 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12007 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12008 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12009 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12010 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12011 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12012 ? 2
12013 : 0);
12014 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12015 return;
12016 }
12017
12018 // Diagnose references or pointers to incomplete types differently,
12019 // since it's far from impossible that the incompleteness triggered
12020 // the failure.
12021 QualType TempFromTy = FromTy.getNonReferenceType();
12022 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12023 TempFromTy = PTy->getPointeeType();
12024 if (TempFromTy->isIncompleteType()) {
12025 // Emit the generic diagnostic and, optionally, add the hints to it.
12026 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12027 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12028 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12029 << (unsigned)(Cand->Fix.Kind);
12030
12031 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12032 return;
12033 }
12034
12035 // Diagnose base -> derived pointer conversions.
12036 unsigned BaseToDerivedConversion = 0;
12037 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12038 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12039 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12040 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12041 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12042 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12043 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12044 Base: FromPtrTy->getPointeeType()))
12045 BaseToDerivedConversion = 1;
12046 }
12047 } else if (const ObjCObjectPointerType *FromPtrTy
12048 = FromTy->getAs<ObjCObjectPointerType>()) {
12049 if (const ObjCObjectPointerType *ToPtrTy
12050 = ToTy->getAs<ObjCObjectPointerType>())
12051 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12052 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12053 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12054 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12055 FromIface->isSuperClassOf(I: ToIface))
12056 BaseToDerivedConversion = 2;
12057 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12058 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12059 Ctx: S.getASTContext()) &&
12060 !FromTy->isIncompleteType() &&
12061 !ToRefTy->getPointeeType()->isIncompleteType() &&
12062 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12063 BaseToDerivedConversion = 3;
12064 }
12065 }
12066
12067 if (BaseToDerivedConversion) {
12068 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12069 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12070 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12071 << I + 1;
12072 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12073 return;
12074 }
12075
12076 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12077 isa<PointerType>(Val: CToTy)) {
12078 Qualifiers FromQs = CFromTy.getQualifiers();
12079 Qualifiers ToQs = CToTy.getQualifiers();
12080 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12081 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12082 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12083 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12084 << I + 1;
12085 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12086 return;
12087 }
12088 }
12089
12090 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12091 return;
12092
12093 // Emit the generic diagnostic and, optionally, add the hints to it.
12094 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12095 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12096 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12097 << (unsigned)(Cand->Fix.Kind);
12098
12099 // Check that location of Fn is not in system header.
12100 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12101 // If we can fix the conversion, suggest the FixIts.
12102 for (const FixItHint &HI : Cand->Fix.Hints)
12103 FDiag << HI;
12104 }
12105
12106 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12107
12108 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12109}
12110
12111/// Additional arity mismatch diagnosis specific to a function overload
12112/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12113/// over a candidate in any candidate set.
12114static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12115 unsigned NumArgs, bool IsAddressOf = false) {
12116 assert(Cand->Function && "Candidate is required to be a function.");
12117 FunctionDecl *Fn = Cand->Function;
12118 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12119 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12120
12121 // With invalid overloaded operators, it's possible that we think we
12122 // have an arity mismatch when in fact it looks like we have the
12123 // right number of arguments, because only overloaded operators have
12124 // the weird behavior of overloading member and non-member functions.
12125 // Just don't report anything.
12126 if (Fn->isInvalidDecl() &&
12127 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12128 return true;
12129
12130 if (NumArgs < MinParams) {
12131 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12132 (Cand->FailureKind == ovl_fail_bad_deduction &&
12133 Cand->DeductionFailure.getResult() ==
12134 TemplateDeductionResult::TooFewArguments));
12135 } else {
12136 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12137 (Cand->FailureKind == ovl_fail_bad_deduction &&
12138 Cand->DeductionFailure.getResult() ==
12139 TemplateDeductionResult::TooManyArguments));
12140 }
12141
12142 return false;
12143}
12144
12145/// General arity mismatch diagnosis over a candidate in a candidate set.
12146static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12147 unsigned NumFormalArgs,
12148 bool IsAddressOf = false) {
12149 assert(isa<FunctionDecl>(D) &&
12150 "The templated declaration should at least be a function"
12151 " when diagnosing bad template argument deduction due to too many"
12152 " or too few arguments");
12153
12154 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12155
12156 // TODO: treat calls to a missing default constructor as a special case
12157 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12158 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12159 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12160
12161 // at least / at most / exactly
12162 bool HasExplicitObjectParam =
12163 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12164
12165 unsigned ParamCount =
12166 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12167 unsigned mode, modeCount;
12168
12169 if (NumFormalArgs < MinParams) {
12170 if (MinParams != ParamCount || FnTy->isVariadic() ||
12171 FnTy->isTemplateVariadic())
12172 mode = 0; // "at least"
12173 else
12174 mode = 2; // "exactly"
12175 modeCount = MinParams;
12176 } else {
12177 if (MinParams != ParamCount)
12178 mode = 1; // "at most"
12179 else
12180 mode = 2; // "exactly"
12181 modeCount = ParamCount;
12182 }
12183
12184 std::string Description;
12185 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12186 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12187
12188 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12189 if (modeCount == 1 && !IsAddressOf &&
12190 FirstNonObjectParamIdx < Fn->getNumParams() &&
12191 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12192 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12193 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12194 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12195 << NumFormalArgs << HasExplicitObjectParam
12196 << Fn->getParametersSourceRange();
12197 else
12198 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12200 << Description << mode << modeCount << NumFormalArgs
12201 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12202
12203 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12204}
12205
12206/// Arity mismatch diagnosis specific to a function overload candidate.
12207static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12208 unsigned NumFormalArgs) {
12209 assert(Cand->Function && "Candidate must be a function");
12210 FunctionDecl *Fn = Cand->Function;
12211 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12212 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12213 IsAddressOf: Cand->TookAddressOfOverload);
12214}
12215
12216static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12217 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12218 return TD;
12219 llvm_unreachable("Unsupported: Getting the described template declaration"
12220 " for bad deduction diagnosis");
12221}
12222
12223/// Diagnose a failed template-argument deduction.
12224static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12225 DeductionFailureInfo &DeductionFailure,
12226 unsigned NumArgs,
12227 bool TakingCandidateAddress) {
12228 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12229 NamedDecl *ParamD;
12230 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12231 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12232 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12233 switch (DeductionFailure.getResult()) {
12234 case TemplateDeductionResult::Success:
12235 llvm_unreachable(
12236 "TemplateDeductionResult::Success while diagnosing bad deduction");
12237 case TemplateDeductionResult::NonDependentConversionFailure:
12238 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12239 "while diagnosing bad deduction");
12240 case TemplateDeductionResult::Invalid:
12241 case TemplateDeductionResult::AlreadyDiagnosed:
12242 return;
12243
12244 case TemplateDeductionResult::Incomplete: {
12245 assert(ParamD && "no parameter found for incomplete deduction result");
12246 S.Diag(Loc: Templated->getLocation(),
12247 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12248 << ParamD->getDeclName();
12249 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12250 return;
12251 }
12252
12253 case TemplateDeductionResult::IncompletePack: {
12254 assert(ParamD && "no parameter found for incomplete deduction result");
12255 S.Diag(Loc: Templated->getLocation(),
12256 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12257 << ParamD->getDeclName()
12258 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12259 << *DeductionFailure.getFirstArg();
12260 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12261 return;
12262 }
12263
12264 case TemplateDeductionResult::Underqualified: {
12265 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12266 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12267
12268 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12269
12270 // Param will have been canonicalized, but it should just be a
12271 // qualified version of ParamD, so move the qualifiers to that.
12272 QualifierCollector Qs;
12273 Qs.strip(type: Param);
12274 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12275 assert(S.Context.hasSameType(Param, NonCanonParam));
12276
12277 // Arg has also been canonicalized, but there's nothing we can do
12278 // about that. It also doesn't matter as much, because it won't
12279 // have any template parameters in it (because deduction isn't
12280 // done on dependent types).
12281 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12282
12283 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12284 << ParamD->getDeclName() << Arg << NonCanonParam;
12285 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12286 return;
12287 }
12288
12289 case TemplateDeductionResult::Inconsistent: {
12290 assert(ParamD && "no parameter found for inconsistent deduction result");
12291 int which = 0;
12292 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12293 which = 0;
12294 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12295 // Deduction might have failed because we deduced arguments of two
12296 // different types for a non-type template parameter.
12297 // FIXME: Use a different TDK value for this.
12298 QualType T1 =
12299 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12300 QualType T2 =
12301 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12302 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12303 S.Diag(Loc: Templated->getLocation(),
12304 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12305 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12306 << *DeductionFailure.getSecondArg() << T2;
12307 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12308 return;
12309 }
12310
12311 which = 1;
12312 } else {
12313 which = 2;
12314 }
12315
12316 // Tweak the diagnostic if the problem is that we deduced packs of
12317 // different arities. We'll print the actual packs anyway in case that
12318 // includes additional useful information.
12319 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12320 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12321 DeductionFailure.getFirstArg()->pack_size() !=
12322 DeductionFailure.getSecondArg()->pack_size()) {
12323 which = 3;
12324 }
12325
12326 S.Diag(Loc: Templated->getLocation(),
12327 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12328 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12329 << *DeductionFailure.getSecondArg();
12330 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12331 return;
12332 }
12333
12334 case TemplateDeductionResult::InvalidExplicitArguments:
12335 assert(ParamD && "no parameter found for invalid explicit arguments");
12336 if (ParamD->getDeclName())
12337 S.Diag(Loc: Templated->getLocation(),
12338 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_named)
12339 << ParamD->getDeclName();
12340 else {
12341 int index = 0;
12342 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
12343 index = TTP->getIndex();
12344 else if (NonTypeTemplateParmDecl *NTTP
12345 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
12346 index = NTTP->getIndex();
12347 else
12348 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
12349 S.Diag(Loc: Templated->getLocation(),
12350 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12351 << (index + 1);
12352 }
12353 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12354 return;
12355
12356 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12357 // Format the template argument list into the argument string.
12358 SmallString<128> TemplateArgString;
12359 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12360 TemplateArgString = " ";
12361 TemplateArgString += S.getTemplateArgumentBindingsText(
12362 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12363 if (TemplateArgString.size() == 1)
12364 TemplateArgString.clear();
12365 S.Diag(Loc: Templated->getLocation(),
12366 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12367 << TemplateArgString;
12368
12369 S.DiagnoseUnsatisfiedConstraint(
12370 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12371 return;
12372 }
12373 case TemplateDeductionResult::TooManyArguments:
12374 case TemplateDeductionResult::TooFewArguments:
12375 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12376 return;
12377
12378 case TemplateDeductionResult::InstantiationDepth:
12379 S.Diag(Loc: Templated->getLocation(),
12380 DiagID: diag::note_ovl_candidate_instantiation_depth);
12381 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12382 return;
12383
12384 case TemplateDeductionResult::SubstitutionFailure: {
12385 // Format the template argument list into the argument string.
12386 SmallString<128> TemplateArgString;
12387 if (TemplateArgumentList *Args =
12388 DeductionFailure.getTemplateArgumentList()) {
12389 TemplateArgString = " ";
12390 TemplateArgString += S.getTemplateArgumentBindingsText(
12391 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12392 if (TemplateArgString.size() == 1)
12393 TemplateArgString.clear();
12394 }
12395
12396 // If this candidate was disabled by enable_if, say so.
12397 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12398 if (PDiag && PDiag->second.getDiagID() ==
12399 diag::err_typename_nested_not_found_enable_if) {
12400 // FIXME: Use the source range of the condition, and the fully-qualified
12401 // name of the enable_if template. These are both present in PDiag.
12402 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12403 << "'enable_if'" << TemplateArgString;
12404 return;
12405 }
12406
12407 // We found a specific requirement that disabled the enable_if.
12408 if (PDiag && PDiag->second.getDiagID() ==
12409 diag::err_typename_nested_not_found_requirement) {
12410 S.Diag(Loc: Templated->getLocation(),
12411 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12412 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12413 return;
12414 }
12415
12416 // Format the SFINAE diagnostic into the argument string.
12417 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12418 // formatted message in another diagnostic.
12419 SmallString<128> SFINAEArgString;
12420 SourceRange R;
12421 if (PDiag) {
12422 SFINAEArgString = ": ";
12423 R = SourceRange(PDiag->first, PDiag->first);
12424 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12425 }
12426
12427 S.Diag(Loc: Templated->getLocation(),
12428 DiagID: diag::note_ovl_candidate_substitution_failure)
12429 << TemplateArgString << SFINAEArgString << R;
12430 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12431 return;
12432 }
12433
12434 case TemplateDeductionResult::DeducedMismatch:
12435 case TemplateDeductionResult::DeducedMismatchNested: {
12436 // Format the template argument list into the argument string.
12437 SmallString<128> TemplateArgString;
12438 if (TemplateArgumentList *Args =
12439 DeductionFailure.getTemplateArgumentList()) {
12440 TemplateArgString = " ";
12441 TemplateArgString += S.getTemplateArgumentBindingsText(
12442 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12443 if (TemplateArgString.size() == 1)
12444 TemplateArgString.clear();
12445 }
12446
12447 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12448 << (*DeductionFailure.getCallArgIndex() + 1)
12449 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12450 << TemplateArgString
12451 << (DeductionFailure.getResult() ==
12452 TemplateDeductionResult::DeducedMismatchNested);
12453 break;
12454 }
12455
12456 case TemplateDeductionResult::NonDeducedMismatch: {
12457 // FIXME: Provide a source location to indicate what we couldn't match.
12458 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12459 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12460 if (FirstTA.getKind() == TemplateArgument::Template &&
12461 SecondTA.getKind() == TemplateArgument::Template) {
12462 TemplateName FirstTN = FirstTA.getAsTemplate();
12463 TemplateName SecondTN = SecondTA.getAsTemplate();
12464 if (FirstTN.getKind() == TemplateName::Template &&
12465 SecondTN.getKind() == TemplateName::Template) {
12466 if (FirstTN.getAsTemplateDecl()->getName() ==
12467 SecondTN.getAsTemplateDecl()->getName()) {
12468 // FIXME: This fixes a bad diagnostic where both templates are named
12469 // the same. This particular case is a bit difficult since:
12470 // 1) It is passed as a string to the diagnostic printer.
12471 // 2) The diagnostic printer only attempts to find a better
12472 // name for types, not decls.
12473 // Ideally, this should folded into the diagnostic printer.
12474 S.Diag(Loc: Templated->getLocation(),
12475 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12476 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12477 return;
12478 }
12479 }
12480 }
12481
12482 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12483 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12484 return;
12485
12486 // FIXME: For generic lambda parameters, check if the function is a lambda
12487 // call operator, and if so, emit a prettier and more informative
12488 // diagnostic that mentions 'auto' and lambda in addition to
12489 // (or instead of?) the canonical template type parameters.
12490 S.Diag(Loc: Templated->getLocation(),
12491 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12492 << FirstTA << SecondTA;
12493 return;
12494 }
12495 // TODO: diagnose these individually, then kill off
12496 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12497 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12498 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12499 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12500 return;
12501 case TemplateDeductionResult::CUDATargetMismatch:
12502 S.Diag(Loc: Templated->getLocation(),
12503 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12504 return;
12505 }
12506}
12507
12508/// Diagnose a failed template-argument deduction, for function calls.
12509static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12510 unsigned NumArgs,
12511 bool TakingCandidateAddress) {
12512 assert(Cand->Function && "Candidate must be a function");
12513 FunctionDecl *Fn = Cand->Function;
12514 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12515 if (TDK == TemplateDeductionResult::TooFewArguments ||
12516 TDK == TemplateDeductionResult::TooManyArguments) {
12517 if (CheckArityMismatch(S, Cand, NumArgs))
12518 return;
12519 }
12520 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12521 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12522}
12523
12524/// CUDA: diagnose an invalid call across targets.
12525static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12526 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12527 assert(Cand->Function && "Candidate must be a Function.");
12528 FunctionDecl *Callee = Cand->Function;
12529
12530 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12531 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12532
12533 std::string FnDesc;
12534 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12535 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12536 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12537
12538 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12539 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12540 << FnDesc /* Ignored */
12541 << CalleeTarget << CallerTarget;
12542
12543 // This could be an implicit constructor for which we could not infer the
12544 // target due to a collsion. Diagnose that case.
12545 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12546 if (Meth != nullptr && Meth->isImplicit()) {
12547 CXXRecordDecl *ParentClass = Meth->getParent();
12548 CXXSpecialMemberKind CSM;
12549
12550 switch (FnKindPair.first) {
12551 default:
12552 return;
12553 case oc_implicit_default_constructor:
12554 CSM = CXXSpecialMemberKind::DefaultConstructor;
12555 break;
12556 case oc_implicit_copy_constructor:
12557 CSM = CXXSpecialMemberKind::CopyConstructor;
12558 break;
12559 case oc_implicit_move_constructor:
12560 CSM = CXXSpecialMemberKind::MoveConstructor;
12561 break;
12562 case oc_implicit_copy_assignment:
12563 CSM = CXXSpecialMemberKind::CopyAssignment;
12564 break;
12565 case oc_implicit_move_assignment:
12566 CSM = CXXSpecialMemberKind::MoveAssignment;
12567 break;
12568 };
12569
12570 bool ConstRHS = false;
12571 if (Meth->getNumParams()) {
12572 if (const ReferenceType *RT =
12573 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12574 ConstRHS = RT->getPointeeType().isConstQualified();
12575 }
12576 }
12577
12578 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12579 /* ConstRHS */ ConstRHS,
12580 /* Diagnose */ true);
12581 }
12582}
12583
12584static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12585 assert(Cand->Function && "Candidate must be a function");
12586 FunctionDecl *Callee = Cand->Function;
12587 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12588
12589 S.Diag(Loc: Callee->getLocation(),
12590 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12591 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12592}
12593
12594static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12595 assert(Cand->Function && "Candidate must be a function");
12596 FunctionDecl *Fn = Cand->Function;
12597 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12598 assert(ES.isExplicit() && "not an explicit candidate");
12599
12600 unsigned Kind;
12601 switch (Fn->getDeclKind()) {
12602 case Decl::Kind::CXXConstructor:
12603 Kind = 0;
12604 break;
12605 case Decl::Kind::CXXConversion:
12606 Kind = 1;
12607 break;
12608 case Decl::Kind::CXXDeductionGuide:
12609 Kind = Fn->isImplicit() ? 0 : 2;
12610 break;
12611 default:
12612 llvm_unreachable("invalid Decl");
12613 }
12614
12615 // Note the location of the first (in-class) declaration; a redeclaration
12616 // (particularly an out-of-class definition) will typically lack the
12617 // 'explicit' specifier.
12618 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12619 FunctionDecl *First = Fn->getFirstDecl();
12620 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12621 First = Pattern->getFirstDecl();
12622
12623 S.Diag(Loc: First->getLocation(),
12624 DiagID: diag::note_ovl_candidate_explicit)
12625 << Kind << (ES.getExpr() ? 1 : 0)
12626 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12627}
12628
12629static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12630 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12631 if (!DG)
12632 return;
12633 TemplateDecl *OriginTemplate =
12634 DG->getDeclName().getCXXDeductionGuideTemplate();
12635 // We want to always print synthesized deduction guides for type aliases.
12636 // They would retain the explicit bit of the corresponding constructor.
12637 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12638 return;
12639 std::string FunctionProto;
12640 llvm::raw_string_ostream OS(FunctionProto);
12641 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12642 if (!Template) {
12643 // This also could be an instantiation. Find out the primary template.
12644 FunctionDecl *Pattern =
12645 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12646 if (!Pattern) {
12647 // The implicit deduction guide is built on an explicit non-template
12648 // deduction guide. Currently, this might be the case only for type
12649 // aliases.
12650 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12651 // gets merged.
12652 assert(OriginTemplate->isTypeAlias() &&
12653 "Non-template implicit deduction guides are only possible for "
12654 "type aliases");
12655 DG->print(Out&: OS);
12656 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12657 << FunctionProto;
12658 return;
12659 }
12660 Template = Pattern->getDescribedFunctionTemplate();
12661 assert(Template && "Cannot find the associated function template of "
12662 "CXXDeductionGuideDecl?");
12663 }
12664 Template->print(Out&: OS);
12665 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12666 << FunctionProto;
12667}
12668
12669/// Generates a 'note' diagnostic for an overload candidate. We've
12670/// already generated a primary error at the call site.
12671///
12672/// It really does need to be a single diagnostic with its caret
12673/// pointed at the candidate declaration. Yes, this creates some
12674/// major challenges of technical writing. Yes, this makes pointing
12675/// out problems with specific arguments quite awkward. It's still
12676/// better than generating twenty screens of text for every failed
12677/// overload.
12678///
12679/// It would be great to be able to express per-candidate problems
12680/// more richly for those diagnostic clients that cared, but we'd
12681/// still have to be just as careful with the default diagnostics.
12682/// \param CtorDestAS Addr space of object being constructed (for ctor
12683/// candidates only).
12684static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12685 unsigned NumArgs,
12686 bool TakingCandidateAddress,
12687 LangAS CtorDestAS = LangAS::Default) {
12688 assert(Cand->Function && "Candidate must be a function");
12689 FunctionDecl *Fn = Cand->Function;
12690 if (shouldSkipNotingLambdaConversionDecl(Fn))
12691 return;
12692
12693 // There is no physical candidate declaration to point to for OpenCL builtins.
12694 // Except for failed conversions, the notes are identical for each candidate,
12695 // so do not generate such notes.
12696 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12697 Cand->FailureKind != ovl_fail_bad_conversion)
12698 return;
12699
12700 // Skip implicit member functions when trying to resolve
12701 // the address of a an overload set for a function pointer.
12702 if (Cand->TookAddressOfOverload &&
12703 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12704 return;
12705
12706 // Note deleted candidates, but only if they're viable.
12707 if (Cand->Viable) {
12708 if (Fn->isDeleted()) {
12709 std::string FnDesc;
12710 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12711 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12712 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12713
12714 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12715 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12716 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12717 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12718 return;
12719 }
12720
12721 // We don't really have anything else to say about viable candidates.
12722 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12723 return;
12724 }
12725
12726 // If this is a synthesized deduction guide we're deducing against, add a note
12727 // for it. These deduction guides are not explicitly spelled in the source
12728 // code, so simply printing a deduction failure note mentioning synthesized
12729 // template parameters or pointing to the header of the surrounding RecordDecl
12730 // would be confusing.
12731 //
12732 // We prefer adding such notes at the end of the deduction failure because
12733 // duplicate code snippets appearing in the diagnostic would likely become
12734 // noisy.
12735 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12736
12737 switch (Cand->FailureKind) {
12738 case ovl_fail_too_many_arguments:
12739 case ovl_fail_too_few_arguments:
12740 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12741
12742 case ovl_fail_bad_deduction:
12743 return DiagnoseBadDeduction(S, Cand, NumArgs,
12744 TakingCandidateAddress);
12745
12746 case ovl_fail_illegal_constructor: {
12747 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12748 << (Fn->getPrimaryTemplate() ? 1 : 0);
12749 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12750 return;
12751 }
12752
12753 case ovl_fail_object_addrspace_mismatch: {
12754 Qualifiers QualsForPrinting;
12755 QualsForPrinting.setAddressSpace(CtorDestAS);
12756 S.Diag(Loc: Fn->getLocation(),
12757 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12758 << QualsForPrinting;
12759 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12760 return;
12761 }
12762
12763 case ovl_fail_trivial_conversion:
12764 case ovl_fail_bad_final_conversion:
12765 case ovl_fail_final_conversion_not_exact:
12766 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12767
12768 case ovl_fail_bad_conversion: {
12769 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12770 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12771 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12772 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12773
12774 // FIXME: this currently happens when we're called from SemaInit
12775 // when user-conversion overload fails. Figure out how to handle
12776 // those conditions and diagnose them well.
12777 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12778 }
12779
12780 case ovl_fail_bad_target:
12781 return DiagnoseBadTarget(S, Cand);
12782
12783 case ovl_fail_enable_if:
12784 return DiagnoseFailedEnableIfAttr(S, Cand);
12785
12786 case ovl_fail_explicit:
12787 return DiagnoseFailedExplicitSpec(S, Cand);
12788
12789 case ovl_fail_inhctor_slice:
12790 // It's generally not interesting to note copy/move constructors here.
12791 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12792 return;
12793 S.Diag(Loc: Fn->getLocation(),
12794 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12795 << (Fn->getPrimaryTemplate() ? 1 : 0)
12796 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12797 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12798 return;
12799
12800 case ovl_fail_addr_not_available: {
12801 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12802 (void)Available;
12803 assert(!Available);
12804 break;
12805 }
12806 case ovl_non_default_multiversion_function:
12807 // Do nothing, these should simply be ignored.
12808 break;
12809
12810 case ovl_fail_constraints_not_satisfied: {
12811 std::string FnDesc;
12812 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12813 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12814 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12815
12816 S.Diag(Loc: Fn->getLocation(),
12817 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12818 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12819 << FnDesc /* Ignored */;
12820 ConstraintSatisfaction Satisfaction;
12821 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
12822 /*ForOverloadResolution=*/true))
12823 break;
12824 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12825 }
12826 }
12827}
12828
12829static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12830 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12831 return;
12832
12833 // Desugar the type of the surrogate down to a function type,
12834 // retaining as many typedefs as possible while still showing
12835 // the function type (and, therefore, its parameter types).
12836 QualType FnType = Cand->Surrogate->getConversionType();
12837 bool isLValueReference = false;
12838 bool isRValueReference = false;
12839 bool isPointer = false;
12840 if (const LValueReferenceType *FnTypeRef =
12841 FnType->getAs<LValueReferenceType>()) {
12842 FnType = FnTypeRef->getPointeeType();
12843 isLValueReference = true;
12844 } else if (const RValueReferenceType *FnTypeRef =
12845 FnType->getAs<RValueReferenceType>()) {
12846 FnType = FnTypeRef->getPointeeType();
12847 isRValueReference = true;
12848 }
12849 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12850 FnType = FnTypePtr->getPointeeType();
12851 isPointer = true;
12852 }
12853 // Desugar down to a function type.
12854 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12855 // Reconstruct the pointer/reference as appropriate.
12856 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12857 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12858 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12859
12860 if (!Cand->Viable &&
12861 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12862 S.Diag(Loc: Cand->Surrogate->getLocation(),
12863 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
12864 << Cand->Surrogate;
12865 ConstraintSatisfaction Satisfaction;
12866 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
12867 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12868 } else {
12869 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
12870 << FnType;
12871 }
12872}
12873
12874static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12875 SourceLocation OpLoc,
12876 OverloadCandidate *Cand) {
12877 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12878 std::string TypeStr("operator");
12879 TypeStr += Opc;
12880 TypeStr += "(";
12881 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12882 if (Cand->Conversions.size() == 1) {
12883 TypeStr += ")";
12884 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12885 } else {
12886 TypeStr += ", ";
12887 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12888 TypeStr += ")";
12889 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12890 }
12891}
12892
12893static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12894 OverloadCandidate *Cand) {
12895 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12896 if (ICS.isBad()) break; // all meaningless after first invalid
12897 if (!ICS.isAmbiguous()) continue;
12898
12899 ICS.DiagnoseAmbiguousConversion(
12900 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
12901 }
12902}
12903
12904static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12905 if (Cand->Function)
12906 return Cand->Function->getLocation();
12907 if (Cand->IsSurrogate)
12908 return Cand->Surrogate->getLocation();
12909 return SourceLocation();
12910}
12911
12912static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12913 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12914 case TemplateDeductionResult::Success:
12915 case TemplateDeductionResult::NonDependentConversionFailure:
12916 case TemplateDeductionResult::AlreadyDiagnosed:
12917 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12918
12919 case TemplateDeductionResult::Invalid:
12920 case TemplateDeductionResult::Incomplete:
12921 case TemplateDeductionResult::IncompletePack:
12922 return 1;
12923
12924 case TemplateDeductionResult::Underqualified:
12925 case TemplateDeductionResult::Inconsistent:
12926 return 2;
12927
12928 case TemplateDeductionResult::SubstitutionFailure:
12929 case TemplateDeductionResult::DeducedMismatch:
12930 case TemplateDeductionResult::ConstraintsNotSatisfied:
12931 case TemplateDeductionResult::DeducedMismatchNested:
12932 case TemplateDeductionResult::NonDeducedMismatch:
12933 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12934 case TemplateDeductionResult::CUDATargetMismatch:
12935 return 3;
12936
12937 case TemplateDeductionResult::InstantiationDepth:
12938 return 4;
12939
12940 case TemplateDeductionResult::InvalidExplicitArguments:
12941 return 5;
12942
12943 case TemplateDeductionResult::TooManyArguments:
12944 case TemplateDeductionResult::TooFewArguments:
12945 return 6;
12946 }
12947 llvm_unreachable("Unhandled deduction result");
12948}
12949
12950namespace {
12951
12952struct CompareOverloadCandidatesForDisplay {
12953 Sema &S;
12954 SourceLocation Loc;
12955 size_t NumArgs;
12956 OverloadCandidateSet::CandidateSetKind CSK;
12957
12958 CompareOverloadCandidatesForDisplay(
12959 Sema &S, SourceLocation Loc, size_t NArgs,
12960 OverloadCandidateSet::CandidateSetKind CSK)
12961 : S(S), NumArgs(NArgs), CSK(CSK) {}
12962
12963 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12964 // If there are too many or too few arguments, that's the high-order bit we
12965 // want to sort by, even if the immediate failure kind was something else.
12966 if (C->FailureKind == ovl_fail_too_many_arguments ||
12967 C->FailureKind == ovl_fail_too_few_arguments)
12968 return static_cast<OverloadFailureKind>(C->FailureKind);
12969
12970 if (C->Function) {
12971 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12972 return ovl_fail_too_many_arguments;
12973 if (NumArgs < C->Function->getMinRequiredArguments())
12974 return ovl_fail_too_few_arguments;
12975 }
12976
12977 return static_cast<OverloadFailureKind>(C->FailureKind);
12978 }
12979
12980 bool operator()(const OverloadCandidate *L,
12981 const OverloadCandidate *R) {
12982 // Fast-path this check.
12983 if (L == R) return false;
12984
12985 // Order first by viability.
12986 if (L->Viable) {
12987 if (!R->Viable) return true;
12988
12989 if (int Ord = CompareConversions(L: *L, R: *R))
12990 return Ord < 0;
12991 // Use other tie breakers.
12992 } else if (R->Viable)
12993 return false;
12994
12995 assert(L->Viable == R->Viable);
12996
12997 // Criteria by which we can sort non-viable candidates:
12998 if (!L->Viable) {
12999 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13000 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13001
13002 // 1. Arity mismatches come after other candidates.
13003 if (LFailureKind == ovl_fail_too_many_arguments ||
13004 LFailureKind == ovl_fail_too_few_arguments) {
13005 if (RFailureKind == ovl_fail_too_many_arguments ||
13006 RFailureKind == ovl_fail_too_few_arguments) {
13007 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13008 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13009 if (LDist == RDist) {
13010 if (LFailureKind == RFailureKind)
13011 // Sort non-surrogates before surrogates.
13012 return !L->IsSurrogate && R->IsSurrogate;
13013 // Sort candidates requiring fewer parameters than there were
13014 // arguments given after candidates requiring more parameters
13015 // than there were arguments given.
13016 return LFailureKind == ovl_fail_too_many_arguments;
13017 }
13018 return LDist < RDist;
13019 }
13020 return false;
13021 }
13022 if (RFailureKind == ovl_fail_too_many_arguments ||
13023 RFailureKind == ovl_fail_too_few_arguments)
13024 return true;
13025
13026 // 2. Bad conversions come first and are ordered by the number
13027 // of bad conversions and quality of good conversions.
13028 if (LFailureKind == ovl_fail_bad_conversion) {
13029 if (RFailureKind != ovl_fail_bad_conversion)
13030 return true;
13031
13032 // The conversion that can be fixed with a smaller number of changes,
13033 // comes first.
13034 unsigned numLFixes = L->Fix.NumConversionsFixed;
13035 unsigned numRFixes = R->Fix.NumConversionsFixed;
13036 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13037 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13038 if (numLFixes != numRFixes) {
13039 return numLFixes < numRFixes;
13040 }
13041
13042 // If there's any ordering between the defined conversions...
13043 if (int Ord = CompareConversions(L: *L, R: *R))
13044 return Ord < 0;
13045 } else if (RFailureKind == ovl_fail_bad_conversion)
13046 return false;
13047
13048 if (LFailureKind == ovl_fail_bad_deduction) {
13049 if (RFailureKind != ovl_fail_bad_deduction)
13050 return true;
13051
13052 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13053 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13054 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13055 if (LRank != RRank)
13056 return LRank < RRank;
13057 }
13058 } else if (RFailureKind == ovl_fail_bad_deduction)
13059 return false;
13060
13061 // TODO: others?
13062 }
13063
13064 // Sort everything else by location.
13065 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13066 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13067
13068 // Put candidates without locations (e.g. builtins) at the end.
13069 if (LLoc.isValid() && RLoc.isValid())
13070 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13071 if (LLoc.isValid() && !RLoc.isValid())
13072 return true;
13073 if (RLoc.isValid() && !LLoc.isValid())
13074 return false;
13075 assert(!LLoc.isValid() && !RLoc.isValid());
13076 // For builtins and other functions without locations, fallback to the order
13077 // in which they were added into the candidate set.
13078 return L < R;
13079 }
13080
13081private:
13082 struct ConversionSignals {
13083 unsigned KindRank = 0;
13084 ImplicitConversionRank Rank = ICR_Exact_Match;
13085
13086 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13087 ConversionSignals Sig;
13088 Sig.KindRank = Seq.getKindRank();
13089 if (Seq.isStandard())
13090 Sig.Rank = Seq.Standard.getRank();
13091 else if (Seq.isUserDefined())
13092 Sig.Rank = Seq.UserDefined.After.getRank();
13093 // We intend StaticObjectArgumentConversion to compare the same as
13094 // StandardConversion with ICR_ExactMatch rank.
13095 return Sig;
13096 }
13097
13098 static ConversionSignals ForObjectArgument() {
13099 // We intend StaticObjectArgumentConversion to compare the same as
13100 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13101 return {};
13102 }
13103 };
13104
13105 // Returns -1 if conversions in L are considered better.
13106 // 0 if they are considered indistinguishable.
13107 // 1 if conversions in R are better.
13108 int CompareConversions(const OverloadCandidate &L,
13109 const OverloadCandidate &R) {
13110 // We cannot use `isBetterOverloadCandidate` because it is defined
13111 // according to the C++ standard and provides a partial order, but we need
13112 // a total order as this function is used in sort.
13113 assert(L.Conversions.size() == R.Conversions.size());
13114 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13115 auto LS = L.IgnoreObjectArgument && I == 0
13116 ? ConversionSignals::ForObjectArgument()
13117 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13118 auto RS = R.IgnoreObjectArgument
13119 ? ConversionSignals::ForObjectArgument()
13120 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13121 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13122 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13123 ? -1
13124 : 1;
13125 }
13126 // FIXME: find a way to compare templates for being more or less
13127 // specialized that provides a strict weak ordering.
13128 return 0;
13129 }
13130};
13131}
13132
13133/// CompleteNonViableCandidate - Normally, overload resolution only
13134/// computes up to the first bad conversion. Produces the FixIt set if
13135/// possible.
13136static void
13137CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13138 ArrayRef<Expr *> Args,
13139 OverloadCandidateSet::CandidateSetKind CSK) {
13140 assert(!Cand->Viable);
13141
13142 // Don't do anything on failures other than bad conversion.
13143 if (Cand->FailureKind != ovl_fail_bad_conversion)
13144 return;
13145
13146 // We only want the FixIts if all the arguments can be corrected.
13147 bool Unfixable = false;
13148 // Use a implicit copy initialization to check conversion fixes.
13149 Cand->Fix.setConversionChecker(TryCopyInitialization);
13150
13151 // Attempt to fix the bad conversion.
13152 unsigned ConvCount = Cand->Conversions.size();
13153 for (unsigned ConvIdx =
13154 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13155 : 0);
13156 /**/; ++ConvIdx) {
13157 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13158 if (Cand->Conversions[ConvIdx].isInitialized() &&
13159 Cand->Conversions[ConvIdx].isBad()) {
13160 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13161 break;
13162 }
13163 }
13164
13165 // FIXME: this should probably be preserved from the overload
13166 // operation somehow.
13167 bool SuppressUserConversions = false;
13168
13169 unsigned ConvIdx = 0;
13170 unsigned ArgIdx = 0;
13171 ArrayRef<QualType> ParamTypes;
13172 bool Reversed = Cand->isReversed();
13173
13174 if (Cand->IsSurrogate) {
13175 QualType ConvType
13176 = Cand->Surrogate->getConversionType().getNonReferenceType();
13177 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13178 ConvType = ConvPtrType->getPointeeType();
13179 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13180 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13181 ConvIdx = 1;
13182 } else if (Cand->Function) {
13183 ParamTypes =
13184 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13185 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13186 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13187 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13188 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13189 ConvIdx = 1;
13190 if (CSK == OverloadCandidateSet::CSK_Operator &&
13191 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13192 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13193 OO_Subscript)
13194 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13195 ArgIdx = 1;
13196 }
13197 } else {
13198 // Builtin operator.
13199 assert(ConvCount <= 3);
13200 ParamTypes = Cand->BuiltinParamTypes;
13201 }
13202
13203 // Fill in the rest of the conversions.
13204 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13205 ConvIdx != ConvCount && ArgIdx < Args.size();
13206 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13207 if (Cand->Conversions[ConvIdx].isInitialized()) {
13208 // We've already checked this conversion.
13209 } else if (ParamIdx < ParamTypes.size()) {
13210 if (ParamTypes[ParamIdx]->isDependentType())
13211 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13212 Args[ArgIdx]->getType());
13213 else {
13214 Cand->Conversions[ConvIdx] =
13215 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13216 SuppressUserConversions,
13217 /*InOverloadResolution=*/true,
13218 /*AllowObjCWritebackConversion=*/
13219 S.getLangOpts().ObjCAutoRefCount);
13220 // Store the FixIt in the candidate if it exists.
13221 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13222 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13223 }
13224 } else
13225 Cand->Conversions[ConvIdx].setEllipsis();
13226 }
13227}
13228
13229SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13230 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13231 SourceLocation OpLoc,
13232 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13233
13234 InjectNonDeducedTemplateCandidates(S);
13235
13236 // Sort the candidates by viability and position. Sorting directly would
13237 // be prohibitive, so we make a set of pointers and sort those.
13238 SmallVector<OverloadCandidate*, 32> Cands;
13239 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13240 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13241 Cand != LastCand; ++Cand) {
13242 if (!Filter(*Cand))
13243 continue;
13244 switch (OCD) {
13245 case OCD_AllCandidates:
13246 if (!Cand->Viable) {
13247 if (!Cand->Function && !Cand->IsSurrogate) {
13248 // This a non-viable builtin candidate. We do not, in general,
13249 // want to list every possible builtin candidate.
13250 continue;
13251 }
13252 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13253 }
13254 break;
13255
13256 case OCD_ViableCandidates:
13257 if (!Cand->Viable)
13258 continue;
13259 break;
13260
13261 case OCD_AmbiguousCandidates:
13262 if (!Cand->Best)
13263 continue;
13264 break;
13265 }
13266
13267 Cands.push_back(Elt: Cand);
13268 }
13269
13270 llvm::stable_sort(
13271 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13272
13273 return Cands;
13274}
13275
13276bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13277 SourceLocation OpLoc) {
13278 bool DeferHint = false;
13279 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13280 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13281 // host device candidates.
13282 auto WrongSidedCands =
13283 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13284 return (Cand.Viable == false &&
13285 Cand.FailureKind == ovl_fail_bad_target) ||
13286 (Cand.Function &&
13287 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13288 Cand.Function->template hasAttr<CUDADeviceAttr>());
13289 });
13290 DeferHint = !WrongSidedCands.empty();
13291 }
13292 return DeferHint;
13293}
13294
13295/// When overload resolution fails, prints diagnostic messages containing the
13296/// candidates in the candidate set.
13297void OverloadCandidateSet::NoteCandidates(
13298 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13299 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13300 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13301
13302 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13303
13304 {
13305 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13306 S.Diag(Loc: PD.first, PD: PD.second);
13307 }
13308
13309 // In WebAssembly we don't want to emit further diagnostics if a table is
13310 // passed as an argument to a function.
13311 bool NoteCands = true;
13312 for (const Expr *Arg : Args) {
13313 if (Arg->getType()->isWebAssemblyTableType())
13314 NoteCands = false;
13315 }
13316
13317 if (NoteCands)
13318 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13319
13320 if (OCD == OCD_AmbiguousCandidates)
13321 MaybeDiagnoseAmbiguousConstraints(S,
13322 Cands: {Candidates.begin(), Candidates.end()});
13323}
13324
13325void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13326 ArrayRef<OverloadCandidate *> Cands,
13327 StringRef Opc, SourceLocation OpLoc) {
13328 bool ReportedAmbiguousConversions = false;
13329
13330 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13331 unsigned CandsShown = 0;
13332 auto I = Cands.begin(), E = Cands.end();
13333 for (; I != E; ++I) {
13334 OverloadCandidate *Cand = *I;
13335
13336 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13337 ShowOverloads == Ovl_Best) {
13338 break;
13339 }
13340 ++CandsShown;
13341
13342 if (Cand->Function)
13343 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13344 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13345 else if (Cand->IsSurrogate)
13346 NoteSurrogateCandidate(S, Cand);
13347 else {
13348 assert(Cand->Viable &&
13349 "Non-viable built-in candidates are not added to Cands.");
13350 // Generally we only see ambiguities including viable builtin
13351 // operators if overload resolution got screwed up by an
13352 // ambiguous user-defined conversion.
13353 //
13354 // FIXME: It's quite possible for different conversions to see
13355 // different ambiguities, though.
13356 if (!ReportedAmbiguousConversions) {
13357 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13358 ReportedAmbiguousConversions = true;
13359 }
13360
13361 // If this is a viable builtin, print it.
13362 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13363 }
13364 }
13365
13366 // Inform S.Diags that we've shown an overload set with N elements. This may
13367 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13368 S.Diags.overloadCandidatesShown(N: CandsShown);
13369
13370 if (I != E) {
13371 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13372 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13373 }
13374}
13375
13376static SourceLocation
13377GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13378 return Cand->Specialization ? Cand->Specialization->getLocation()
13379 : SourceLocation();
13380}
13381
13382namespace {
13383struct CompareTemplateSpecCandidatesForDisplay {
13384 Sema &S;
13385 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13386
13387 bool operator()(const TemplateSpecCandidate *L,
13388 const TemplateSpecCandidate *R) {
13389 // Fast-path this check.
13390 if (L == R)
13391 return false;
13392
13393 // Assuming that both candidates are not matches...
13394
13395 // Sort by the ranking of deduction failures.
13396 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13397 return RankDeductionFailure(DFI: L->DeductionFailure) <
13398 RankDeductionFailure(DFI: R->DeductionFailure);
13399
13400 // Sort everything else by location.
13401 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13402 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13403
13404 // Put candidates without locations (e.g. builtins) at the end.
13405 if (LLoc.isInvalid())
13406 return false;
13407 if (RLoc.isInvalid())
13408 return true;
13409
13410 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13411 }
13412};
13413}
13414
13415/// Diagnose a template argument deduction failure.
13416/// We are treating these failures as overload failures due to bad
13417/// deductions.
13418void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13419 bool ForTakingAddress) {
13420 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13421 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13422}
13423
13424void TemplateSpecCandidateSet::destroyCandidates() {
13425 for (iterator i = begin(), e = end(); i != e; ++i) {
13426 i->DeductionFailure.Destroy();
13427 }
13428}
13429
13430void TemplateSpecCandidateSet::clear() {
13431 destroyCandidates();
13432 Candidates.clear();
13433}
13434
13435/// NoteCandidates - When no template specialization match is found, prints
13436/// diagnostic messages containing the non-matching specializations that form
13437/// the candidate set.
13438/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13439/// OCD == OCD_AllCandidates and Cand->Viable == false.
13440void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13441 // Sort the candidates by position (assuming no candidate is a match).
13442 // Sorting directly would be prohibitive, so we make a set of pointers
13443 // and sort those.
13444 SmallVector<TemplateSpecCandidate *, 32> Cands;
13445 Cands.reserve(N: size());
13446 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13447 if (Cand->Specialization)
13448 Cands.push_back(Elt: Cand);
13449 // Otherwise, this is a non-matching builtin candidate. We do not,
13450 // in general, want to list every possible builtin candidate.
13451 }
13452
13453 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13454
13455 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13456 // for generalization purposes (?).
13457 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13458
13459 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13460 unsigned CandsShown = 0;
13461 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13462 TemplateSpecCandidate *Cand = *I;
13463
13464 // Set an arbitrary limit on the number of candidates we'll spam
13465 // the user with. FIXME: This limit should depend on details of the
13466 // candidate list.
13467 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13468 break;
13469 ++CandsShown;
13470
13471 assert(Cand->Specialization &&
13472 "Non-matching built-in candidates are not added to Cands.");
13473 Cand->NoteDeductionFailure(S, ForTakingAddress);
13474 }
13475
13476 if (I != E)
13477 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13478}
13479
13480// [PossiblyAFunctionType] --> [Return]
13481// NonFunctionType --> NonFunctionType
13482// R (A) --> R(A)
13483// R (*)(A) --> R (A)
13484// R (&)(A) --> R (A)
13485// R (S::*)(A) --> R (A)
13486QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13487 QualType Ret = PossiblyAFunctionType;
13488 if (const PointerType *ToTypePtr =
13489 PossiblyAFunctionType->getAs<PointerType>())
13490 Ret = ToTypePtr->getPointeeType();
13491 else if (const ReferenceType *ToTypeRef =
13492 PossiblyAFunctionType->getAs<ReferenceType>())
13493 Ret = ToTypeRef->getPointeeType();
13494 else if (const MemberPointerType *MemTypePtr =
13495 PossiblyAFunctionType->getAs<MemberPointerType>())
13496 Ret = MemTypePtr->getPointeeType();
13497 Ret =
13498 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13499 return Ret;
13500}
13501
13502static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13503 bool Complain = true) {
13504 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13505 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13506 return true;
13507
13508 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13509 if (S.getLangOpts().CPlusPlus17 &&
13510 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13511 !S.ResolveExceptionSpec(Loc, FPT))
13512 return true;
13513
13514 return false;
13515}
13516
13517namespace {
13518// A helper class to help with address of function resolution
13519// - allows us to avoid passing around all those ugly parameters
13520class AddressOfFunctionResolver {
13521 Sema& S;
13522 Expr* SourceExpr;
13523 const QualType& TargetType;
13524 QualType TargetFunctionType; // Extracted function type from target type
13525
13526 bool Complain;
13527 //DeclAccessPair& ResultFunctionAccessPair;
13528 ASTContext& Context;
13529
13530 bool TargetTypeIsNonStaticMemberFunction;
13531 bool FoundNonTemplateFunction;
13532 bool StaticMemberFunctionFromBoundPointer;
13533 bool HasComplained;
13534
13535 OverloadExpr::FindResult OvlExprInfo;
13536 OverloadExpr *OvlExpr;
13537 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13538 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13539 TemplateSpecCandidateSet FailedCandidates;
13540
13541public:
13542 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13543 const QualType &TargetType, bool Complain)
13544 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13545 Complain(Complain), Context(S.getASTContext()),
13546 TargetTypeIsNonStaticMemberFunction(
13547 !!TargetType->getAs<MemberPointerType>()),
13548 FoundNonTemplateFunction(false),
13549 StaticMemberFunctionFromBoundPointer(false),
13550 HasComplained(false),
13551 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13552 OvlExpr(OvlExprInfo.Expression),
13553 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13554 ExtractUnqualifiedFunctionTypeFromTargetType();
13555
13556 if (TargetFunctionType->isFunctionType()) {
13557 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13558 if (!UME->isImplicitAccess() &&
13559 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13560 StaticMemberFunctionFromBoundPointer = true;
13561 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13562 DeclAccessPair dap;
13563 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13564 ovl: OvlExpr, Complain: false, Found: &dap)) {
13565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13566 if (!Method->isStatic()) {
13567 // If the target type is a non-function type and the function found
13568 // is a non-static member function, pretend as if that was the
13569 // target, it's the only possible type to end up with.
13570 TargetTypeIsNonStaticMemberFunction = true;
13571
13572 // And skip adding the function if its not in the proper form.
13573 // We'll diagnose this due to an empty set of functions.
13574 if (!OvlExprInfo.HasFormOfMemberPointer)
13575 return;
13576 }
13577
13578 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13579 }
13580 return;
13581 }
13582
13583 if (OvlExpr->hasExplicitTemplateArgs())
13584 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13585
13586 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13587 // C++ [over.over]p4:
13588 // If more than one function is selected, [...]
13589 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13590 if (FoundNonTemplateFunction) {
13591 EliminateAllTemplateMatches();
13592 EliminateLessPartialOrderingConstrainedMatches();
13593 } else
13594 EliminateAllExceptMostSpecializedTemplate();
13595 }
13596 }
13597
13598 if (S.getLangOpts().CUDA && Matches.size() > 1)
13599 EliminateSuboptimalCudaMatches();
13600 }
13601
13602 bool hasComplained() const { return HasComplained; }
13603
13604private:
13605 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13606 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13607 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13608 }
13609
13610 /// \return true if A is considered a better overload candidate for the
13611 /// desired type than B.
13612 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13613 // If A doesn't have exactly the correct type, we don't want to classify it
13614 // as "better" than anything else. This way, the user is required to
13615 // disambiguate for us if there are multiple candidates and no exact match.
13616 return candidateHasExactlyCorrectType(FD: A) &&
13617 (!candidateHasExactlyCorrectType(FD: B) ||
13618 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13619 }
13620
13621 /// \return true if we were able to eliminate all but one overload candidate,
13622 /// false otherwise.
13623 bool eliminiateSuboptimalOverloadCandidates() {
13624 // Same algorithm as overload resolution -- one pass to pick the "best",
13625 // another pass to be sure that nothing is better than the best.
13626 auto Best = Matches.begin();
13627 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13628 if (isBetterCandidate(A: I->second, B: Best->second))
13629 Best = I;
13630
13631 const FunctionDecl *BestFn = Best->second;
13632 auto IsBestOrInferiorToBest = [this, BestFn](
13633 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13634 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13635 };
13636
13637 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13638 // option, so we can potentially give the user a better error
13639 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13640 return false;
13641 Matches[0] = *Best;
13642 Matches.resize(N: 1);
13643 return true;
13644 }
13645
13646 bool isTargetTypeAFunction() const {
13647 return TargetFunctionType->isFunctionType();
13648 }
13649
13650 // [ToType] [Return]
13651
13652 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13653 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13654 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13655 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13656 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13657 }
13658
13659 // return true if any matching specializations were found
13660 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13661 const DeclAccessPair& CurAccessFunPair) {
13662 if (CXXMethodDecl *Method
13663 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13664 // Skip non-static function templates when converting to pointer, and
13665 // static when converting to member pointer.
13666 bool CanConvertToFunctionPointer =
13667 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13668 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13669 return false;
13670 }
13671 else if (TargetTypeIsNonStaticMemberFunction)
13672 return false;
13673
13674 // C++ [over.over]p2:
13675 // If the name is a function template, template argument deduction is
13676 // done (14.8.2.2), and if the argument deduction succeeds, the
13677 // resulting template argument list is used to generate a single
13678 // function template specialization, which is added to the set of
13679 // overloaded functions considered.
13680 FunctionDecl *Specialization = nullptr;
13681 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13682 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13683 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13684 Specialization, Info, /*IsAddressOfFunction*/ true);
13685 Result != TemplateDeductionResult::Success) {
13686 // Make a note of the failed deduction for diagnostics.
13687 FailedCandidates.addCandidate()
13688 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13689 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13690 return false;
13691 }
13692
13693 // Template argument deduction ensures that we have an exact match or
13694 // compatible pointer-to-function arguments that would be adjusted by ICS.
13695 // This function template specicalization works.
13696 assert(S.isSameOrCompatibleFunctionType(
13697 Context.getCanonicalType(Specialization->getType()),
13698 Context.getCanonicalType(TargetFunctionType)));
13699
13700 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13701 return false;
13702
13703 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13704 return true;
13705 }
13706
13707 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13708 const DeclAccessPair& CurAccessFunPair) {
13709 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13710 // Skip non-static functions when converting to pointer, and static
13711 // when converting to member pointer.
13712 bool CanConvertToFunctionPointer =
13713 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13714 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13715 return false;
13716 }
13717 else if (TargetTypeIsNonStaticMemberFunction)
13718 return false;
13719
13720 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13721 if (S.getLangOpts().CUDA) {
13722 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13723 if (!(Caller && Caller->isImplicit()) &&
13724 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13725 return false;
13726 }
13727 if (FunDecl->isMultiVersion()) {
13728 const auto *TA = FunDecl->getAttr<TargetAttr>();
13729 if (TA && !TA->isDefaultVersion())
13730 return false;
13731 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13732 if (TVA && !TVA->isDefaultVersion())
13733 return false;
13734 }
13735
13736 // If any candidate has a placeholder return type, trigger its deduction
13737 // now.
13738 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13739 Complain)) {
13740 HasComplained |= Complain;
13741 return false;
13742 }
13743
13744 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13745 return false;
13746
13747 // If we're in C, we need to support types that aren't exactly identical.
13748 if (!S.getLangOpts().CPlusPlus ||
13749 candidateHasExactlyCorrectType(FD: FunDecl)) {
13750 Matches.push_back(Elt: std::make_pair(
13751 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13752 FoundNonTemplateFunction = true;
13753 return true;
13754 }
13755 }
13756
13757 return false;
13758 }
13759
13760 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13761 bool Ret = false;
13762
13763 // If the overload expression doesn't have the form of a pointer to
13764 // member, don't try to convert it to a pointer-to-member type.
13765 if (IsInvalidFormOfPointerToMemberFunction())
13766 return false;
13767
13768 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13769 E = OvlExpr->decls_end();
13770 I != E; ++I) {
13771 // Look through any using declarations to find the underlying function.
13772 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13773
13774 // C++ [over.over]p3:
13775 // Non-member functions and static member functions match
13776 // targets of type "pointer-to-function" or "reference-to-function."
13777 // Nonstatic member functions match targets of
13778 // type "pointer-to-member-function."
13779 // Note that according to DR 247, the containing class does not matter.
13780 if (FunctionTemplateDecl *FunctionTemplate
13781 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13782 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13783 Ret = true;
13784 }
13785 // If we have explicit template arguments supplied, skip non-templates.
13786 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13787 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13788 Ret = true;
13789 }
13790 assert(Ret || Matches.empty());
13791 return Ret;
13792 }
13793
13794 void EliminateAllExceptMostSpecializedTemplate() {
13795 // [...] and any given function template specialization F1 is
13796 // eliminated if the set contains a second function template
13797 // specialization whose function template is more specialized
13798 // than the function template of F1 according to the partial
13799 // ordering rules of 14.5.5.2.
13800
13801 // The algorithm specified above is quadratic. We instead use a
13802 // two-pass algorithm (similar to the one used to identify the
13803 // best viable function in an overload set) that identifies the
13804 // best function template (if it exists).
13805
13806 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13807 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13808 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13809
13810 // TODO: It looks like FailedCandidates does not serve much purpose
13811 // here, since the no_viable diagnostic has index 0.
13812 UnresolvedSetIterator Result = S.getMostSpecialized(
13813 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
13814 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
13815 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
13816 << Matches[0].second->getDeclName(),
13817 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
13818 << (unsigned)oc_function << (unsigned)ocs_described_template,
13819 Complain, TargetType: TargetFunctionType);
13820
13821 if (Result != MatchesCopy.end()) {
13822 // Make it the first and only element
13823 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13824 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13825 Matches.resize(N: 1);
13826 } else
13827 HasComplained |= Complain;
13828 }
13829
13830 void EliminateAllTemplateMatches() {
13831 // [...] any function template specializations in the set are
13832 // eliminated if the set also contains a non-template function, [...]
13833 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13834 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13835 ++I;
13836 else {
13837 Matches[I] = Matches[--N];
13838 Matches.resize(N);
13839 }
13840 }
13841 }
13842
13843 void EliminateLessPartialOrderingConstrainedMatches() {
13844 // C++ [over.over]p5:
13845 // [...] Any given non-template function F0 is eliminated if the set
13846 // contains a second non-template function that is more
13847 // partial-ordering-constrained than F0. [...]
13848 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13849 "Call EliminateAllTemplateMatches() first");
13850 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13851 Results.push_back(Elt: Matches[0]);
13852 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13853 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13854 FunctionDecl *F = getMorePartialOrderingConstrained(
13855 S, Fn1: Matches[I].second, Fn2: Results[0].second,
13856 /*IsFn1Reversed=*/false,
13857 /*IsFn2Reversed=*/false);
13858 if (!F) {
13859 Results.push_back(Elt: Matches[I]);
13860 continue;
13861 }
13862 if (F == Matches[I].second) {
13863 Results.clear();
13864 Results.push_back(Elt: Matches[I]);
13865 }
13866 }
13867 std::swap(LHS&: Matches, RHS&: Results);
13868 }
13869
13870 void EliminateSuboptimalCudaMatches() {
13871 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
13872 Matches);
13873 }
13874
13875public:
13876 void ComplainNoMatchesFound() const {
13877 assert(Matches.empty());
13878 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
13879 << OvlExpr->getName() << TargetFunctionType
13880 << OvlExpr->getSourceRange();
13881 if (FailedCandidates.empty())
13882 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13883 /*TakingAddress=*/true);
13884 else {
13885 // We have some deduction failure messages. Use them to diagnose
13886 // the function templates, and diagnose the non-template candidates
13887 // normally.
13888 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13889 IEnd = OvlExpr->decls_end();
13890 I != IEnd; ++I)
13891 if (FunctionDecl *Fun =
13892 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
13893 if (!functionHasPassObjectSizeParams(FD: Fun))
13894 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
13895 /*TakingAddress=*/true);
13896 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
13897 }
13898 }
13899
13900 bool IsInvalidFormOfPointerToMemberFunction() const {
13901 return TargetTypeIsNonStaticMemberFunction &&
13902 !OvlExprInfo.HasFormOfMemberPointer;
13903 }
13904
13905 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13906 // TODO: Should we condition this on whether any functions might
13907 // have matched, or is it more appropriate to do that in callers?
13908 // TODO: a fixit wouldn't hurt.
13909 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
13910 << TargetType << OvlExpr->getSourceRange();
13911 }
13912
13913 bool IsStaticMemberFunctionFromBoundPointer() const {
13914 return StaticMemberFunctionFromBoundPointer;
13915 }
13916
13917 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13918 S.Diag(Loc: OvlExpr->getBeginLoc(),
13919 DiagID: diag::err_invalid_form_pointer_member_function)
13920 << OvlExpr->getSourceRange();
13921 }
13922
13923 void ComplainOfInvalidConversion() const {
13924 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
13925 << OvlExpr->getName() << TargetType;
13926 }
13927
13928 void ComplainMultipleMatchesFound() const {
13929 assert(Matches.size() > 1);
13930 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
13931 << OvlExpr->getName() << OvlExpr->getSourceRange();
13932 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13933 /*TakingAddress=*/true);
13934 }
13935
13936 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13937
13938 int getNumMatches() const { return Matches.size(); }
13939
13940 FunctionDecl* getMatchingFunctionDecl() const {
13941 if (Matches.size() != 1) return nullptr;
13942 return Matches[0].second;
13943 }
13944
13945 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13946 if (Matches.size() != 1) return nullptr;
13947 return &Matches[0].first;
13948 }
13949};
13950}
13951
13952FunctionDecl *
13953Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13954 QualType TargetType,
13955 bool Complain,
13956 DeclAccessPair &FoundResult,
13957 bool *pHadMultipleCandidates) {
13958 assert(AddressOfExpr->getType() == Context.OverloadTy);
13959
13960 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13961 Complain);
13962 int NumMatches = Resolver.getNumMatches();
13963 FunctionDecl *Fn = nullptr;
13964 bool ShouldComplain = Complain && !Resolver.hasComplained();
13965 if (NumMatches == 0 && ShouldComplain) {
13966 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13967 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13968 else
13969 Resolver.ComplainNoMatchesFound();
13970 }
13971 else if (NumMatches > 1 && ShouldComplain)
13972 Resolver.ComplainMultipleMatchesFound();
13973 else if (NumMatches == 1) {
13974 Fn = Resolver.getMatchingFunctionDecl();
13975 assert(Fn);
13976 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13977 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
13978 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13979 if (Complain) {
13980 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13981 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13982 else
13983 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
13984 }
13985 }
13986
13987 if (pHadMultipleCandidates)
13988 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13989 return Fn;
13990}
13991
13992FunctionDecl *
13993Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13994 OverloadExpr::FindResult R = OverloadExpr::find(E);
13995 OverloadExpr *Ovl = R.Expression;
13996 bool IsResultAmbiguous = false;
13997 FunctionDecl *Result = nullptr;
13998 DeclAccessPair DAP;
13999 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14000
14001 // Return positive for better, negative for worse, 0 for equal preference.
14002 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14003 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14004 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14005 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14006 };
14007
14008 // Don't use the AddressOfResolver because we're specifically looking for
14009 // cases where we have one overload candidate that lacks
14010 // enable_if/pass_object_size/...
14011 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14012 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14013 if (!FD)
14014 return nullptr;
14015
14016 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14017 continue;
14018
14019 // If we found a better result, update Result.
14020 auto FoundBetter = [&]() {
14021 IsResultAmbiguous = false;
14022 DAP = I.getPair();
14023 Result = FD;
14024 };
14025
14026 // We have more than one result - see if it is more
14027 // partial-ordering-constrained than the previous one.
14028 if (Result) {
14029 // Check CUDA preference first. If the candidates have differennt CUDA
14030 // preference, choose the one with higher CUDA preference. Otherwise,
14031 // choose the one with more constraints.
14032 if (getLangOpts().CUDA) {
14033 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14034 // FD has different preference than Result.
14035 if (PreferenceByCUDA != 0) {
14036 // FD is more preferable than Result.
14037 if (PreferenceByCUDA > 0)
14038 FoundBetter();
14039 continue;
14040 }
14041 }
14042 // FD has the same CUDA preference than Result. Continue to check
14043 // constraints.
14044
14045 // C++ [over.over]p5:
14046 // [...] Any given non-template function F0 is eliminated if the set
14047 // contains a second non-template function that is more
14048 // partial-ordering-constrained than F0 [...]
14049 FunctionDecl *MoreConstrained =
14050 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14051 /*IsFn1Reversed=*/false,
14052 /*IsFn2Reversed=*/false);
14053 if (MoreConstrained != FD) {
14054 if (!MoreConstrained) {
14055 IsResultAmbiguous = true;
14056 AmbiguousDecls.push_back(Elt: FD);
14057 }
14058 continue;
14059 }
14060 // FD is more constrained - replace Result with it.
14061 }
14062 FoundBetter();
14063 }
14064
14065 if (IsResultAmbiguous)
14066 return nullptr;
14067
14068 if (Result) {
14069 // We skipped over some ambiguous declarations which might be ambiguous with
14070 // the selected result.
14071 for (FunctionDecl *Skipped : AmbiguousDecls) {
14072 // If skipped candidate has different CUDA preference than the result,
14073 // there is no ambiguity. Otherwise check whether they have different
14074 // constraints.
14075 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14076 continue;
14077 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14078 return nullptr;
14079 }
14080 Pair = DAP;
14081 }
14082 return Result;
14083}
14084
14085bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14086 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14087 Expr *E = SrcExpr.get();
14088 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14089
14090 DeclAccessPair DAP;
14091 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14092 if (!Found || Found->isCPUDispatchMultiVersion() ||
14093 Found->isCPUSpecificMultiVersion())
14094 return false;
14095
14096 // Emitting multiple diagnostics for a function that is both inaccessible and
14097 // unavailable is consistent with our behavior elsewhere. So, always check
14098 // for both.
14099 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14100 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14101 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14102 if (Res.isInvalid())
14103 return false;
14104 Expr *Fixed = Res.get();
14105 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14106 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14107 else
14108 SrcExpr = Fixed;
14109 return true;
14110}
14111
14112FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14113 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14114 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14115 // C++ [over.over]p1:
14116 // [...] [Note: any redundant set of parentheses surrounding the
14117 // overloaded function name is ignored (5.1). ]
14118 // C++ [over.over]p1:
14119 // [...] The overloaded function name can be preceded by the &
14120 // operator.
14121
14122 // If we didn't actually find any template-ids, we're done.
14123 if (!ovl->hasExplicitTemplateArgs())
14124 return nullptr;
14125
14126 TemplateArgumentListInfo ExplicitTemplateArgs;
14127 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14128
14129 // Look through all of the overloaded functions, searching for one
14130 // whose type matches exactly.
14131 FunctionDecl *Matched = nullptr;
14132 for (UnresolvedSetIterator I = ovl->decls_begin(),
14133 E = ovl->decls_end(); I != E; ++I) {
14134 // C++0x [temp.arg.explicit]p3:
14135 // [...] In contexts where deduction is done and fails, or in contexts
14136 // where deduction is not done, if a template argument list is
14137 // specified and it, along with any default template arguments,
14138 // identifies a single function template specialization, then the
14139 // template-id is an lvalue for the function template specialization.
14140 FunctionTemplateDecl *FunctionTemplate =
14141 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14142 if (!FunctionTemplate)
14143 continue;
14144
14145 // C++ [over.over]p2:
14146 // If the name is a function template, template argument deduction is
14147 // done (14.8.2.2), and if the argument deduction succeeds, the
14148 // resulting template argument list is used to generate a single
14149 // function template specialization, which is added to the set of
14150 // overloaded functions considered.
14151 FunctionDecl *Specialization = nullptr;
14152 TemplateDeductionInfo Info(ovl->getNameLoc());
14153 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14154 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14155 /*IsAddressOfFunction*/ true);
14156 Result != TemplateDeductionResult::Success) {
14157 // Make a note of the failed deduction for diagnostics.
14158 if (FailedTSC)
14159 FailedTSC->addCandidate().set(
14160 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14161 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14162 continue;
14163 }
14164
14165 assert(Specialization && "no specialization and no error?");
14166
14167 // C++ [temp.deduct.call]p6:
14168 // [...] If all successful deductions yield the same deduced A, that
14169 // deduced A is the result of deduction; otherwise, the parameter is
14170 // treated as a non-deduced context.
14171 if (Matched) {
14172 if (ForTypeDeduction &&
14173 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14174 Arg: Specialization->getType()))
14175 continue;
14176 // Multiple matches; we can't resolve to a single declaration.
14177 if (Complain) {
14178 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14179 << ovl->getName();
14180 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14181 }
14182 return nullptr;
14183 }
14184
14185 Matched = Specialization;
14186 if (FoundResult) *FoundResult = I.getPair();
14187 }
14188
14189 if (Matched &&
14190 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14191 return nullptr;
14192
14193 return Matched;
14194}
14195
14196bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14197 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14198 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14199 unsigned DiagIDForComplaining) {
14200 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14201
14202 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14203
14204 DeclAccessPair found;
14205 ExprResult SingleFunctionExpression;
14206 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14207 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14208 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14209 SrcExpr = ExprError();
14210 return true;
14211 }
14212
14213 // It is only correct to resolve to an instance method if we're
14214 // resolving a form that's permitted to be a pointer to member.
14215 // Otherwise we'll end up making a bound member expression, which
14216 // is illegal in all the contexts we resolve like this.
14217 if (!ovl.HasFormOfMemberPointer &&
14218 isa<CXXMethodDecl>(Val: fn) &&
14219 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14220 if (!complain) return false;
14221
14222 Diag(Loc: ovl.Expression->getExprLoc(),
14223 DiagID: diag::err_bound_member_function)
14224 << 0 << ovl.Expression->getSourceRange();
14225
14226 // TODO: I believe we only end up here if there's a mix of
14227 // static and non-static candidates (otherwise the expression
14228 // would have 'bound member' type, not 'overload' type).
14229 // Ideally we would note which candidate was chosen and why
14230 // the static candidates were rejected.
14231 SrcExpr = ExprError();
14232 return true;
14233 }
14234
14235 // Fix the expression to refer to 'fn'.
14236 SingleFunctionExpression =
14237 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14238
14239 // If desired, do function-to-pointer decay.
14240 if (doFunctionPointerConversion) {
14241 SingleFunctionExpression =
14242 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14243 if (SingleFunctionExpression.isInvalid()) {
14244 SrcExpr = ExprError();
14245 return true;
14246 }
14247 }
14248 }
14249
14250 if (!SingleFunctionExpression.isUsable()) {
14251 if (complain) {
14252 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14253 << ovl.Expression->getName()
14254 << DestTypeForComplaining
14255 << OpRangeForComplaining
14256 << ovl.Expression->getQualifierLoc().getSourceRange();
14257 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14258
14259 SrcExpr = ExprError();
14260 return true;
14261 }
14262
14263 return false;
14264 }
14265
14266 SrcExpr = SingleFunctionExpression;
14267 return true;
14268}
14269
14270/// Add a single candidate to the overload set.
14271static void AddOverloadedCallCandidate(Sema &S,
14272 DeclAccessPair FoundDecl,
14273 TemplateArgumentListInfo *ExplicitTemplateArgs,
14274 ArrayRef<Expr *> Args,
14275 OverloadCandidateSet &CandidateSet,
14276 bool PartialOverloading,
14277 bool KnownValid) {
14278 NamedDecl *Callee = FoundDecl.getDecl();
14279 if (isa<UsingShadowDecl>(Val: Callee))
14280 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14281
14282 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14283 if (ExplicitTemplateArgs) {
14284 assert(!KnownValid && "Explicit template arguments?");
14285 return;
14286 }
14287 // Prevent ill-formed function decls to be added as overload candidates.
14288 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14289 return;
14290
14291 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14292 /*SuppressUserConversions=*/false,
14293 PartialOverloading);
14294 return;
14295 }
14296
14297 if (FunctionTemplateDecl *FuncTemplate
14298 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14299 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14300 ExplicitTemplateArgs, Args, CandidateSet,
14301 /*SuppressUserConversions=*/false,
14302 PartialOverloading);
14303 return;
14304 }
14305
14306 assert(!KnownValid && "unhandled case in overloaded call candidate");
14307}
14308
14309void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14310 ArrayRef<Expr *> Args,
14311 OverloadCandidateSet &CandidateSet,
14312 bool PartialOverloading) {
14313
14314#ifndef NDEBUG
14315 // Verify that ArgumentDependentLookup is consistent with the rules
14316 // in C++0x [basic.lookup.argdep]p3:
14317 //
14318 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14319 // and let Y be the lookup set produced by argument dependent
14320 // lookup (defined as follows). If X contains
14321 //
14322 // -- a declaration of a class member, or
14323 //
14324 // -- a block-scope function declaration that is not a
14325 // using-declaration, or
14326 //
14327 // -- a declaration that is neither a function or a function
14328 // template
14329 //
14330 // then Y is empty.
14331
14332 if (ULE->requiresADL()) {
14333 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14334 E = ULE->decls_end(); I != E; ++I) {
14335 assert(!(*I)->getDeclContext()->isRecord());
14336 assert(isa<UsingShadowDecl>(*I) ||
14337 !(*I)->getDeclContext()->isFunctionOrMethod());
14338 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14339 }
14340 }
14341#endif
14342
14343 // It would be nice to avoid this copy.
14344 TemplateArgumentListInfo TABuffer;
14345 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14346 if (ULE->hasExplicitTemplateArgs()) {
14347 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14348 ExplicitTemplateArgs = &TABuffer;
14349 }
14350
14351 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14352 E = ULE->decls_end(); I != E; ++I)
14353 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14354 CandidateSet, PartialOverloading,
14355 /*KnownValid*/ true);
14356
14357 if (ULE->requiresADL())
14358 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14359 Args, ExplicitTemplateArgs,
14360 CandidateSet, PartialOverloading);
14361}
14362
14363void Sema::AddOverloadedCallCandidates(
14364 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14365 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14366 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14367 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14368 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14369}
14370
14371/// Determine whether a declaration with the specified name could be moved into
14372/// a different namespace.
14373static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14374 switch (Name.getCXXOverloadedOperator()) {
14375 case OO_New: case OO_Array_New:
14376 case OO_Delete: case OO_Array_Delete:
14377 return false;
14378
14379 default:
14380 return true;
14381 }
14382}
14383
14384/// Attempt to recover from an ill-formed use of a non-dependent name in a
14385/// template, where the non-dependent name was declared after the template
14386/// was defined. This is common in code written for a compilers which do not
14387/// correctly implement two-stage name lookup.
14388///
14389/// Returns true if a viable candidate was found and a diagnostic was issued.
14390static bool DiagnoseTwoPhaseLookup(
14391 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14392 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14393 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14394 CXXRecordDecl **FoundInClass = nullptr) {
14395 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14396 return false;
14397
14398 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14399 if (DC->isTransparentContext())
14400 continue;
14401
14402 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14403
14404 if (!R.empty()) {
14405 R.suppressDiagnostics();
14406
14407 OverloadCandidateSet Candidates(FnLoc, CSK);
14408 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14409 CandidateSet&: Candidates);
14410
14411 OverloadCandidateSet::iterator Best;
14412 OverloadingResult OR =
14413 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14414
14415 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14416 // We either found non-function declarations or a best viable function
14417 // at class scope. A class-scope lookup result disables ADL. Don't
14418 // look past this, but let the caller know that we found something that
14419 // either is, or might be, usable in this class.
14420 if (FoundInClass) {
14421 *FoundInClass = RD;
14422 if (OR == OR_Success) {
14423 R.clear();
14424 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14425 R.resolveKind();
14426 }
14427 }
14428 return false;
14429 }
14430
14431 if (OR != OR_Success) {
14432 // There wasn't a unique best function or function template.
14433 return false;
14434 }
14435
14436 // Find the namespaces where ADL would have looked, and suggest
14437 // declaring the function there instead.
14438 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14439 Sema::AssociatedClassSet AssociatedClasses;
14440 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14441 AssociatedNamespaces,
14442 AssociatedClasses);
14443 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14444 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14445 DeclContext *Std = SemaRef.getStdNamespace();
14446 for (Sema::AssociatedNamespaceSet::iterator
14447 it = AssociatedNamespaces.begin(),
14448 end = AssociatedNamespaces.end(); it != end; ++it) {
14449 // Never suggest declaring a function within namespace 'std'.
14450 if (Std && Std->Encloses(DC: *it))
14451 continue;
14452
14453 // Never suggest declaring a function within a namespace with a
14454 // reserved name, like __gnu_cxx.
14455 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14456 if (NS &&
14457 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14458 continue;
14459
14460 SuggestedNamespaces.insert(X: *it);
14461 }
14462 }
14463
14464 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14465 << R.getLookupName();
14466 if (SuggestedNamespaces.empty()) {
14467 SemaRef.Diag(Loc: Best->Function->getLocation(),
14468 DiagID: diag::note_not_found_by_two_phase_lookup)
14469 << R.getLookupName() << 0;
14470 } else if (SuggestedNamespaces.size() == 1) {
14471 SemaRef.Diag(Loc: Best->Function->getLocation(),
14472 DiagID: diag::note_not_found_by_two_phase_lookup)
14473 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14474 } else {
14475 // FIXME: It would be useful to list the associated namespaces here,
14476 // but the diagnostics infrastructure doesn't provide a way to produce
14477 // a localized representation of a list of items.
14478 SemaRef.Diag(Loc: Best->Function->getLocation(),
14479 DiagID: diag::note_not_found_by_two_phase_lookup)
14480 << R.getLookupName() << 2;
14481 }
14482
14483 // Try to recover by calling this function.
14484 return true;
14485 }
14486
14487 R.clear();
14488 }
14489
14490 return false;
14491}
14492
14493/// Attempt to recover from ill-formed use of a non-dependent operator in a
14494/// template, where the non-dependent operator was declared after the template
14495/// was defined.
14496///
14497/// Returns true if a viable candidate was found and a diagnostic was issued.
14498static bool
14499DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14500 SourceLocation OpLoc,
14501 ArrayRef<Expr *> Args) {
14502 DeclarationName OpName =
14503 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14504 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14505 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14506 CSK: OverloadCandidateSet::CSK_Operator,
14507 /*ExplicitTemplateArgs=*/nullptr, Args);
14508}
14509
14510namespace {
14511class BuildRecoveryCallExprRAII {
14512 Sema &SemaRef;
14513 Sema::SatisfactionStackResetRAII SatStack;
14514
14515public:
14516 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14517 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14518 SemaRef.IsBuildingRecoveryCallExpr = true;
14519 }
14520
14521 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14522};
14523}
14524
14525/// Attempts to recover from a call where no functions were found.
14526///
14527/// This function will do one of three things:
14528/// * Diagnose, recover, and return a recovery expression.
14529/// * Diagnose, fail to recover, and return ExprError().
14530/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14531/// expected to diagnose as appropriate.
14532static ExprResult
14533BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14534 UnresolvedLookupExpr *ULE,
14535 SourceLocation LParenLoc,
14536 MutableArrayRef<Expr *> Args,
14537 SourceLocation RParenLoc,
14538 bool EmptyLookup, bool AllowTypoCorrection) {
14539 // Do not try to recover if it is already building a recovery call.
14540 // This stops infinite loops for template instantiations like
14541 //
14542 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14543 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14544 if (SemaRef.IsBuildingRecoveryCallExpr)
14545 return ExprResult();
14546 BuildRecoveryCallExprRAII RCE(SemaRef);
14547
14548 CXXScopeSpec SS;
14549 SS.Adopt(Other: ULE->getQualifierLoc());
14550 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14551
14552 TemplateArgumentListInfo TABuffer;
14553 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14554 if (ULE->hasExplicitTemplateArgs()) {
14555 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14556 ExplicitTemplateArgs = &TABuffer;
14557 }
14558
14559 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14560 Sema::LookupOrdinaryName);
14561 CXXRecordDecl *FoundInClass = nullptr;
14562 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14563 CSK: OverloadCandidateSet::CSK_Normal,
14564 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14565 // OK, diagnosed a two-phase lookup issue.
14566 } else if (EmptyLookup) {
14567 // Try to recover from an empty lookup with typo correction.
14568 R.clear();
14569 NoTypoCorrectionCCC NoTypoValidator{};
14570 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14571 ExplicitTemplateArgs != nullptr,
14572 dyn_cast<MemberExpr>(Val: Fn));
14573 CorrectionCandidateCallback &Validator =
14574 AllowTypoCorrection
14575 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14576 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14577 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14578 Args))
14579 return ExprError();
14580 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14581 // We found a usable declaration of the name in a dependent base of some
14582 // enclosing class.
14583 // FIXME: We should also explain why the candidates found by name lookup
14584 // were not viable.
14585 if (SemaRef.DiagnoseDependentMemberLookup(R))
14586 return ExprError();
14587 } else {
14588 // We had viable candidates and couldn't recover; let the caller diagnose
14589 // this.
14590 return ExprResult();
14591 }
14592
14593 // If we get here, we should have issued a diagnostic and formed a recovery
14594 // lookup result.
14595 assert(!R.empty() && "lookup results empty despite recovery");
14596
14597 // If recovery created an ambiguity, just bail out.
14598 if (R.isAmbiguous()) {
14599 R.suppressDiagnostics();
14600 return ExprError();
14601 }
14602
14603 // Build an implicit member call if appropriate. Just drop the
14604 // casts and such from the call, we don't really care.
14605 ExprResult NewFn = ExprError();
14606 if ((*R.begin())->isCXXClassMember())
14607 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14608 TemplateArgs: ExplicitTemplateArgs, S);
14609 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14610 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14611 TemplateArgs: ExplicitTemplateArgs);
14612 else
14613 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14614
14615 if (NewFn.isInvalid())
14616 return ExprError();
14617
14618 // This shouldn't cause an infinite loop because we're giving it
14619 // an expression with viable lookup results, which should never
14620 // end up here.
14621 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14622 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14623 RParenLoc);
14624}
14625
14626bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14627 UnresolvedLookupExpr *ULE,
14628 MultiExprArg Args,
14629 SourceLocation RParenLoc,
14630 OverloadCandidateSet *CandidateSet,
14631 ExprResult *Result) {
14632#ifndef NDEBUG
14633 if (ULE->requiresADL()) {
14634 // To do ADL, we must have found an unqualified name.
14635 assert(!ULE->getQualifier() && "qualified name with ADL");
14636
14637 // We don't perform ADL for implicit declarations of builtins.
14638 // Verify that this was correctly set up.
14639 FunctionDecl *F;
14640 if (ULE->decls_begin() != ULE->decls_end() &&
14641 ULE->decls_begin() + 1 == ULE->decls_end() &&
14642 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14643 F->getBuiltinID() && F->isImplicit())
14644 llvm_unreachable("performing ADL for builtin");
14645
14646 // We don't perform ADL in C.
14647 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14648 }
14649#endif
14650
14651 UnbridgedCastsSet UnbridgedCasts;
14652 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14653 *Result = ExprError();
14654 return true;
14655 }
14656
14657 // Add the functions denoted by the callee to the set of candidate
14658 // functions, including those from argument-dependent lookup.
14659 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14660
14661 if (getLangOpts().MSVCCompat &&
14662 CurContext->isDependentContext() && !isSFINAEContext() &&
14663 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14664
14665 OverloadCandidateSet::iterator Best;
14666 if (CandidateSet->empty() ||
14667 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14668 OR_No_Viable_Function) {
14669 // In Microsoft mode, if we are inside a template class member function
14670 // then create a type dependent CallExpr. The goal is to postpone name
14671 // lookup to instantiation time to be able to search into type dependent
14672 // base classes.
14673 CallExpr *CE =
14674 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14675 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14676 CE->markDependentForPostponedNameLookup();
14677 *Result = CE;
14678 return true;
14679 }
14680 }
14681
14682 if (CandidateSet->empty())
14683 return false;
14684
14685 UnbridgedCasts.restore();
14686 return false;
14687}
14688
14689// Guess at what the return type for an unresolvable overload should be.
14690static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14691 OverloadCandidateSet::iterator *Best) {
14692 std::optional<QualType> Result;
14693 // Adjust Type after seeing a candidate.
14694 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14695 if (!Candidate.Function)
14696 return;
14697 if (Candidate.Function->isInvalidDecl())
14698 return;
14699 QualType T = Candidate.Function->getReturnType();
14700 if (T.isNull())
14701 return;
14702 if (!Result)
14703 Result = T;
14704 else if (Result != T)
14705 Result = QualType();
14706 };
14707
14708 // Look for an unambiguous type from a progressively larger subset.
14709 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14710 //
14711 // First, consider only the best candidate.
14712 if (Best && *Best != CS.end())
14713 ConsiderCandidate(**Best);
14714 // Next, consider only viable candidates.
14715 if (!Result)
14716 for (const auto &C : CS)
14717 if (C.Viable)
14718 ConsiderCandidate(C);
14719 // Finally, consider all candidates.
14720 if (!Result)
14721 for (const auto &C : CS)
14722 ConsiderCandidate(C);
14723
14724 if (!Result)
14725 return QualType();
14726 auto Value = *Result;
14727 if (Value.isNull() || Value->isUndeducedType())
14728 return QualType();
14729 return Value;
14730}
14731
14732/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14733/// the completed call expression. If overload resolution fails, emits
14734/// diagnostics and returns ExprError()
14735static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14736 UnresolvedLookupExpr *ULE,
14737 SourceLocation LParenLoc,
14738 MultiExprArg Args,
14739 SourceLocation RParenLoc,
14740 Expr *ExecConfig,
14741 OverloadCandidateSet *CandidateSet,
14742 OverloadCandidateSet::iterator *Best,
14743 OverloadingResult OverloadResult,
14744 bool AllowTypoCorrection) {
14745 switch (OverloadResult) {
14746 case OR_Success: {
14747 FunctionDecl *FDecl = (*Best)->Function;
14748 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14749 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14750 return ExprError();
14751 ExprResult Res =
14752 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14753 if (Res.isInvalid())
14754 return ExprError();
14755 return SemaRef.BuildResolvedCallExpr(
14756 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14757 /*IsExecConfig=*/false,
14758 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14759 }
14760
14761 case OR_No_Viable_Function: {
14762 if (*Best != CandidateSet->end() &&
14763 CandidateSet->getKind() ==
14764 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14765 if (CXXMethodDecl *M =
14766 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14767 M && M->isImplicitObjectMemberFunction()) {
14768 CandidateSet->NoteCandidates(
14769 PD: PartialDiagnosticAt(
14770 Fn->getBeginLoc(),
14771 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14772 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14773 return ExprError();
14774 }
14775 }
14776
14777 // Try to recover by looking for viable functions which the user might
14778 // have meant to call.
14779 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14780 Args, RParenLoc,
14781 EmptyLookup: CandidateSet->empty(),
14782 AllowTypoCorrection);
14783 if (Recovery.isInvalid() || Recovery.isUsable())
14784 return Recovery;
14785
14786 // If the user passes in a function that we can't take the address of, we
14787 // generally end up emitting really bad error messages. Here, we attempt to
14788 // emit better ones.
14789 for (const Expr *Arg : Args) {
14790 if (!Arg->getType()->isFunctionType())
14791 continue;
14792 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14793 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14794 if (FD &&
14795 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14796 Loc: Arg->getExprLoc()))
14797 return ExprError();
14798 }
14799 }
14800
14801 CandidateSet->NoteCandidates(
14802 PD: PartialDiagnosticAt(
14803 Fn->getBeginLoc(),
14804 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
14805 << ULE->getName() << Fn->getSourceRange()),
14806 S&: SemaRef, OCD: OCD_AllCandidates, Args);
14807 break;
14808 }
14809
14810 case OR_Ambiguous:
14811 CandidateSet->NoteCandidates(
14812 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
14813 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
14814 << ULE->getName() << Fn->getSourceRange()),
14815 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14816 break;
14817
14818 case OR_Deleted: {
14819 FunctionDecl *FDecl = (*Best)->Function;
14820 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14821 Range: Fn->getSourceRange(), Name: ULE->getName(),
14822 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14823
14824 // We emitted an error for the unavailable/deleted function call but keep
14825 // the call in the AST.
14826 ExprResult Res =
14827 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14828 if (Res.isInvalid())
14829 return ExprError();
14830 return SemaRef.BuildResolvedCallExpr(
14831 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14832 /*IsExecConfig=*/false,
14833 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14834 }
14835 }
14836
14837 // Overload resolution failed, try to recover.
14838 SmallVector<Expr *, 8> SubExprs = {Fn};
14839 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14840 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14841 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14842}
14843
14844static void markUnaddressableCandidatesUnviable(Sema &S,
14845 OverloadCandidateSet &CS) {
14846 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14847 if (I->Viable &&
14848 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14849 I->Viable = false;
14850 I->FailureKind = ovl_fail_addr_not_available;
14851 }
14852 }
14853}
14854
14855ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14856 UnresolvedLookupExpr *ULE,
14857 SourceLocation LParenLoc,
14858 MultiExprArg Args,
14859 SourceLocation RParenLoc,
14860 Expr *ExecConfig,
14861 bool AllowTypoCorrection,
14862 bool CalleesAddressIsTaken) {
14863
14864 OverloadCandidateSet::CandidateSetKind CSK =
14865 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14866 : OverloadCandidateSet::CSK_Normal;
14867
14868 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14869 ExprResult result;
14870
14871 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
14872 Result: &result))
14873 return result;
14874
14875 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14876 // functions that aren't addressible are considered unviable.
14877 if (CalleesAddressIsTaken)
14878 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
14879
14880 OverloadCandidateSet::iterator Best;
14881 OverloadingResult OverloadResult =
14882 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
14883
14884 // [C++23][over.call.func]
14885 // if overload resolution selects a non-static member function,
14886 // the call is ill-formed;
14887 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
14888 Best != CandidateSet.end()) {
14889 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
14890 M && M->isImplicitObjectMemberFunction()) {
14891 OverloadResult = OR_No_Viable_Function;
14892 }
14893 }
14894
14895 // Model the case with a call to a templated function whose definition
14896 // encloses the call and whose return type contains a placeholder type as if
14897 // the UnresolvedLookupExpr was type-dependent.
14898 if (OverloadResult == OR_Success) {
14899 const FunctionDecl *FDecl = Best->Function;
14900 if (LangOpts.CUDA)
14901 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14902 if (FDecl && FDecl->isTemplateInstantiation() &&
14903 FDecl->getReturnType()->isUndeducedType()) {
14904
14905 // Creating dependent CallExpr is not okay if the enclosing context itself
14906 // is not dependent. This situation notably arises if a non-dependent
14907 // member function calls the later-defined overloaded static function.
14908 //
14909 // For example, in
14910 // class A {
14911 // void c() { callee(1); }
14912 // static auto callee(auto x) { }
14913 // };
14914 //
14915 // Here callee(1) is unresolved at the call site, but is not inside a
14916 // dependent context. There will be no further attempt to resolve this
14917 // call if it is made dependent.
14918
14919 if (const auto *TP =
14920 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14921 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14922 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
14923 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
14924 }
14925 }
14926 }
14927
14928 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14929 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
14930 OverloadResult, AllowTypoCorrection);
14931}
14932
14933ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14934 NestedNameSpecifierLoc NNSLoc,
14935 DeclarationNameInfo DNI,
14936 const UnresolvedSetImpl &Fns,
14937 bool PerformADL) {
14938 return UnresolvedLookupExpr::Create(
14939 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
14940 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14941}
14942
14943ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14944 CXXConversionDecl *Method,
14945 bool HadMultipleCandidates) {
14946 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14947 // the FoundDecl as it impedes TransformMemberExpr.
14948 // We go a bit further here: if there's no difference in UnderlyingDecl,
14949 // then using FoundDecl vs Method shouldn't make a difference either.
14950 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14951 FoundDecl = Method;
14952 // Convert the expression to match the conversion function's implicit object
14953 // parameter.
14954 ExprResult Exp;
14955 if (Method->isExplicitObjectMemberFunction())
14956 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
14957 else
14958 Exp = PerformImplicitObjectArgumentInitialization(
14959 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14960 if (Exp.isInvalid())
14961 return true;
14962
14963 if (Method->getParent()->isLambda() &&
14964 Method->getConversionType()->isBlockPointerType()) {
14965 // This is a lambda conversion to block pointer; check if the argument
14966 // was a LambdaExpr.
14967 Expr *SubE = E;
14968 auto *CE = dyn_cast<CastExpr>(Val: SubE);
14969 if (CE && CE->getCastKind() == CK_NoOp)
14970 SubE = CE->getSubExpr();
14971 SubE = SubE->IgnoreParens();
14972 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
14973 SubE = BE->getSubExpr();
14974 if (isa<LambdaExpr>(Val: SubE)) {
14975 // For the conversion to block pointer on a lambda expression, we
14976 // construct a special BlockLiteral instead; this doesn't really make
14977 // a difference in ARC, but outside of ARC the resulting block literal
14978 // follows the normal lifetime rules for block literals instead of being
14979 // autoreleased.
14980 PushExpressionEvaluationContext(
14981 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
14982 ExprResult BlockExp = BuildBlockForLambdaConversion(
14983 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
14984 PopExpressionEvaluationContext();
14985
14986 // FIXME: This note should be produced by a CodeSynthesisContext.
14987 if (BlockExp.isInvalid())
14988 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
14989 return BlockExp;
14990 }
14991 }
14992 CallExpr *CE;
14993 QualType ResultType = Method->getReturnType();
14994 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
14995 ResultType = ResultType.getNonLValueExprType(Context);
14996 if (Method->isExplicitObjectMemberFunction()) {
14997 ExprResult FnExpr =
14998 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
14999 HadMultipleCandidates, Loc: E->getBeginLoc());
15000 if (FnExpr.isInvalid())
15001 return ExprError();
15002 Expr *ObjectParam = Exp.get();
15003 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15004 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15005 FPFeatures: CurFPFeatureOverrides());
15006 CE->setUsesMemberSyntax(true);
15007 } else {
15008 MemberExpr *ME =
15009 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15010 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15011 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15012 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15013 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15014
15015 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15016 RP: Exp.get()->getEndLoc(),
15017 FPFeatures: CurFPFeatureOverrides());
15018 }
15019
15020 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15021 Proto: Method->getType()->castAs<FunctionProtoType>()))
15022 return ExprError();
15023
15024 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15025}
15026
15027ExprResult
15028Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15029 const UnresolvedSetImpl &Fns,
15030 Expr *Input, bool PerformADL) {
15031 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15032 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15033 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15034 // TODO: provide better source location info.
15035 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15036
15037 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15038 return ExprError();
15039
15040 Expr *Args[2] = { Input, nullptr };
15041 unsigned NumArgs = 1;
15042
15043 // For post-increment and post-decrement, add the implicit '0' as
15044 // the second argument, so that we know this is a post-increment or
15045 // post-decrement.
15046 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15047 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15048 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15049 l: SourceLocation());
15050 NumArgs = 2;
15051 }
15052
15053 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15054
15055 if (Input->isTypeDependent()) {
15056 ExprValueKind VK = ExprValueKind::VK_PRValue;
15057 // [C++26][expr.unary.op][expr.pre.incr]
15058 // The * operator yields an lvalue of type
15059 // The pre/post increment operators yied an lvalue.
15060 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15061 VK = VK_LValue;
15062
15063 if (Fns.empty())
15064 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15065 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15066 FPFeatures: CurFPFeatureOverrides());
15067
15068 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15069 ExprResult Fn = CreateUnresolvedLookupExpr(
15070 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15071 if (Fn.isInvalid())
15072 return ExprError();
15073 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15074 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15075 FPFeatures: CurFPFeatureOverrides());
15076 }
15077
15078 // Build an empty overload set.
15079 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15080
15081 // Add the candidates from the given function set.
15082 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
15083
15084 // Add operator candidates that are member functions.
15085 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15086
15087 // Add candidates from ADL.
15088 if (PerformADL) {
15089 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15090 /*ExplicitTemplateArgs*/nullptr,
15091 CandidateSet);
15092 }
15093
15094 // Add builtin operator candidates.
15095 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15096
15097 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15098
15099 // Perform overload resolution.
15100 OverloadCandidateSet::iterator Best;
15101 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15102 case OR_Success: {
15103 // We found a built-in operator or an overloaded operator.
15104 FunctionDecl *FnDecl = Best->Function;
15105
15106 if (FnDecl) {
15107 Expr *Base = nullptr;
15108 // We matched an overloaded operator. Build a call to that
15109 // operator.
15110
15111 // Convert the arguments.
15112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15113 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15114
15115 ExprResult InputInit;
15116 if (Method->isExplicitObjectMemberFunction())
15117 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15118 else
15119 InputInit = PerformImplicitObjectArgumentInitialization(
15120 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15121 if (InputInit.isInvalid())
15122 return ExprError();
15123 Base = Input = InputInit.get();
15124 } else {
15125 // Convert the arguments.
15126 ExprResult InputInit
15127 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15128 Context,
15129 Parm: FnDecl->getParamDecl(i: 0)),
15130 EqualLoc: SourceLocation(),
15131 Init: Input);
15132 if (InputInit.isInvalid())
15133 return ExprError();
15134 Input = InputInit.get();
15135 }
15136
15137 // Build the actual expression node.
15138 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15139 Base, HadMultipleCandidates,
15140 Loc: OpLoc);
15141 if (FnExpr.isInvalid())
15142 return ExprError();
15143
15144 // Determine the result type.
15145 QualType ResultTy = FnDecl->getReturnType();
15146 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15147 ResultTy = ResultTy.getNonLValueExprType(Context);
15148
15149 Args[0] = Input;
15150 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15151 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15152 FPFeatures: CurFPFeatureOverrides(),
15153 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15154
15155 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15156 return ExprError();
15157
15158 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15159 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15160 return ExprError();
15161 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15162 } else {
15163 // We matched a built-in operator. Convert the arguments, then
15164 // break out so that we will build the appropriate built-in
15165 // operator node.
15166 ExprResult InputRes = PerformImplicitConversion(
15167 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15168 Action: AssignmentAction::Passing,
15169 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15170 if (InputRes.isInvalid())
15171 return ExprError();
15172 Input = InputRes.get();
15173 break;
15174 }
15175 }
15176
15177 case OR_No_Viable_Function:
15178 // This is an erroneous use of an operator which can be overloaded by
15179 // a non-member function. Check for non-member operators which were
15180 // defined too late to be candidates.
15181 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15182 // FIXME: Recover by calling the found function.
15183 return ExprError();
15184
15185 // No viable function; fall through to handling this as a
15186 // built-in operator, which will produce an error message for us.
15187 break;
15188
15189 case OR_Ambiguous:
15190 CandidateSet.NoteCandidates(
15191 PD: PartialDiagnosticAt(OpLoc,
15192 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15193 << UnaryOperator::getOpcodeStr(Op: Opc)
15194 << Input->getType() << Input->getSourceRange()),
15195 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15196 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15197 return ExprError();
15198
15199 case OR_Deleted: {
15200 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15201 // object whose method was called. Later in NoteCandidates size of ArgsArray
15202 // is passed further and it eventually ends up compared to number of
15203 // function candidate parameters which never includes the object parameter,
15204 // so slice ArgsArray to make sure apples are compared to apples.
15205 StringLiteral *Msg = Best->Function->getDeletedMessage();
15206 CandidateSet.NoteCandidates(
15207 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15208 << UnaryOperator::getOpcodeStr(Op: Opc)
15209 << (Msg != nullptr)
15210 << (Msg ? Msg->getString() : StringRef())
15211 << Input->getSourceRange()),
15212 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15213 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15214 return ExprError();
15215 }
15216 }
15217
15218 // Either we found no viable overloaded operator or we matched a
15219 // built-in operator. In either case, fall through to trying to
15220 // build a built-in operation.
15221 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15222}
15223
15224void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15225 OverloadedOperatorKind Op,
15226 const UnresolvedSetImpl &Fns,
15227 ArrayRef<Expr *> Args, bool PerformADL) {
15228 SourceLocation OpLoc = CandidateSet.getLocation();
15229
15230 OverloadedOperatorKind ExtraOp =
15231 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15232 ? getRewrittenOverloadedOperator(Kind: Op)
15233 : OO_None;
15234
15235 // Add the candidates from the given function set. This also adds the
15236 // rewritten candidates using these functions if necessary.
15237 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15238
15239 // As template candidates are not deduced immediately,
15240 // persist the array in the overload set.
15241 ArrayRef<Expr *> ReversedArgs;
15242 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15243 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15244 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15245
15246 // Add operator candidates that are member functions.
15247 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15248 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15249 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15250 PO: OverloadCandidateParamOrder::Reversed);
15251
15252 // In C++20, also add any rewritten member candidates.
15253 if (ExtraOp) {
15254 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15255 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15256 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15257 PO: OverloadCandidateParamOrder::Reversed);
15258 }
15259
15260 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15261 // performed for an assignment operator (nor for operator[] nor operator->,
15262 // which don't get here).
15263 if (Op != OO_Equal && PerformADL) {
15264 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15265 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15266 /*ExplicitTemplateArgs*/ nullptr,
15267 CandidateSet);
15268 if (ExtraOp) {
15269 DeclarationName ExtraOpName =
15270 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15271 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15272 /*ExplicitTemplateArgs*/ nullptr,
15273 CandidateSet);
15274 }
15275 }
15276
15277 // Add builtin operator candidates.
15278 //
15279 // FIXME: We don't add any rewritten candidates here. This is strictly
15280 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15281 // resulting in our selecting a rewritten builtin candidate. For example:
15282 //
15283 // enum class E { e };
15284 // bool operator!=(E, E) requires false;
15285 // bool k = E::e != E::e;
15286 //
15287 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15288 // it seems unreasonable to consider rewritten builtin candidates. A core
15289 // issue has been filed proposing to removed this requirement.
15290 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15291}
15292
15293ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15294 BinaryOperatorKind Opc,
15295 const UnresolvedSetImpl &Fns, Expr *LHS,
15296 Expr *RHS, bool PerformADL,
15297 bool AllowRewrittenCandidates,
15298 FunctionDecl *DefaultedFn) {
15299 Expr *Args[2] = { LHS, RHS };
15300 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15301
15302 if (!getLangOpts().CPlusPlus20)
15303 AllowRewrittenCandidates = false;
15304
15305 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15306
15307 // If either side is type-dependent, create an appropriate dependent
15308 // expression.
15309 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15310 if (Fns.empty()) {
15311 // If there are no functions to store, just build a dependent
15312 // BinaryOperator or CompoundAssignment.
15313 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15314 return CompoundAssignOperator::Create(
15315 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15316 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15317 CompResultType: Context.DependentTy);
15318 return BinaryOperator::Create(
15319 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15320 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15321 }
15322
15323 // FIXME: save results of ADL from here?
15324 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15325 // TODO: provide better source location info in DNLoc component.
15326 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15327 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15328 ExprResult Fn = CreateUnresolvedLookupExpr(
15329 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15330 if (Fn.isInvalid())
15331 return ExprError();
15332 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15333 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15334 FPFeatures: CurFPFeatureOverrides());
15335 }
15336
15337 // If this is the .* operator, which is not overloadable, just
15338 // create a built-in binary operator.
15339 if (Opc == BO_PtrMemD) {
15340 auto CheckPlaceholder = [&](Expr *&Arg) {
15341 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15342 if (Res.isUsable())
15343 Arg = Res.get();
15344 return !Res.isUsable();
15345 };
15346
15347 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15348 // expression that contains placeholders (in either the LHS or RHS).
15349 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15350 return ExprError();
15351 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15352 }
15353
15354 // Always do placeholder-like conversions on the RHS.
15355 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15356 return ExprError();
15357
15358 // Do placeholder-like conversion on the LHS; note that we should
15359 // not get here with a PseudoObject LHS.
15360 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15361 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15362 return ExprError();
15363
15364 // If this is the assignment operator, we only perform overload resolution
15365 // if the left-hand side is a class or enumeration type. This is actually
15366 // a hack. The standard requires that we do overload resolution between the
15367 // various built-in candidates, but as DR507 points out, this can lead to
15368 // problems. So we do it this way, which pretty much follows what GCC does.
15369 // Note that we go the traditional code path for compound assignment forms.
15370 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15371 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15372
15373 // Build the overload set.
15374 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15375 OverloadCandidateSet::OperatorRewriteInfo(
15376 Op, OpLoc, AllowRewrittenCandidates));
15377 if (DefaultedFn)
15378 CandidateSet.exclude(F: DefaultedFn);
15379 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15380
15381 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15382
15383 // Perform overload resolution.
15384 OverloadCandidateSet::iterator Best;
15385 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15386 case OR_Success: {
15387 // We found a built-in operator or an overloaded operator.
15388 FunctionDecl *FnDecl = Best->Function;
15389
15390 bool IsReversed = Best->isReversed();
15391 if (IsReversed)
15392 std::swap(a&: Args[0], b&: Args[1]);
15393
15394 if (FnDecl) {
15395
15396 if (FnDecl->isInvalidDecl())
15397 return ExprError();
15398
15399 Expr *Base = nullptr;
15400 // We matched an overloaded operator. Build a call to that
15401 // operator.
15402
15403 OverloadedOperatorKind ChosenOp =
15404 FnDecl->getDeclName().getCXXOverloadedOperator();
15405
15406 // C++2a [over.match.oper]p9:
15407 // If a rewritten operator== candidate is selected by overload
15408 // resolution for an operator@, its return type shall be cv bool
15409 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15410 !FnDecl->getReturnType()->isBooleanType()) {
15411 bool IsExtension =
15412 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15413 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15414 : diag::err_ovl_rewrite_equalequal_not_bool)
15415 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15416 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15417 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15418 if (!IsExtension)
15419 return ExprError();
15420 }
15421
15422 if (AllowRewrittenCandidates && !IsReversed &&
15423 CandidateSet.getRewriteInfo().isReversible()) {
15424 // We could have reversed this operator, but didn't. Check if some
15425 // reversed form was a viable candidate, and if so, if it had a
15426 // better conversion for either parameter. If so, this call is
15427 // formally ambiguous, and allowing it is an extension.
15428 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15429 for (OverloadCandidate &Cand : CandidateSet) {
15430 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15431 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15432 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15433 if (CompareImplicitConversionSequences(
15434 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15435 ICS2: Best->Conversions[ArgIdx]) ==
15436 ImplicitConversionSequence::Better) {
15437 AmbiguousWith.push_back(Elt: Cand.Function);
15438 break;
15439 }
15440 }
15441 }
15442 }
15443
15444 if (!AmbiguousWith.empty()) {
15445 bool AmbiguousWithSelf =
15446 AmbiguousWith.size() == 1 &&
15447 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15448 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15449 << BinaryOperator::getOpcodeStr(Op: Opc)
15450 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15451 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15452 if (AmbiguousWithSelf) {
15453 Diag(Loc: FnDecl->getLocation(),
15454 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15455 // Mark member== const or provide matching != to disallow reversed
15456 // args. Eg.
15457 // struct S { bool operator==(const S&); };
15458 // S()==S();
15459 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15460 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15461 !MD->isConst() &&
15462 !MD->hasCXXExplicitFunctionObjectParameter() &&
15463 Context.hasSameUnqualifiedType(
15464 T1: MD->getFunctionObjectParameterType(),
15465 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15466 Context.hasSameUnqualifiedType(
15467 T1: MD->getFunctionObjectParameterType(),
15468 T2: Args[0]->getType()) &&
15469 Context.hasSameUnqualifiedType(
15470 T1: MD->getFunctionObjectParameterType(),
15471 T2: Args[1]->getType()))
15472 Diag(Loc: FnDecl->getLocation(),
15473 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15474 } else {
15475 Diag(Loc: FnDecl->getLocation(),
15476 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15477 for (auto *F : AmbiguousWith)
15478 Diag(Loc: F->getLocation(),
15479 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15480 }
15481 }
15482 }
15483
15484 // Check for nonnull = nullable.
15485 // This won't be caught in the arg's initialization: the parameter to
15486 // the assignment operator is not marked nonnull.
15487 if (Op == OO_Equal)
15488 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15489 SrcType: Args[1]->getType(), Loc: OpLoc);
15490
15491 // Convert the arguments.
15492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15493 // Best->Access is only meaningful for class members.
15494 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15495
15496 ExprResult Arg0, Arg1;
15497 unsigned ParamIdx = 0;
15498 if (Method->isExplicitObjectMemberFunction()) {
15499 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15500 ParamIdx = 1;
15501 } else {
15502 Arg0 = PerformImplicitObjectArgumentInitialization(
15503 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15504 }
15505 Arg1 = PerformCopyInitialization(
15506 Entity: InitializedEntity::InitializeParameter(
15507 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15508 EqualLoc: SourceLocation(), Init: Args[1]);
15509 if (Arg0.isInvalid() || Arg1.isInvalid())
15510 return ExprError();
15511
15512 Base = Args[0] = Arg0.getAs<Expr>();
15513 Args[1] = RHS = Arg1.getAs<Expr>();
15514 } else {
15515 // Convert the arguments.
15516 ExprResult Arg0 = PerformCopyInitialization(
15517 Entity: InitializedEntity::InitializeParameter(Context,
15518 Parm: FnDecl->getParamDecl(i: 0)),
15519 EqualLoc: SourceLocation(), Init: Args[0]);
15520 if (Arg0.isInvalid())
15521 return ExprError();
15522
15523 ExprResult Arg1 =
15524 PerformCopyInitialization(
15525 Entity: InitializedEntity::InitializeParameter(Context,
15526 Parm: FnDecl->getParamDecl(i: 1)),
15527 EqualLoc: SourceLocation(), Init: Args[1]);
15528 if (Arg1.isInvalid())
15529 return ExprError();
15530 Args[0] = LHS = Arg0.getAs<Expr>();
15531 Args[1] = RHS = Arg1.getAs<Expr>();
15532 }
15533
15534 // Build the actual expression node.
15535 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15536 FoundDecl: Best->FoundDecl, Base,
15537 HadMultipleCandidates, Loc: OpLoc);
15538 if (FnExpr.isInvalid())
15539 return ExprError();
15540
15541 // Determine the result type.
15542 QualType ResultTy = FnDecl->getReturnType();
15543 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15544 ResultTy = ResultTy.getNonLValueExprType(Context);
15545
15546 CallExpr *TheCall;
15547 ArrayRef<const Expr *> ArgsArray(Args, 2);
15548 const Expr *ImplicitThis = nullptr;
15549
15550 // We always create a CXXOperatorCallExpr, even for explicit object
15551 // members; CodeGen should take care not to emit the this pointer.
15552 TheCall = CXXOperatorCallExpr::Create(
15553 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15554 FPFeatures: CurFPFeatureOverrides(),
15555 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15556
15557 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15558 Method && Method->isImplicitObjectMemberFunction()) {
15559 // Cut off the implicit 'this'.
15560 ImplicitThis = ArgsArray[0];
15561 ArgsArray = ArgsArray.slice(N: 1);
15562 }
15563
15564 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15565 FD: FnDecl))
15566 return ExprError();
15567
15568 if (Op == OO_Equal) {
15569 // Check for a self move.
15570 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15571 // lifetime check.
15572 checkAssignmentLifetime(
15573 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15574 Init: Args[1]);
15575 }
15576 if (ImplicitThis) {
15577 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15578 QualType ThisTypeFromDecl = Context.getPointerType(
15579 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15580
15581 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15582 ParamTy: ThisTypeFromDecl);
15583 }
15584
15585 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15586 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15587 CallType: VariadicCallType::DoesNotApply);
15588
15589 ExprResult R = MaybeBindToTemporary(E: TheCall);
15590 if (R.isInvalid())
15591 return ExprError();
15592
15593 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15594 if (R.isInvalid())
15595 return ExprError();
15596
15597 // For a rewritten candidate, we've already reversed the arguments
15598 // if needed. Perform the rest of the rewrite now.
15599 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15600 (Op == OO_Spaceship && IsReversed)) {
15601 if (Op == OO_ExclaimEqual) {
15602 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15603 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15604 } else {
15605 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15606 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15607 Expr *ZeroLiteral =
15608 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15609
15610 Sema::CodeSynthesisContext Ctx;
15611 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15612 Ctx.Entity = FnDecl;
15613 pushCodeSynthesisContext(Ctx);
15614
15615 R = CreateOverloadedBinOp(
15616 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15617 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15618 /*AllowRewrittenCandidates=*/false);
15619
15620 popCodeSynthesisContext();
15621 }
15622 if (R.isInvalid())
15623 return ExprError();
15624 } else {
15625 assert(ChosenOp == Op && "unexpected operator name");
15626 }
15627
15628 // Make a note in the AST if we did any rewriting.
15629 if (Best->RewriteKind != CRK_None)
15630 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15631
15632 return R;
15633 } else {
15634 // We matched a built-in operator. Convert the arguments, then
15635 // break out so that we will build the appropriate built-in
15636 // operator node.
15637 ExprResult ArgsRes0 = PerformImplicitConversion(
15638 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15639 Action: AssignmentAction::Passing,
15640 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15641 if (ArgsRes0.isInvalid())
15642 return ExprError();
15643 Args[0] = ArgsRes0.get();
15644
15645 ExprResult ArgsRes1 = PerformImplicitConversion(
15646 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15647 Action: AssignmentAction::Passing,
15648 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15649 if (ArgsRes1.isInvalid())
15650 return ExprError();
15651 Args[1] = ArgsRes1.get();
15652 break;
15653 }
15654 }
15655
15656 case OR_No_Viable_Function: {
15657 // C++ [over.match.oper]p9:
15658 // If the operator is the operator , [...] and there are no
15659 // viable functions, then the operator is assumed to be the
15660 // built-in operator and interpreted according to clause 5.
15661 if (Opc == BO_Comma)
15662 break;
15663
15664 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15665 // compare result using '==' and '<'.
15666 if (DefaultedFn && Opc == BO_Cmp) {
15667 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15668 RHS: Args[1], DefaultedFn);
15669 if (E.isInvalid() || E.isUsable())
15670 return E;
15671 }
15672
15673 // For class as left operand for assignment or compound assignment
15674 // operator do not fall through to handling in built-in, but report that
15675 // no overloaded assignment operator found
15676 ExprResult Result = ExprError();
15677 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15678 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15679 Args, OpLoc);
15680 DeferDiagsRAII DDR(*this,
15681 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15682 if (Args[0]->getType()->isRecordType() &&
15683 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15684 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15685 << BinaryOperator::getOpcodeStr(Op: Opc)
15686 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15687 if (Args[0]->getType()->isIncompleteType()) {
15688 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15689 << Args[0]->getType()
15690 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15691 }
15692 } else {
15693 // This is an erroneous use of an operator which can be overloaded by
15694 // a non-member function. Check for non-member operators which were
15695 // defined too late to be candidates.
15696 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15697 // FIXME: Recover by calling the found function.
15698 return ExprError();
15699
15700 // No viable function; try to create a built-in operation, which will
15701 // produce an error. Then, show the non-viable candidates.
15702 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15703 }
15704 assert(Result.isInvalid() &&
15705 "C++ binary operator overloading is missing candidates!");
15706 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15707 return Result;
15708 }
15709
15710 case OR_Ambiguous:
15711 CandidateSet.NoteCandidates(
15712 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15713 << BinaryOperator::getOpcodeStr(Op: Opc)
15714 << Args[0]->getType()
15715 << Args[1]->getType()
15716 << Args[0]->getSourceRange()
15717 << Args[1]->getSourceRange()),
15718 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15719 OpLoc);
15720 return ExprError();
15721
15722 case OR_Deleted: {
15723 if (isImplicitlyDeleted(FD: Best->Function)) {
15724 FunctionDecl *DeletedFD = Best->Function;
15725 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15726 if (DFK.isSpecialMember()) {
15727 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15728 << Args[0]->getType() << DFK.asSpecialMember();
15729 } else {
15730 assert(DFK.isComparison());
15731 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15732 << Args[0]->getType() << DeletedFD;
15733 }
15734
15735 // The user probably meant to call this special member. Just
15736 // explain why it's deleted.
15737 NoteDeletedFunction(FD: DeletedFD);
15738 return ExprError();
15739 }
15740
15741 StringLiteral *Msg = Best->Function->getDeletedMessage();
15742 CandidateSet.NoteCandidates(
15743 PD: PartialDiagnosticAt(
15744 OpLoc,
15745 PDiag(DiagID: diag::err_ovl_deleted_oper)
15746 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15747 .getCXXOverloadedOperator())
15748 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15749 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15750 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15751 OpLoc);
15752 return ExprError();
15753 }
15754 }
15755
15756 // We matched a built-in operator; build it.
15757 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15758}
15759
15760ExprResult Sema::BuildSynthesizedThreeWayComparison(
15761 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15762 FunctionDecl *DefaultedFn) {
15763 const ComparisonCategoryInfo *Info =
15764 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15765 // If we're not producing a known comparison category type, we can't
15766 // synthesize a three-way comparison. Let the caller diagnose this.
15767 if (!Info)
15768 return ExprResult((Expr*)nullptr);
15769
15770 // If we ever want to perform this synthesis more generally, we will need to
15771 // apply the temporary materialization conversion to the operands.
15772 assert(LHS->isGLValue() && RHS->isGLValue() &&
15773 "cannot use prvalue expressions more than once");
15774 Expr *OrigLHS = LHS;
15775 Expr *OrigRHS = RHS;
15776
15777 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15778 // each of them multiple times below.
15779 LHS = new (Context)
15780 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15781 LHS->getObjectKind(), LHS);
15782 RHS = new (Context)
15783 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15784 RHS->getObjectKind(), RHS);
15785
15786 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15787 DefaultedFn);
15788 if (Eq.isInvalid())
15789 return ExprError();
15790
15791 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15792 AllowRewrittenCandidates: true, DefaultedFn);
15793 if (Less.isInvalid())
15794 return ExprError();
15795
15796 ExprResult Greater;
15797 if (Info->isPartial()) {
15798 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15799 DefaultedFn);
15800 if (Greater.isInvalid())
15801 return ExprError();
15802 }
15803
15804 // Form the list of comparisons we're going to perform.
15805 struct Comparison {
15806 ExprResult Cmp;
15807 ComparisonCategoryResult Result;
15808 } Comparisons[4] =
15809 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15810 : ComparisonCategoryResult::Equivalent},
15811 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15812 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15813 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15814 };
15815
15816 int I = Info->isPartial() ? 3 : 2;
15817
15818 // Combine the comparisons with suitable conditional expressions.
15819 ExprResult Result;
15820 for (; I >= 0; --I) {
15821 // Build a reference to the comparison category constant.
15822 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15823 // FIXME: Missing a constant for a comparison category. Diagnose this?
15824 if (!VI)
15825 return ExprResult((Expr*)nullptr);
15826 ExprResult ThisResult =
15827 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
15828 if (ThisResult.isInvalid())
15829 return ExprError();
15830
15831 // Build a conditional unless this is the final case.
15832 if (Result.get()) {
15833 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15834 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15835 if (Result.isInvalid())
15836 return ExprError();
15837 } else {
15838 Result = ThisResult;
15839 }
15840 }
15841
15842 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15843 // bind the OpaqueValueExprs before they're (repeatedly) used.
15844 Expr *SyntacticForm = BinaryOperator::Create(
15845 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15846 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15847 FPFeatures: CurFPFeatureOverrides());
15848 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15849 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15850}
15851
15852static bool PrepareArgumentsForCallToObjectOfClassType(
15853 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15854 MultiExprArg Args, SourceLocation LParenLoc) {
15855
15856 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15857 unsigned NumParams = Proto->getNumParams();
15858 unsigned NumArgsSlots =
15859 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
15860 // Build the full argument list for the method call (the implicit object
15861 // parameter is placed at the beginning of the list).
15862 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
15863 bool IsError = false;
15864 // Initialize the implicit object parameter.
15865 // Check the argument types.
15866 for (unsigned i = 0; i != NumParams; i++) {
15867 Expr *Arg;
15868 if (i < Args.size()) {
15869 Arg = Args[i];
15870 ExprResult InputInit =
15871 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15872 Context&: S.Context, Parm: Method->getParamDecl(i)),
15873 EqualLoc: SourceLocation(), Init: Arg);
15874 IsError |= InputInit.isInvalid();
15875 Arg = InputInit.getAs<Expr>();
15876 } else {
15877 ExprResult DefArg =
15878 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
15879 if (DefArg.isInvalid()) {
15880 IsError = true;
15881 break;
15882 }
15883 Arg = DefArg.getAs<Expr>();
15884 }
15885
15886 MethodArgs.push_back(Elt: Arg);
15887 }
15888 return IsError;
15889}
15890
15891ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15892 SourceLocation RLoc,
15893 Expr *Base,
15894 MultiExprArg ArgExpr) {
15895 SmallVector<Expr *, 2> Args;
15896 Args.push_back(Elt: Base);
15897 for (auto *e : ArgExpr) {
15898 Args.push_back(Elt: e);
15899 }
15900 DeclarationName OpName =
15901 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
15902
15903 SourceRange Range = ArgExpr.empty()
15904 ? SourceRange{}
15905 : SourceRange(ArgExpr.front()->getBeginLoc(),
15906 ArgExpr.back()->getEndLoc());
15907
15908 // If either side is type-dependent, create an appropriate dependent
15909 // expression.
15910 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
15911
15912 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15913 // CHECKME: no 'operator' keyword?
15914 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15915 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15916 ExprResult Fn = CreateUnresolvedLookupExpr(
15917 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
15918 if (Fn.isInvalid())
15919 return ExprError();
15920 // Can't add any actual overloads yet
15921
15922 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
15923 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
15924 FPFeatures: CurFPFeatureOverrides());
15925 }
15926
15927 // Handle placeholders
15928 UnbridgedCastsSet UnbridgedCasts;
15929 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
15930 return ExprError();
15931 }
15932 // Build an empty overload set.
15933 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15934
15935 // Subscript can only be overloaded as a member function.
15936
15937 // Add operator candidates that are member functions.
15938 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15939
15940 // Add builtin operator candidates.
15941 if (Args.size() == 2)
15942 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15943
15944 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15945
15946 // Perform overload resolution.
15947 OverloadCandidateSet::iterator Best;
15948 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
15949 case OR_Success: {
15950 // We found a built-in operator or an overloaded operator.
15951 FunctionDecl *FnDecl = Best->Function;
15952
15953 if (FnDecl) {
15954 // We matched an overloaded operator. Build a call to that
15955 // operator.
15956
15957 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
15958
15959 // Convert the arguments.
15960 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
15961 SmallVector<Expr *, 2> MethodArgs;
15962
15963 // Initialize the object parameter.
15964 if (Method->isExplicitObjectMemberFunction()) {
15965 ExprResult Res =
15966 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
15967 if (Res.isInvalid())
15968 return ExprError();
15969 Args[0] = Res.get();
15970 ArgExpr = Args;
15971 } else {
15972 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15973 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15974 if (Arg0.isInvalid())
15975 return ExprError();
15976
15977 MethodArgs.push_back(Elt: Arg0.get());
15978 }
15979
15980 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15981 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
15982 if (IsError)
15983 return ExprError();
15984
15985 // Build the actual expression node.
15986 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15987 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15988 ExprResult FnExpr = CreateFunctionRefExpr(
15989 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
15990 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
15991 if (FnExpr.isInvalid())
15992 return ExprError();
15993
15994 // Determine the result type
15995 QualType ResultTy = FnDecl->getReturnType();
15996 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15997 ResultTy = ResultTy.getNonLValueExprType(Context);
15998
15999 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16000 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16001 FPFeatures: CurFPFeatureOverrides());
16002
16003 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16004 return ExprError();
16005
16006 if (CheckFunctionCall(FDecl: Method, TheCall,
16007 Proto: Method->getType()->castAs<FunctionProtoType>()))
16008 return ExprError();
16009
16010 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16011 Decl: FnDecl);
16012 } else {
16013 // We matched a built-in operator. Convert the arguments, then
16014 // break out so that we will build the appropriate built-in
16015 // operator node.
16016 ExprResult ArgsRes0 = PerformImplicitConversion(
16017 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16018 Action: AssignmentAction::Passing,
16019 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16020 if (ArgsRes0.isInvalid())
16021 return ExprError();
16022 Args[0] = ArgsRes0.get();
16023
16024 ExprResult ArgsRes1 = PerformImplicitConversion(
16025 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16026 Action: AssignmentAction::Passing,
16027 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16028 if (ArgsRes1.isInvalid())
16029 return ExprError();
16030 Args[1] = ArgsRes1.get();
16031
16032 break;
16033 }
16034 }
16035
16036 case OR_No_Viable_Function: {
16037 PartialDiagnostic PD =
16038 CandidateSet.empty()
16039 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16040 << Args[0]->getType() << /*subscript*/ 0
16041 << Args[0]->getSourceRange() << Range)
16042 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16043 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16044 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16045 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16046 return ExprError();
16047 }
16048
16049 case OR_Ambiguous:
16050 if (Args.size() == 2) {
16051 CandidateSet.NoteCandidates(
16052 PD: PartialDiagnosticAt(
16053 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16054 << "[]" << Args[0]->getType() << Args[1]->getType()
16055 << Args[0]->getSourceRange() << Range),
16056 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16057 } else {
16058 CandidateSet.NoteCandidates(
16059 PD: PartialDiagnosticAt(LLoc,
16060 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16061 << Args[0]->getType()
16062 << Args[0]->getSourceRange() << Range),
16063 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16064 }
16065 return ExprError();
16066
16067 case OR_Deleted: {
16068 StringLiteral *Msg = Best->Function->getDeletedMessage();
16069 CandidateSet.NoteCandidates(
16070 PD: PartialDiagnosticAt(LLoc,
16071 PDiag(DiagID: diag::err_ovl_deleted_oper)
16072 << "[]" << (Msg != nullptr)
16073 << (Msg ? Msg->getString() : StringRef())
16074 << Args[0]->getSourceRange() << Range),
16075 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16076 return ExprError();
16077 }
16078 }
16079
16080 // We matched a built-in operator; build it.
16081 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16082}
16083
16084ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16085 SourceLocation LParenLoc,
16086 MultiExprArg Args,
16087 SourceLocation RParenLoc,
16088 Expr *ExecConfig, bool IsExecConfig,
16089 bool AllowRecovery) {
16090 assert(MemExprE->getType() == Context.BoundMemberTy ||
16091 MemExprE->getType() == Context.OverloadTy);
16092
16093 // Dig out the member expression. This holds both the object
16094 // argument and the member function we're referring to.
16095 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16096
16097 // Determine whether this is a call to a pointer-to-member function.
16098 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16099 assert(op->getType() == Context.BoundMemberTy);
16100 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16101
16102 QualType fnType =
16103 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16104
16105 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16106 QualType resultType = proto->getCallResultType(Context);
16107 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16108
16109 // Check that the object type isn't more qualified than the
16110 // member function we're calling.
16111 Qualifiers funcQuals = proto->getMethodQuals();
16112
16113 QualType objectType = op->getLHS()->getType();
16114 if (op->getOpcode() == BO_PtrMemI)
16115 objectType = objectType->castAs<PointerType>()->getPointeeType();
16116 Qualifiers objectQuals = objectType.getQualifiers();
16117
16118 Qualifiers difference = objectQuals - funcQuals;
16119 difference.removeObjCGCAttr();
16120 difference.removeAddressSpace();
16121 if (difference) {
16122 std::string qualsString = difference.getAsString();
16123 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16124 << fnType.getUnqualifiedType()
16125 << qualsString
16126 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16127 }
16128
16129 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16130 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16131 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16132
16133 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16134 CE: call, FD: nullptr))
16135 return ExprError();
16136
16137 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16138 return ExprError();
16139
16140 if (CheckOtherCall(TheCall: call, Proto: proto))
16141 return ExprError();
16142
16143 return MaybeBindToTemporary(E: call);
16144 }
16145
16146 // We only try to build a recovery expr at this level if we can preserve
16147 // the return type, otherwise we return ExprError() and let the caller
16148 // recover.
16149 auto BuildRecoveryExpr = [&](QualType Type) {
16150 if (!AllowRecovery)
16151 return ExprError();
16152 std::vector<Expr *> SubExprs = {MemExprE};
16153 llvm::append_range(C&: SubExprs, R&: Args);
16154 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16155 T: Type);
16156 };
16157 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16158 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16159 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16160
16161 UnbridgedCastsSet UnbridgedCasts;
16162 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16163 return ExprError();
16164
16165 MemberExpr *MemExpr;
16166 CXXMethodDecl *Method = nullptr;
16167 bool HadMultipleCandidates = false;
16168 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16169 NestedNameSpecifier Qualifier = std::nullopt;
16170 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16171 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16172 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16173 FoundDecl = MemExpr->getFoundDecl();
16174 Qualifier = MemExpr->getQualifier();
16175 UnbridgedCasts.restore();
16176 } else {
16177 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16178 Qualifier = UnresExpr->getQualifier();
16179
16180 QualType ObjectType = UnresExpr->getBaseType();
16181 Expr::Classification ObjectClassification
16182 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16183 : UnresExpr->getBase()->Classify(Ctx&: Context);
16184
16185 // Add overload candidates
16186 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16187 OverloadCandidateSet::CSK_Normal);
16188
16189 // FIXME: avoid copy.
16190 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16191 if (UnresExpr->hasExplicitTemplateArgs()) {
16192 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16193 TemplateArgs = &TemplateArgsBuffer;
16194 }
16195
16196 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16197 E = UnresExpr->decls_end(); I != E; ++I) {
16198
16199 QualType ExplicitObjectType = ObjectType;
16200
16201 NamedDecl *Func = *I;
16202 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16203 if (isa<UsingShadowDecl>(Val: Func))
16204 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16205
16206 bool HasExplicitParameter = false;
16207 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16208 M && M->hasCXXExplicitFunctionObjectParameter())
16209 HasExplicitParameter = true;
16210 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16211 M &&
16212 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16213 HasExplicitParameter = true;
16214
16215 if (HasExplicitParameter)
16216 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16217
16218 // Microsoft supports direct constructor calls.
16219 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16220 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16221 CandidateSet,
16222 /*SuppressUserConversions*/ false);
16223 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16224 // If explicit template arguments were provided, we can't call a
16225 // non-template member function.
16226 if (TemplateArgs)
16227 continue;
16228
16229 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16230 ObjectClassification, Args, CandidateSet,
16231 /*SuppressUserConversions=*/false);
16232 } else {
16233 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16234 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16235 ObjectType: ExplicitObjectType, ObjectClassification,
16236 Args, CandidateSet,
16237 /*SuppressUserConversions=*/false);
16238 }
16239 }
16240
16241 HadMultipleCandidates = (CandidateSet.size() > 1);
16242
16243 DeclarationName DeclName = UnresExpr->getMemberName();
16244
16245 UnbridgedCasts.restore();
16246
16247 OverloadCandidateSet::iterator Best;
16248 bool Succeeded = false;
16249 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16250 Best)) {
16251 case OR_Success:
16252 Method = cast<CXXMethodDecl>(Val: Best->Function);
16253 FoundDecl = Best->FoundDecl;
16254 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16255 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16256 break;
16257 // If FoundDecl is different from Method (such as if one is a template
16258 // and the other a specialization), make sure DiagnoseUseOfDecl is
16259 // called on both.
16260 // FIXME: This would be more comprehensively addressed by modifying
16261 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16262 // being used.
16263 if (Method != FoundDecl.getDecl() &&
16264 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16265 break;
16266 Succeeded = true;
16267 break;
16268
16269 case OR_No_Viable_Function:
16270 CandidateSet.NoteCandidates(
16271 PD: PartialDiagnosticAt(
16272 UnresExpr->getMemberLoc(),
16273 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16274 << DeclName << MemExprE->getSourceRange()),
16275 S&: *this, OCD: OCD_AllCandidates, Args);
16276 break;
16277 case OR_Ambiguous:
16278 CandidateSet.NoteCandidates(
16279 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16280 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16281 << DeclName << MemExprE->getSourceRange()),
16282 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16283 break;
16284 case OR_Deleted:
16285 DiagnoseUseOfDeletedFunction(
16286 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16287 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16288 break;
16289 }
16290 // Overload resolution fails, try to recover.
16291 if (!Succeeded)
16292 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16293
16294 ExprResult Res =
16295 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16296 if (Res.isInvalid())
16297 return ExprError();
16298 MemExprE = Res.get();
16299
16300 // If overload resolution picked a static member
16301 // build a non-member call based on that function.
16302 if (Method->isStatic()) {
16303 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16304 Config: ExecConfig, IsExecConfig);
16305 }
16306
16307 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16308 }
16309
16310 QualType ResultType = Method->getReturnType();
16311 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16312 ResultType = ResultType.getNonLValueExprType(Context);
16313
16314 assert(Method && "Member call to something that isn't a method?");
16315 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16316
16317 CallExpr *TheCall = nullptr;
16318 llvm::SmallVector<Expr *, 8> NewArgs;
16319 if (Method->isExplicitObjectMemberFunction()) {
16320 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16321 NewArgs))
16322 return ExprError();
16323
16324 // Build the actual expression node.
16325 ExprResult FnExpr =
16326 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16327 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16328 if (FnExpr.isInvalid())
16329 return ExprError();
16330
16331 TheCall =
16332 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16333 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16334 TheCall->setUsesMemberSyntax(true);
16335 } else {
16336 // Convert the object argument (for a non-static member function call).
16337 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16338 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16339 if (ObjectArg.isInvalid())
16340 return ExprError();
16341 MemExpr->setBase(ObjectArg.get());
16342 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16343 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16344 MinNumArgs: Proto->getNumParams());
16345 }
16346
16347 // Check for a valid return type.
16348 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16349 CE: TheCall, FD: Method))
16350 return BuildRecoveryExpr(ResultType);
16351
16352 // Convert the rest of the arguments
16353 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16354 RParenLoc))
16355 return BuildRecoveryExpr(ResultType);
16356
16357 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16358
16359 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16360 return ExprError();
16361
16362 // In the case the method to call was not selected by the overloading
16363 // resolution process, we still need to handle the enable_if attribute. Do
16364 // that here, so it will not hide previous -- and more relevant -- errors.
16365 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16366 if (const EnableIfAttr *Attr =
16367 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16368 Diag(Loc: MemE->getMemberLoc(),
16369 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16370 << Method << Method->getSourceRange();
16371 Diag(Loc: Method->getLocation(),
16372 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16373 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16374 return ExprError();
16375 }
16376 }
16377
16378 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16379 TheCall->getDirectCallee()->isPureVirtual()) {
16380 const FunctionDecl *MD = TheCall->getDirectCallee();
16381
16382 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16383 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16384 Diag(Loc: MemExpr->getBeginLoc(),
16385 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16386 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16387 << MD->getParent();
16388
16389 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16390 if (getLangOpts().AppleKext)
16391 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16392 << MD->getParent() << MD->getDeclName();
16393 }
16394 }
16395
16396 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16397 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16398 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16399 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16400 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16401 DtorLoc: MemExpr->getMemberLoc());
16402 }
16403
16404 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16405 Decl: TheCall->getDirectCallee());
16406}
16407
16408ExprResult
16409Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16410 SourceLocation LParenLoc,
16411 MultiExprArg Args,
16412 SourceLocation RParenLoc) {
16413 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16414 return ExprError();
16415 ExprResult Object = Obj;
16416
16417 UnbridgedCastsSet UnbridgedCasts;
16418 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16419 return ExprError();
16420
16421 assert(Object.get()->getType()->isRecordType() &&
16422 "Requires object type argument");
16423
16424 // C++ [over.call.object]p1:
16425 // If the primary-expression E in the function call syntax
16426 // evaluates to a class object of type "cv T", then the set of
16427 // candidate functions includes at least the function call
16428 // operators of T. The function call operators of T are obtained by
16429 // ordinary lookup of the name operator() in the context of
16430 // (E).operator().
16431 OverloadCandidateSet CandidateSet(LParenLoc,
16432 OverloadCandidateSet::CSK_Operator);
16433 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16434
16435 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16436 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16437 return true;
16438
16439 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16440 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16441 LookupQualifiedName(R, LookupCtx: Record);
16442 R.suppressAccessDiagnostics();
16443
16444 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16445 Oper != OperEnd; ++Oper) {
16446 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16447 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16448 /*SuppressUserConversion=*/SuppressUserConversions: false);
16449 }
16450
16451 // When calling a lambda, both the call operator, and
16452 // the conversion operator to function pointer
16453 // are considered. But when constraint checking
16454 // on the call operator fails, it will also fail on the
16455 // conversion operator as the constraints are always the same.
16456 // As the user probably does not intend to perform a surrogate call,
16457 // we filter them out to produce better error diagnostics, ie to avoid
16458 // showing 2 failed overloads instead of one.
16459 bool IgnoreSurrogateFunctions = false;
16460 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16461 const OverloadCandidate &Candidate = *CandidateSet.begin();
16462 if (!Candidate.Viable &&
16463 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16464 IgnoreSurrogateFunctions = true;
16465 }
16466
16467 // C++ [over.call.object]p2:
16468 // In addition, for each (non-explicit in C++0x) conversion function
16469 // declared in T of the form
16470 //
16471 // operator conversion-type-id () cv-qualifier;
16472 //
16473 // where cv-qualifier is the same cv-qualification as, or a
16474 // greater cv-qualification than, cv, and where conversion-type-id
16475 // denotes the type "pointer to function of (P1,...,Pn) returning
16476 // R", or the type "reference to pointer to function of
16477 // (P1,...,Pn) returning R", or the type "reference to function
16478 // of (P1,...,Pn) returning R", a surrogate call function [...]
16479 // is also considered as a candidate function. Similarly,
16480 // surrogate call functions are added to the set of candidate
16481 // functions for each conversion function declared in an
16482 // accessible base class provided the function is not hidden
16483 // within T by another intervening declaration.
16484 const auto &Conversions = Record->getVisibleConversionFunctions();
16485 for (auto I = Conversions.begin(), E = Conversions.end();
16486 !IgnoreSurrogateFunctions && I != E; ++I) {
16487 NamedDecl *D = *I;
16488 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16489 if (isa<UsingShadowDecl>(Val: D))
16490 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16491
16492 // Skip over templated conversion functions; they aren't
16493 // surrogates.
16494 if (isa<FunctionTemplateDecl>(Val: D))
16495 continue;
16496
16497 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16498 if (!Conv->isExplicit()) {
16499 // Strip the reference type (if any) and then the pointer type (if
16500 // any) to get down to what might be a function type.
16501 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16502 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16503 ConvType = ConvPtrType->getPointeeType();
16504
16505 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16506 {
16507 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16508 Object: Object.get(), Args, CandidateSet);
16509 }
16510 }
16511 }
16512
16513 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16514
16515 // Perform overload resolution.
16516 OverloadCandidateSet::iterator Best;
16517 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16518 Best)) {
16519 case OR_Success:
16520 // Overload resolution succeeded; we'll build the appropriate call
16521 // below.
16522 break;
16523
16524 case OR_No_Viable_Function: {
16525 PartialDiagnostic PD =
16526 CandidateSet.empty()
16527 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16528 << Object.get()->getType() << /*call*/ 1
16529 << Object.get()->getSourceRange())
16530 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16531 << Object.get()->getType() << Object.get()->getSourceRange());
16532 CandidateSet.NoteCandidates(
16533 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16534 OCD: OCD_AllCandidates, Args);
16535 break;
16536 }
16537 case OR_Ambiguous:
16538 if (!R.isAmbiguous())
16539 CandidateSet.NoteCandidates(
16540 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16541 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16542 << Object.get()->getType()
16543 << Object.get()->getSourceRange()),
16544 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16545 break;
16546
16547 case OR_Deleted: {
16548 // FIXME: Is this diagnostic here really necessary? It seems that
16549 // 1. we don't have any tests for this diagnostic, and
16550 // 2. we already issue err_deleted_function_use for this later on anyway.
16551 StringLiteral *Msg = Best->Function->getDeletedMessage();
16552 CandidateSet.NoteCandidates(
16553 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16554 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16555 << Object.get()->getType() << (Msg != nullptr)
16556 << (Msg ? Msg->getString() : StringRef())
16557 << Object.get()->getSourceRange()),
16558 S&: *this, OCD: OCD_AllCandidates, Args);
16559 break;
16560 }
16561 }
16562
16563 if (Best == CandidateSet.end())
16564 return true;
16565
16566 UnbridgedCasts.restore();
16567
16568 if (Best->Function == nullptr) {
16569 // Since there is no function declaration, this is one of the
16570 // surrogate candidates. Dig out the conversion function.
16571 CXXConversionDecl *Conv
16572 = cast<CXXConversionDecl>(
16573 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16574
16575 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16576 FoundDecl: Best->FoundDecl);
16577 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16578 return ExprError();
16579 assert(Conv == Best->FoundDecl.getDecl() &&
16580 "Found Decl & conversion-to-functionptr should be same, right?!");
16581 // We selected one of the surrogate functions that converts the
16582 // object parameter to a function pointer. Perform the conversion
16583 // on the object argument, then let BuildCallExpr finish the job.
16584
16585 // Create an implicit member expr to refer to the conversion operator.
16586 // and then call it.
16587 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16588 Method: Conv, HadMultipleCandidates);
16589 if (Call.isInvalid())
16590 return ExprError();
16591 // Record usage of conversion in an implicit cast.
16592 Call = ImplicitCastExpr::Create(
16593 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16594 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16595
16596 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16597 }
16598
16599 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16600
16601 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16602 // that calls this method, using Object for the implicit object
16603 // parameter and passing along the remaining arguments.
16604 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16605
16606 // An error diagnostic has already been printed when parsing the declaration.
16607 if (Method->isInvalidDecl())
16608 return ExprError();
16609
16610 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16611 unsigned NumParams = Proto->getNumParams();
16612
16613 DeclarationNameInfo OpLocInfo(
16614 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16615 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16616 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16617 Base: Obj, HadMultipleCandidates,
16618 Loc: OpLocInfo.getLoc(),
16619 LocInfo: OpLocInfo.getInfo());
16620 if (NewFn.isInvalid())
16621 return true;
16622
16623 SmallVector<Expr *, 8> MethodArgs;
16624 MethodArgs.reserve(N: NumParams + 1);
16625
16626 bool IsError = false;
16627
16628 // Initialize the object parameter.
16629 llvm::SmallVector<Expr *, 8> NewArgs;
16630 if (Method->isExplicitObjectMemberFunction()) {
16631 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16632 } else {
16633 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16634 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16635 if (ObjRes.isInvalid())
16636 IsError = true;
16637 else
16638 Object = ObjRes;
16639 MethodArgs.push_back(Elt: Object.get());
16640 }
16641
16642 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16643 S&: *this, MethodArgs, Method, Args, LParenLoc);
16644
16645 // If this is a variadic call, handle args passed through "...".
16646 if (Proto->isVariadic()) {
16647 // Promote the arguments (C99 6.5.2.2p7).
16648 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16649 ExprResult Arg = DefaultVariadicArgumentPromotion(
16650 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16651 IsError |= Arg.isInvalid();
16652 MethodArgs.push_back(Elt: Arg.get());
16653 }
16654 }
16655
16656 if (IsError)
16657 return true;
16658
16659 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16660
16661 // Once we've built TheCall, all of the expressions are properly owned.
16662 QualType ResultTy = Method->getReturnType();
16663 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16664 ResultTy = ResultTy.getNonLValueExprType(Context);
16665
16666 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16667 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16668 FPFeatures: CurFPFeatureOverrides());
16669
16670 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16671 return true;
16672
16673 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16674 return true;
16675
16676 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16677}
16678
16679ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16680 SourceLocation OpLoc,
16681 bool *NoArrowOperatorFound) {
16682 assert(Base->getType()->isRecordType() &&
16683 "left-hand side must have class type");
16684
16685 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16686 return ExprError();
16687
16688 SourceLocation Loc = Base->getExprLoc();
16689
16690 // C++ [over.ref]p1:
16691 //
16692 // [...] An expression x->m is interpreted as (x.operator->())->m
16693 // for a class object x of type T if T::operator->() exists and if
16694 // the operator is selected as the best match function by the
16695 // overload resolution mechanism (13.3).
16696 DeclarationName OpName =
16697 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16698 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16699
16700 if (RequireCompleteType(Loc, T: Base->getType(),
16701 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16702 return ExprError();
16703
16704 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16705 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16706 R.suppressAccessDiagnostics();
16707
16708 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16709 Oper != OperEnd; ++Oper) {
16710 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16711 Args: {}, CandidateSet,
16712 /*SuppressUserConversion=*/SuppressUserConversions: false);
16713 }
16714
16715 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16716
16717 // Perform overload resolution.
16718 OverloadCandidateSet::iterator Best;
16719 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16720 case OR_Success:
16721 // Overload resolution succeeded; we'll build the call below.
16722 break;
16723
16724 case OR_No_Viable_Function: {
16725 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16726 if (CandidateSet.empty()) {
16727 QualType BaseType = Base->getType();
16728 if (NoArrowOperatorFound) {
16729 // Report this specific error to the caller instead of emitting a
16730 // diagnostic, as requested.
16731 *NoArrowOperatorFound = true;
16732 return ExprError();
16733 }
16734 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16735 << BaseType << Base->getSourceRange();
16736 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16737 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16738 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16739 }
16740 } else
16741 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16742 << "operator->" << Base->getSourceRange();
16743 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16744 return ExprError();
16745 }
16746 case OR_Ambiguous:
16747 if (!R.isAmbiguous())
16748 CandidateSet.NoteCandidates(
16749 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16750 << "->" << Base->getType()
16751 << Base->getSourceRange()),
16752 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16753 return ExprError();
16754
16755 case OR_Deleted: {
16756 StringLiteral *Msg = Best->Function->getDeletedMessage();
16757 CandidateSet.NoteCandidates(
16758 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16759 << "->" << (Msg != nullptr)
16760 << (Msg ? Msg->getString() : StringRef())
16761 << Base->getSourceRange()),
16762 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16763 return ExprError();
16764 }
16765 }
16766
16767 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16768
16769 // Convert the object parameter.
16770 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16771
16772 if (Method->isExplicitObjectMemberFunction()) {
16773 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16774 if (R.isInvalid())
16775 return ExprError();
16776 Base = R.get();
16777 } else {
16778 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16779 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16780 if (BaseResult.isInvalid())
16781 return ExprError();
16782 Base = BaseResult.get();
16783 }
16784
16785 // Build the operator call.
16786 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16787 Base, HadMultipleCandidates, Loc: OpLoc);
16788 if (FnExpr.isInvalid())
16789 return ExprError();
16790
16791 QualType ResultTy = Method->getReturnType();
16792 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16793 ResultTy = ResultTy.getNonLValueExprType(Context);
16794
16795 CallExpr *TheCall =
16796 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16797 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16798
16799 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16800 return ExprError();
16801
16802 if (CheckFunctionCall(FDecl: Method, TheCall,
16803 Proto: Method->getType()->castAs<FunctionProtoType>()))
16804 return ExprError();
16805
16806 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16807}
16808
16809ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16810 DeclarationNameInfo &SuffixInfo,
16811 ArrayRef<Expr*> Args,
16812 SourceLocation LitEndLoc,
16813 TemplateArgumentListInfo *TemplateArgs) {
16814 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16815
16816 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16817 OverloadCandidateSet::CSK_Normal);
16818 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16819 ExplicitTemplateArgs: TemplateArgs);
16820
16821 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16822
16823 // Perform overload resolution. This will usually be trivial, but might need
16824 // to perform substitutions for a literal operator template.
16825 OverloadCandidateSet::iterator Best;
16826 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16827 case OR_Success:
16828 case OR_Deleted:
16829 break;
16830
16831 case OR_No_Viable_Function:
16832 CandidateSet.NoteCandidates(
16833 PD: PartialDiagnosticAt(UDSuffixLoc,
16834 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
16835 << R.getLookupName()),
16836 S&: *this, OCD: OCD_AllCandidates, Args);
16837 return ExprError();
16838
16839 case OR_Ambiguous:
16840 CandidateSet.NoteCandidates(
16841 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
16842 << R.getLookupName()),
16843 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16844 return ExprError();
16845 }
16846
16847 FunctionDecl *FD = Best->Function;
16848 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16849 Base: nullptr, HadMultipleCandidates,
16850 Loc: SuffixInfo.getLoc(),
16851 LocInfo: SuffixInfo.getInfo());
16852 if (Fn.isInvalid())
16853 return true;
16854
16855 // Check the argument types. This should almost always be a no-op, except
16856 // that array-to-pointer decay is applied to string literals.
16857 Expr *ConvArgs[2];
16858 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16859 ExprResult InputInit = PerformCopyInitialization(
16860 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
16861 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
16862 if (InputInit.isInvalid())
16863 return true;
16864 ConvArgs[ArgIdx] = InputInit.get();
16865 }
16866
16867 QualType ResultTy = FD->getReturnType();
16868 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16869 ResultTy = ResultTy.getNonLValueExprType(Context);
16870
16871 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16872 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
16873 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
16874
16875 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
16876 return ExprError();
16877
16878 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
16879 return ExprError();
16880
16881 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
16882}
16883
16884Sema::ForRangeStatus
16885Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16886 SourceLocation RangeLoc,
16887 const DeclarationNameInfo &NameInfo,
16888 LookupResult &MemberLookup,
16889 OverloadCandidateSet *CandidateSet,
16890 Expr *Range, ExprResult *CallExpr) {
16891 Scope *S = nullptr;
16892
16893 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
16894 if (!MemberLookup.empty()) {
16895 ExprResult MemberRef =
16896 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
16897 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
16898 /*TemplateKWLoc=*/SourceLocation(),
16899 /*FirstQualifierInScope=*/nullptr,
16900 R&: MemberLookup,
16901 /*TemplateArgs=*/nullptr, S);
16902 if (MemberRef.isInvalid()) {
16903 *CallExpr = ExprError();
16904 return FRS_DiagnosticIssued;
16905 }
16906 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
16907 if (CallExpr->isInvalid()) {
16908 *CallExpr = ExprError();
16909 return FRS_DiagnosticIssued;
16910 }
16911 } else {
16912 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16913 NNSLoc: NestedNameSpecifierLoc(),
16914 DNI: NameInfo, Fns: UnresolvedSet<0>());
16915 if (FnR.isInvalid())
16916 return FRS_DiagnosticIssued;
16917 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
16918
16919 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
16920 CandidateSet, Result: CallExpr);
16921 if (CandidateSet->empty() || CandidateSetError) {
16922 *CallExpr = ExprError();
16923 return FRS_NoViableFunction;
16924 }
16925 OverloadCandidateSet::iterator Best;
16926 OverloadingResult OverloadResult =
16927 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
16928
16929 if (OverloadResult == OR_No_Viable_Function) {
16930 *CallExpr = ExprError();
16931 return FRS_NoViableFunction;
16932 }
16933 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
16934 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
16935 OverloadResult,
16936 /*AllowTypoCorrection=*/false);
16937 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16938 *CallExpr = ExprError();
16939 return FRS_DiagnosticIssued;
16940 }
16941 }
16942 return FRS_Success;
16943}
16944
16945ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16946 FunctionDecl *Fn) {
16947 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
16948 ExprResult SubExpr =
16949 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
16950 if (SubExpr.isInvalid())
16951 return ExprError();
16952 if (SubExpr.get() == PE->getSubExpr())
16953 return PE;
16954
16955 return new (Context)
16956 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16957 }
16958
16959 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
16960 ExprResult SubExpr =
16961 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
16962 if (SubExpr.isInvalid())
16963 return ExprError();
16964 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16965 SubExpr.get()->getType()) &&
16966 "Implicit cast type cannot be determined from overload");
16967 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16968 if (SubExpr.get() == ICE->getSubExpr())
16969 return ICE;
16970
16971 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
16972 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
16973 FPO: CurFPFeatureOverrides());
16974 }
16975
16976 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
16977 if (!GSE->isResultDependent()) {
16978 ExprResult SubExpr =
16979 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
16980 if (SubExpr.isInvalid())
16981 return ExprError();
16982 if (SubExpr.get() == GSE->getResultExpr())
16983 return GSE;
16984
16985 // Replace the resulting type information before rebuilding the generic
16986 // selection expression.
16987 ArrayRef<Expr *> A = GSE->getAssocExprs();
16988 SmallVector<Expr *, 4> AssocExprs(A);
16989 unsigned ResultIdx = GSE->getResultIndex();
16990 AssocExprs[ResultIdx] = SubExpr.get();
16991
16992 if (GSE->isExprPredicate())
16993 return GenericSelectionExpr::Create(
16994 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
16995 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
16996 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
16997 ResultIndex: ResultIdx);
16998 return GenericSelectionExpr::Create(
16999 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17000 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17001 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17002 ResultIndex: ResultIdx);
17003 }
17004 // Rather than fall through to the unreachable, return the original generic
17005 // selection expression.
17006 return GSE;
17007 }
17008
17009 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17010 assert(UnOp->getOpcode() == UO_AddrOf &&
17011 "Can only take the address of an overloaded function");
17012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17013 if (!Method->isImplicitObjectMemberFunction()) {
17014 // Do nothing: the address of static and
17015 // explicit object member functions is a (non-member) function pointer.
17016 } else {
17017 // Fix the subexpression, which really has to be an
17018 // UnresolvedLookupExpr holding an overloaded member function
17019 // or template.
17020 ExprResult SubExpr =
17021 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17022 if (SubExpr.isInvalid())
17023 return ExprError();
17024 if (SubExpr.get() == UnOp->getSubExpr())
17025 return UnOp;
17026
17027 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17028 Op: SubExpr.get(), MD: Method))
17029 return ExprError();
17030
17031 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17032 "fixed to something other than a decl ref");
17033 NestedNameSpecifier Qualifier =
17034 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17035 assert(Qualifier &&
17036 "fixed to a member ref with no nested name qualifier");
17037
17038 // We have taken the address of a pointer to member
17039 // function. Perform the computation here so that we get the
17040 // appropriate pointer to member type.
17041 QualType MemPtrType = Context.getMemberPointerType(
17042 T: Fn->getType(), Qualifier,
17043 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17044 // Under the MS ABI, lock down the inheritance model now.
17045 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17046 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17047
17048 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17049 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17050 l: UnOp->getOperatorLoc(), CanOverflow: false,
17051 FPFeatures: CurFPFeatureOverrides());
17052 }
17053 }
17054 ExprResult SubExpr =
17055 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17056 if (SubExpr.isInvalid())
17057 return ExprError();
17058 if (SubExpr.get() == UnOp->getSubExpr())
17059 return UnOp;
17060
17061 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17062 InputExpr: SubExpr.get());
17063 }
17064
17065 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17066 if (Found.getAccess() == AS_none) {
17067 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17068 }
17069 // FIXME: avoid copy.
17070 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17071 if (ULE->hasExplicitTemplateArgs()) {
17072 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17073 TemplateArgs = &TemplateArgsBuffer;
17074 }
17075
17076 QualType Type = Fn->getType();
17077 ExprValueKind ValueKind =
17078 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17079 ? VK_LValue
17080 : VK_PRValue;
17081
17082 // FIXME: Duplicated from BuildDeclarationNameExpr.
17083 if (unsigned BID = Fn->getBuiltinID()) {
17084 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17085 Type = Context.BuiltinFnTy;
17086 ValueKind = VK_PRValue;
17087 }
17088 }
17089
17090 DeclRefExpr *DRE = BuildDeclRefExpr(
17091 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17092 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17093 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17094 return DRE;
17095 }
17096
17097 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17098 // FIXME: avoid copy.
17099 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17100 if (MemExpr->hasExplicitTemplateArgs()) {
17101 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17102 TemplateArgs = &TemplateArgsBuffer;
17103 }
17104
17105 Expr *Base;
17106
17107 // If we're filling in a static method where we used to have an
17108 // implicit member access, rewrite to a simple decl ref.
17109 if (MemExpr->isImplicitAccess()) {
17110 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17111 DeclRefExpr *DRE = BuildDeclRefExpr(
17112 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17113 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17114 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17115 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17116 return DRE;
17117 } else {
17118 SourceLocation Loc = MemExpr->getMemberLoc();
17119 if (MemExpr->getQualifier())
17120 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17121 Base =
17122 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17123 }
17124 } else
17125 Base = MemExpr->getBase();
17126
17127 ExprValueKind valueKind;
17128 QualType type;
17129 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17130 valueKind = VK_LValue;
17131 type = Fn->getType();
17132 } else {
17133 valueKind = VK_PRValue;
17134 type = Context.BoundMemberTy;
17135 }
17136
17137 return BuildMemberExpr(
17138 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17139 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17140 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17141 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17142 }
17143
17144 llvm_unreachable("Invalid reference to overloaded function");
17145}
17146
17147ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17148 DeclAccessPair Found,
17149 FunctionDecl *Fn) {
17150 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17151}
17152
17153bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17154 FunctionDecl *Function) {
17155 if (!PartialOverloading || !Function)
17156 return true;
17157 if (Function->isVariadic())
17158 return false;
17159 if (const auto *Proto =
17160 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17161 if (Proto->isTemplateVariadic())
17162 return false;
17163 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17164 if (const auto *Proto =
17165 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17166 if (Proto->isTemplateVariadic())
17167 return false;
17168 return true;
17169}
17170
17171void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17172 DeclarationName Name,
17173 OverloadCandidateSet &CandidateSet,
17174 FunctionDecl *Fn, MultiExprArg Args,
17175 bool IsMember) {
17176 StringLiteral *Msg = Fn->getDeletedMessage();
17177 CandidateSet.NoteCandidates(
17178 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17179 << IsMember << Name << (Msg != nullptr)
17180 << (Msg ? Msg->getString() : StringRef())
17181 << Range),
17182 S&: *this, OCD: OCD_AllCandidates, Args);
17183}
17184