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/SemaAMDGPU.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaInternal.h"
37#include "clang/Sema/SemaObjC.h"
38#include "clang/Sema/Template.h"
39#include "clang/Sema/TemplateDeduction.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/STLForwardCompat.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdlib>
50#include <optional>
51
52using namespace clang;
53using namespace sema;
54
55using AllowedExplicit = Sema::AllowedExplicit;
56
57static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
58 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
59 return P->hasAttr<PassObjectSizeAttr>();
60 });
61}
62
63/// A convenience routine for creating a decayed reference to a function.
64static ExprResult CreateFunctionRefExpr(
65 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
66 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
67 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
68 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
69 return ExprError();
70 // If FoundDecl is different from Fn (such as if one is a template
71 // and the other a specialization), make sure DiagnoseUseOfDecl is
72 // called on both.
73 // FIXME: This would be more comprehensively addressed by modifying
74 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
75 // being used.
76 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
77 return ExprError();
78 DeclRefExpr *DRE = new (S.Context)
79 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
80 if (HadMultipleCandidates)
81 DRE->setHadMultipleCandidates(true);
82
83 S.MarkDeclRefReferenced(E: DRE, Base);
84 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
85 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
86 S.ResolveExceptionSpec(Loc, FPT);
87 DRE->setType(Fn->getType());
88 }
89 }
90 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
91 CK: CK_FunctionToPointerDecay);
92}
93
94static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
95 bool InOverloadResolution,
96 StandardConversionSequence &SCS,
97 bool CStyle,
98 bool AllowObjCWritebackConversion);
99
100static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
101 QualType &ToType,
102 bool InOverloadResolution,
103 StandardConversionSequence &SCS,
104 bool CStyle);
105static OverloadingResult
106IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
107 UserDefinedConversionSequence& User,
108 OverloadCandidateSet& Conversions,
109 AllowedExplicit AllowExplicit,
110 bool AllowObjCConversionOnExplicit);
111
112static ImplicitConversionSequence::CompareKind
113CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
114 const StandardConversionSequence& SCS1,
115 const StandardConversionSequence& SCS2);
116
117static ImplicitConversionSequence::CompareKind
118CompareQualificationConversions(Sema &S,
119 const StandardConversionSequence& SCS1,
120 const StandardConversionSequence& SCS2);
121
122static ImplicitConversionSequence::CompareKind
123CompareOverflowBehaviorConversions(Sema &S,
124 const StandardConversionSequence &SCS1,
125 const StandardConversionSequence &SCS2);
126
127static ImplicitConversionSequence::CompareKind
128CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
129 const StandardConversionSequence& SCS1,
130 const StandardConversionSequence& SCS2);
131
132/// GetConversionRank - Retrieve the implicit conversion rank
133/// corresponding to the given implicit conversion kind.
134ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
135 static const ImplicitConversionRank Rank[] = {
136 ICR_Exact_Match,
137 ICR_Exact_Match,
138 ICR_Exact_Match,
139 ICR_Exact_Match,
140 ICR_Exact_Match,
141 ICR_Exact_Match,
142 ICR_Promotion,
143 ICR_Promotion,
144 ICR_Promotion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_Conversion,
151 ICR_Conversion,
152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_OCL_Scalar_Widening,
158 ICR_Complex_Real_Conversion,
159 ICR_Conversion,
160 ICR_Conversion,
161 ICR_Writeback_Conversion,
162 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
163 // it was omitted by the patch that added
164 // ICK_Zero_Event_Conversion
165 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
166 // it was omitted by the patch that added
167 // ICK_Zero_Queue_Conversion
168 ICR_C_Conversion,
169 ICR_C_Conversion_Extension,
170 ICR_Conversion,
171 ICR_HLSL_Dimension_Reduction,
172 ICR_HLSL_Dimension_Reduction,
173 ICR_Conversion,
174 ICR_HLSL_Scalar_Widening,
175 ICR_HLSL_Scalar_Widening,
176 };
177 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
178 return Rank[(int)Kind];
179}
180
181ImplicitConversionRank
182clang::GetDimensionConversionRank(ImplicitConversionRank Base,
183 ImplicitConversionKind Dimension) {
184 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
185 if (Rank == ICR_HLSL_Scalar_Widening) {
186 if (Base == ICR_Promotion)
187 return ICR_HLSL_Scalar_Widening_Promotion;
188 if (Base == ICR_Conversion)
189 return ICR_HLSL_Scalar_Widening_Conversion;
190 }
191 if (Rank == ICR_HLSL_Dimension_Reduction) {
192 if (Base == ICR_Promotion)
193 return ICR_HLSL_Dimension_Reduction_Promotion;
194 if (Base == ICR_Conversion)
195 return ICR_HLSL_Dimension_Reduction_Conversion;
196 }
197 return Rank;
198}
199
200/// GetImplicitConversionName - Return the name of this kind of
201/// implicit conversion.
202static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
203 static const char *const Name[] = {
204 "No conversion",
205 "Lvalue-to-rvalue",
206 "Array-to-pointer",
207 "Function-to-pointer",
208 "Function pointer conversion",
209 "Qualification",
210 "Integral promotion",
211 "Floating point promotion",
212 "Complex promotion",
213 "Integral conversion",
214 "Floating conversion",
215 "Complex conversion",
216 "Floating-integral conversion",
217 "Pointer conversion",
218 "Pointer-to-member conversion",
219 "Boolean conversion",
220 "Compatible-types conversion",
221 "Derived-to-base conversion",
222 "Vector conversion",
223 "SVE Vector conversion",
224 "RVV Vector conversion",
225 "Vector splat",
226 "Complex-real conversion",
227 "Block Pointer conversion",
228 "Transparent Union Conversion",
229 "Writeback conversion",
230 "OpenCL Zero Event Conversion",
231 "OpenCL Zero Queue Conversion",
232 "C specific type conversion",
233 "Incompatible pointer conversion",
234 "Fixed point conversion",
235 "HLSL vector truncation",
236 "HLSL matrix truncation",
237 "Non-decaying array conversion",
238 "HLSL vector splat",
239 "HLSL matrix splat",
240 };
241 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
242 return Name[Kind];
243}
244
245/// StandardConversionSequence - Set the standard conversion
246/// sequence to the identity conversion.
247void StandardConversionSequence::setAsIdentityConversion() {
248 First = ICK_Identity;
249 Second = ICK_Identity;
250 Dimension = ICK_Identity;
251 Third = ICK_Identity;
252 DeprecatedStringLiteralToCharPtr = false;
253 QualificationIncludesObjCLifetime = false;
254 ReferenceBinding = false;
255 DirectBinding = false;
256 IsLvalueReference = true;
257 BindsToFunctionLvalue = false;
258 BindsToRvalue = false;
259 BindsImplicitObjectArgumentWithoutRefQualifier = false;
260 ObjCLifetimeConversionBinding = false;
261 FromBracedInitList = false;
262 CopyConstructor = nullptr;
263}
264
265/// getRank - Retrieve the rank of this standard conversion sequence
266/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
267/// implicit conversions.
268ImplicitConversionRank StandardConversionSequence::getRank() const {
269 ImplicitConversionRank Rank = ICR_Exact_Match;
270 if (GetConversionRank(Kind: First) > Rank)
271 Rank = GetConversionRank(Kind: First);
272 if (GetConversionRank(Kind: Second) > Rank)
273 Rank = GetConversionRank(Kind: Second);
274 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
275 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
276 if (GetConversionRank(Kind: Third) > Rank)
277 Rank = GetConversionRank(Kind: Third);
278 return Rank;
279}
280
281/// isPointerConversionToBool - Determines whether this conversion is
282/// a conversion of a pointer or pointer-to-member to bool. This is
283/// used as part of the ranking of standard conversion sequences
284/// (C++ 13.3.3.2p4).
285bool StandardConversionSequence::isPointerConversionToBool() const {
286 // Note that FromType has not necessarily been transformed by the
287 // array-to-pointer or function-to-pointer implicit conversions, so
288 // check for their presence as well as checking whether FromType is
289 // a pointer.
290 if (getToType(Idx: 1)->isBooleanType() &&
291 (getFromType()->isPointerType() ||
292 getFromType()->isMemberPointerType() ||
293 getFromType()->isObjCObjectPointerType() ||
294 getFromType()->isBlockPointerType() ||
295 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
296 return true;
297
298 return false;
299}
300
301/// isPointerConversionToVoidPointer - Determines whether this
302/// conversion is a conversion of a pointer to a void pointer. This is
303/// used as part of the ranking of standard conversion sequences (C++
304/// 13.3.3.2p4).
305bool
306StandardConversionSequence::
307isPointerConversionToVoidPointer(ASTContext& Context) const {
308 QualType FromType = getFromType();
309 QualType ToType = getToType(Idx: 1);
310
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer implicit conversion, so check for its presence
313 // and redo the conversion to get a pointer.
314 if (First == ICK_Array_To_Pointer)
315 FromType = Context.getArrayDecayedType(T: FromType);
316
317 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
318 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
319 return ToPtrType->getPointeeType()->isVoidType();
320
321 return false;
322}
323
324/// Skip any implicit casts which could be either part of a narrowing conversion
325/// or after one in an implicit conversion.
326static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
327 const Expr *Converted) {
328 // We can have cleanups wrapping the converted expression; these need to be
329 // preserved so that destructors run if necessary.
330 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
331 Expr *Inner =
332 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
333 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
334 objects: EWC->getObjects());
335 }
336
337 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
338 switch (ICE->getCastKind()) {
339 case CK_NoOp:
340 case CK_IntegralCast:
341 case CK_IntegralToBoolean:
342 case CK_IntegralToFloating:
343 case CK_BooleanToSignedIntegral:
344 case CK_FloatingToIntegral:
345 case CK_FloatingToBoolean:
346 case CK_FloatingCast:
347 Converted = ICE->getSubExpr();
348 continue;
349
350 default:
351 return Converted;
352 }
353 }
354
355 return Converted;
356}
357
358/// Check if this standard conversion sequence represents a narrowing
359/// conversion, according to C++11 [dcl.init.list]p7.
360///
361/// \param Ctx The AST context.
362/// \param Converted The result of applying this standard conversion sequence.
363/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
364/// value of the expression prior to the narrowing conversion.
365/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
366/// type of the expression prior to the narrowing conversion.
367/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
368/// from floating point types to integral types should be ignored.
369NarrowingKind StandardConversionSequence::getNarrowingKind(
370 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
371 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
372 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
373 "narrowing check outside C++");
374
375 // C++11 [dcl.init.list]p7:
376 // A narrowing conversion is an implicit conversion ...
377 QualType FromType = getToType(Idx: 0);
378 QualType ToType = getToType(Idx: 1);
379
380 // A conversion to an enumeration type is narrowing if the conversion to
381 // the underlying type is narrowing. This only arises for expressions of
382 // the form 'Enum{init}'.
383 if (const auto *ED = ToType->getAsEnumDecl())
384 ToType = ED->getIntegerType();
385
386 switch (Second) {
387 // 'bool' is an integral type; dispatch to the right place to handle it.
388 case ICK_Boolean_Conversion:
389 if (FromType->isRealFloatingType())
390 goto FloatingIntegralConversion;
391 if (FromType->isIntegralOrUnscopedEnumerationType())
392 goto IntegralConversion;
393 // -- from a pointer type or pointer-to-member type to bool, or
394 return NK_Type_Narrowing;
395
396 // -- from a floating-point type to an integer type, or
397 //
398 // -- from an integer type or unscoped enumeration type to a floating-point
399 // type, except where the source is a constant expression and the actual
400 // value after conversion will fit into the target type and will produce
401 // the original value when converted back to the original type, or
402 case ICK_Floating_Integral:
403 FloatingIntegralConversion:
404 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
405 return NK_Type_Narrowing;
406 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
407 ToType->isRealFloatingType()) {
408 if (IgnoreFloatToIntegralConversion)
409 return NK_Not_Narrowing;
410 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
411 assert(Initializer && "Unknown conversion expression");
412
413 // If it's value-dependent, we can't tell whether it's narrowing.
414 if (Initializer->isValueDependent())
415 return NK_Dependent_Narrowing;
416
417 if (std::optional<llvm::APSInt> IntConstantValue =
418 Initializer->getIntegerConstantExpr(Ctx)) {
419 // Convert the integer to the floating type.
420 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
421 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
422 RM: llvm::APFloat::rmNearestTiesToEven);
423 // And back.
424 llvm::APSInt ConvertedValue = *IntConstantValue;
425 bool ignored;
426 llvm::APFloat::opStatus Status = Result.convertToInteger(
427 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
428 // If the converted-back integer has unspecified value, or if the
429 // resulting value is different, this was a narrowing conversion.
430 if (Status == llvm::APFloat::opInvalidOp ||
431 *IntConstantValue != ConvertedValue) {
432 ConstantValue = APValue(*IntConstantValue);
433 ConstantType = Initializer->getType();
434 return NK_Constant_Narrowing;
435 }
436 } else {
437 // Variables are always narrowings.
438 return NK_Variable_Narrowing;
439 }
440 }
441 return NK_Not_Narrowing;
442
443 // -- from long double to double or float, or from double to float, except
444 // where the source is a constant expression and the actual value after
445 // conversion is within the range of values that can be represented (even
446 // if it cannot be represented exactly), or
447 case ICK_Floating_Conversion:
448 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
449 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
450 // FromType is larger than ToType.
451 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
452
453 // If it's value-dependent, we can't tell whether it's narrowing.
454 if (Initializer->isValueDependent())
455 return NK_Dependent_Narrowing;
456
457 Expr::EvalResult R;
458 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
459 ((Ctx.getLangOpts().CPlusPlus &&
460 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)))) {
461 // Constant!
462 if (Ctx.getLangOpts().C23)
463 ConstantValue = R.Val;
464 assert(ConstantValue.isFloat());
465 llvm::APFloat FloatVal = ConstantValue.getFloat();
466 // Convert the source value into the target type.
467 bool ignored;
468 llvm::APFloat Converted = FloatVal;
469 llvm::APFloat::opStatus ConvertStatus =
470 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
471 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
472 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
473 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
474 if (Ctx.getLangOpts().C23) {
475 if (FloatVal.isNaN() && Converted.isNaN() &&
476 !FloatVal.isSignaling() && !Converted.isSignaling()) {
477 // Quiet NaNs are considered the same value, regardless of
478 // payloads.
479 return NK_Not_Narrowing;
480 }
481 // For normal values, check exact equality.
482 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
483 ConstantType = Initializer->getType();
484 return NK_Constant_Narrowing;
485 }
486 } else {
487 // If there was no overflow, the source value is within the range of
488 // values that can be represented.
489 if (ConvertStatus & llvm::APFloat::opOverflow) {
490 ConstantType = Initializer->getType();
491 return NK_Constant_Narrowing;
492 }
493 }
494 } else {
495 return NK_Variable_Narrowing;
496 }
497 }
498 return NK_Not_Narrowing;
499
500 // -- from an integer type or unscoped enumeration type to an integer type
501 // that cannot represent all the values of the original type, except where
502 // (CWG2627) -- the source is a bit-field whose width w is less than that
503 // of its type (or, for an enumeration type, its underlying type) and the
504 // target type can represent all the values of a hypothetical extended
505 // integer type with width w and with the same signedness as the original
506 // type or
507 // -- the source is a constant expression and the actual value after
508 // conversion will fit into the target type and will produce the original
509 // value when converted back to the original type.
510 case ICK_Integral_Conversion:
511 IntegralConversion: {
512 assert(FromType->isIntegralOrUnscopedEnumerationType());
513 assert(ToType->isIntegralOrUnscopedEnumerationType());
514 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
515 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
516 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
517 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
518
519 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
520 bool ToSigned, unsigned ToWidth) {
521 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
522 !(FromSigned && !ToSigned);
523 };
524
525 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // Not all values of FromType can be represented in ToType.
529 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
530
531 bool DependentBitField = false;
532 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
533 if (BitField->getBitWidth()->isValueDependent())
534 DependentBitField = true;
535 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
536 BitFieldWidth < FromWidth) {
537 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
538 return NK_Not_Narrowing;
539
540 // The initializer will be truncated to the bit-field width
541 FromWidth = BitFieldWidth;
542 }
543 }
544
545 // If it's value-dependent, we can't tell whether it's narrowing.
546 if (Initializer->isValueDependent())
547 return NK_Dependent_Narrowing;
548
549 std::optional<llvm::APSInt> OptInitializerValue =
550 Initializer->getIntegerConstantExpr(Ctx);
551 if (!OptInitializerValue) {
552 // If the bit-field width was dependent, it might end up being small
553 // enough to fit in the target type (unless the target type is unsigned
554 // and the source type is signed, in which case it will never fit)
555 if (DependentBitField && !(FromSigned && !ToSigned))
556 return NK_Dependent_Narrowing;
557
558 // Otherwise, such a conversion is always narrowing
559 return NK_Variable_Narrowing;
560 }
561 llvm::APSInt &InitializerValue = *OptInitializerValue;
562 bool Narrowing = false;
563 if (FromWidth < ToWidth) {
564 // Negative -> unsigned is narrowing. Otherwise, more bits is never
565 // narrowing.
566 if (InitializerValue.isSigned() && InitializerValue.isNegative())
567 Narrowing = true;
568 } else {
569 // Add a bit to the InitializerValue so we don't have to worry about
570 // signed vs. unsigned comparisons.
571 InitializerValue =
572 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
573 // Convert the initializer to and from the target width and signed-ness.
574 llvm::APSInt ConvertedValue = InitializerValue;
575 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
576 ConvertedValue.setIsSigned(ToSigned);
577 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
578 ConvertedValue.setIsSigned(InitializerValue.isSigned());
579 // If the result is different, this was a narrowing conversion.
580 if (ConvertedValue != InitializerValue)
581 Narrowing = true;
582 }
583 if (Narrowing) {
584 ConstantType = Initializer->getType();
585 ConstantValue = APValue(InitializerValue);
586 return NK_Constant_Narrowing;
587 }
588
589 return NK_Not_Narrowing;
590 }
591 case ICK_Complex_Real:
592 if (FromType->isComplexType() && !ToType->isComplexType())
593 return NK_Type_Narrowing;
594 return NK_Not_Narrowing;
595
596 case ICK_Floating_Promotion:
597 if (Ctx.getLangOpts().C23) {
598 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
599 Expr::EvalResult R;
600 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
601 ConstantValue = R.Val;
602 assert(ConstantValue.isFloat());
603 llvm::APFloat FloatVal = ConstantValue.getFloat();
604 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
605 // value, the unqualified versions of the type of the initializer and
606 // the corresponding real type of the object declared shall be
607 // compatible.
608 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
609 ConstantType = Initializer->getType();
610 return NK_Constant_Narrowing;
611 }
612 }
613 }
614 return NK_Not_Narrowing;
615 default:
616 // Other kinds of conversions are not narrowings.
617 return NK_Not_Narrowing;
618 }
619}
620
621/// dump - Print this standard conversion sequence to standard
622/// error. Useful for debugging overloading issues.
623LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
624 raw_ostream &OS = llvm::errs();
625 bool PrintedSomething = false;
626 if (First != ICK_Identity) {
627 OS << GetImplicitConversionName(Kind: First);
628 PrintedSomething = true;
629 }
630
631 if (Second != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
635 OS << GetImplicitConversionName(Kind: Second);
636
637 if (CopyConstructor) {
638 OS << " (by copy constructor)";
639 } else if (DirectBinding) {
640 OS << " (direct reference binding)";
641 } else if (ReferenceBinding) {
642 OS << " (reference binding)";
643 }
644 PrintedSomething = true;
645 }
646
647 if (Third != ICK_Identity) {
648 if (PrintedSomething) {
649 OS << " -> ";
650 }
651 OS << GetImplicitConversionName(Kind: Third);
652 PrintedSomething = true;
653 }
654
655 if (!PrintedSomething) {
656 OS << "No conversions required";
657 }
658}
659
660/// dump - Print this user-defined conversion sequence to standard
661/// error. Useful for debugging overloading issues.
662void UserDefinedConversionSequence::dump() const {
663 raw_ostream &OS = llvm::errs();
664 if (Before.First || Before.Second || Before.Third) {
665 Before.dump();
666 OS << " -> ";
667 }
668 if (ConversionFunction)
669 OS << '\'' << *ConversionFunction << '\'';
670 else
671 OS << "aggregate initialization";
672 if (After.First || After.Second || After.Third) {
673 OS << " -> ";
674 After.dump();
675 }
676}
677
678/// dump - Print this implicit conversion sequence to standard
679/// error. Useful for debugging overloading issues.
680void ImplicitConversionSequence::dump() const {
681 raw_ostream &OS = llvm::errs();
682 if (hasInitializerListContainerType())
683 OS << "Worst list element conversion: ";
684 switch (ConversionKind) {
685 case StandardConversion:
686 OS << "Standard conversion: ";
687 Standard.dump();
688 break;
689 case UserDefinedConversion:
690 OS << "User-defined conversion: ";
691 UserDefined.dump();
692 break;
693 case EllipsisConversion:
694 OS << "Ellipsis conversion";
695 break;
696 case AmbiguousConversion:
697 OS << "Ambiguous conversion";
698 break;
699 case BadConversion:
700 OS << "Bad conversion";
701 break;
702 }
703
704 OS << "\n";
705}
706
707void AmbiguousConversionSequence::construct() {
708 new (&conversions()) ConversionSet();
709}
710
711void AmbiguousConversionSequence::destruct() {
712 conversions().~ConversionSet();
713}
714
715void
716AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
717 FromTypePtr = O.FromTypePtr;
718 ToTypePtr = O.ToTypePtr;
719 new (&conversions()) ConversionSet(O.conversions());
720}
721
722namespace {
723 // Structure used by DeductionFailureInfo to store
724 // template argument information.
725 struct DFIArguments {
726 TemplateArgument FirstArg;
727 TemplateArgument SecondArg;
728 };
729 // Structure used by DeductionFailureInfo to store
730 // template parameter and template argument information.
731 struct DFIParamWithArguments : DFIArguments {
732 TemplateParameter Param;
733 };
734 // Structure used by DeductionFailureInfo to store template argument
735 // information and the index of the problematic call argument.
736 struct DFIDeducedMismatchArgs : DFIArguments {
737 TemplateArgumentList *TemplateArgs;
738 unsigned CallArgIndex;
739 };
740 // Structure used by DeductionFailureInfo to store information about
741 // unsatisfied constraints.
742 struct CNSInfo {
743 TemplateArgumentList *TemplateArgs;
744 ConstraintSatisfaction Satisfaction;
745 };
746}
747
748/// Convert from Sema's representation of template deduction information
749/// to the form used in overload-candidate information.
750DeductionFailureInfo
751clang::MakeDeductionFailureInfo(ASTContext &Context,
752 TemplateDeductionResult TDK,
753 TemplateDeductionInfo &Info) {
754 DeductionFailureInfo Result;
755 Result.Result = static_cast<unsigned>(TDK);
756 Result.HasDiagnostic = false;
757 switch (TDK) {
758 case TemplateDeductionResult::Invalid:
759 case TemplateDeductionResult::InstantiationDepth:
760 case TemplateDeductionResult::TooManyArguments:
761 case TemplateDeductionResult::TooFewArguments:
762 case TemplateDeductionResult::MiscellaneousDeductionFailure:
763 case TemplateDeductionResult::CUDATargetMismatch:
764 Result.Data = nullptr;
765 break;
766
767 case TemplateDeductionResult::Incomplete:
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
770 case TemplateDeductionResult::InvalidExplicitArguments:
771 Result.Data = Info.Param.getOpaqueValue();
772 if (Info.hasSFINAEDiagnostic()) {
773 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
774 SourceLocation(), PartialDiagnostic::NullDiagnostic());
775 Info.takeSFINAEDiagnostic(PD&: *Diag);
776 Result.HasDiagnostic = true;
777 }
778 break;
779
780 case TemplateDeductionResult::DeducedMismatch:
781 case TemplateDeductionResult::DeducedMismatchNested: {
782 // FIXME: Should allocate from normal heap so that we can free this later.
783 auto *Saved = new (Context) DFIDeducedMismatchArgs;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Saved->TemplateArgs = Info.takeSugared();
787 Saved->CallArgIndex = Info.CallArgIndex;
788 Result.Data = Saved;
789 break;
790 }
791
792 case TemplateDeductionResult::NonDeducedMismatch: {
793 // FIXME: Should allocate from normal heap so that we can free this later.
794 DFIArguments *Saved = new (Context) DFIArguments;
795 Saved->FirstArg = Info.FirstArg;
796 Saved->SecondArg = Info.SecondArg;
797 Result.Data = Saved;
798 break;
799 }
800
801 case TemplateDeductionResult::IncompletePack:
802 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
803 case TemplateDeductionResult::Inconsistent:
804 case TemplateDeductionResult::Underqualified: {
805 // FIXME: Should allocate from normal heap so that we can free this later.
806 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
807 Saved->Param = Info.Param;
808 Saved->FirstArg = Info.FirstArg;
809 Saved->SecondArg = Info.SecondArg;
810 Result.Data = Saved;
811 break;
812 }
813
814 case TemplateDeductionResult::SubstitutionFailure:
815 Result.Data = Info.takeSugared();
816 if (Info.hasSFINAEDiagnostic()) {
817 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
818 SourceLocation(), PartialDiagnostic::NullDiagnostic());
819 Info.takeSFINAEDiagnostic(PD&: *Diag);
820 Result.HasDiagnostic = true;
821 }
822 break;
823
824 case TemplateDeductionResult::ConstraintsNotSatisfied: {
825 CNSInfo *Saved = new (Context) CNSInfo;
826 Saved->TemplateArgs = Info.takeSugared();
827 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
828 Result.Data = Saved;
829 break;
830 }
831
832 case TemplateDeductionResult::Success:
833 case TemplateDeductionResult::NonDependentConversionFailure:
834 case TemplateDeductionResult::AlreadyDiagnosed:
835 llvm_unreachable("not a deduction failure");
836 }
837
838 return Result;
839}
840
841void DeductionFailureInfo::Destroy() {
842 switch (static_cast<TemplateDeductionResult>(Result)) {
843 case TemplateDeductionResult::Success:
844 case TemplateDeductionResult::Invalid:
845 case TemplateDeductionResult::InstantiationDepth:
846 case TemplateDeductionResult::Incomplete:
847 case TemplateDeductionResult::TooManyArguments:
848 case TemplateDeductionResult::TooFewArguments:
849 case TemplateDeductionResult::CUDATargetMismatch:
850 case TemplateDeductionResult::NonDependentConversionFailure:
851 break;
852
853 case TemplateDeductionResult::IncompletePack:
854 case TemplateDeductionResult::Inconsistent:
855 case TemplateDeductionResult::Underqualified:
856 case TemplateDeductionResult::DeducedMismatch:
857 case TemplateDeductionResult::DeducedMismatchNested:
858 case TemplateDeductionResult::NonDeducedMismatch:
859 // FIXME: Destroy the data?
860 Data = nullptr;
861 break;
862
863 case TemplateDeductionResult::InvalidExplicitArguments:
864 case TemplateDeductionResult::SubstitutionFailure:
865 // FIXME: Destroy the template argument list?
866 Data = nullptr;
867 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
873 case TemplateDeductionResult::ConstraintsNotSatisfied:
874 // FIXME: Destroy the template argument list?
875 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
876 Data = nullptr;
877 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
878 Diag->~PartialDiagnosticAt();
879 HasDiagnostic = false;
880 }
881 break;
882
883 // Unhandled
884 case TemplateDeductionResult::MiscellaneousDeductionFailure:
885 case TemplateDeductionResult::AlreadyDiagnosed:
886 break;
887 }
888}
889
890PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
891 if (HasDiagnostic)
892 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
893 return nullptr;
894}
895
896TemplateParameter DeductionFailureInfo::getTemplateParameter() {
897 switch (static_cast<TemplateDeductionResult>(Result)) {
898 case TemplateDeductionResult::Success:
899 case TemplateDeductionResult::Invalid:
900 case TemplateDeductionResult::InstantiationDepth:
901 case TemplateDeductionResult::TooManyArguments:
902 case TemplateDeductionResult::TooFewArguments:
903 case TemplateDeductionResult::SubstitutionFailure:
904 case TemplateDeductionResult::DeducedMismatch:
905 case TemplateDeductionResult::DeducedMismatchNested:
906 case TemplateDeductionResult::NonDeducedMismatch:
907 case TemplateDeductionResult::CUDATargetMismatch:
908 case TemplateDeductionResult::NonDependentConversionFailure:
909 case TemplateDeductionResult::ConstraintsNotSatisfied:
910 return TemplateParameter();
911
912 case TemplateDeductionResult::Incomplete:
913 case TemplateDeductionResult::InvalidExplicitArguments:
914 return TemplateParameter::getFromOpaqueValue(VP: Data);
915
916 case TemplateDeductionResult::IncompletePack:
917 case TemplateDeductionResult::Inconsistent:
918 case TemplateDeductionResult::Underqualified:
919 return static_cast<DFIParamWithArguments*>(Data)->Param;
920
921 // Unhandled
922 case TemplateDeductionResult::MiscellaneousDeductionFailure:
923 case TemplateDeductionResult::AlreadyDiagnosed:
924 break;
925 }
926
927 return TemplateParameter();
928}
929
930TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
931 switch (static_cast<TemplateDeductionResult>(Result)) {
932 case TemplateDeductionResult::Success:
933 case TemplateDeductionResult::Invalid:
934 case TemplateDeductionResult::InstantiationDepth:
935 case TemplateDeductionResult::TooManyArguments:
936 case TemplateDeductionResult::TooFewArguments:
937 case TemplateDeductionResult::Incomplete:
938 case TemplateDeductionResult::IncompletePack:
939 case TemplateDeductionResult::InvalidExplicitArguments:
940 case TemplateDeductionResult::Inconsistent:
941 case TemplateDeductionResult::Underqualified:
942 case TemplateDeductionResult::NonDeducedMismatch:
943 case TemplateDeductionResult::CUDATargetMismatch:
944 case TemplateDeductionResult::NonDependentConversionFailure:
945 return nullptr;
946
947 case TemplateDeductionResult::DeducedMismatch:
948 case TemplateDeductionResult::DeducedMismatchNested:
949 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
950
951 case TemplateDeductionResult::SubstitutionFailure:
952 return static_cast<TemplateArgumentList*>(Data);
953
954 case TemplateDeductionResult::ConstraintsNotSatisfied:
955 return static_cast<CNSInfo*>(Data)->TemplateArgs;
956
957 // Unhandled
958 case TemplateDeductionResult::MiscellaneousDeductionFailure:
959 case TemplateDeductionResult::AlreadyDiagnosed:
960 break;
961 }
962
963 return nullptr;
964}
965
966const TemplateArgument *DeductionFailureInfo::getFirstArg() {
967 switch (static_cast<TemplateDeductionResult>(Result)) {
968 case TemplateDeductionResult::Success:
969 case TemplateDeductionResult::Invalid:
970 case TemplateDeductionResult::InstantiationDepth:
971 case TemplateDeductionResult::Incomplete:
972 case TemplateDeductionResult::TooManyArguments:
973 case TemplateDeductionResult::TooFewArguments:
974 case TemplateDeductionResult::InvalidExplicitArguments:
975 case TemplateDeductionResult::SubstitutionFailure:
976 case TemplateDeductionResult::CUDATargetMismatch:
977 case TemplateDeductionResult::NonDependentConversionFailure:
978 case TemplateDeductionResult::ConstraintsNotSatisfied:
979 return nullptr;
980
981 case TemplateDeductionResult::IncompletePack:
982 case TemplateDeductionResult::Inconsistent:
983 case TemplateDeductionResult::Underqualified:
984 case TemplateDeductionResult::DeducedMismatch:
985 case TemplateDeductionResult::DeducedMismatchNested:
986 case TemplateDeductionResult::NonDeducedMismatch:
987 return &static_cast<DFIArguments*>(Data)->FirstArg;
988
989 // Unhandled
990 case TemplateDeductionResult::MiscellaneousDeductionFailure:
991 case TemplateDeductionResult::AlreadyDiagnosed:
992 break;
993 }
994
995 return nullptr;
996}
997
998const TemplateArgument *DeductionFailureInfo::getSecondArg() {
999 switch (static_cast<TemplateDeductionResult>(Result)) {
1000 case TemplateDeductionResult::Success:
1001 case TemplateDeductionResult::Invalid:
1002 case TemplateDeductionResult::InstantiationDepth:
1003 case TemplateDeductionResult::Incomplete:
1004 case TemplateDeductionResult::IncompletePack:
1005 case TemplateDeductionResult::TooManyArguments:
1006 case TemplateDeductionResult::TooFewArguments:
1007 case TemplateDeductionResult::InvalidExplicitArguments:
1008 case TemplateDeductionResult::SubstitutionFailure:
1009 case TemplateDeductionResult::CUDATargetMismatch:
1010 case TemplateDeductionResult::NonDependentConversionFailure:
1011 case TemplateDeductionResult::ConstraintsNotSatisfied:
1012 return nullptr;
1013
1014 case TemplateDeductionResult::Inconsistent:
1015 case TemplateDeductionResult::Underqualified:
1016 case TemplateDeductionResult::DeducedMismatch:
1017 case TemplateDeductionResult::DeducedMismatchNested:
1018 case TemplateDeductionResult::NonDeducedMismatch:
1019 return &static_cast<DFIArguments*>(Data)->SecondArg;
1020
1021 // Unhandled
1022 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1023 case TemplateDeductionResult::AlreadyDiagnosed:
1024 break;
1025 }
1026
1027 return nullptr;
1028}
1029
1030UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1031 switch (static_cast<TemplateDeductionResult>(Result)) {
1032 case TemplateDeductionResult::DeducedMismatch:
1033 case TemplateDeductionResult::DeducedMismatchNested:
1034 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1035
1036 default:
1037 return std::nullopt;
1038 }
1039}
1040
1041static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1042 const FunctionDecl *Y) {
1043 if (!X || !Y)
1044 return false;
1045 if (X->getNumParams() != Y->getNumParams())
1046 return false;
1047 // FIXME: when do rewritten comparison operators
1048 // with explicit object parameters correspond?
1049 // https://cplusplus.github.io/CWG/issues/2797.html
1050 for (unsigned I = 0; I < X->getNumParams(); ++I)
1051 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1052 T2: Y->getParamDecl(i: I)->getType()))
1053 return false;
1054 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1055 auto *FTY = Y->getDescribedFunctionTemplate();
1056 if (!FTY)
1057 return false;
1058 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1059 Y: FTY->getTemplateParameters()))
1060 return false;
1061 }
1062 return true;
1063}
1064
1065static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1066 Expr *FirstOperand, FunctionDecl *EqFD) {
1067 assert(EqFD->getOverloadedOperator() ==
1068 OverloadedOperatorKind::OO_EqualEqual);
1069 // C++2a [over.match.oper]p4:
1070 // A non-template function or function template F named operator== is a
1071 // rewrite target with first operand o unless a search for the name operator!=
1072 // in the scope S from the instantiation context of the operator expression
1073 // finds a function or function template that would correspond
1074 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1075 // scope of the class type of o if F is a class member, and the namespace
1076 // scope of which F is a member otherwise. A function template specialization
1077 // named operator== is a rewrite target if its function template is a rewrite
1078 // target.
1079 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1080 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1081 if (isa<CXXMethodDecl>(Val: EqFD)) {
1082 // If F is a class member, search scope is class type of first operand.
1083 QualType RHS = FirstOperand->getType();
1084 auto *RHSRec = RHS->getAsCXXRecordDecl();
1085 if (!RHSRec)
1086 return true;
1087 LookupResult Members(S, NotEqOp, OpLoc,
1088 Sema::LookupNameKind::LookupMemberName);
1089 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1090 Members.suppressAccessDiagnostics();
1091 for (NamedDecl *Op : Members)
1092 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1093 return false;
1094 return true;
1095 }
1096 // Otherwise the search scope is the namespace scope of which F is a member.
1097 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1098 auto *NotEqFD = Op->getAsFunction();
1099 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1100 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1101 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1102 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1103 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1104 return false;
1105 }
1106 return true;
1107}
1108
1109bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1110 OverloadedOperatorKind Op) const {
1111 if (!AllowRewrittenCandidates)
1112 return false;
1113 return Op == OO_EqualEqual || Op == OO_Spaceship;
1114}
1115
1116bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1117 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1118 auto Op = FD->getOverloadedOperator();
1119 if (!allowsReversed(Op))
1120 return false;
1121 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1122 assert(OriginalArgs.size() == 2);
1123 if (!shouldAddReversedEqEq(
1124 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1125 return false;
1126 }
1127 // Don't bother adding a reversed candidate that can never be a better
1128 // match than the non-reversed version.
1129 return FD->getNumNonObjectParams() != 2 ||
1130 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1131 T2: FD->getParamDecl(i: 1)->getType()) ||
1132 FD->hasAttr<EnableIfAttr>();
1133}
1134
1135void OverloadCandidateSet::destroyCandidates() {
1136 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1137 for (auto &C : i->Conversions)
1138 C.~ImplicitConversionSequence();
1139 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1140 i->DeductionFailure.Destroy();
1141 }
1142}
1143
1144void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1145 destroyCandidates();
1146 SlabAllocator.Reset();
1147 NumInlineBytesUsed = 0;
1148 Candidates.clear();
1149 Functions.clear();
1150 Kind = CSK;
1151 FirstDeferredCandidate = nullptr;
1152 DeferredCandidatesCount = 0;
1153 HasDeferredTemplateConstructors = false;
1154 ResolutionByPerfectCandidateIsDisabled = false;
1155}
1156
1157namespace {
1158 class UnbridgedCastsSet {
1159 struct Entry {
1160 Expr **Addr;
1161 Expr *Saved;
1162 };
1163 SmallVector<Entry, 2> Entries;
1164
1165 public:
1166 void save(Sema &S, Expr *&E) {
1167 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1168 Entry entry = { .Addr: &E, .Saved: E };
1169 Entries.push_back(Elt: entry);
1170 E = S.ObjC().stripARCUnbridgedCast(e: E);
1171 }
1172
1173 void restore() {
1174 for (SmallVectorImpl<Entry>::iterator
1175 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1176 *i->Addr = i->Saved;
1177 }
1178 };
1179}
1180
1181/// checkPlaceholderForOverload - Do any interesting placeholder-like
1182/// preprocessing on the given expression.
1183///
1184/// \param unbridgedCasts a collection to which to add unbridged casts;
1185/// without this, they will be immediately diagnosed as errors
1186///
1187/// Return true on unrecoverable error.
1188static bool
1189checkPlaceholderForOverload(Sema &S, Expr *&E,
1190 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1191 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1192 // We can't handle overloaded expressions here because overload
1193 // resolution might reasonably tweak them.
1194 if (placeholder->getKind() == BuiltinType::Overload) return false;
1195
1196 // If the context potentially accepts unbridged ARC casts, strip
1197 // the unbridged cast and add it to the collection for later restoration.
1198 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1199 unbridgedCasts) {
1200 unbridgedCasts->save(S, E);
1201 return false;
1202 }
1203
1204 // Go ahead and check everything else.
1205 ExprResult result = S.CheckPlaceholderExpr(E);
1206 if (result.isInvalid())
1207 return true;
1208
1209 E = result.get();
1210 return false;
1211 }
1212
1213 // Nothing to do.
1214 return false;
1215}
1216
1217/// checkArgPlaceholdersForOverload - Check a set of call operands for
1218/// placeholders.
1219static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1220 UnbridgedCastsSet &unbridged) {
1221 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1222 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1223 return true;
1224
1225 return false;
1226}
1227
1228OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1229 const LookupResult &Old, NamedDecl *&Match,
1230 bool NewIsUsingDecl) {
1231 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1232 I != E; ++I) {
1233 NamedDecl *OldD = *I;
1234
1235 bool OldIsUsingDecl = false;
1236 if (isa<UsingShadowDecl>(Val: OldD)) {
1237 OldIsUsingDecl = true;
1238
1239 // We can always introduce two using declarations into the same
1240 // context, even if they have identical signatures.
1241 if (NewIsUsingDecl) continue;
1242
1243 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1244 }
1245
1246 // A using-declaration does not conflict with another declaration
1247 // if one of them is hidden.
1248 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1249 continue;
1250
1251 // If either declaration was introduced by a using declaration,
1252 // we'll need to use slightly different rules for matching.
1253 // Essentially, these rules are the normal rules, except that
1254 // function templates hide function templates with different
1255 // return types or template parameter lists.
1256 bool UseMemberUsingDeclRules =
1257 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1258 !New->getFriendObjectKind();
1259
1260 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1261 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1262 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1263 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1264 continue;
1265 }
1266
1267 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1268 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1269 continue;
1270
1271 Match = *I;
1272 return OverloadKind::Match;
1273 }
1274
1275 // Builtins that have custom typechecking or have a reference should
1276 // not be overloadable or redeclarable.
1277 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1278 Match = *I;
1279 return OverloadKind::NonFunction;
1280 }
1281 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1282 // We can overload with these, which can show up when doing
1283 // redeclaration checks for UsingDecls.
1284 assert(Old.getLookupKind() == LookupUsingDeclName);
1285 } else if (isa<TagDecl>(Val: OldD)) {
1286 // We can always overload with tags by hiding them.
1287 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1288 // Optimistically assume that an unresolved using decl will
1289 // overload; if it doesn't, we'll have to diagnose during
1290 // template instantiation.
1291 //
1292 // Exception: if the scope is dependent and this is not a class
1293 // member, the using declaration can only introduce an enumerator.
1294 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1295 Match = *I;
1296 return OverloadKind::NonFunction;
1297 }
1298 } else {
1299 // (C++ 13p1):
1300 // Only function declarations can be overloaded; object and type
1301 // declarations cannot be overloaded.
1302 Match = *I;
1303 return OverloadKind::NonFunction;
1304 }
1305 }
1306
1307 // C++ [temp.friend]p1:
1308 // For a friend function declaration that is not a template declaration:
1309 // -- if the name of the friend is a qualified or unqualified template-id,
1310 // [...], otherwise
1311 // -- if the name of the friend is a qualified-id and a matching
1312 // non-template function is found in the specified class or namespace,
1313 // the friend declaration refers to that function, otherwise,
1314 // -- if the name of the friend is a qualified-id and a matching function
1315 // template is found in the specified class or namespace, the friend
1316 // declaration refers to the deduced specialization of that function
1317 // template, otherwise
1318 // -- the name shall be an unqualified-id [...]
1319 // If we get here for a qualified friend declaration, we've just reached the
1320 // third bullet. If the type of the friend is dependent, skip this lookup
1321 // until instantiation.
1322 if (New->getFriendObjectKind() && New->getQualifier() &&
1323 !New->getDescribedFunctionTemplate() &&
1324 !New->getDependentSpecializationInfo() &&
1325 !New->getType()->isDependentType()) {
1326 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1327 TemplateSpecResult.addAllDecls(Other: Old);
1328 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1329 /*QualifiedFriend*/true)) {
1330 New->setInvalidDecl();
1331 return OverloadKind::Overload;
1332 }
1333
1334 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1335 return OverloadKind::Match;
1336 }
1337
1338 return OverloadKind::Overload;
1339}
1340
1341template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1342 assert(D && "function decl should not be null");
1343 if (auto *A = D->getAttr<AttrT>())
1344 return !A->isImplicit();
1345 return false;
1346}
1347
1348static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1349 FunctionDecl *Old,
1350 bool UseMemberUsingDeclRules,
1351 bool ConsiderCudaAttrs,
1352 bool UseOverrideRules = false) {
1353 // C++ [basic.start.main]p2: This function shall not be overloaded.
1354 if (New->isMain())
1355 return false;
1356
1357 // MSVCRT user defined entry points cannot be overloaded.
1358 if (New->isMSVCRTEntryPoint())
1359 return false;
1360
1361 NamedDecl *OldDecl = Old;
1362 NamedDecl *NewDecl = New;
1363 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1364 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1365
1366 // C++ [temp.fct]p2:
1367 // A function template can be overloaded with other function templates
1368 // and with normal (non-template) functions.
1369 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1370 return true;
1371
1372 // Is the function New an overload of the function Old?
1373 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1374 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1375
1376 // Compare the signatures (C++ 1.3.10) of the two functions to
1377 // determine whether they are overloads. If we find any mismatch
1378 // in the signature, they are overloads.
1379
1380 // If either of these functions is a K&R-style function (no
1381 // prototype), then we consider them to have matching signatures.
1382 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1383 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1384 return false;
1385
1386 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1387 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1388
1389 // The signature of a function includes the types of its
1390 // parameters (C++ 1.3.10), which includes the presence or absence
1391 // of the ellipsis; see C++ DR 357).
1392 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1393 return true;
1394
1395 // For member-like friends, the enclosing class is part of the signature.
1396 if ((New->isMemberLikeConstrainedFriend() ||
1397 Old->isMemberLikeConstrainedFriend()) &&
1398 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1399 return true;
1400
1401 // Compare the parameter lists.
1402 // This can only be done once we have establish that friend functions
1403 // inhabit the same context, otherwise we might tried to instantiate
1404 // references to non-instantiated entities during constraint substitution.
1405 // GH78101.
1406 if (NewTemplate) {
1407 OldDecl = OldTemplate;
1408 NewDecl = NewTemplate;
1409 // C++ [temp.over.link]p4:
1410 // The signature of a function template consists of its function
1411 // signature, its return type and its template parameter list. The names
1412 // of the template parameters are significant only for establishing the
1413 // relationship between the template parameters and the rest of the
1414 // signature.
1415 //
1416 // We check the return type and template parameter lists for function
1417 // templates first; the remaining checks follow.
1418 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1419 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1420 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1421 bool SameReturnType = SemaRef.Context.hasSameType(
1422 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1423 // FIXME(GH58571): Match template parameter list even for non-constrained
1424 // template heads. This currently ensures that the code prior to C++20 is
1425 // not newly broken.
1426 bool ConstraintsInTemplateHead =
1427 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1428 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1429 // C++ [namespace.udecl]p11:
1430 // The set of declarations named by a using-declarator that inhabits a
1431 // class C does not include member functions and member function
1432 // templates of a base class that "correspond" to (and thus would
1433 // conflict with) a declaration of a function or function template in
1434 // C.
1435 // Comparing return types is not required for the "correspond" check to
1436 // decide whether a member introduced by a shadow declaration is hidden.
1437 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1438 !SameTemplateParameterList)
1439 return true;
1440 if (!UseMemberUsingDeclRules &&
1441 (!SameTemplateParameterList || !SameReturnType))
1442 return true;
1443 }
1444
1445 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1446 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1447
1448 int OldParamsOffset = 0;
1449 int NewParamsOffset = 0;
1450
1451 // When determining if a method is an overload from a base class, act as if
1452 // the implicit object parameter are of the same type.
1453
1454 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1455 if (M->isExplicitObjectMemberFunction()) {
1456 auto ThisType = M->getFunctionObjectParameterReferenceType();
1457 if (ThisType.isConstQualified())
1458 Q.removeConst();
1459 return Q;
1460 }
1461
1462 // We do not allow overloading based off of '__restrict'.
1463 Q.removeRestrict();
1464
1465 // We may not have applied the implicit const for a constexpr member
1466 // function yet (because we haven't yet resolved whether this is a static
1467 // or non-static member function). Add it now, on the assumption that this
1468 // is a redeclaration of OldMethod.
1469 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1470 (M->isConstexpr() || M->isConsteval()) &&
1471 !isa<CXXConstructorDecl>(Val: NewMethod))
1472 Q.addConst();
1473 return Q;
1474 };
1475
1476 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1477 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1478 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1479
1480 if (OldMethod->isExplicitObjectMemberFunction()) {
1481 BS.Quals.removeVolatile();
1482 DS.Quals.removeVolatile();
1483 }
1484
1485 return BS.Quals == DS.Quals;
1486 };
1487
1488 auto CompareType = [&](QualType Base, QualType D) {
1489 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1490 auto DS = D.getNonReferenceType().getCanonicalType().split();
1491
1492 if (!AreQualifiersEqual(BS, DS))
1493 return false;
1494
1495 if (OldMethod->isImplicitObjectMemberFunction() &&
1496 OldMethod->getParent() != NewMethod->getParent()) {
1497 CanQualType ParentType =
1498 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1499 if (ParentType.getTypePtr() != BS.Ty)
1500 return false;
1501 BS.Ty = DS.Ty;
1502 }
1503
1504 // FIXME: should we ignore some type attributes here?
1505 if (BS.Ty != DS.Ty)
1506 return false;
1507
1508 if (Base->isLValueReferenceType())
1509 return D->isLValueReferenceType();
1510 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1511 };
1512
1513 // If the function is a class member, its signature includes the
1514 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1515 auto DiagnoseInconsistentRefQualifiers = [&]() {
1516 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1517 return false;
1518 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1519 return false;
1520 if (OldMethod->isExplicitObjectMemberFunction() ||
1521 NewMethod->isExplicitObjectMemberFunction())
1522 return false;
1523 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1524 NewMethod->getRefQualifier() == RQ_None)) {
1525 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1526 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1527 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1528 return true;
1529 }
1530 return false;
1531 };
1532
1533 // We look at the parameters first, as it is the common case.
1534 // However we should not emit diagnostic before checking
1535 // the overloads do not differ by constraints or other discriminant.
1536 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1537 bool HaveInconsistentQualifiers = false;
1538
1539 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1540 OldParamsOffset++;
1541 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1542 NewParamsOffset++;
1543
1544 if (OldType->getNumParams() - OldParamsOffset !=
1545 NewType->getNumParams() - NewParamsOffset ||
1546 !SemaRef.FunctionParamTypesAreEqual(
1547 Old: {OldType->param_type_begin() + OldParamsOffset,
1548 OldType->param_type_end()},
1549 New: {NewType->param_type_begin() + NewParamsOffset,
1550 NewType->param_type_end()},
1551 ArgPos: nullptr)) {
1552 return true;
1553 }
1554
1555 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1556 !NewMethod->isStatic()) {
1557 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1558 const CXXMethodDecl *New) {
1559 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1560 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1561
1562 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1563 return F->getRefQualifier() == RQ_None &&
1564 !F->isExplicitObjectMemberFunction();
1565 };
1566
1567 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1568 CompareType(OldObjectType.getNonReferenceType(),
1569 NewObjectType.getNonReferenceType()))
1570 return true;
1571 return CompareType(OldObjectType, NewObjectType);
1572 }(OldMethod, NewMethod);
1573
1574 if (!HaveCorrespondingObjectParameters) {
1575 ShouldDiagnoseInconsistentRefQualifiers = true;
1576 // CWG2554
1577 // and, if at least one is an explicit object member function, ignoring
1578 // object parameters
1579 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1580 !OldMethod->isExplicitObjectMemberFunction()))
1581 HaveInconsistentQualifiers = true;
1582 }
1583 }
1584
1585 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1586 NewMethod->isImplicitObjectMemberFunction())
1587 ShouldDiagnoseInconsistentRefQualifiers = true;
1588
1589 if (!UseOverrideRules &&
1590 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1591 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1592 OldRC = Old->getTrailingRequiresClause();
1593 if (!NewRC != !OldRC)
1594 return true;
1595 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1596 return true;
1597 if (NewRC &&
1598 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1599 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1600 return true;
1601 }
1602
1603 // Though pass_object_size is placed on parameters and takes an argument, we
1604 // consider it to be a function-level modifier for the sake of function
1605 // identity. Either the function has one or more parameters with
1606 // pass_object_size or it doesn't.
1607 if (functionHasPassObjectSizeParams(FD: New) !=
1608 functionHasPassObjectSizeParams(FD: Old))
1609 return true;
1610
1611 // enable_if attributes are an order-sensitive part of the signature.
1612 for (specific_attr_iterator<EnableIfAttr>
1613 NewI = New->specific_attr_begin<EnableIfAttr>(),
1614 NewE = New->specific_attr_end<EnableIfAttr>(),
1615 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1616 OldE = Old->specific_attr_end<EnableIfAttr>();
1617 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1618 if (NewI == NewE || OldI == OldE)
1619 return true;
1620 llvm::FoldingSetNodeID NewID, OldID;
1621 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1622 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1623 if (NewID != OldID)
1624 return true;
1625 }
1626
1627 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1628 DiagnoseInconsistentRefQualifiers()) ||
1629 HaveInconsistentQualifiers)
1630 return true;
1631
1632 // At this point, it is known that the two functions have the same signature.
1633 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1634 // Don't allow overloading of destructors. (In theory we could, but it
1635 // would be a giant change to clang.)
1636 if (!isa<CXXDestructorDecl>(Val: New)) {
1637 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1638 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1639 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1640 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1641 "Unexpected invalid target.");
1642
1643 // Allow overloading of functions with same signature and different CUDA
1644 // target attributes.
1645 if (NewTarget != OldTarget) {
1646 // Special case: non-constexpr function is allowed to override
1647 // constexpr virtual function
1648 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1649 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1650 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1651 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1652 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1653 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1654 return false;
1655 }
1656 return true;
1657 }
1658 }
1659 }
1660 }
1661
1662 // The signatures match; this is not an overload.
1663 return false;
1664}
1665
1666bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1667 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1668 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1669 ConsiderCudaAttrs);
1670}
1671
1672bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1673 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1674 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1675 /*UseMemberUsingDeclRules=*/false,
1676 /*ConsiderCudaAttrs=*/true,
1677 /*UseOverrideRules=*/true);
1678}
1679
1680/// Tries a user-defined conversion from From to ToType.
1681///
1682/// Produces an implicit conversion sequence for when a standard conversion
1683/// is not an option. See TryImplicitConversion for more information.
1684static ImplicitConversionSequence
1685TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1686 bool SuppressUserConversions,
1687 AllowedExplicit AllowExplicit,
1688 bool InOverloadResolution,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion,
1691 bool AllowObjCConversionOnExplicit) {
1692 ImplicitConversionSequence ICS;
1693
1694 if (SuppressUserConversions) {
1695 // We're not in the case above, so there is no conversion that
1696 // we can perform.
1697 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1698 return ICS;
1699 }
1700
1701 // Attempt user-defined conversion.
1702 OverloadCandidateSet Conversions(From->getExprLoc(),
1703 OverloadCandidateSet::CSK_Normal);
1704 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1705 Conversions, AllowExplicit,
1706 AllowObjCConversionOnExplicit)) {
1707 case OR_Success:
1708 case OR_Deleted:
1709 ICS.setUserDefined();
1710 // C++ [over.ics.user]p4:
1711 // A conversion of an expression of class type to the same class
1712 // type is given Exact Match rank, and a conversion of an
1713 // expression of class type to a base class of that type is
1714 // given Conversion rank, in spite of the fact that a copy
1715 // constructor (i.e., a user-defined conversion function) is
1716 // called for those cases.
1717 if (CXXConstructorDecl *Constructor
1718 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1719 QualType FromType;
1720 SourceLocation FromLoc;
1721 // C++11 [over.ics.list]p6, per DR2137:
1722 // C++17 [over.ics.list]p6:
1723 // If C is not an initializer-list constructor and the initializer list
1724 // has a single element of type cv U, where U is X or a class derived
1725 // from X, the implicit conversion sequence has Exact Match rank if U is
1726 // X, or Conversion rank if U is derived from X.
1727 bool FromListInit = false;
1728 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1729 InitList && InitList->getNumInits() == 1 &&
1730 !S.isInitListConstructor(Ctor: Constructor)) {
1731 const Expr *SingleInit = InitList->getInit(Init: 0);
1732 FromType = SingleInit->getType();
1733 FromLoc = SingleInit->getBeginLoc();
1734 FromListInit = true;
1735 } else {
1736 FromType = From->getType();
1737 FromLoc = From->getBeginLoc();
1738 }
1739 QualType FromCanon =
1740 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1741 QualType ToCanon
1742 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1743 if ((FromCanon == ToCanon ||
1744 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1745 // Turn this into a "standard" conversion sequence, so that it
1746 // gets ranked with standard conversion sequences.
1747 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1748 ICS.setStandard();
1749 ICS.Standard.setAsIdentityConversion();
1750 ICS.Standard.setFromType(FromType);
1751 ICS.Standard.setAllToTypes(ToType);
1752 ICS.Standard.FromBracedInitList = FromListInit;
1753 ICS.Standard.CopyConstructor = Constructor;
1754 ICS.Standard.FoundCopyConstructor = Found;
1755 if (ToCanon != FromCanon)
1756 ICS.Standard.Second = ICK_Derived_To_Base;
1757 }
1758 }
1759 break;
1760
1761 case OR_Ambiguous:
1762 ICS.setAmbiguous();
1763 ICS.Ambiguous.setFromType(From->getType());
1764 ICS.Ambiguous.setToType(ToType);
1765 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1766 Cand != Conversions.end(); ++Cand)
1767 if (Cand->Best)
1768 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1769 break;
1770
1771 // Fall through.
1772 case OR_No_Viable_Function:
1773 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1774 break;
1775 }
1776
1777 return ICS;
1778}
1779
1780/// TryImplicitConversion - Attempt to perform an implicit conversion
1781/// from the given expression (Expr) to the given type (ToType). This
1782/// function returns an implicit conversion sequence that can be used
1783/// to perform the initialization. Given
1784///
1785/// void f(float f);
1786/// void g(int i) { f(i); }
1787///
1788/// this routine would produce an implicit conversion sequence to
1789/// describe the initialization of f from i, which will be a standard
1790/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1791/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1792//
1793/// Note that this routine only determines how the conversion can be
1794/// performed; it does not actually perform the conversion. As such,
1795/// it will not produce any diagnostics if no conversion is available,
1796/// but will instead return an implicit conversion sequence of kind
1797/// "BadConversion".
1798///
1799/// If @p SuppressUserConversions, then user-defined conversions are
1800/// not permitted.
1801/// If @p AllowExplicit, then explicit user-defined conversions are
1802/// permitted.
1803///
1804/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1805/// writeback conversion, which allows __autoreleasing id* parameters to
1806/// be initialized with __strong id* or __weak id* arguments.
1807static ImplicitConversionSequence
1808TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1809 bool SuppressUserConversions,
1810 AllowedExplicit AllowExplicit,
1811 bool InOverloadResolution,
1812 bool CStyle,
1813 bool AllowObjCWritebackConversion,
1814 bool AllowObjCConversionOnExplicit) {
1815 ImplicitConversionSequence ICS;
1816 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1817 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1818 ICS.setStandard();
1819 return ICS;
1820 }
1821
1822 if (!S.getLangOpts().CPlusPlus) {
1823 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1824 return ICS;
1825 }
1826
1827 // C++ [over.ics.user]p4:
1828 // A conversion of an expression of class type to the same class
1829 // type is given Exact Match rank, and a conversion of an
1830 // expression of class type to a base class of that type is
1831 // given Conversion rank, in spite of the fact that a copy/move
1832 // constructor (i.e., a user-defined conversion function) is
1833 // called for those cases.
1834 QualType FromType = From->getType();
1835 if (ToType->isRecordType() &&
1836 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1837 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1838 ICS.setStandard();
1839 ICS.Standard.setAsIdentityConversion();
1840 ICS.Standard.setFromType(FromType);
1841 ICS.Standard.setAllToTypes(ToType);
1842
1843 // We don't actually check at this point whether there is a valid
1844 // copy/move constructor, since overloading just assumes that it
1845 // exists. When we actually perform initialization, we'll find the
1846 // appropriate constructor to copy the returned object, if needed.
1847 ICS.Standard.CopyConstructor = nullptr;
1848
1849 // In HLSL, a conversion of an expression of class type to the same class
1850 // type needs implicit LvaluetoRvalue conversion.
1851 if (S.getLangOpts().HLSL)
1852 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
1853
1854 // Determine whether this is considered a derived-to-base conversion.
1855 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1856 ICS.Standard.Second = ICK_Derived_To_Base;
1857
1858 return ICS;
1859 }
1860
1861 if (S.getLangOpts().HLSL) {
1862 // Handle conversion of the HLSL resource types.
1863 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1864 if (FromTy->isHLSLAttributedResourceType()) {
1865 // Attributed resource types can convert to other attributed
1866 // resource types with the same attributes and contained types,
1867 // or to __hlsl_resource_t without any attributes.
1868 bool CanConvert = false;
1869 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1870 if (ToTy->isHLSLAttributedResourceType()) {
1871 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1872 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1873 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1874 T2: FromResType->getWrappedType()) &&
1875 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1876 T2: FromResType->getContainedType()) &&
1877 ToResType->getAttrs() == FromResType->getAttrs())
1878 CanConvert = true;
1879 } else if (ToTy->isHLSLResourceType()) {
1880 CanConvert = true;
1881 }
1882 if (CanConvert) {
1883 ICS.setStandard();
1884 ICS.Standard.setAsIdentityConversion();
1885 ICS.Standard.setFromType(FromType);
1886 ICS.Standard.setAllToTypes(ToType);
1887 return ICS;
1888 }
1889 }
1890 }
1891
1892 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1893 AllowExplicit, InOverloadResolution, CStyle,
1894 AllowObjCWritebackConversion,
1895 AllowObjCConversionOnExplicit);
1896}
1897
1898ImplicitConversionSequence
1899Sema::TryImplicitConversion(Expr *From, QualType ToType,
1900 bool SuppressUserConversions,
1901 AllowedExplicit AllowExplicit,
1902 bool InOverloadResolution,
1903 bool CStyle,
1904 bool AllowObjCWritebackConversion) {
1905 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1906 AllowExplicit, InOverloadResolution, CStyle,
1907 AllowObjCWritebackConversion,
1908 /*AllowObjCConversionOnExplicit=*/false);
1909}
1910
1911ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1912 AssignmentAction Action,
1913 bool AllowExplicit) {
1914 if (checkPlaceholderForOverload(S&: *this, E&: From))
1915 return ExprError();
1916
1917 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1918 bool AllowObjCWritebackConversion =
1919 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1920 Action == AssignmentAction::Sending);
1921 if (getLangOpts().ObjC)
1922 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1923 SrcType: From->getType(), SrcExpr&: From);
1924 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1925 S&: *this, From, ToType,
1926 /*SuppressUserConversions=*/false,
1927 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1928 /*InOverloadResolution=*/false,
1929 /*CStyle=*/false, AllowObjCWritebackConversion,
1930 /*AllowObjCConversionOnExplicit=*/false);
1931 return PerformImplicitConversion(From, ToType, ICS, Action);
1932}
1933
1934bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1935 QualType &ResultTy) const {
1936 bool Changed = IsFunctionConversion(FromType, ToType);
1937 if (Changed)
1938 ResultTy = ToType;
1939 return Changed;
1940}
1941
1942bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1943 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1944 return false;
1945
1946 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1947 // or F(t noexcept) -> F(t)
1948 // where F adds one of the following at most once:
1949 // - a pointer
1950 // - a member pointer
1951 // - a block pointer
1952 // Changes here need matching changes in FindCompositePointerType.
1953 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1954 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1955 Type::TypeClass TyClass = CanTo->getTypeClass();
1956 if (TyClass != CanFrom->getTypeClass()) return false;
1957 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1958 if (TyClass == Type::Pointer) {
1959 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1960 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1961 } else if (TyClass == Type::BlockPointer) {
1962 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1963 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1964 } else if (TyClass == Type::MemberPointer) {
1965 auto ToMPT = CanTo.castAs<MemberPointerType>();
1966 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1967 // A function pointer conversion cannot change the class of the function.
1968 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1969 D2: FromMPT->getMostRecentCXXRecordDecl()))
1970 return false;
1971 CanTo = ToMPT->getPointeeType();
1972 CanFrom = FromMPT->getPointeeType();
1973 } else {
1974 return false;
1975 }
1976
1977 TyClass = CanTo->getTypeClass();
1978 if (TyClass != CanFrom->getTypeClass()) return false;
1979 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1980 return false;
1981 }
1982
1983 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1984 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1985
1986 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1987 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1988
1989 bool Changed = false;
1990
1991 // Drop 'noreturn' if not present in target type.
1992 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1993 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1994 Changed = true;
1995 }
1996
1997 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1998 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1999
2000 if (FromFPT && ToFPT) {
2001 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2002 QualType NewTy = Context.getFunctionType(
2003 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
2004 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2005 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
2006 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
2007 FromFn = FromFPT;
2008 Changed = true;
2009 }
2010 }
2011
2012 // Drop 'noexcept' if not present in target type.
2013 if (FromFPT && ToFPT) {
2014 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2015 FromFn = cast<FunctionType>(
2016 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
2017 ESI: EST_None)
2018 .getTypePtr());
2019 Changed = true;
2020 }
2021
2022 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2023 // only if the ExtParameterInfo lists of the two function prototypes can be
2024 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2025 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2026 bool CanUseToFPT, CanUseFromFPT;
2027 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2028 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2029 CanUseToFPT && !CanUseFromFPT) {
2030 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2031 ExtInfo.ExtParameterInfos =
2032 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2033 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2034 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2035 FromFn = QT->getAs<FunctionType>();
2036 Changed = true;
2037 }
2038
2039 if (Context.hasAnyFunctionEffects()) {
2040 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2041
2042 // Transparently add/drop effects; here we are concerned with
2043 // language rules/canonicalization. Adding/dropping effects is a warning.
2044 const auto FromFX = FromFPT->getFunctionEffects();
2045 const auto ToFX = ToFPT->getFunctionEffects();
2046 if (FromFX != ToFX) {
2047 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2048 ExtInfo.FunctionEffects = ToFX;
2049 QualType QT = Context.getFunctionType(
2050 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2051 FromFn = QT->getAs<FunctionType>();
2052 Changed = true;
2053 }
2054 }
2055 }
2056
2057 if (!Changed)
2058 return false;
2059
2060 assert(QualType(FromFn, 0).isCanonical());
2061 if (QualType(FromFn, 0) != CanTo) return false;
2062
2063 return true;
2064}
2065
2066/// Determine whether the conversion from FromType to ToType is a valid
2067/// floating point conversion.
2068///
2069static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2070 QualType ToType) {
2071 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2072 return false;
2073 // FIXME: disable conversions between long double, __ibm128 and __float128
2074 // if their representation is different until there is back end support
2075 // We of course allow this conversion if long double is really double.
2076
2077 // Conversions between bfloat16 and float16 are currently not supported.
2078 if ((FromType->isBFloat16Type() &&
2079 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2080 (ToType->isBFloat16Type() &&
2081 (FromType->isFloat16Type() || FromType->isHalfType())))
2082 return false;
2083
2084 // Conversions between IEEE-quad and IBM-extended semantics are not
2085 // permitted.
2086 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2087 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2088 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2089 &ToSem == &llvm::APFloat::IEEEquad()) ||
2090 (&FromSem == &llvm::APFloat::IEEEquad() &&
2091 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2092 return false;
2093 return true;
2094}
2095
2096static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2097 QualType ToType,
2098 ImplicitConversionKind &ICK,
2099 Expr *From) {
2100 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2101 return true;
2102
2103 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2104 ICK = ICK_Floating_Promotion;
2105 return true;
2106 }
2107
2108 if (IsFloatingPointConversion(S, FromType, ToType)) {
2109 ICK = ICK_Floating_Conversion;
2110 return true;
2111 }
2112
2113 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2114 ICK = ICK_Boolean_Conversion;
2115 return true;
2116 }
2117
2118 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2119 (FromType->isIntegralOrUnscopedEnumerationType() &&
2120 ToType->isRealFloatingType())) {
2121 ICK = ICK_Floating_Integral;
2122 return true;
2123 }
2124
2125 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2126 ICK = ICK_Integral_Promotion;
2127 return true;
2128 }
2129
2130 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2131 ToType->isIntegralType(Ctx: S.Context)) {
2132 ICK = ICK_Integral_Conversion;
2133 return true;
2134 }
2135
2136 return false;
2137}
2138
2139/// Determine whether the conversion from FromType to ToType is a valid
2140/// matrix conversion.
2141///
2142/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2143/// conversion.
2144static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2145 ImplicitConversionKind &ICK,
2146 ImplicitConversionKind &ElConv, Expr *From,
2147 bool InOverloadResolution, bool CStyle) {
2148 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2149 if (!S.getLangOpts().HLSL)
2150 return false;
2151
2152 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2153 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2154
2155 // If both arguments are matrix, handle possible matrix truncation and
2156 // element conversion.
2157 if (ToMatrixType && FromMatrixType) {
2158 unsigned FromCols = FromMatrixType->getNumColumns();
2159 unsigned ToCols = ToMatrixType->getNumColumns();
2160 if (FromCols < ToCols)
2161 return false;
2162
2163 unsigned FromRows = FromMatrixType->getNumRows();
2164 unsigned ToRows = ToMatrixType->getNumRows();
2165 if (FromRows < ToRows)
2166 return false;
2167
2168 if (FromRows == ToRows && FromCols == ToCols)
2169 ElConv = ICK_Identity;
2170 else
2171 ElConv = ICK_HLSL_Matrix_Truncation;
2172
2173 QualType FromElTy = FromMatrixType->getElementType();
2174 QualType ToElTy = ToMatrixType->getElementType();
2175 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2176 return true;
2177 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2178 }
2179
2180 // Matrix splat from any arithmetic type to a matrix.
2181 if (ToMatrixType && FromType->isArithmeticType()) {
2182 ElConv = ICK_HLSL_Matrix_Splat;
2183 QualType ToElTy = ToMatrixType->getElementType();
2184 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2185 }
2186 if (FromMatrixType && !ToMatrixType) {
2187 ElConv = ICK_HLSL_Matrix_Truncation;
2188 QualType FromElTy = FromMatrixType->getElementType();
2189 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2190 return true;
2191 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2192 }
2193
2194 return false;
2195}
2196
2197/// Determine whether the conversion from FromType to ToType is a valid
2198/// vector conversion.
2199///
2200/// \param ICK Will be set to the vector conversion kind, if this is a vector
2201/// conversion.
2202static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2203 ImplicitConversionKind &ICK,
2204 ImplicitConversionKind &ElConv, Expr *From,
2205 bool InOverloadResolution, bool CStyle) {
2206 // We need at least one of these types to be a vector type to have a vector
2207 // conversion.
2208 if (!ToType->isVectorType() && !FromType->isVectorType())
2209 return false;
2210
2211 // Identical types require no conversions.
2212 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2213 return false;
2214
2215 // HLSL allows implicit truncation of vector types.
2216 if (S.getLangOpts().HLSL) {
2217 auto *ToExtType = ToType->getAs<ExtVectorType>();
2218 auto *FromExtType = FromType->getAs<ExtVectorType>();
2219
2220 // If both arguments are vectors, handle possible vector truncation and
2221 // element conversion.
2222 if (ToExtType && FromExtType) {
2223 unsigned FromElts = FromExtType->getNumElements();
2224 unsigned ToElts = ToExtType->getNumElements();
2225 if (FromElts < ToElts)
2226 return false;
2227 if (FromElts == ToElts)
2228 ElConv = ICK_Identity;
2229 else
2230 ElConv = ICK_HLSL_Vector_Truncation;
2231
2232 QualType FromElTy = FromExtType->getElementType();
2233 QualType ToElTy = ToExtType->getElementType();
2234 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2235 return true;
2236 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2237 }
2238 if (FromExtType && !ToExtType) {
2239 ElConv = ICK_HLSL_Vector_Truncation;
2240 QualType FromElTy = FromExtType->getElementType();
2241 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2242 return true;
2243 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2244 }
2245 // Fallthrough for the case where ToType is a vector and FromType is not.
2246 }
2247
2248 // There are no conversions between extended vector types, only identity.
2249 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2250 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2251 // Implicit conversions require the same number of elements.
2252 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2253 return false;
2254
2255 // Permit implicit conversions from integral values to boolean vectors.
2256 if (ToType->isExtVectorBoolType() &&
2257 FromExtType->getElementType()->isIntegerType()) {
2258 ICK = ICK_Boolean_Conversion;
2259 return true;
2260 }
2261 // There are no other conversions between extended vector types.
2262 return false;
2263 }
2264
2265 // Vector splat from any arithmetic type to a vector.
2266 if (FromType->isArithmeticType()) {
2267 if (S.getLangOpts().HLSL) {
2268 ElConv = ICK_HLSL_Vector_Splat;
2269 QualType ToElTy = ToExtType->getElementType();
2270 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2271 From);
2272 }
2273 ICK = ICK_Vector_Splat;
2274 return true;
2275 }
2276 }
2277
2278 if (ToType->isSVESizelessBuiltinType() ||
2279 FromType->isSVESizelessBuiltinType())
2280 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2281 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2282 ICK = ICK_SVE_Vector_Conversion;
2283 return true;
2284 }
2285
2286 if (ToType->isRVVSizelessBuiltinType() ||
2287 FromType->isRVVSizelessBuiltinType())
2288 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2289 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2290 ICK = ICK_RVV_Vector_Conversion;
2291 return true;
2292 }
2293
2294 // We can perform the conversion between vector types in the following cases:
2295 // 1)vector types are equivalent AltiVec and GCC vector types
2296 // 2)lax vector conversions are permitted and the vector types are of the
2297 // same size
2298 // 3)the destination type does not have the ARM MVE strict-polymorphism
2299 // attribute, which inhibits lax vector conversion for overload resolution
2300 // only
2301 if (ToType->isVectorType() && FromType->isVectorType()) {
2302 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2303 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2304 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2305 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2306 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2307 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2308 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2309 !InOverloadResolution && !CStyle) {
2310 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2311 << FromType << ToType;
2312 }
2313 ICK = ICK_Vector_Conversion;
2314 return true;
2315 }
2316 }
2317
2318 return false;
2319}
2320
2321static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2322 bool InOverloadResolution,
2323 StandardConversionSequence &SCS,
2324 bool CStyle);
2325
2326static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2327 QualType ToType,
2328 bool InOverloadResolution,
2329 StandardConversionSequence &SCS,
2330 bool CStyle);
2331
2332/// IsStandardConversion - Determines whether there is a standard
2333/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2334/// expression From to the type ToType. Standard conversion sequences
2335/// only consider non-class types; for conversions that involve class
2336/// types, use TryImplicitConversion. If a conversion exists, SCS will
2337/// contain the standard conversion sequence required to perform this
2338/// conversion and this routine will return true. Otherwise, this
2339/// routine will return false and the value of SCS is unspecified.
2340static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2341 bool InOverloadResolution,
2342 StandardConversionSequence &SCS,
2343 bool CStyle,
2344 bool AllowObjCWritebackConversion) {
2345 QualType FromType = From->getType();
2346
2347 // Standard conversions (C++ [conv])
2348 SCS.setAsIdentityConversion();
2349 SCS.IncompatibleObjC = false;
2350 SCS.setFromType(FromType);
2351 SCS.CopyConstructor = nullptr;
2352
2353 // There are no standard conversions for class types in C++, so
2354 // abort early. When overloading in C, however, we do permit them.
2355 if (S.getLangOpts().CPlusPlus &&
2356 (FromType->isRecordType() || ToType->isRecordType()))
2357 return false;
2358
2359 // The first conversion can be an lvalue-to-rvalue conversion,
2360 // array-to-pointer conversion, or function-to-pointer conversion
2361 // (C++ 4p1).
2362
2363 if (FromType == S.Context.OverloadTy) {
2364 DeclAccessPair AccessPair;
2365 if (FunctionDecl *Fn
2366 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2367 Found&: AccessPair)) {
2368 // We were able to resolve the address of the overloaded function,
2369 // so we can convert to the type of that function.
2370 FromType = Fn->getType();
2371 SCS.setFromType(FromType);
2372
2373 // we can sometimes resolve &foo<int> regardless of ToType, so check
2374 // if the type matches (identity) or we are converting to bool
2375 if (!S.Context.hasSameUnqualifiedType(
2376 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2377 // if the function type matches except for [[noreturn]], it's ok
2378 if (!S.IsFunctionConversion(FromType,
2379 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2380 // otherwise, only a boolean conversion is standard
2381 if (!ToType->isBooleanType())
2382 return false;
2383 }
2384
2385 // Check if the "from" expression is taking the address of an overloaded
2386 // function and recompute the FromType accordingly. Take advantage of the
2387 // fact that non-static member functions *must* have such an address-of
2388 // expression.
2389 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2390 if (Method && !Method->isStatic() &&
2391 !Method->isExplicitObjectMemberFunction()) {
2392 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2393 "Non-unary operator on non-static member address");
2394 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2395 == UO_AddrOf &&
2396 "Non-address-of operator on non-static member address");
2397 FromType = S.Context.getMemberPointerType(
2398 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2399 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2400 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2401 UO_AddrOf &&
2402 "Non-address-of operator for overloaded function expression");
2403 FromType = S.Context.getPointerType(T: FromType);
2404 }
2405 } else {
2406 return false;
2407 }
2408 }
2409
2410 bool argIsLValue = From->isGLValue();
2411 // To handle conversion from ArrayParameterType to ConstantArrayType
2412 // this block must be above the one below because Array parameters
2413 // do not decay and when handling HLSLOutArgExprs and
2414 // the From expression is an LValue.
2415 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2416 ToType->isConstantArrayType()) {
2417 // HLSL constant array parameters do not decay, so if the argument is a
2418 // constant array and the parameter is an ArrayParameterType we have special
2419 // handling here.
2420 if (ToType->isArrayParameterType()) {
2421 FromType = S.Context.getArrayParameterType(Ty: FromType);
2422 } else if (FromType->isArrayParameterType()) {
2423 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2424 FromType = APT->getConstantArrayType(Ctx: S.Context);
2425 }
2426
2427 SCS.First = ICK_HLSL_Array_RValue;
2428
2429 // Don't consider qualifiers, which include things like address spaces
2430 if (FromType.getCanonicalType().getUnqualifiedType() !=
2431 ToType.getCanonicalType().getUnqualifiedType())
2432 return false;
2433
2434 SCS.setAllToTypes(ToType);
2435 return true;
2436 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2437 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2438 // Lvalue-to-rvalue conversion (C++11 4.1):
2439 // A glvalue (3.10) of a non-function, non-array type T can
2440 // be converted to a prvalue.
2441
2442 SCS.First = ICK_Lvalue_To_Rvalue;
2443
2444 // C11 6.3.2.1p2:
2445 // ... if the lvalue has atomic type, the value has the non-atomic version
2446 // of the type of the lvalue ...
2447 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2448 FromType = Atomic->getValueType();
2449
2450 // If T is a non-class type, the type of the rvalue is the
2451 // cv-unqualified version of T. Otherwise, the type of the rvalue
2452 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2453 // just strip the qualifiers because they don't matter.
2454 FromType = FromType.getUnqualifiedType();
2455 } else if (FromType->isArrayType()) {
2456 // Array-to-pointer conversion (C++ 4.2)
2457 SCS.First = ICK_Array_To_Pointer;
2458
2459 // An lvalue or rvalue of type "array of N T" or "array of unknown
2460 // bound of T" can be converted to an rvalue of type "pointer to
2461 // T" (C++ 4.2p1).
2462 FromType = S.Context.getArrayDecayedType(T: FromType);
2463
2464 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2465 // This conversion is deprecated in C++03 (D.4)
2466 SCS.DeprecatedStringLiteralToCharPtr = true;
2467
2468 // For the purpose of ranking in overload resolution
2469 // (13.3.3.1.1), this conversion is considered an
2470 // array-to-pointer conversion followed by a qualification
2471 // conversion (4.4). (C++ 4.2p2)
2472 SCS.Second = ICK_Identity;
2473 SCS.Third = ICK_Qualification;
2474 SCS.QualificationIncludesObjCLifetime = false;
2475 SCS.setAllToTypes(FromType);
2476 return true;
2477 }
2478 } else if (FromType->isFunctionType() && argIsLValue) {
2479 // Function-to-pointer conversion (C++ 4.3).
2480 SCS.First = ICK_Function_To_Pointer;
2481
2482 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2483 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2484 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2485 return false;
2486
2487 // An lvalue of function type T can be converted to an rvalue of
2488 // type "pointer to T." The result is a pointer to the
2489 // function. (C++ 4.3p1).
2490 FromType = S.Context.getPointerType(T: FromType);
2491 } else {
2492 // We don't require any conversions for the first step.
2493 SCS.First = ICK_Identity;
2494 }
2495 SCS.setToType(Idx: 0, T: FromType);
2496
2497 // The second conversion can be an integral promotion, floating
2498 // point promotion, integral conversion, floating point conversion,
2499 // floating-integral conversion, pointer conversion,
2500 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2501 // For overloading in C, this can also be a "compatible-type"
2502 // conversion.
2503 bool IncompatibleObjC = false;
2504 ImplicitConversionKind SecondICK = ICK_Identity;
2505 ImplicitConversionKind DimensionICK = ICK_Identity;
2506 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2507 // The unqualified versions of the types are the same: there's no
2508 // conversion to do.
2509 SCS.Second = ICK_Identity;
2510 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2511 // Integral promotion (C++ 4.5).
2512 SCS.Second = ICK_Integral_Promotion;
2513 FromType = ToType.getUnqualifiedType();
2514 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2515 // Floating point promotion (C++ 4.6).
2516 SCS.Second = ICK_Floating_Promotion;
2517 FromType = ToType.getUnqualifiedType();
2518 } else if (S.IsComplexPromotion(FromType, ToType)) {
2519 // Complex promotion (Clang extension)
2520 SCS.Second = ICK_Complex_Promotion;
2521 FromType = ToType.getUnqualifiedType();
2522 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2523 // OverflowBehaviorType promotions
2524 SCS.Second = ICK_Integral_Promotion;
2525 FromType = ToType.getUnqualifiedType();
2526 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2527 // OverflowBehaviorType conversions
2528 SCS.Second = ICK_Integral_Conversion;
2529 FromType = ToType.getUnqualifiedType();
2530 } else if (ToType->isBooleanType() &&
2531 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2532 FromType->isBlockPointerType() ||
2533 FromType->isMemberPointerType())) {
2534 // Boolean conversions (C++ 4.12).
2535 SCS.Second = ICK_Boolean_Conversion;
2536 FromType = S.Context.BoolTy;
2537 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2538 ToType->isIntegralType(Ctx: S.Context)) {
2539 // Integral conversions (C++ 4.7).
2540 SCS.Second = ICK_Integral_Conversion;
2541 FromType = ToType.getUnqualifiedType();
2542 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2543 // Complex conversions (C99 6.3.1.6)
2544 SCS.Second = ICK_Complex_Conversion;
2545 FromType = ToType.getUnqualifiedType();
2546 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2547 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2548 // Complex-real conversions (C99 6.3.1.7)
2549 SCS.Second = ICK_Complex_Real;
2550 FromType = ToType.getUnqualifiedType();
2551 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2552 // Floating point conversions (C++ 4.8).
2553 SCS.Second = ICK_Floating_Conversion;
2554 FromType = ToType.getUnqualifiedType();
2555 } else if ((FromType->isRealFloatingType() &&
2556 ToType->isIntegralType(Ctx: S.Context)) ||
2557 (FromType->isIntegralOrUnscopedEnumerationType() &&
2558 ToType->isRealFloatingType())) {
2559
2560 // Floating-integral conversions (C++ 4.9).
2561 SCS.Second = ICK_Floating_Integral;
2562 FromType = ToType.getUnqualifiedType();
2563 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2564 SCS.Second = ICK_Block_Pointer_Conversion;
2565 } else if (AllowObjCWritebackConversion &&
2566 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2567 SCS.Second = ICK_Writeback_Conversion;
2568 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2569 ConvertedType&: FromType, IncompatibleObjC)) {
2570 // Pointer conversions (C++ 4.10).
2571 SCS.Second = ICK_Pointer_Conversion;
2572 SCS.IncompatibleObjC = IncompatibleObjC;
2573 FromType = FromType.getUnqualifiedType();
2574 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2575 InOverloadResolution, ConvertedType&: FromType)) {
2576 // Pointer to member conversions (4.11).
2577 SCS.Second = ICK_Pointer_Member;
2578 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2579 From, InOverloadResolution, CStyle)) {
2580 SCS.Second = SecondICK;
2581 SCS.Dimension = DimensionICK;
2582 FromType = ToType.getUnqualifiedType();
2583 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2584 From, InOverloadResolution, CStyle)) {
2585 SCS.Second = SecondICK;
2586 SCS.Dimension = DimensionICK;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (!S.getLangOpts().CPlusPlus &&
2589 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2590 // Compatible conversions (Clang extension for C function overloading)
2591 SCS.Second = ICK_Compatible_Conversion;
2592 FromType = ToType.getUnqualifiedType();
2593 } else if (IsTransparentUnionStandardConversion(
2594 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2595 SCS.Second = ICK_TransparentUnionConversion;
2596 FromType = ToType;
2597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2598 CStyle)) {
2599 // tryAtomicConversion has updated the standard conversion sequence
2600 // appropriately.
2601 return true;
2602 } else if (tryOverflowBehaviorTypeConversion(
2603 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2604 return true;
2605 } else if (ToType->isEventT() &&
2606 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2607 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2608 SCS.Second = ICK_Zero_Event_Conversion;
2609 FromType = ToType;
2610 } else if (ToType->isQueueT() &&
2611 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2612 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2613 SCS.Second = ICK_Zero_Queue_Conversion;
2614 FromType = ToType;
2615 } else if (ToType->isSamplerT() &&
2616 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2617 SCS.Second = ICK_Compatible_Conversion;
2618 FromType = ToType;
2619 } else if ((ToType->isFixedPointType() &&
2620 FromType->isConvertibleToFixedPointType()) ||
2621 (FromType->isFixedPointType() &&
2622 ToType->isConvertibleToFixedPointType())) {
2623 SCS.Second = ICK_Fixed_Point_Conversion;
2624 FromType = ToType;
2625 } else {
2626 // No second conversion required.
2627 SCS.Second = ICK_Identity;
2628 }
2629 SCS.setToType(Idx: 1, T: FromType);
2630
2631 // The third conversion can be a function pointer conversion or a
2632 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2633 bool ObjCLifetimeConversion;
2634 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2635 // Function pointer conversions (removing 'noexcept') including removal of
2636 // 'noreturn' (Clang extension).
2637 SCS.Third = ICK_Function_Conversion;
2638 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2639 ObjCLifetimeConversion)) {
2640 SCS.Third = ICK_Qualification;
2641 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2642 FromType = ToType;
2643 } else {
2644 // No conversion required
2645 SCS.Third = ICK_Identity;
2646 }
2647
2648 // C++ [over.best.ics]p6:
2649 // [...] Any difference in top-level cv-qualification is
2650 // subsumed by the initialization itself and does not constitute
2651 // a conversion. [...]
2652 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2653 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2654 if (CanonFrom.getLocalUnqualifiedType()
2655 == CanonTo.getLocalUnqualifiedType() &&
2656 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2657 FromType = ToType;
2658 CanonFrom = CanonTo;
2659 }
2660
2661 SCS.setToType(Idx: 2, T: FromType);
2662
2663 if (CanonFrom == CanonTo)
2664 return true;
2665
2666 // If we have not converted the argument type to the parameter type,
2667 // this is a bad conversion sequence, unless we're resolving an overload in C.
2668 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2669 return false;
2670
2671 ExprResult ER = ExprResult{From};
2672 AssignConvertType Conv =
2673 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2674 /*Diagnose=*/false,
2675 /*DiagnoseCFAudited=*/false,
2676 /*ConvertRHS=*/false);
2677 ImplicitConversionKind SecondConv;
2678 switch (Conv) {
2679 case AssignConvertType::Compatible:
2680 case AssignConvertType::
2681 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2682 SecondConv = ICK_C_Only_Conversion;
2683 break;
2684 // For our purposes, discarding qualifiers is just as bad as using an
2685 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2686 // qualifiers, as well.
2687 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2688 case AssignConvertType::IncompatiblePointer:
2689 case AssignConvertType::IncompatiblePointerSign:
2690 SecondConv = ICK_Incompatible_Pointer_Conversion;
2691 break;
2692 default:
2693 return false;
2694 }
2695
2696 // First can only be an lvalue conversion, so we pretend that this was the
2697 // second conversion. First should already be valid from earlier in the
2698 // function.
2699 SCS.Second = SecondConv;
2700 SCS.setToType(Idx: 1, T: ToType);
2701
2702 // Third is Identity, because Second should rank us worse than any other
2703 // conversion. This could also be ICK_Qualification, but it's simpler to just
2704 // lump everything in with the second conversion, and we don't gain anything
2705 // from making this ICK_Qualification.
2706 SCS.Third = ICK_Identity;
2707 SCS.setToType(Idx: 2, T: ToType);
2708 return true;
2709}
2710
2711static bool
2712IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2713 QualType &ToType,
2714 bool InOverloadResolution,
2715 StandardConversionSequence &SCS,
2716 bool CStyle) {
2717
2718 const RecordType *UT = ToType->getAsUnionType();
2719 if (!UT)
2720 return false;
2721 // The field to initialize within the transparent union.
2722 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2723 if (!UD->hasAttr<TransparentUnionAttr>())
2724 return false;
2725 // It's compatible if the expression matches any of the fields.
2726 for (const auto *it : UD->fields()) {
2727 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2728 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2729 ToType = it->getType();
2730 return true;
2731 }
2732 }
2733 return false;
2734}
2735
2736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2737 const BuiltinType *To = ToType->getAs<BuiltinType>();
2738 // All integers are built-in.
2739 if (!To) {
2740 return false;
2741 }
2742
2743 // An rvalue of type char, signed char, unsigned char, short int, or
2744 // unsigned short int can be converted to an rvalue of type int if
2745 // int can represent all the values of the source type; otherwise,
2746 // the source rvalue can be converted to an rvalue of type unsigned
2747 // int (C++ 4.5p1).
2748 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2749 !FromType->isEnumeralType()) {
2750 if ( // We can promote any signed, promotable integer type to an int
2751 (FromType->isSignedIntegerType() ||
2752 // We can promote any unsigned integer type whose size is
2753 // less than int to an int.
2754 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2755 return To->getKind() == BuiltinType::Int;
2756 }
2757
2758 return To->getKind() == BuiltinType::UInt;
2759 }
2760
2761 // C++11 [conv.prom]p3:
2762 // A prvalue of an unscoped enumeration type whose underlying type is not
2763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2764 // following types that can represent all the values of the enumeration
2765 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2766 // unsigned int, long int, unsigned long int, long long int, or unsigned
2767 // long long int. If none of the types in that list can represent all the
2768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2769 // type can be converted to an rvalue a prvalue of the extended integer type
2770 // with lowest integer conversion rank (4.13) greater than the rank of long
2771 // long in which all the values of the enumeration can be represented. If
2772 // there are two such extended types, the signed one is chosen.
2773 // C++11 [conv.prom]p4:
2774 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2775 // can be converted to a prvalue of its underlying type. Moreover, if
2776 // integral promotion can be applied to its underlying type, a prvalue of an
2777 // unscoped enumeration type whose underlying type is fixed can also be
2778 // converted to a prvalue of the promoted underlying type.
2779 if (const auto *FromED = FromType->getAsEnumDecl()) {
2780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2781 // provided for a scoped enumeration.
2782 if (FromED->isScoped())
2783 return false;
2784
2785 // We can perform an integral promotion to the underlying type of the enum,
2786 // even if that's not the promoted type. Note that the check for promoting
2787 // the underlying type is based on the type alone, and does not consider
2788 // the bitfield-ness of the actual source expression.
2789 if (FromED->isFixed()) {
2790 QualType Underlying = FromED->getIntegerType();
2791 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2792 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2793 }
2794
2795 // We have already pre-calculated the promotion type, so this is trivial.
2796 if (ToType->isIntegerType() &&
2797 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2798 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2799
2800 // C++ [conv.prom]p5:
2801 // If the bit-field has an enumerated type, it is treated as any other
2802 // value of that type for promotion purposes.
2803 //
2804 // ... so do not fall through into the bit-field checks below in C++.
2805 if (getLangOpts().CPlusPlus)
2806 return false;
2807 }
2808
2809 // C++0x [conv.prom]p2:
2810 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2811 // to an rvalue a prvalue of the first of the following types that can
2812 // represent all the values of its underlying type: int, unsigned int,
2813 // long int, unsigned long int, long long int, or unsigned long long int.
2814 // If none of the types in that list can represent all the values of its
2815 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2816 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2817 // type.
2818 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2819 ToType->isIntegerType()) {
2820 // Determine whether the type we're converting from is signed or
2821 // unsigned.
2822 bool FromIsSigned = FromType->isSignedIntegerType();
2823 uint64_t FromSize = Context.getTypeSize(T: FromType);
2824
2825 // The types we'll try to promote to, in the appropriate
2826 // order. Try each of these types.
2827 QualType PromoteTypes[6] = {
2828 Context.IntTy, Context.UnsignedIntTy,
2829 Context.LongTy, Context.UnsignedLongTy ,
2830 Context.LongLongTy, Context.UnsignedLongLongTy
2831 };
2832 for (int Idx = 0; Idx < 6; ++Idx) {
2833 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2834 if (FromSize < ToSize ||
2835 (FromSize == ToSize &&
2836 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2837 // We found the type that we can promote to. If this is the
2838 // type we wanted, we have a promotion. Otherwise, no
2839 // promotion.
2840 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2841 }
2842 }
2843 }
2844
2845 // An rvalue for an integral bit-field (9.6) can be converted to an
2846 // rvalue of type int if int can represent all the values of the
2847 // bit-field; otherwise, it can be converted to unsigned int if
2848 // unsigned int can represent all the values of the bit-field. If
2849 // the bit-field is larger yet, no integral promotion applies to
2850 // it. If the bit-field has an enumerated type, it is treated as any
2851 // other value of that type for promotion purposes (C++ 4.5p3).
2852 // FIXME: We should delay checking of bit-fields until we actually perform the
2853 // conversion.
2854 //
2855 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2856 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2857 // bit-fields and those whose underlying type is larger than int) for GCC
2858 // compatibility.
2859 if (From) {
2860 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2861 std::optional<llvm::APSInt> BitWidth;
2862 if (FromType->isIntegralType(Ctx: Context) &&
2863 (BitWidth =
2864 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2865 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2866 ToSize = Context.getTypeSize(T: ToType);
2867
2868 // Are we promoting to an int from a bitfield that fits in an int?
2869 if (*BitWidth < ToSize ||
2870 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2871 return To->getKind() == BuiltinType::Int;
2872 }
2873
2874 // Are we promoting to an unsigned int from an unsigned bitfield
2875 // that fits into an unsigned int?
2876 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2877 return To->getKind() == BuiltinType::UInt;
2878 }
2879
2880 return false;
2881 }
2882 }
2883 }
2884
2885 // An rvalue of type bool can be converted to an rvalue of type int,
2886 // with false becoming zero and true becoming one (C++ 4.5p4).
2887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2888 return true;
2889 }
2890
2891 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2892 // integral type.
2893 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2894 ToType->isIntegerType())
2895 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2896
2897 return false;
2898}
2899
2900bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2901 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2902 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2903 /// An rvalue of type float can be converted to an rvalue of type
2904 /// double. (C++ 4.6p1).
2905 if (FromBuiltin->getKind() == BuiltinType::Float &&
2906 ToBuiltin->getKind() == BuiltinType::Double)
2907 return true;
2908
2909 // C99 6.3.1.5p1:
2910 // When a float is promoted to double or long double, or a
2911 // double is promoted to long double [...].
2912 if (!getLangOpts().CPlusPlus &&
2913 (FromBuiltin->getKind() == BuiltinType::Float ||
2914 FromBuiltin->getKind() == BuiltinType::Double) &&
2915 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2916 ToBuiltin->getKind() == BuiltinType::Float128 ||
2917 ToBuiltin->getKind() == BuiltinType::Ibm128))
2918 return true;
2919
2920 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2921 // or not native half types are enabled.
2922 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2923 (ToBuiltin->getKind() == BuiltinType::Float ||
2924 ToBuiltin->getKind() == BuiltinType::Double))
2925 return true;
2926
2927 // Half can be promoted to float.
2928 if (!getLangOpts().NativeHalfType &&
2929 FromBuiltin->getKind() == BuiltinType::Half &&
2930 ToBuiltin->getKind() == BuiltinType::Float)
2931 return true;
2932 }
2933
2934 return false;
2935}
2936
2937bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2938 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2939 if (!FromComplex)
2940 return false;
2941
2942 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2943 if (!ToComplex)
2944 return false;
2945
2946 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2947 ToType: ToComplex->getElementType()) ||
2948 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2949 ToType: ToComplex->getElementType());
2950}
2951
2952bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
2953 if (!getLangOpts().OverflowBehaviorTypes)
2954 return false;
2955
2956 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2957 return false;
2958
2959 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2960}
2961
2962bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
2963 QualType ToType) {
2964 if (!getLangOpts().OverflowBehaviorTypes)
2965 return false;
2966
2967 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2968 if (ToType->isBooleanType())
2969 return false;
2970 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2971 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2972 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2973 if (ToED->isScoped())
2974 return false;
2975 }
2976 return true;
2977 }
2978
2979 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2980 return true;
2981
2982 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2983 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
2984
2985 return false;
2986}
2987
2988/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2989/// the pointer type FromPtr to a pointer to type ToPointee, with the
2990/// same type qualifiers as FromPtr has on its pointee type. ToType,
2991/// if non-empty, will be a pointer to ToType that may or may not have
2992/// the right set of qualifiers on its pointee.
2993///
2994static QualType
2995BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2996 QualType ToPointee, QualType ToType,
2997 ASTContext &Context,
2998 bool StripObjCLifetime = false) {
2999 assert((FromPtr->getTypeClass() == Type::Pointer ||
3000 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3001 "Invalid similarly-qualified pointer type");
3002
3003 /// Conversions to 'id' subsume cv-qualifier conversions.
3004 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3005 return ToType.getUnqualifiedType();
3006
3007 QualType CanonFromPointee
3008 = Context.getCanonicalType(T: FromPtr->getPointeeType());
3009 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
3010 Qualifiers Quals = CanonFromPointee.getQualifiers();
3011
3012 if (StripObjCLifetime)
3013 Quals.removeObjCLifetime();
3014
3015 // Exact qualifier match -> return the pointer type we're converting to.
3016 if (CanonToPointee.getLocalQualifiers() == Quals) {
3017 // ToType is exactly what we need. Return it.
3018 if (!ToType.isNull())
3019 return ToType.getUnqualifiedType();
3020
3021 // Build a pointer to ToPointee. It has the right qualifiers
3022 // already.
3023 if (isa<ObjCObjectPointerType>(Val: ToType))
3024 return Context.getObjCObjectPointerType(OIT: ToPointee);
3025 return Context.getPointerType(T: ToPointee);
3026 }
3027
3028 // Just build a canonical type that has the right qualifiers.
3029 QualType QualifiedCanonToPointee
3030 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3031
3032 if (isa<ObjCObjectPointerType>(Val: ToType))
3033 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3034 return Context.getPointerType(T: QualifiedCanonToPointee);
3035}
3036
3037static bool isNullPointerConstantForConversion(Expr *Expr,
3038 bool InOverloadResolution,
3039 ASTContext &Context) {
3040 // Handle value-dependent integral null pointer constants correctly.
3041 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3042 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3043 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3044 return !InOverloadResolution;
3045
3046 return Expr->isNullPointerConstant(Ctx&: Context,
3047 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3048 : Expr::NPC_ValueDependentIsNull);
3049}
3050
3051bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3052 bool InOverloadResolution,
3053 QualType& ConvertedType,
3054 bool &IncompatibleObjC) {
3055 IncompatibleObjC = false;
3056 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3057 IncompatibleObjC))
3058 return true;
3059
3060 // Conversion from a null pointer constant to any Objective-C pointer type.
3061 if (ToType->isObjCObjectPointerType() &&
3062 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3063 ConvertedType = ToType;
3064 return true;
3065 }
3066
3067 // Blocks: Block pointers can be converted to void*.
3068 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3069 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073 // Blocks: A null pointer constant can be converted to a block
3074 // pointer type.
3075 if (ToType->isBlockPointerType() &&
3076 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3077 ConvertedType = ToType;
3078 return true;
3079 }
3080
3081 // If the left-hand-side is nullptr_t, the right side can be a null
3082 // pointer constant.
3083 if (ToType->isNullPtrType() &&
3084 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3085 ConvertedType = ToType;
3086 return true;
3087 }
3088
3089 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3090 if (!ToTypePtr)
3091 return false;
3092
3093 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3094 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3095 ConvertedType = ToType;
3096 return true;
3097 }
3098
3099 // Beyond this point, both types need to be pointers
3100 // , including objective-c pointers.
3101 QualType ToPointeeType = ToTypePtr->getPointeeType();
3102 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3103 !getLangOpts().ObjCAutoRefCount) {
3104 ConvertedType = BuildSimilarlyQualifiedPointerType(
3105 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3106 Context);
3107 return true;
3108 }
3109 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3110 if (!FromTypePtr)
3111 return false;
3112
3113 QualType FromPointeeType = FromTypePtr->getPointeeType();
3114
3115 // If the unqualified pointee types are the same, this can't be a
3116 // pointer conversion, so don't do all of the work below.
3117 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3118 return false;
3119
3120 // An rvalue of type "pointer to cv T," where T is an object type,
3121 // can be converted to an rvalue of type "pointer to cv void" (C++
3122 // 4.10p2).
3123 if (FromPointeeType->isIncompleteOrObjectType() &&
3124 ToPointeeType->isVoidType()) {
3125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3126 ToPointee: ToPointeeType,
3127 ToType, Context,
3128 /*StripObjCLifetime=*/true);
3129 return true;
3130 }
3131
3132 // MSVC allows implicit function to void* type conversion.
3133 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3134 ToPointeeType->isVoidType()) {
3135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3136 ToPointee: ToPointeeType,
3137 ToType, Context);
3138 return true;
3139 }
3140
3141 // When we're overloading in C, we allow a special kind of pointer
3142 // conversion for compatible-but-not-identical pointee types.
3143 if (!getLangOpts().CPlusPlus &&
3144 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3146 ToPointee: ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 // C++ [conv.ptr]p3:
3152 //
3153 // An rvalue of type "pointer to cv D," where D is a class type,
3154 // can be converted to an rvalue of type "pointer to cv B," where
3155 // B is a base class (clause 10) of D. If B is an inaccessible
3156 // (clause 11) or ambiguous (10.2) base class of D, a program that
3157 // necessitates this conversion is ill-formed. The result of the
3158 // conversion is a pointer to the base class sub-object of the
3159 // derived class object. The null pointer value is converted to
3160 // the null pointer value of the destination type.
3161 //
3162 // Note that we do not check for ambiguity or inaccessibility
3163 // here. That is handled by CheckPointerConversion.
3164 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3165 ToPointeeType->isRecordType() &&
3166 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3167 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3169 ToPointee: ToPointeeType,
3170 ToType, Context);
3171 return true;
3172 }
3173
3174 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3175 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3176 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3177 ToPointee: ToPointeeType,
3178 ToType, Context);
3179 return true;
3180 }
3181
3182 return false;
3183}
3184
3185/// Adopt the given qualifiers for the given type.
3186static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3187 Qualifiers TQs = T.getQualifiers();
3188
3189 // Check whether qualifiers already match.
3190 if (TQs == Qs)
3191 return T;
3192
3193 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3194 return Context.getQualifiedType(T, Qs);
3195
3196 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3197}
3198
3199bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3200 QualType& ConvertedType,
3201 bool &IncompatibleObjC) {
3202 if (!getLangOpts().ObjC)
3203 return false;
3204
3205 // The set of qualifiers on the type we're converting from.
3206 Qualifiers FromQualifiers = FromType.getQualifiers();
3207
3208 // First, we handle all conversions on ObjC object pointer types.
3209 const ObjCObjectPointerType* ToObjCPtr =
3210 ToType->getAs<ObjCObjectPointerType>();
3211 const ObjCObjectPointerType *FromObjCPtr =
3212 FromType->getAs<ObjCObjectPointerType>();
3213
3214 if (ToObjCPtr && FromObjCPtr) {
3215 // If the pointee types are the same (ignoring qualifications),
3216 // then this is not a pointer conversion.
3217 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3218 T2: FromObjCPtr->getPointeeType()))
3219 return false;
3220
3221 // Conversion between Objective-C pointers.
3222 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3223 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3224 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3225 if (getLangOpts().CPlusPlus && LHS && RHS &&
3226 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3227 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3228 return false;
3229 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3230 ToPointee: ToObjCPtr->getPointeeType(),
3231 ToType, Context);
3232 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3233 return true;
3234 }
3235
3236 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3237 // Okay: this is some kind of implicit downcast of Objective-C
3238 // interfaces, which is permitted. However, we're going to
3239 // complain about it.
3240 IncompatibleObjC = true;
3241 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3242 ToPointee: ToObjCPtr->getPointeeType(),
3243 ToType, Context);
3244 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3245 return true;
3246 }
3247 }
3248 // Beyond this point, both types need to be C pointers or block pointers.
3249 QualType ToPointeeType;
3250 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3251 ToPointeeType = ToCPtr->getPointeeType();
3252 else if (const BlockPointerType *ToBlockPtr =
3253 ToType->getAs<BlockPointerType>()) {
3254 // Objective C++: We're able to convert from a pointer to any object
3255 // to a block pointer type.
3256 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3257 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3258 return true;
3259 }
3260 ToPointeeType = ToBlockPtr->getPointeeType();
3261 }
3262 else if (FromType->getAs<BlockPointerType>() &&
3263 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3264 // Objective C++: We're able to convert from a block pointer type to a
3265 // pointer to any object.
3266 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3267 return true;
3268 }
3269 else
3270 return false;
3271
3272 QualType FromPointeeType;
3273 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3274 FromPointeeType = FromCPtr->getPointeeType();
3275 else if (const BlockPointerType *FromBlockPtr =
3276 FromType->getAs<BlockPointerType>())
3277 FromPointeeType = FromBlockPtr->getPointeeType();
3278 else
3279 return false;
3280
3281 // If we have pointers to pointers, recursively check whether this
3282 // is an Objective-C conversion.
3283 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3284 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3285 IncompatibleObjC)) {
3286 // We always complain about this conversion.
3287 IncompatibleObjC = true;
3288 ConvertedType = Context.getPointerType(T: ConvertedType);
3289 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3290 return true;
3291 }
3292 // Allow conversion of pointee being objective-c pointer to another one;
3293 // as in I* to id.
3294 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3295 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3296 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3297 IncompatibleObjC)) {
3298
3299 ConvertedType = Context.getPointerType(T: ConvertedType);
3300 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3301 return true;
3302 }
3303
3304 // If we have pointers to functions or blocks, check whether the only
3305 // differences in the argument and result types are in Objective-C
3306 // pointer conversions. If so, we permit the conversion (but
3307 // complain about it).
3308 const FunctionProtoType *FromFunctionType
3309 = FromPointeeType->getAs<FunctionProtoType>();
3310 const FunctionProtoType *ToFunctionType
3311 = ToPointeeType->getAs<FunctionProtoType>();
3312 if (FromFunctionType && ToFunctionType) {
3313 // If the function types are exactly the same, this isn't an
3314 // Objective-C pointer conversion.
3315 if (Context.getCanonicalType(T: FromPointeeType)
3316 == Context.getCanonicalType(T: ToPointeeType))
3317 return false;
3318
3319 // Perform the quick checks that will tell us whether these
3320 // function types are obviously different.
3321 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3322 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3323 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3324 return false;
3325
3326 bool HasObjCConversion = false;
3327 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3328 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3329 // Okay, the types match exactly. Nothing to do.
3330 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3331 ToType: ToFunctionType->getReturnType(),
3332 ConvertedType, IncompatibleObjC)) {
3333 // Okay, we have an Objective-C pointer conversion.
3334 HasObjCConversion = true;
3335 } else {
3336 // Function types are too different. Abort.
3337 return false;
3338 }
3339
3340 // Check argument types.
3341 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3342 ArgIdx != NumArgs; ++ArgIdx) {
3343 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3344 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3345 if (Context.getCanonicalType(T: FromArgType)
3346 == Context.getCanonicalType(T: ToArgType)) {
3347 // Okay, the types match exactly. Nothing to do.
3348 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3349 ConvertedType, IncompatibleObjC)) {
3350 // Okay, we have an Objective-C pointer conversion.
3351 HasObjCConversion = true;
3352 } else {
3353 // Argument types are too different. Abort.
3354 return false;
3355 }
3356 }
3357
3358 if (HasObjCConversion) {
3359 // We had an Objective-C conversion. Allow this pointer
3360 // conversion, but complain about it.
3361 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3362 IncompatibleObjC = true;
3363 return true;
3364 }
3365 }
3366
3367 return false;
3368}
3369
3370bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3371 QualType& ConvertedType) {
3372 QualType ToPointeeType;
3373 if (const BlockPointerType *ToBlockPtr =
3374 ToType->getAs<BlockPointerType>())
3375 ToPointeeType = ToBlockPtr->getPointeeType();
3376 else
3377 return false;
3378
3379 QualType FromPointeeType;
3380 if (const BlockPointerType *FromBlockPtr =
3381 FromType->getAs<BlockPointerType>())
3382 FromPointeeType = FromBlockPtr->getPointeeType();
3383 else
3384 return false;
3385 // We have pointer to blocks, check whether the only
3386 // differences in the argument and result types are in Objective-C
3387 // pointer conversions. If so, we permit the conversion.
3388
3389 const FunctionProtoType *FromFunctionType
3390 = FromPointeeType->getAs<FunctionProtoType>();
3391 const FunctionProtoType *ToFunctionType
3392 = ToPointeeType->getAs<FunctionProtoType>();
3393
3394 if (!FromFunctionType || !ToFunctionType)
3395 return false;
3396
3397 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3398 return true;
3399
3400 // Perform the quick checks that will tell us whether these
3401 // function types are obviously different.
3402 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3403 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3404 return false;
3405
3406 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3407 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3408 if (FromEInfo != ToEInfo)
3409 return false;
3410
3411 bool IncompatibleObjC = false;
3412 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3413 T2: ToFunctionType->getReturnType())) {
3414 // Okay, the types match exactly. Nothing to do.
3415 } else {
3416 QualType RHS = FromFunctionType->getReturnType();
3417 QualType LHS = ToFunctionType->getReturnType();
3418 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3419 !RHS.hasQualifiers() && LHS.hasQualifiers())
3420 LHS = LHS.getUnqualifiedType();
3421
3422 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3423 // OK exact match.
3424 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3425 ConvertedType, IncompatibleObjC)) {
3426 if (IncompatibleObjC)
3427 return false;
3428 // Okay, we have an Objective-C pointer conversion.
3429 }
3430 else
3431 return false;
3432 }
3433
3434 // Check argument types.
3435 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3436 ArgIdx != NumArgs; ++ArgIdx) {
3437 IncompatibleObjC = false;
3438 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3439 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3440 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3441 // Okay, the types match exactly. Nothing to do.
3442 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3443 ConvertedType, IncompatibleObjC)) {
3444 if (IncompatibleObjC)
3445 return false;
3446 // Okay, we have an Objective-C pointer conversion.
3447 } else
3448 // Argument types are too different. Abort.
3449 return false;
3450 }
3451
3452 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3453 bool CanUseToFPT, CanUseFromFPT;
3454 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3455 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3456 NewParamInfos))
3457 return false;
3458
3459 ConvertedType = ToType;
3460 return true;
3461}
3462
3463enum {
3464 ft_default,
3465 ft_different_class,
3466 ft_parameter_arity,
3467 ft_parameter_mismatch,
3468 ft_return_type,
3469 ft_qualifer_mismatch,
3470 ft_noexcept
3471};
3472
3473/// Attempts to get the FunctionProtoType from a Type. Handles
3474/// MemberFunctionPointers properly.
3475static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3476 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3477 return FPT;
3478
3479 if (auto *MPT = FromType->getAs<MemberPointerType>())
3480 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3481
3482 return nullptr;
3483}
3484
3485void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3486 QualType FromType, QualType ToType) {
3487 // If either type is not valid, include no extra info.
3488 if (FromType.isNull() || ToType.isNull()) {
3489 PDiag << ft_default;
3490 return;
3491 }
3492
3493 // Get the function type from the pointers.
3494 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3495 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3496 *ToMember = ToType->castAs<MemberPointerType>();
3497 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3498 D2: ToMember->getMostRecentCXXRecordDecl())) {
3499 PDiag << ft_different_class;
3500 if (ToMember->isSugared())
3501 PDiag << Context.getCanonicalTagType(
3502 TD: ToMember->getMostRecentCXXRecordDecl());
3503 else
3504 PDiag << ToMember->getQualifier();
3505 if (FromMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 TD: FromMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << FromMember->getQualifier();
3510 return;
3511 }
3512 FromType = FromMember->getPointeeType();
3513 ToType = ToMember->getPointeeType();
3514 }
3515
3516 if (FromType->isPointerType())
3517 FromType = FromType->getPointeeType();
3518 if (ToType->isPointerType())
3519 ToType = ToType->getPointeeType();
3520
3521 // Remove references.
3522 FromType = FromType.getNonReferenceType();
3523 ToType = ToType.getNonReferenceType();
3524
3525 // Don't print extra info for non-specialized template functions.
3526 if (FromType->isInstantiationDependentType() &&
3527 !FromType->getAs<TemplateSpecializationType>()) {
3528 PDiag << ft_default;
3529 return;
3530 }
3531
3532 // No extra info for same types.
3533 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3534 PDiag << ft_default;
3535 return;
3536 }
3537
3538 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3539 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3540
3541 // Both types need to be function types.
3542 if (!FromFunction || !ToFunction) {
3543 PDiag << ft_default;
3544 return;
3545 }
3546
3547 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3548 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3549 << FromFunction->getNumParams();
3550 return;
3551 }
3552
3553 // Handle different parameter types.
3554 unsigned ArgPos;
3555 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3556 PDiag << ft_parameter_mismatch << ArgPos + 1
3557 << ToFunction->getParamType(i: ArgPos)
3558 << FromFunction->getParamType(i: ArgPos);
3559 return;
3560 }
3561
3562 // Handle different return type.
3563 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3564 T2: ToFunction->getReturnType())) {
3565 PDiag << ft_return_type << ToFunction->getReturnType()
3566 << FromFunction->getReturnType();
3567 return;
3568 }
3569
3570 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3571 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3572 << FromFunction->getMethodQuals();
3573 return;
3574 }
3575
3576 // Handle exception specification differences on canonical type (in C++17
3577 // onwards).
3578 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3579 ->isNothrow() !=
3580 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3581 ->isNothrow()) {
3582 PDiag << ft_noexcept;
3583 return;
3584 }
3585
3586 // Unable to find a difference, so add no extra info.
3587 PDiag << ft_default;
3588}
3589
3590bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3591 ArrayRef<QualType> New, unsigned *ArgPos,
3592 bool Reversed) {
3593 assert(llvm::size(Old) == llvm::size(New) &&
3594 "Can't compare parameters of functions with different number of "
3595 "parameters!");
3596
3597 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3598 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3599 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3600
3601 // Ignore address spaces in pointee type. This is to disallow overloading
3602 // on __ptr32/__ptr64 address spaces.
3603 QualType OldType =
3604 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3605 QualType NewType =
3606 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3607
3608 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3609 if (ArgPos)
3610 *ArgPos = Idx;
3611 return false;
3612 }
3613 }
3614 return true;
3615}
3616
3617bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3618 const FunctionProtoType *NewType,
3619 unsigned *ArgPos, bool Reversed) {
3620 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3621 New: NewType->param_types(), ArgPos, Reversed);
3622}
3623
3624bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3625 const FunctionDecl *NewFunction,
3626 unsigned *ArgPos,
3627 bool Reversed) {
3628
3629 if (OldFunction->getNumNonObjectParams() !=
3630 NewFunction->getNumNonObjectParams())
3631 return false;
3632
3633 unsigned OldIgnore =
3634 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3635 unsigned NewIgnore =
3636 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3637
3638 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3639 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3640
3641 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3642 New: NewPT->param_types().slice(N: NewIgnore),
3643 ArgPos, Reversed);
3644}
3645
3646bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3647 CastKind &Kind,
3648 CXXCastPath& BasePath,
3649 bool IgnoreBaseAccess,
3650 bool Diagnose) {
3651 QualType FromType = From->getType();
3652 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3653
3654 Kind = CK_BitCast;
3655
3656 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3657 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3658 Expr::NPCK_ZeroExpression) {
3659 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3660 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3661 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3662 << ToType << From->getSourceRange());
3663 else if (!isUnevaluatedContext())
3664 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3665 << ToType << From->getSourceRange();
3666 }
3667 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3668 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3669 QualType FromPointeeType = FromPtrType->getPointeeType(),
3670 ToPointeeType = ToPtrType->getPointeeType();
3671
3672 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3673 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3674 // We must have a derived-to-base conversion. Check an
3675 // ambiguous or inaccessible conversion.
3676 unsigned InaccessibleID = 0;
3677 unsigned AmbiguousID = 0;
3678 if (Diagnose) {
3679 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3680 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3681 }
3682 if (CheckDerivedToBaseConversion(
3683 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3684 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3685 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3686 return true;
3687
3688 // The conversion was successful.
3689 Kind = CK_DerivedToBase;
3690 }
3691
3692 if (Diagnose && !IsCStyleOrFunctionalCast &&
3693 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3694 assert(getLangOpts().MSVCCompat &&
3695 "this should only be possible with MSVCCompat!");
3696 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3697 << From->getSourceRange();
3698 }
3699 }
3700 } else if (const ObjCObjectPointerType *ToPtrType =
3701 ToType->getAs<ObjCObjectPointerType>()) {
3702 if (const ObjCObjectPointerType *FromPtrType =
3703 FromType->getAs<ObjCObjectPointerType>()) {
3704 // Objective-C++ conversions are always okay.
3705 // FIXME: We should have a different class of conversions for the
3706 // Objective-C++ implicit conversions.
3707 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3708 return false;
3709 } else if (FromType->isBlockPointerType()) {
3710 Kind = CK_BlockPointerToObjCPointerCast;
3711 } else {
3712 Kind = CK_CPointerToObjCPointerCast;
3713 }
3714 } else if (ToType->isBlockPointerType()) {
3715 if (!FromType->isBlockPointerType())
3716 Kind = CK_AnyPointerToBlockPointerCast;
3717 }
3718
3719 // We shouldn't fall into this case unless it's valid for other
3720 // reasons.
3721 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3722 Kind = CK_NullToPointer;
3723
3724 return false;
3725}
3726
3727bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3728 QualType ToType,
3729 bool InOverloadResolution,
3730 QualType &ConvertedType) {
3731 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3732 if (!ToTypePtr)
3733 return false;
3734
3735 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3736 if (From->isNullPointerConstant(Ctx&: Context,
3737 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3738 : Expr::NPC_ValueDependentIsNull)) {
3739 ConvertedType = ToType;
3740 return true;
3741 }
3742
3743 // Otherwise, both types have to be member pointers.
3744 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3745 if (!FromTypePtr)
3746 return false;
3747
3748 // A pointer to member of B can be converted to a pointer to member of D,
3749 // where D is derived from B (C++ 4.11p2).
3750 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3751 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3752
3753 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3754 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3755 ConvertedType = Context.getMemberPointerType(
3756 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3757 return true;
3758 }
3759
3760 return false;
3761}
3762
3763Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3764 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3765 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3766 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3767 // Lock down the inheritance model right now in MS ABI, whether or not the
3768 // pointee types are the same.
3769 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3770 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3771 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3772 }
3773
3774 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3775 if (!FromPtrType) {
3776 // This must be a null pointer to member pointer conversion
3777 Kind = CK_NullToMemberPointer;
3778 return MemberPointerConversionResult::Success;
3779 }
3780
3781 // T == T, modulo cv
3782 if (Direction == MemberPointerConversionDirection::Upcast &&
3783 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3784 T2: ToPtrType->getPointeeType()))
3785 return MemberPointerConversionResult::DifferentPointee;
3786
3787 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3788 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3789
3790 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3791 const CXXRecordDecl *Cls) {
3792 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3793 PD << Qual;
3794 else
3795 PD << Context.getCanonicalTagType(TD: Cls);
3796 };
3797 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3798 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3799 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3800 return PD;
3801 };
3802
3803 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3804 if (Direction == MemberPointerConversionDirection::Upcast)
3805 std::swap(a&: Base, b&: Derived);
3806
3807 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3808 /*DetectVirtual=*/true);
3809 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3810 return MemberPointerConversionResult::NotDerived;
3811
3812 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3813 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3814 PD << int(Direction);
3815 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3816 Diag(Loc: CheckLoc, PD);
3817 return MemberPointerConversionResult::Ambiguous;
3818 }
3819
3820 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3821 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3822 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3823 Diag(Loc: CheckLoc, PD);
3824 return MemberPointerConversionResult::Virtual;
3825 }
3826
3827 // Must be a base to derived member conversion.
3828 BuildBasePathArray(Paths, BasePath);
3829 Kind = Direction == MemberPointerConversionDirection::Upcast
3830 ? CK_DerivedToBaseMemberPointer
3831 : CK_BaseToDerivedMemberPointer;
3832
3833 if (!IgnoreBaseAccess)
3834 switch (CheckBaseClassAccess(
3835 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3836 DiagID: Direction == MemberPointerConversionDirection::Upcast
3837 ? diag::err_upcast_to_inaccessible_base
3838 : diag::err_downcast_from_inaccessible_base,
3839 SetupPDiag: [&](PartialDiagnostic &PD) {
3840 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3841 DerivedQual = ToPtrType->getQualifier();
3842 if (Direction == MemberPointerConversionDirection::Upcast)
3843 std::swap(a&: BaseQual, b&: DerivedQual);
3844 DiagCls(PD, DerivedQual, Derived);
3845 DiagCls(PD, BaseQual, Base);
3846 })) {
3847 case Sema::AR_accessible:
3848 case Sema::AR_delayed:
3849 case Sema::AR_dependent:
3850 // Optimistically assume that the delayed and dependent cases
3851 // will work out.
3852 break;
3853
3854 case Sema::AR_inaccessible:
3855 return MemberPointerConversionResult::Inaccessible;
3856 }
3857
3858 return MemberPointerConversionResult::Success;
3859}
3860
3861/// Determine whether the lifetime conversion between the two given
3862/// qualifiers sets is nontrivial.
3863static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3864 Qualifiers ToQuals) {
3865 // Converting anything to const __unsafe_unretained is trivial.
3866 if (ToQuals.hasConst() &&
3867 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3868 return false;
3869
3870 return true;
3871}
3872
3873/// Perform a single iteration of the loop for checking if a qualification
3874/// conversion is valid.
3875///
3876/// Specifically, check whether any change between the qualifiers of \p
3877/// FromType and \p ToType is permissible, given knowledge about whether every
3878/// outer layer is const-qualified.
3879static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3880 bool CStyle, bool IsTopLevel,
3881 bool &PreviousToQualsIncludeConst,
3882 bool &ObjCLifetimeConversion,
3883 const ASTContext &Ctx) {
3884 Qualifiers FromQuals = FromType.getQualifiers();
3885 Qualifiers ToQuals = ToType.getQualifiers();
3886
3887 // Ignore __unaligned qualifier.
3888 FromQuals.removeUnaligned();
3889
3890 // Objective-C ARC:
3891 // Check Objective-C lifetime conversions.
3892 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3893 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3894 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3895 ObjCLifetimeConversion = true;
3896 FromQuals.removeObjCLifetime();
3897 ToQuals.removeObjCLifetime();
3898 } else {
3899 // Qualification conversions cannot cast between different
3900 // Objective-C lifetime qualifiers.
3901 return false;
3902 }
3903 }
3904
3905 // Allow addition/removal of GC attributes but not changing GC attributes.
3906 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3907 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3908 FromQuals.removeObjCGCAttr();
3909 ToQuals.removeObjCGCAttr();
3910 }
3911
3912 // __ptrauth qualifiers must match exactly.
3913 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3914 return false;
3915
3916 // -- for every j > 0, if const is in cv 1,j then const is in cv
3917 // 2,j, and similarly for volatile.
3918 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3919 return false;
3920
3921 // If address spaces mismatch:
3922 // - in top level it is only valid to convert to addr space that is a
3923 // superset in all cases apart from C-style casts where we allow
3924 // conversions between overlapping address spaces.
3925 // - in non-top levels it is not a valid conversion.
3926 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3927 (!IsTopLevel ||
3928 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3929 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3930 return false;
3931
3932 // -- if the cv 1,j and cv 2,j are different, then const is in
3933 // every cv for 0 < k < j.
3934 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3935 !PreviousToQualsIncludeConst)
3936 return false;
3937
3938 // The following wording is from C++20, where the result of the conversion
3939 // is T3, not T2.
3940 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3941 // "array of unknown bound of"
3942 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3943 return false;
3944
3945 // -- if the resulting P3,i is different from P1,i [...], then const is
3946 // added to every cv 3_k for 0 < k < i.
3947 if (!CStyle && FromType->isConstantArrayType() &&
3948 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3949 return false;
3950
3951 // Keep track of whether all prior cv-qualifiers in the "to" type
3952 // include const.
3953 PreviousToQualsIncludeConst =
3954 PreviousToQualsIncludeConst && ToQuals.hasConst();
3955 return true;
3956}
3957
3958bool
3959Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3960 bool CStyle, bool &ObjCLifetimeConversion) {
3961 FromType = Context.getCanonicalType(T: FromType);
3962 ToType = Context.getCanonicalType(T: ToType);
3963 ObjCLifetimeConversion = false;
3964
3965 // If FromType and ToType are the same type, this is not a
3966 // qualification conversion.
3967 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3968 return false;
3969
3970 // (C++ 4.4p4):
3971 // A conversion can add cv-qualifiers at levels other than the first
3972 // in multi-level pointers, subject to the following rules: [...]
3973 bool PreviousToQualsIncludeConst = true;
3974 bool UnwrappedAnyPointer = false;
3975 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3976 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3977 IsTopLevel: !UnwrappedAnyPointer,
3978 PreviousToQualsIncludeConst,
3979 ObjCLifetimeConversion, Ctx: getASTContext()))
3980 return false;
3981 UnwrappedAnyPointer = true;
3982 }
3983
3984 // We are left with FromType and ToType being the pointee types
3985 // after unwrapping the original FromType and ToType the same number
3986 // of times. If we unwrapped any pointers, and if FromType and
3987 // ToType have the same unqualified type (since we checked
3988 // qualifiers above), then this is a qualification conversion.
3989 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3990}
3991
3992/// - Determine whether this is a conversion from a scalar type to an
3993/// atomic type.
3994///
3995/// If successful, updates \c SCS's second and third steps in the conversion
3996/// sequence to finish the conversion.
3997static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3998 bool InOverloadResolution,
3999 StandardConversionSequence &SCS,
4000 bool CStyle) {
4001 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4002 if (!ToAtomic)
4003 return false;
4004
4005 StandardConversionSequence InnerSCS;
4006 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
4007 InOverloadResolution, SCS&: InnerSCS,
4008 CStyle, /*AllowObjCWritebackConversion=*/false))
4009 return false;
4010
4011 SCS.Second = InnerSCS.Second;
4012 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4013 SCS.Third = InnerSCS.Third;
4014 SCS.QualificationIncludesObjCLifetime
4015 = InnerSCS.QualificationIncludesObjCLifetime;
4016 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4017 return true;
4018}
4019
4020static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
4021 QualType ToType,
4022 bool InOverloadResolution,
4023 StandardConversionSequence &SCS,
4024 bool CStyle) {
4025 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4026 if (!ToOBT)
4027 return false;
4028
4029 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4030 QualType FromType = From->getType();
4031 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4032 return false;
4033
4034 StandardConversionSequence InnerSCS;
4035 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4036 InOverloadResolution, SCS&: InnerSCS, CStyle,
4037 /*AllowObjCWritebackConversion=*/false))
4038 return false;
4039
4040 SCS.Second = InnerSCS.Second;
4041 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4042 SCS.Third = InnerSCS.Third;
4043 SCS.QualificationIncludesObjCLifetime =
4044 InnerSCS.QualificationIncludesObjCLifetime;
4045 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4046 return true;
4047}
4048
4049static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4050 CXXConstructorDecl *Constructor,
4051 QualType Type) {
4052 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4053 if (CtorType->getNumParams() > 0) {
4054 QualType FirstArg = CtorType->getParamType(i: 0);
4055 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4056 return true;
4057 }
4058 return false;
4059}
4060
4061static OverloadingResult
4062IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4063 CXXRecordDecl *To,
4064 UserDefinedConversionSequence &User,
4065 OverloadCandidateSet &CandidateSet,
4066 bool AllowExplicit) {
4067 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4068 for (auto *D : S.LookupConstructors(Class: To)) {
4069 auto Info = getConstructorInfo(ND: D);
4070 if (!Info)
4071 continue;
4072
4073 bool Usable = !Info.Constructor->isInvalidDecl() &&
4074 S.isInitListConstructor(Ctor: Info.Constructor);
4075 if (Usable) {
4076 bool SuppressUserConversions = false;
4077 if (Info.ConstructorTmpl)
4078 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4079 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4080 CandidateSet, SuppressUserConversions,
4081 /*PartialOverloading*/ false,
4082 AllowExplicit);
4083 else
4084 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false, AllowExplicit);
4087 }
4088 }
4089
4090 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4091
4092 OverloadCandidateSet::iterator Best;
4093 switch (auto Result =
4094 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4095 case OR_Deleted:
4096 case OR_Success: {
4097 // Record the standard conversion we used and the conversion function.
4098 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4099 QualType ThisType = Constructor->getFunctionObjectParameterType();
4100 // Initializer lists don't have conversions as such.
4101 User.Before.setAsIdentityConversion();
4102 User.HadMultipleCandidates = HadMultipleCandidates;
4103 User.ConversionFunction = Constructor;
4104 User.FoundConversionFunction = Best->FoundDecl;
4105 User.After.setAsIdentityConversion();
4106 User.After.setFromType(ThisType);
4107 User.After.setAllToTypes(ToType);
4108 return Result;
4109 }
4110
4111 case OR_No_Viable_Function:
4112 return OR_No_Viable_Function;
4113 case OR_Ambiguous:
4114 return OR_Ambiguous;
4115 }
4116
4117 llvm_unreachable("Invalid OverloadResult!");
4118}
4119
4120/// Determines whether there is a user-defined conversion sequence
4121/// (C++ [over.ics.user]) that converts expression From to the type
4122/// ToType. If such a conversion exists, User will contain the
4123/// user-defined conversion sequence that performs such a conversion
4124/// and this routine will return true. Otherwise, this routine returns
4125/// false and User is unspecified.
4126///
4127/// \param AllowExplicit true if the conversion should consider C++0x
4128/// "explicit" conversion functions as well as non-explicit conversion
4129/// functions (C++0x [class.conv.fct]p2).
4130///
4131/// \param AllowObjCConversionOnExplicit true if the conversion should
4132/// allow an extra Objective-C pointer conversion on uses of explicit
4133/// constructors. Requires \c AllowExplicit to also be set.
4134static OverloadingResult
4135IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4136 UserDefinedConversionSequence &User,
4137 OverloadCandidateSet &CandidateSet,
4138 AllowedExplicit AllowExplicit,
4139 bool AllowObjCConversionOnExplicit) {
4140 assert(AllowExplicit != AllowedExplicit::None ||
4141 !AllowObjCConversionOnExplicit);
4142 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4143
4144 // Whether we will only visit constructors.
4145 bool ConstructorsOnly = false;
4146
4147 // If the type we are conversion to is a class type, enumerate its
4148 // constructors.
4149 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4150 // C++ [over.match.ctor]p1:
4151 // When objects of class type are direct-initialized (8.5), or
4152 // copy-initialized from an expression of the same or a
4153 // derived class type (8.5), overload resolution selects the
4154 // constructor. [...] For copy-initialization, the candidate
4155 // functions are all the converting constructors (12.3.1) of
4156 // that class. The argument list is the expression-list within
4157 // the parentheses of the initializer.
4158 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4159 (From->getType()->isRecordType() &&
4160 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4161 ConstructorsOnly = true;
4162
4163 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4164 // We're not going to find any constructors.
4165 } else if (auto *ToRecordDecl =
4166 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4167 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4168
4169 Expr **Args = &From;
4170 unsigned NumArgs = 1;
4171 bool ListInitializing = false;
4172 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4173 // But first, see if there is an init-list-constructor that will work.
4174 OverloadingResult Result = IsInitializerListConstructorConversion(
4175 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4176 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4177 if (Result != OR_No_Viable_Function)
4178 return Result;
4179 // Never mind.
4180 CandidateSet.clear(
4181 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4182
4183 // If we're list-initializing, we pass the individual elements as
4184 // arguments, not the entire list.
4185 Args = InitList->getInits();
4186 NumArgs = InitList->getNumInits();
4187 ListInitializing = true;
4188 }
4189
4190 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4191 auto Info = getConstructorInfo(ND: D);
4192 if (!Info)
4193 continue;
4194
4195 bool Usable = !Info.Constructor->isInvalidDecl();
4196 if (!ListInitializing)
4197 Usable = Usable && Info.Constructor->isConvertingConstructor(
4198 /*AllowExplicit*/ true);
4199 if (Usable) {
4200 bool SuppressUserConversions = !ConstructorsOnly;
4201 // C++20 [over.best.ics.general]/4.5:
4202 // if the target is the first parameter of a constructor [of class
4203 // X] and the constructor [...] is a candidate by [...] the second
4204 // phase of [over.match.list] when the initializer list has exactly
4205 // one element that is itself an initializer list, [...] and the
4206 // conversion is to X or reference to cv X, user-defined conversion
4207 // sequences are not considered.
4208 if (SuppressUserConversions && ListInitializing) {
4209 SuppressUserConversions =
4210 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4211 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4212 Type: ToType);
4213 }
4214 if (Info.ConstructorTmpl)
4215 S.AddTemplateOverloadCandidate(
4216 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4217 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4218 CandidateSet, SuppressUserConversions,
4219 /*PartialOverloading*/ false,
4220 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4221 else
4222 // Allow one user-defined conversion when user specifies a
4223 // From->ToType conversion via an static cast (c-style, etc).
4224 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4225 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4226 SuppressUserConversions,
4227 /*PartialOverloading*/ false,
4228 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4229 }
4230 }
4231 }
4232 }
4233
4234 // Enumerate conversion functions, if we're allowed to.
4235 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4236 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4237 // No conversion functions from incomplete types.
4238 } else if (const RecordType *FromRecordType =
4239 From->getType()->getAsCanonical<RecordType>()) {
4240 if (auto *FromRecordDecl =
4241 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4242 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4243 // Add all of the conversion functions as candidates.
4244 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4245 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4246 DeclAccessPair FoundDecl = I.getPair();
4247 NamedDecl *D = FoundDecl.getDecl();
4248 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4249 if (isa<UsingShadowDecl>(Val: D))
4250 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4251
4252 CXXConversionDecl *Conv;
4253 FunctionTemplateDecl *ConvTemplate;
4254 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4255 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4256 else
4257 Conv = cast<CXXConversionDecl>(Val: D);
4258
4259 if (ConvTemplate)
4260 S.AddTemplateConversionCandidate(
4261 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4262 CandidateSet, AllowObjCConversionOnExplicit,
4263 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4264 else
4265 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4266 CandidateSet, AllowObjCConversionOnExplicit,
4267 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4268 }
4269 }
4270 }
4271
4272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4273
4274 OverloadCandidateSet::iterator Best;
4275 switch (auto Result =
4276 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4277 case OR_Success:
4278 case OR_Deleted:
4279 // Record the standard conversion we used and the conversion function.
4280 if (CXXConstructorDecl *Constructor
4281 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4282 // C++ [over.ics.user]p1:
4283 // If the user-defined conversion is specified by a
4284 // constructor (12.3.1), the initial standard conversion
4285 // sequence converts the source type to the type required by
4286 // the argument of the constructor.
4287 //
4288 if (isa<InitListExpr>(Val: From)) {
4289 // Initializer lists don't have conversions as such.
4290 User.Before.setAsIdentityConversion();
4291 User.Before.FromBracedInitList = true;
4292 } else {
4293 if (Best->Conversions[0].isEllipsis())
4294 User.EllipsisConversion = true;
4295 else {
4296 User.Before = Best->Conversions[0].Standard;
4297 User.EllipsisConversion = false;
4298 }
4299 }
4300 User.HadMultipleCandidates = HadMultipleCandidates;
4301 User.ConversionFunction = Constructor;
4302 User.FoundConversionFunction = Best->FoundDecl;
4303 User.After.setAsIdentityConversion();
4304 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4305 User.After.setAllToTypes(ToType);
4306 return Result;
4307 }
4308 if (CXXConversionDecl *Conversion
4309 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4310
4311 assert(Best->HasFinalConversion);
4312
4313 // C++ [over.ics.user]p1:
4314 //
4315 // [...] If the user-defined conversion is specified by a
4316 // conversion function (12.3.2), the initial standard
4317 // conversion sequence converts the source type to the
4318 // implicit object parameter of the conversion function.
4319 User.Before = Best->Conversions[0].Standard;
4320 User.HadMultipleCandidates = HadMultipleCandidates;
4321 User.ConversionFunction = Conversion;
4322 User.FoundConversionFunction = Best->FoundDecl;
4323 User.EllipsisConversion = false;
4324
4325 // C++ [over.ics.user]p2:
4326 // The second standard conversion sequence converts the
4327 // result of the user-defined conversion to the target type
4328 // for the sequence. Since an implicit conversion sequence
4329 // is an initialization, the special rules for
4330 // initialization by user-defined conversion apply when
4331 // selecting the best user-defined conversion for a
4332 // user-defined conversion sequence (see 13.3.3 and
4333 // 13.3.3.1).
4334 User.After = Best->FinalConversion;
4335 return Result;
4336 }
4337 llvm_unreachable("Not a constructor or conversion function?");
4338
4339 case OR_No_Viable_Function:
4340 return OR_No_Viable_Function;
4341
4342 case OR_Ambiguous:
4343 return OR_Ambiguous;
4344 }
4345
4346 llvm_unreachable("Invalid OverloadResult!");
4347}
4348
4349bool
4350Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4351 ImplicitConversionSequence ICS;
4352 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4353 OverloadCandidateSet::CSK_Normal);
4354 OverloadingResult OvResult =
4355 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4356 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4357
4358 if (!(OvResult == OR_Ambiguous ||
4359 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4360 return false;
4361
4362 auto Cands = CandidateSet.CompleteCandidates(
4363 S&: *this,
4364 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4365 Args: From);
4366 if (OvResult == OR_Ambiguous)
4367 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4368 << From->getType() << ToType << From->getSourceRange();
4369 else { // OR_No_Viable_Function && !CandidateSet.empty()
4370 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4371 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4372 Args: From->getType(), Args: From->getSourceRange()))
4373 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4374 << false << From->getType() << From->getSourceRange() << ToType;
4375 }
4376
4377 CandidateSet.NoteCandidates(
4378 S&: *this, Args: From, Cands);
4379 return true;
4380}
4381
4382// Helper for compareConversionFunctions that gets the FunctionType that the
4383// conversion-operator return value 'points' to, or nullptr.
4384static const FunctionType *
4385getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4386 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4387 const PointerType *RetPtrTy =
4388 ConvFuncTy->getReturnType()->getAs<PointerType>();
4389
4390 if (!RetPtrTy)
4391 return nullptr;
4392
4393 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4394}
4395
4396/// Compare the user-defined conversion functions or constructors
4397/// of two user-defined conversion sequences to determine whether any ordering
4398/// is possible.
4399static ImplicitConversionSequence::CompareKind
4400compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4401 FunctionDecl *Function2) {
4402 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4403 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4404 if (!Conv1 || !Conv2)
4405 return ImplicitConversionSequence::Indistinguishable;
4406
4407 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4408 return ImplicitConversionSequence::Indistinguishable;
4409
4410 // Objective-C++:
4411 // If both conversion functions are implicitly-declared conversions from
4412 // a lambda closure type to a function pointer and a block pointer,
4413 // respectively, always prefer the conversion to a function pointer,
4414 // because the function pointer is more lightweight and is more likely
4415 // to keep code working.
4416 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4417 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4418 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4419 if (Block1 != Block2)
4420 return Block1 ? ImplicitConversionSequence::Worse
4421 : ImplicitConversionSequence::Better;
4422 }
4423
4424 // In order to support multiple calling conventions for the lambda conversion
4425 // operator (such as when the free and member function calling convention is
4426 // different), prefer the 'free' mechanism, followed by the calling-convention
4427 // of operator(). The latter is in place to support the MSVC-like solution of
4428 // defining ALL of the possible conversions in regards to calling-convention.
4429 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4430 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4431
4432 if (Conv1FuncRet && Conv2FuncRet &&
4433 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4434 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4435 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4436
4437 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4438 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4439
4440 CallingConv CallOpCC =
4441 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4442 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4443 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4444 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4445 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4446
4447 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4448 for (CallingConv CC : PrefOrder) {
4449 if (Conv1CC == CC)
4450 return ImplicitConversionSequence::Better;
4451 if (Conv2CC == CC)
4452 return ImplicitConversionSequence::Worse;
4453 }
4454 }
4455
4456 return ImplicitConversionSequence::Indistinguishable;
4457}
4458
4459static bool hasDeprecatedStringLiteralToCharPtrConversion(
4460 const ImplicitConversionSequence &ICS) {
4461 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4462 (ICS.isUserDefined() &&
4463 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4464}
4465
4466/// CompareImplicitConversionSequences - Compare two implicit
4467/// conversion sequences to determine whether one is better than the
4468/// other or if they are indistinguishable (C++ 13.3.3.2).
4469static ImplicitConversionSequence::CompareKind
4470CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4471 const ImplicitConversionSequence& ICS1,
4472 const ImplicitConversionSequence& ICS2)
4473{
4474 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4475 // conversion sequences (as defined in 13.3.3.1)
4476 // -- a standard conversion sequence (13.3.3.1.1) is a better
4477 // conversion sequence than a user-defined conversion sequence or
4478 // an ellipsis conversion sequence, and
4479 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4480 // conversion sequence than an ellipsis conversion sequence
4481 // (13.3.3.1.3).
4482 //
4483 // C++0x [over.best.ics]p10:
4484 // For the purpose of ranking implicit conversion sequences as
4485 // described in 13.3.3.2, the ambiguous conversion sequence is
4486 // treated as a user-defined sequence that is indistinguishable
4487 // from any other user-defined conversion sequence.
4488
4489 // String literal to 'char *' conversion has been deprecated in C++03. It has
4490 // been removed from C++11. We still accept this conversion, if it happens at
4491 // the best viable function. Otherwise, this conversion is considered worse
4492 // than ellipsis conversion. Consider this as an extension; this is not in the
4493 // standard. For example:
4494 //
4495 // int &f(...); // #1
4496 // void f(char*); // #2
4497 // void g() { int &r = f("foo"); }
4498 //
4499 // In C++03, we pick #2 as the best viable function.
4500 // In C++11, we pick #1 as the best viable function, because ellipsis
4501 // conversion is better than string-literal to char* conversion (since there
4502 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4503 // convert arguments, #2 would be the best viable function in C++11.
4504 // If the best viable function has this conversion, a warning will be issued
4505 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4506
4507 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4508 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4509 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4510 // Ill-formedness must not differ
4511 ICS1.isBad() == ICS2.isBad())
4512 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4513 ? ImplicitConversionSequence::Worse
4514 : ImplicitConversionSequence::Better;
4515
4516 if (ICS1.getKindRank() < ICS2.getKindRank())
4517 return ImplicitConversionSequence::Better;
4518 if (ICS2.getKindRank() < ICS1.getKindRank())
4519 return ImplicitConversionSequence::Worse;
4520
4521 // The following checks require both conversion sequences to be of
4522 // the same kind.
4523 if (ICS1.getKind() != ICS2.getKind())
4524 return ImplicitConversionSequence::Indistinguishable;
4525
4526 ImplicitConversionSequence::CompareKind Result =
4527 ImplicitConversionSequence::Indistinguishable;
4528
4529 // Two implicit conversion sequences of the same form are
4530 // indistinguishable conversion sequences unless one of the
4531 // following rules apply: (C++ 13.3.3.2p3):
4532
4533 // List-initialization sequence L1 is a better conversion sequence than
4534 // list-initialization sequence L2 if:
4535 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4536 // if not that,
4537 // — L1 and L2 convert to arrays of the same element type, and either the
4538 // number of elements n_1 initialized by L1 is less than the number of
4539 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4540 // an array of unknown bound and L1 does not,
4541 // even if one of the other rules in this paragraph would otherwise apply.
4542 if (!ICS1.isBad()) {
4543 bool StdInit1 = false, StdInit2 = false;
4544 if (ICS1.hasInitializerListContainerType())
4545 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4546 Element: nullptr);
4547 if (ICS2.hasInitializerListContainerType())
4548 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4549 Element: nullptr);
4550 if (StdInit1 != StdInit2)
4551 return StdInit1 ? ImplicitConversionSequence::Better
4552 : ImplicitConversionSequence::Worse;
4553
4554 if (ICS1.hasInitializerListContainerType() &&
4555 ICS2.hasInitializerListContainerType())
4556 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4557 T: ICS1.getInitializerListContainerType()))
4558 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4559 T: ICS2.getInitializerListContainerType())) {
4560 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4561 T2: CAT2->getElementType())) {
4562 // Both to arrays of the same element type
4563 if (CAT1->getSize() != CAT2->getSize())
4564 // Different sized, the smaller wins
4565 return CAT1->getSize().ult(RHS: CAT2->getSize())
4566 ? ImplicitConversionSequence::Better
4567 : ImplicitConversionSequence::Worse;
4568 if (ICS1.isInitializerListOfIncompleteArray() !=
4569 ICS2.isInitializerListOfIncompleteArray())
4570 // One is incomplete, it loses
4571 return ICS2.isInitializerListOfIncompleteArray()
4572 ? ImplicitConversionSequence::Better
4573 : ImplicitConversionSequence::Worse;
4574 }
4575 }
4576 }
4577
4578 if (ICS1.isStandard())
4579 // Standard conversion sequence S1 is a better conversion sequence than
4580 // standard conversion sequence S2 if [...]
4581 Result = CompareStandardConversionSequences(S, Loc,
4582 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4583 else if (ICS1.isUserDefined()) {
4584 // With lazy template loading, it is possible to find non-canonical
4585 // FunctionDecls, depending on when redecl chains are completed. Make sure
4586 // to compare the canonical decls of conversion functions. This avoids
4587 // ambiguity problems for templated conversion operators.
4588 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4589 if (ConvFunc1)
4590 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4591 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4592 if (ConvFunc2)
4593 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4594 // User-defined conversion sequence U1 is a better conversion
4595 // sequence than another user-defined conversion sequence U2 if
4596 // they contain the same user-defined conversion function or
4597 // constructor and if the second standard conversion sequence of
4598 // U1 is better than the second standard conversion sequence of
4599 // U2 (C++ 13.3.3.2p3).
4600 if (ConvFunc1 == ConvFunc2)
4601 Result = CompareStandardConversionSequences(S, Loc,
4602 SCS1: ICS1.UserDefined.After,
4603 SCS2: ICS2.UserDefined.After);
4604 else
4605 Result = compareConversionFunctions(S,
4606 Function1: ICS1.UserDefined.ConversionFunction,
4607 Function2: ICS2.UserDefined.ConversionFunction);
4608 }
4609
4610 return Result;
4611}
4612
4613// Per 13.3.3.2p3, compare the given standard conversion sequences to
4614// determine if one is a proper subset of the other.
4615static ImplicitConversionSequence::CompareKind
4616compareStandardConversionSubsets(ASTContext &Context,
4617 const StandardConversionSequence& SCS1,
4618 const StandardConversionSequence& SCS2) {
4619 ImplicitConversionSequence::CompareKind Result
4620 = ImplicitConversionSequence::Indistinguishable;
4621
4622 // the identity conversion sequence is considered to be a subsequence of
4623 // any non-identity conversion sequence
4624 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4625 return ImplicitConversionSequence::Better;
4626 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4627 return ImplicitConversionSequence::Worse;
4628
4629 if (SCS1.Second != SCS2.Second) {
4630 if (SCS1.Second == ICK_Identity)
4631 Result = ImplicitConversionSequence::Better;
4632 else if (SCS2.Second == ICK_Identity)
4633 Result = ImplicitConversionSequence::Worse;
4634 else
4635 return ImplicitConversionSequence::Indistinguishable;
4636 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4637 return ImplicitConversionSequence::Indistinguishable;
4638
4639 if (SCS1.Third == SCS2.Third) {
4640 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4641 : ImplicitConversionSequence::Indistinguishable;
4642 }
4643
4644 if (SCS1.Third == ICK_Identity)
4645 return Result == ImplicitConversionSequence::Worse
4646 ? ImplicitConversionSequence::Indistinguishable
4647 : ImplicitConversionSequence::Better;
4648
4649 if (SCS2.Third == ICK_Identity)
4650 return Result == ImplicitConversionSequence::Better
4651 ? ImplicitConversionSequence::Indistinguishable
4652 : ImplicitConversionSequence::Worse;
4653
4654 return ImplicitConversionSequence::Indistinguishable;
4655}
4656
4657/// Determine whether one of the given reference bindings is better
4658/// than the other based on what kind of bindings they are.
4659static bool
4660isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4661 const StandardConversionSequence &SCS2) {
4662 // C++0x [over.ics.rank]p3b4:
4663 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4664 // implicit object parameter of a non-static member function declared
4665 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4666 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4667 // lvalue reference to a function lvalue and S2 binds an rvalue
4668 // reference*.
4669 //
4670 // FIXME: Rvalue references. We're going rogue with the above edits,
4671 // because the semantics in the current C++0x working paper (N3225 at the
4672 // time of this writing) break the standard definition of std::forward
4673 // and std::reference_wrapper when dealing with references to functions.
4674 // Proposed wording changes submitted to CWG for consideration.
4675 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4676 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4677 return false;
4678
4679 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4680 SCS2.IsLvalueReference) ||
4681 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4682 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4683}
4684
4685enum class FixedEnumPromotion {
4686 None,
4687 ToUnderlyingType,
4688 ToPromotedUnderlyingType
4689};
4690
4691/// Returns kind of fixed enum promotion the \a SCS uses.
4692static FixedEnumPromotion
4693getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4694
4695 if (SCS.Second != ICK_Integral_Promotion)
4696 return FixedEnumPromotion::None;
4697
4698 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4699 if (!Enum)
4700 return FixedEnumPromotion::None;
4701
4702 if (!Enum->isFixed())
4703 return FixedEnumPromotion::None;
4704
4705 QualType UnderlyingType = Enum->getIntegerType();
4706 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4707 return FixedEnumPromotion::ToUnderlyingType;
4708
4709 return FixedEnumPromotion::ToPromotedUnderlyingType;
4710}
4711
4712/// CompareStandardConversionSequences - Compare two standard
4713/// conversion sequences to determine whether one is better than the
4714/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4715static ImplicitConversionSequence::CompareKind
4716CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4717 const StandardConversionSequence& SCS1,
4718 const StandardConversionSequence& SCS2)
4719{
4720 // Standard conversion sequence S1 is a better conversion sequence
4721 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4722
4723 // -- S1 is a proper subsequence of S2 (comparing the conversion
4724 // sequences in the canonical form defined by 13.3.3.1.1,
4725 // excluding any Lvalue Transformation; the identity conversion
4726 // sequence is considered to be a subsequence of any
4727 // non-identity conversion sequence) or, if not that,
4728 if (ImplicitConversionSequence::CompareKind CK
4729 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4730 return CK;
4731
4732 // -- the rank of S1 is better than the rank of S2 (by the rules
4733 // defined below), or, if not that,
4734 ImplicitConversionRank Rank1 = SCS1.getRank();
4735 ImplicitConversionRank Rank2 = SCS2.getRank();
4736 if (Rank1 < Rank2)
4737 return ImplicitConversionSequence::Better;
4738 else if (Rank2 < Rank1)
4739 return ImplicitConversionSequence::Worse;
4740
4741 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4742 // are indistinguishable unless one of the following rules
4743 // applies:
4744
4745 // A conversion that is not a conversion of a pointer, or
4746 // pointer to member, to bool is better than another conversion
4747 // that is such a conversion.
4748 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4749 return SCS2.isPointerConversionToBool()
4750 ? ImplicitConversionSequence::Better
4751 : ImplicitConversionSequence::Worse;
4752
4753 // C++14 [over.ics.rank]p4b2:
4754 // This is retroactively applied to C++11 by CWG 1601.
4755 //
4756 // A conversion that promotes an enumeration whose underlying type is fixed
4757 // to its underlying type is better than one that promotes to the promoted
4758 // underlying type, if the two are different.
4759 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4760 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4761 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4762 FEP1 != FEP2)
4763 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4764 ? ImplicitConversionSequence::Better
4765 : ImplicitConversionSequence::Worse;
4766
4767 // C++ [over.ics.rank]p4b2:
4768 //
4769 // If class B is derived directly or indirectly from class A,
4770 // conversion of B* to A* is better than conversion of B* to
4771 // void*, and conversion of A* to void* is better than conversion
4772 // of B* to void*.
4773 bool SCS1ConvertsToVoid
4774 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4775 bool SCS2ConvertsToVoid
4776 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4777 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4778 // Exactly one of the conversion sequences is a conversion to
4779 // a void pointer; it's the worse conversion.
4780 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4781 : ImplicitConversionSequence::Worse;
4782 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4783 // Neither conversion sequence converts to a void pointer; compare
4784 // their derived-to-base conversions.
4785 if (ImplicitConversionSequence::CompareKind DerivedCK
4786 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4787 return DerivedCK;
4788 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4789 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4790 // Both conversion sequences are conversions to void
4791 // pointers. Compare the source types to determine if there's an
4792 // inheritance relationship in their sources.
4793 QualType FromType1 = SCS1.getFromType();
4794 QualType FromType2 = SCS2.getFromType();
4795
4796 // Adjust the types we're converting from via the array-to-pointer
4797 // conversion, if we need to.
4798 if (SCS1.First == ICK_Array_To_Pointer)
4799 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4800 if (SCS2.First == ICK_Array_To_Pointer)
4801 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4802
4803 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4804 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4805
4806 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4807 return ImplicitConversionSequence::Better;
4808 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4809 return ImplicitConversionSequence::Worse;
4810
4811 // Objective-C++: If one interface is more specific than the
4812 // other, it is the better one.
4813 const ObjCObjectPointerType* FromObjCPtr1
4814 = FromType1->getAs<ObjCObjectPointerType>();
4815 const ObjCObjectPointerType* FromObjCPtr2
4816 = FromType2->getAs<ObjCObjectPointerType>();
4817 if (FromObjCPtr1 && FromObjCPtr2) {
4818 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4819 RHSOPT: FromObjCPtr2);
4820 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4821 RHSOPT: FromObjCPtr1);
4822 if (AssignLeft != AssignRight) {
4823 return AssignLeft? ImplicitConversionSequence::Better
4824 : ImplicitConversionSequence::Worse;
4825 }
4826 }
4827 }
4828
4829 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4830 // Check for a better reference binding based on the kind of bindings.
4831 if (isBetterReferenceBindingKind(SCS1, SCS2))
4832 return ImplicitConversionSequence::Better;
4833 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4834 return ImplicitConversionSequence::Worse;
4835 }
4836
4837 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4838 // bullet 3).
4839 if (ImplicitConversionSequence::CompareKind QualCK
4840 = CompareQualificationConversions(S, SCS1, SCS2))
4841 return QualCK;
4842
4843 if (ImplicitConversionSequence::CompareKind ObtCK =
4844 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4845 return ObtCK;
4846
4847 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4848 // C++ [over.ics.rank]p3b4:
4849 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4850 // which the references refer are the same type except for
4851 // top-level cv-qualifiers, and the type to which the reference
4852 // initialized by S2 refers is more cv-qualified than the type
4853 // to which the reference initialized by S1 refers.
4854 QualType T1 = SCS1.getToType(Idx: 2);
4855 QualType T2 = SCS2.getToType(Idx: 2);
4856 T1 = S.Context.getCanonicalType(T: T1);
4857 T2 = S.Context.getCanonicalType(T: T2);
4858 Qualifiers T1Quals, T2Quals;
4859 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4860 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4861 if (UnqualT1 == UnqualT2) {
4862 // Objective-C++ ARC: If the references refer to objects with different
4863 // lifetimes, prefer bindings that don't change lifetime.
4864 if (SCS1.ObjCLifetimeConversionBinding !=
4865 SCS2.ObjCLifetimeConversionBinding) {
4866 return SCS1.ObjCLifetimeConversionBinding
4867 ? ImplicitConversionSequence::Worse
4868 : ImplicitConversionSequence::Better;
4869 }
4870
4871 // If the type is an array type, promote the element qualifiers to the
4872 // type for comparison.
4873 if (isa<ArrayType>(Val: T1) && T1Quals)
4874 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4875 if (isa<ArrayType>(Val: T2) && T2Quals)
4876 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4877 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4878 return ImplicitConversionSequence::Better;
4879 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4880 return ImplicitConversionSequence::Worse;
4881 }
4882 }
4883
4884 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4885 // floating-to-integral conversion if the integral conversion
4886 // is between types of the same size.
4887 // For example:
4888 // void f(float);
4889 // void f(int);
4890 // int main {
4891 // long a;
4892 // f(a);
4893 // }
4894 // Here, MSVC will call f(int) instead of generating a compile error
4895 // as clang will do in standard mode.
4896 if (S.getLangOpts().MSVCCompat &&
4897 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4898 SCS1.Second == ICK_Integral_Conversion &&
4899 SCS2.Second == ICK_Floating_Integral &&
4900 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4901 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4902 return ImplicitConversionSequence::Better;
4903
4904 // Prefer a compatible vector conversion over a lax vector conversion
4905 // For example:
4906 //
4907 // typedef float __v4sf __attribute__((__vector_size__(16)));
4908 // void f(vector float);
4909 // void f(vector signed int);
4910 // int main() {
4911 // __v4sf a;
4912 // f(a);
4913 // }
4914 // Here, we'd like to choose f(vector float) and not
4915 // report an ambiguous call error
4916 if (SCS1.Second == ICK_Vector_Conversion &&
4917 SCS2.Second == ICK_Vector_Conversion) {
4918 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4919 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4920 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4921 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4922
4923 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4924 return SCS1IsCompatibleVectorConversion
4925 ? ImplicitConversionSequence::Better
4926 : ImplicitConversionSequence::Worse;
4927 }
4928
4929 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4930 SCS2.Second == ICK_SVE_Vector_Conversion) {
4931 bool SCS1IsCompatibleSVEVectorConversion =
4932 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4933 bool SCS2IsCompatibleSVEVectorConversion =
4934 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4935
4936 if (SCS1IsCompatibleSVEVectorConversion !=
4937 SCS2IsCompatibleSVEVectorConversion)
4938 return SCS1IsCompatibleSVEVectorConversion
4939 ? ImplicitConversionSequence::Better
4940 : ImplicitConversionSequence::Worse;
4941 }
4942
4943 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4944 SCS2.Second == ICK_RVV_Vector_Conversion) {
4945 bool SCS1IsCompatibleRVVVectorConversion =
4946 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4947 bool SCS2IsCompatibleRVVVectorConversion =
4948 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4949
4950 if (SCS1IsCompatibleRVVVectorConversion !=
4951 SCS2IsCompatibleRVVVectorConversion)
4952 return SCS1IsCompatibleRVVVectorConversion
4953 ? ImplicitConversionSequence::Better
4954 : ImplicitConversionSequence::Worse;
4955 }
4956 return ImplicitConversionSequence::Indistinguishable;
4957}
4958
4959/// CompareOverflowBehaviorConversions - Compares two standard conversion
4960/// sequences to determine whether they can be ranked based on their
4961/// OverflowBehaviorType's underlying type.
4962static ImplicitConversionSequence::CompareKind
4963CompareOverflowBehaviorConversions(Sema &S,
4964 const StandardConversionSequence &SCS1,
4965 const StandardConversionSequence &SCS2) {
4966
4967 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4968 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4969 return ImplicitConversionSequence::Better;
4970
4971 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4972 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
4973 return ImplicitConversionSequence::Worse;
4974
4975 return ImplicitConversionSequence::Indistinguishable;
4976}
4977
4978/// CompareQualificationConversions - Compares two standard conversion
4979/// sequences to determine whether they can be ranked based on their
4980/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4981static ImplicitConversionSequence::CompareKind
4982CompareQualificationConversions(Sema &S,
4983 const StandardConversionSequence& SCS1,
4984 const StandardConversionSequence& SCS2) {
4985 // C++ [over.ics.rank]p3:
4986 // -- S1 and S2 differ only in their qualification conversion and
4987 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4988 // [C++98]
4989 // [...] and the cv-qualification signature of type T1 is a proper subset
4990 // of the cv-qualification signature of type T2, and S1 is not the
4991 // deprecated string literal array-to-pointer conversion (4.2).
4992 // [C++2a]
4993 // [...] where T1 can be converted to T2 by a qualification conversion.
4994 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4995 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4996 return ImplicitConversionSequence::Indistinguishable;
4997
4998 // FIXME: the example in the standard doesn't use a qualification
4999 // conversion (!)
5000 QualType T1 = SCS1.getToType(Idx: 2);
5001 QualType T2 = SCS2.getToType(Idx: 2);
5002 T1 = S.Context.getCanonicalType(T: T1);
5003 T2 = S.Context.getCanonicalType(T: T2);
5004 assert(!T1->isReferenceType() && !T2->isReferenceType());
5005 Qualifiers T1Quals, T2Quals;
5006 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5007 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5008
5009 // If the types are the same, we won't learn anything by unwrapping
5010 // them.
5011 if (UnqualT1 == UnqualT2)
5012 return ImplicitConversionSequence::Indistinguishable;
5013
5014 // Don't ever prefer a standard conversion sequence that uses the deprecated
5015 // string literal array to pointer conversion.
5016 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5017 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5018
5019 // Objective-C++ ARC:
5020 // Prefer qualification conversions not involving a change in lifetime
5021 // to qualification conversions that do change lifetime.
5022 if (SCS1.QualificationIncludesObjCLifetime &&
5023 !SCS2.QualificationIncludesObjCLifetime)
5024 CanPick1 = false;
5025 if (SCS2.QualificationIncludesObjCLifetime &&
5026 !SCS1.QualificationIncludesObjCLifetime)
5027 CanPick2 = false;
5028
5029 bool ObjCLifetimeConversion;
5030 if (CanPick1 &&
5031 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5032 CanPick1 = false;
5033 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5034 // directions, so we can't short-cut this second check in general.
5035 if (CanPick2 &&
5036 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5037 CanPick2 = false;
5038
5039 if (CanPick1 != CanPick2)
5040 return CanPick1 ? ImplicitConversionSequence::Better
5041 : ImplicitConversionSequence::Worse;
5042 return ImplicitConversionSequence::Indistinguishable;
5043}
5044
5045/// CompareDerivedToBaseConversions - Compares two standard conversion
5046/// sequences to determine whether they can be ranked based on their
5047/// various kinds of derived-to-base conversions (C++
5048/// [over.ics.rank]p4b3). As part of these checks, we also look at
5049/// conversions between Objective-C interface types.
5050static ImplicitConversionSequence::CompareKind
5051CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5052 const StandardConversionSequence& SCS1,
5053 const StandardConversionSequence& SCS2) {
5054 QualType FromType1 = SCS1.getFromType();
5055 QualType ToType1 = SCS1.getToType(Idx: 1);
5056 QualType FromType2 = SCS2.getFromType();
5057 QualType ToType2 = SCS2.getToType(Idx: 1);
5058
5059 // Adjust the types we're converting from via the array-to-pointer
5060 // conversion, if we need to.
5061 if (SCS1.First == ICK_Array_To_Pointer)
5062 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5063 if (SCS2.First == ICK_Array_To_Pointer)
5064 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5065
5066 // Canonicalize all of the types.
5067 FromType1 = S.Context.getCanonicalType(T: FromType1);
5068 ToType1 = S.Context.getCanonicalType(T: ToType1);
5069 FromType2 = S.Context.getCanonicalType(T: FromType2);
5070 ToType2 = S.Context.getCanonicalType(T: ToType2);
5071
5072 // C++ [over.ics.rank]p4b3:
5073 //
5074 // If class B is derived directly or indirectly from class A and
5075 // class C is derived directly or indirectly from B,
5076 //
5077 // Compare based on pointer conversions.
5078 if (SCS1.Second == ICK_Pointer_Conversion &&
5079 SCS2.Second == ICK_Pointer_Conversion &&
5080 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5081 FromType1->isPointerType() && FromType2->isPointerType() &&
5082 ToType1->isPointerType() && ToType2->isPointerType()) {
5083 QualType FromPointee1 =
5084 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5085 QualType ToPointee1 =
5086 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5087 QualType FromPointee2 =
5088 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5089 QualType ToPointee2 =
5090 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5091
5092 // -- conversion of C* to B* is better than conversion of C* to A*,
5093 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5094 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5095 return ImplicitConversionSequence::Better;
5096 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5097 return ImplicitConversionSequence::Worse;
5098 }
5099
5100 // -- conversion of B* to A* is better than conversion of C* to A*,
5101 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5102 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5103 return ImplicitConversionSequence::Better;
5104 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5105 return ImplicitConversionSequence::Worse;
5106 }
5107 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5108 SCS2.Second == ICK_Pointer_Conversion) {
5109 const ObjCObjectPointerType *FromPtr1
5110 = FromType1->getAs<ObjCObjectPointerType>();
5111 const ObjCObjectPointerType *FromPtr2
5112 = FromType2->getAs<ObjCObjectPointerType>();
5113 const ObjCObjectPointerType *ToPtr1
5114 = ToType1->getAs<ObjCObjectPointerType>();
5115 const ObjCObjectPointerType *ToPtr2
5116 = ToType2->getAs<ObjCObjectPointerType>();
5117
5118 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5119 // Apply the same conversion ranking rules for Objective-C pointer types
5120 // that we do for C++ pointers to class types. However, we employ the
5121 // Objective-C pseudo-subtyping relationship used for assignment of
5122 // Objective-C pointer types.
5123 bool FromAssignLeft
5124 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5125 bool FromAssignRight
5126 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5127 bool ToAssignLeft
5128 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5129 bool ToAssignRight
5130 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5131
5132 // A conversion to an a non-id object pointer type or qualified 'id'
5133 // type is better than a conversion to 'id'.
5134 if (ToPtr1->isObjCIdType() &&
5135 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5136 return ImplicitConversionSequence::Worse;
5137 if (ToPtr2->isObjCIdType() &&
5138 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5139 return ImplicitConversionSequence::Better;
5140
5141 // A conversion to a non-id object pointer type is better than a
5142 // conversion to a qualified 'id' type
5143 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5144 return ImplicitConversionSequence::Worse;
5145 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5146 return ImplicitConversionSequence::Better;
5147
5148 // A conversion to an a non-Class object pointer type or qualified 'Class'
5149 // type is better than a conversion to 'Class'.
5150 if (ToPtr1->isObjCClassType() &&
5151 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5152 return ImplicitConversionSequence::Worse;
5153 if (ToPtr2->isObjCClassType() &&
5154 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5155 return ImplicitConversionSequence::Better;
5156
5157 // A conversion to a non-Class object pointer type is better than a
5158 // conversion to a qualified 'Class' type.
5159 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5160 return ImplicitConversionSequence::Worse;
5161 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5162 return ImplicitConversionSequence::Better;
5163
5164 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5165 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5166 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5167 (ToAssignLeft != ToAssignRight)) {
5168 if (FromPtr1->isSpecialized()) {
5169 // "conversion of B<A> * to B * is better than conversion of B * to
5170 // C *.
5171 bool IsFirstSame =
5172 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5173 bool IsSecondSame =
5174 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5175 if (IsFirstSame) {
5176 if (!IsSecondSame)
5177 return ImplicitConversionSequence::Better;
5178 } else if (IsSecondSame)
5179 return ImplicitConversionSequence::Worse;
5180 }
5181 return ToAssignLeft? ImplicitConversionSequence::Worse
5182 : ImplicitConversionSequence::Better;
5183 }
5184
5185 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5186 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5187 (FromAssignLeft != FromAssignRight))
5188 return FromAssignLeft? ImplicitConversionSequence::Better
5189 : ImplicitConversionSequence::Worse;
5190 }
5191 }
5192
5193 // Ranking of member-pointer types.
5194 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5195 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5196 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5197 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5198 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5199 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5200 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5201 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5202 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5203 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5204 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5205 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5206 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5207 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5208 return ImplicitConversionSequence::Worse;
5209 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5210 return ImplicitConversionSequence::Better;
5211 }
5212 // conversion of B::* to C::* is better than conversion of A::* to C::*
5213 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5214 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5215 return ImplicitConversionSequence::Better;
5216 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5217 return ImplicitConversionSequence::Worse;
5218 }
5219 }
5220
5221 if (SCS1.Second == ICK_Derived_To_Base) {
5222 // -- conversion of C to B is better than conversion of C to A,
5223 // -- binding of an expression of type C to a reference of type
5224 // B& is better than binding an expression of type C to a
5225 // reference of type A&,
5226 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5227 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5228 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5229 return ImplicitConversionSequence::Better;
5230 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5231 return ImplicitConversionSequence::Worse;
5232 }
5233
5234 // -- conversion of B to A is better than conversion of C to A.
5235 // -- binding of an expression of type B to a reference of type
5236 // A& is better than binding an expression of type C to a
5237 // reference of type A&,
5238 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5239 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5240 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5241 return ImplicitConversionSequence::Better;
5242 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5243 return ImplicitConversionSequence::Worse;
5244 }
5245 }
5246
5247 return ImplicitConversionSequence::Indistinguishable;
5248}
5249
5250static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5251 if (!T.getQualifiers().hasUnaligned())
5252 return T;
5253
5254 Qualifiers Q;
5255 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5256 Q.removeUnaligned();
5257 return Ctx.getQualifiedType(T, Qs: Q);
5258}
5259
5260Sema::ReferenceCompareResult
5261Sema::CompareReferenceRelationship(SourceLocation Loc,
5262 QualType OrigT1, QualType OrigT2,
5263 ReferenceConversions *ConvOut) {
5264 assert(!OrigT1->isReferenceType() &&
5265 "T1 must be the pointee type of the reference type");
5266 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5267
5268 QualType T1 = Context.getCanonicalType(T: OrigT1);
5269 QualType T2 = Context.getCanonicalType(T: OrigT2);
5270 Qualifiers T1Quals, T2Quals;
5271 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5272 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5273
5274 ReferenceConversions ConvTmp;
5275 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5276 Conv = ReferenceConversions();
5277
5278 // C++2a [dcl.init.ref]p4:
5279 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5280 // reference-related to "cv2 T2" if T1 is similar to T2, or
5281 // T1 is a base class of T2.
5282 // "cv1 T1" is reference-compatible with "cv2 T2" if
5283 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5284 // "pointer to cv1 T1" via a standard conversion sequence.
5285
5286 // Check for standard conversions we can apply to pointers: derived-to-base
5287 // conversions, ObjC pointer conversions, and function pointer conversions.
5288 // (Qualification conversions are checked last.)
5289 if (UnqualT1 == UnqualT2) {
5290 // Nothing to do.
5291 } else if (isCompleteType(Loc, T: OrigT2) &&
5292 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5293 Conv |= ReferenceConversions::DerivedToBase;
5294 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5295 UnqualT2->isObjCObjectOrInterfaceType() &&
5296 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5297 Conv |= ReferenceConversions::ObjC;
5298 else if (UnqualT2->isFunctionType() &&
5299 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5300 Conv |= ReferenceConversions::Function;
5301 // No need to check qualifiers; function types don't have them.
5302 return Ref_Compatible;
5303 }
5304 bool ConvertedReferent = Conv != 0;
5305
5306 // We can have a qualification conversion. Compute whether the types are
5307 // similar at the same time.
5308 bool PreviousToQualsIncludeConst = true;
5309 bool TopLevel = true;
5310 do {
5311 if (T1 == T2)
5312 break;
5313
5314 // We will need a qualification conversion.
5315 Conv |= ReferenceConversions::Qualification;
5316
5317 // Track whether we performed a qualification conversion anywhere other
5318 // than the top level. This matters for ranking reference bindings in
5319 // overload resolution.
5320 if (!TopLevel)
5321 Conv |= ReferenceConversions::NestedQualification;
5322
5323 // MS compiler ignores __unaligned qualifier for references; do the same.
5324 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5325 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5326
5327 // If we find a qualifier mismatch, the types are not reference-compatible,
5328 // but are still be reference-related if they're similar.
5329 bool ObjCLifetimeConversion = false;
5330 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5331 PreviousToQualsIncludeConst,
5332 ObjCLifetimeConversion, Ctx: getASTContext()))
5333 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5334 ? Ref_Related
5335 : Ref_Incompatible;
5336
5337 // FIXME: Should we track this for any level other than the first?
5338 if (ObjCLifetimeConversion)
5339 Conv |= ReferenceConversions::ObjCLifetime;
5340
5341 TopLevel = false;
5342 } while (Context.UnwrapSimilarTypes(T1, T2));
5343
5344 // At this point, if the types are reference-related, we must either have the
5345 // same inner type (ignoring qualifiers), or must have already worked out how
5346 // to convert the referent.
5347 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5348 ? Ref_Compatible
5349 : Ref_Incompatible;
5350}
5351
5352/// Look for a user-defined conversion to a value reference-compatible
5353/// with DeclType. Return true if something definite is found.
5354static bool
5355FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5356 QualType DeclType, SourceLocation DeclLoc,
5357 Expr *Init, QualType T2, bool AllowRvalues,
5358 bool AllowExplicit) {
5359 assert(T2->isRecordType() && "Can only find conversions of record types.");
5360 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5361 OverloadCandidateSet CandidateSet(
5362 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5363 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5364 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5365 NamedDecl *D = *I;
5366 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5367 if (isa<UsingShadowDecl>(Val: D))
5368 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5369
5370 FunctionTemplateDecl *ConvTemplate
5371 = dyn_cast<FunctionTemplateDecl>(Val: D);
5372 CXXConversionDecl *Conv;
5373 if (ConvTemplate)
5374 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5375 else
5376 Conv = cast<CXXConversionDecl>(Val: D);
5377
5378 if (AllowRvalues) {
5379 // If we are initializing an rvalue reference, don't permit conversion
5380 // functions that return lvalues.
5381 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5382 const ReferenceType *RefType
5383 = Conv->getConversionType()->getAs<LValueReferenceType>();
5384 if (RefType && !RefType->getPointeeType()->isFunctionType())
5385 continue;
5386 }
5387
5388 if (!ConvTemplate &&
5389 S.CompareReferenceRelationship(
5390 Loc: DeclLoc,
5391 OrigT1: Conv->getConversionType()
5392 .getNonReferenceType()
5393 .getUnqualifiedType(),
5394 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5395 Sema::Ref_Incompatible)
5396 continue;
5397 } else {
5398 // If the conversion function doesn't return a reference type,
5399 // it can't be considered for this conversion. An rvalue reference
5400 // is only acceptable if its referencee is a function type.
5401
5402 const ReferenceType *RefType =
5403 Conv->getConversionType()->getAs<ReferenceType>();
5404 if (!RefType ||
5405 (!RefType->isLValueReferenceType() &&
5406 !RefType->getPointeeType()->isFunctionType()))
5407 continue;
5408 }
5409
5410 if (ConvTemplate)
5411 S.AddTemplateConversionCandidate(
5412 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5413 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5414 else
5415 S.AddConversionCandidate(
5416 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5417 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5418 }
5419
5420 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5421
5422 OverloadCandidateSet::iterator Best;
5423 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5424 case OR_Success:
5425
5426 assert(Best->HasFinalConversion);
5427
5428 // C++ [over.ics.ref]p1:
5429 //
5430 // [...] If the parameter binds directly to the result of
5431 // applying a conversion function to the argument
5432 // expression, the implicit conversion sequence is a
5433 // user-defined conversion sequence (13.3.3.1.2), with the
5434 // second standard conversion sequence either an identity
5435 // conversion or, if the conversion function returns an
5436 // entity of a type that is a derived class of the parameter
5437 // type, a derived-to-base Conversion.
5438 if (!Best->FinalConversion.DirectBinding)
5439 return false;
5440
5441 ICS.setUserDefined();
5442 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5443 ICS.UserDefined.After = Best->FinalConversion;
5444 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5445 ICS.UserDefined.ConversionFunction = Best->Function;
5446 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5447 ICS.UserDefined.EllipsisConversion = false;
5448 assert(ICS.UserDefined.After.ReferenceBinding &&
5449 ICS.UserDefined.After.DirectBinding &&
5450 "Expected a direct reference binding!");
5451 return true;
5452
5453 case OR_Ambiguous:
5454 ICS.setAmbiguous();
5455 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5456 Cand != CandidateSet.end(); ++Cand)
5457 if (Cand->Best)
5458 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5459 return true;
5460
5461 case OR_No_Viable_Function:
5462 case OR_Deleted:
5463 // There was no suitable conversion, or we found a deleted
5464 // conversion; continue with other checks.
5465 return false;
5466 }
5467
5468 llvm_unreachable("Invalid OverloadResult!");
5469}
5470
5471/// Compute an implicit conversion sequence for reference
5472/// initialization.
5473static ImplicitConversionSequence
5474TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5475 SourceLocation DeclLoc,
5476 bool SuppressUserConversions,
5477 bool AllowExplicit) {
5478 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5479
5480 // Most paths end in a failed conversion.
5481 ImplicitConversionSequence ICS;
5482 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5483
5484 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5485 QualType T2 = Init->getType();
5486
5487 // If the initializer is the address of an overloaded function, try
5488 // to resolve the overloaded function. If all goes well, T2 is the
5489 // type of the resulting function.
5490 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5491 DeclAccessPair Found;
5492 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5493 Complain: false, Found))
5494 T2 = Fn->getType();
5495 }
5496
5497 // Compute some basic properties of the types and the initializer.
5498 bool isRValRef = DeclType->isRValueReferenceType();
5499 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5500
5501 Sema::ReferenceConversions RefConv;
5502 Sema::ReferenceCompareResult RefRelationship =
5503 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5504
5505 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5506 ICS.setStandard();
5507 ICS.Standard.First = ICK_Identity;
5508 // FIXME: A reference binding can be a function conversion too. We should
5509 // consider that when ordering reference-to-function bindings.
5510 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5511 ? ICK_Derived_To_Base
5512 : (RefConv & Sema::ReferenceConversions::ObjC)
5513 ? ICK_Compatible_Conversion
5514 : ICK_Identity;
5515 ICS.Standard.Dimension = ICK_Identity;
5516 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5517 // a reference binding that performs a non-top-level qualification
5518 // conversion as a qualification conversion, not as an identity conversion.
5519 ICS.Standard.Third = (RefConv &
5520 Sema::ReferenceConversions::NestedQualification)
5521 ? ICK_Qualification
5522 : ICK_Identity;
5523 ICS.Standard.setFromType(T2);
5524 ICS.Standard.setToType(Idx: 0, T: T2);
5525 ICS.Standard.setToType(Idx: 1, T: T1);
5526 ICS.Standard.setToType(Idx: 2, T: T1);
5527 ICS.Standard.ReferenceBinding = true;
5528 ICS.Standard.DirectBinding = BindsDirectly;
5529 ICS.Standard.IsLvalueReference = !isRValRef;
5530 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5531 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5532 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5533 ICS.Standard.ObjCLifetimeConversionBinding =
5534 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5535 ICS.Standard.FromBracedInitList = false;
5536 ICS.Standard.CopyConstructor = nullptr;
5537 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5538 };
5539
5540 // C++0x [dcl.init.ref]p5:
5541 // A reference to type "cv1 T1" is initialized by an expression
5542 // of type "cv2 T2" as follows:
5543
5544 // -- If reference is an lvalue reference and the initializer expression
5545 if (!isRValRef) {
5546 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5547 // reference-compatible with "cv2 T2," or
5548 //
5549 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5550 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5551 // C++ [over.ics.ref]p1:
5552 // When a parameter of reference type binds directly (8.5.3)
5553 // to an argument expression, the implicit conversion sequence
5554 // is the identity conversion, unless the argument expression
5555 // has a type that is a derived class of the parameter type,
5556 // in which case the implicit conversion sequence is a
5557 // derived-to-base Conversion (13.3.3.1).
5558 SetAsReferenceBinding(/*BindsDirectly=*/true);
5559
5560 // Nothing more to do: the inaccessibility/ambiguity check for
5561 // derived-to-base conversions is suppressed when we're
5562 // computing the implicit conversion sequence (C++
5563 // [over.best.ics]p2).
5564 return ICS;
5565 }
5566
5567 // -- has a class type (i.e., T2 is a class type), where T1 is
5568 // not reference-related to T2, and can be implicitly
5569 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5570 // is reference-compatible with "cv3 T3" 92) (this
5571 // conversion is selected by enumerating the applicable
5572 // conversion functions (13.3.1.6) and choosing the best
5573 // one through overload resolution (13.3)),
5574 if (!SuppressUserConversions && T2->isRecordType() &&
5575 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5576 RefRelationship == Sema::Ref_Incompatible) {
5577 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5578 Init, T2, /*AllowRvalues=*/false,
5579 AllowExplicit))
5580 return ICS;
5581 }
5582 }
5583
5584 // -- Otherwise, the reference shall be an lvalue reference to a
5585 // non-volatile const type (i.e., cv1 shall be const), or the reference
5586 // shall be an rvalue reference.
5587 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5588 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5589 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5590 return ICS;
5591 }
5592
5593 // -- If the initializer expression
5594 //
5595 // -- is an xvalue, class prvalue, array prvalue or function
5596 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5597 if (RefRelationship == Sema::Ref_Compatible &&
5598 (InitCategory.isXValue() ||
5599 (InitCategory.isPRValue() &&
5600 (T2->isRecordType() || T2->isArrayType())) ||
5601 (InitCategory.isLValue() && T2->isFunctionType()))) {
5602 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5603 // binding unless we're binding to a class prvalue.
5604 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5605 // allow the use of rvalue references in C++98/03 for the benefit of
5606 // standard library implementors; therefore, we need the xvalue check here.
5607 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5608 !(InitCategory.isPRValue() || T2->isRecordType()));
5609 return ICS;
5610 }
5611
5612 // -- has a class type (i.e., T2 is a class type), where T1 is not
5613 // reference-related to T2, and can be implicitly converted to
5614 // an xvalue, class prvalue, or function lvalue of type
5615 // "cv3 T3", where "cv1 T1" is reference-compatible with
5616 // "cv3 T3",
5617 //
5618 // then the reference is bound to the value of the initializer
5619 // expression in the first case and to the result of the conversion
5620 // in the second case (or, in either case, to an appropriate base
5621 // class subobject).
5622 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5623 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5624 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5625 Init, T2, /*AllowRvalues=*/true,
5626 AllowExplicit)) {
5627 // In the second case, if the reference is an rvalue reference
5628 // and the second standard conversion sequence of the
5629 // user-defined conversion sequence includes an lvalue-to-rvalue
5630 // conversion, the program is ill-formed.
5631 if (ICS.isUserDefined() && isRValRef &&
5632 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5633 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5634
5635 return ICS;
5636 }
5637
5638 // A temporary of function type cannot be created; don't even try.
5639 if (T1->isFunctionType())
5640 return ICS;
5641
5642 // -- Otherwise, a temporary of type "cv1 T1" is created and
5643 // initialized from the initializer expression using the
5644 // rules for a non-reference copy initialization (8.5). The
5645 // reference is then bound to the temporary. If T1 is
5646 // reference-related to T2, cv1 must be the same
5647 // cv-qualification as, or greater cv-qualification than,
5648 // cv2; otherwise, the program is ill-formed.
5649 if (RefRelationship == Sema::Ref_Related) {
5650 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5651 // we would be reference-compatible or reference-compatible with
5652 // added qualification. But that wasn't the case, so the reference
5653 // initialization fails.
5654 //
5655 // Note that we only want to check address spaces and cvr-qualifiers here.
5656 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5657 Qualifiers T1Quals = T1.getQualifiers();
5658 Qualifiers T2Quals = T2.getQualifiers();
5659 T1Quals.removeObjCGCAttr();
5660 T1Quals.removeObjCLifetime();
5661 T2Quals.removeObjCGCAttr();
5662 T2Quals.removeObjCLifetime();
5663 // MS compiler ignores __unaligned qualifier for references; do the same.
5664 T1Quals.removeUnaligned();
5665 T2Quals.removeUnaligned();
5666 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5667 return ICS;
5668 }
5669
5670 // If at least one of the types is a class type, the types are not
5671 // related, and we aren't allowed any user conversions, the
5672 // reference binding fails. This case is important for breaking
5673 // recursion, since TryImplicitConversion below will attempt to
5674 // create a temporary through the use of a copy constructor.
5675 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5676 (T1->isRecordType() || T2->isRecordType()))
5677 return ICS;
5678
5679 // If T1 is reference-related to T2 and the reference is an rvalue
5680 // reference, the initializer expression shall not be an lvalue.
5681 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5682 Init->Classify(Ctx&: S.Context).isLValue()) {
5683 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5684 return ICS;
5685 }
5686
5687 // C++ [over.ics.ref]p2:
5688 // When a parameter of reference type is not bound directly to
5689 // an argument expression, the conversion sequence is the one
5690 // required to convert the argument expression to the
5691 // underlying type of the reference according to
5692 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5693 // to copy-initializing a temporary of the underlying type with
5694 // the argument expression. Any difference in top-level
5695 // cv-qualification is subsumed by the initialization itself
5696 // and does not constitute a conversion.
5697 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5698 AllowExplicit: AllowedExplicit::None,
5699 /*InOverloadResolution=*/false,
5700 /*CStyle=*/false,
5701 /*AllowObjCWritebackConversion=*/false,
5702 /*AllowObjCConversionOnExplicit=*/false);
5703
5704 // Of course, that's still a reference binding.
5705 if (ICS.isStandard()) {
5706 ICS.Standard.ReferenceBinding = true;
5707 ICS.Standard.IsLvalueReference = !isRValRef;
5708 ICS.Standard.BindsToFunctionLvalue = false;
5709 ICS.Standard.BindsToRvalue = true;
5710 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5711 ICS.Standard.ObjCLifetimeConversionBinding = false;
5712 } else if (ICS.isUserDefined()) {
5713 const ReferenceType *LValRefType =
5714 ICS.UserDefined.ConversionFunction->getReturnType()
5715 ->getAs<LValueReferenceType>();
5716
5717 // C++ [over.ics.ref]p3:
5718 // Except for an implicit object parameter, for which see 13.3.1, a
5719 // standard conversion sequence cannot be formed if it requires [...]
5720 // binding an rvalue reference to an lvalue other than a function
5721 // lvalue.
5722 // Note that the function case is not possible here.
5723 if (isRValRef && LValRefType) {
5724 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5725 return ICS;
5726 }
5727
5728 ICS.UserDefined.After.ReferenceBinding = true;
5729 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5730 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5731 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5732 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5733 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5734 ICS.UserDefined.After.FromBracedInitList = false;
5735 }
5736
5737 return ICS;
5738}
5739
5740static ImplicitConversionSequence
5741TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5742 bool SuppressUserConversions,
5743 bool InOverloadResolution,
5744 bool AllowObjCWritebackConversion,
5745 bool AllowExplicit = false);
5746
5747/// TryListConversion - Try to copy-initialize a value of type ToType from the
5748/// initializer list From.
5749static ImplicitConversionSequence
5750TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5751 bool SuppressUserConversions,
5752 bool InOverloadResolution,
5753 bool AllowObjCWritebackConversion) {
5754 // C++11 [over.ics.list]p1:
5755 // When an argument is an initializer list, it is not an expression and
5756 // special rules apply for converting it to a parameter type.
5757
5758 ImplicitConversionSequence Result;
5759 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5760
5761 // We need a complete type for what follows. With one C++20 exception,
5762 // incomplete types can never be initialized from init lists.
5763 QualType InitTy = ToType;
5764 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5765 if (AT && S.getLangOpts().CPlusPlus20)
5766 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5767 // C++20 allows list initialization of an incomplete array type.
5768 InitTy = IAT->getElementType();
5769 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5770 return Result;
5771
5772 // C++20 [over.ics.list]/2:
5773 // If the initializer list is a designated-initializer-list, a conversion
5774 // is only possible if the parameter has an aggregate type
5775 //
5776 // FIXME: The exception for reference initialization here is not part of the
5777 // language rules, but follow other compilers in adding it as a tentative DR
5778 // resolution.
5779 bool IsDesignatedInit = From->hasDesignatedInit();
5780 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5781 IsDesignatedInit)
5782 return Result;
5783
5784 // Per DR1467 and DR2137:
5785 // If the parameter type is an aggregate class X and the initializer list
5786 // has a single element of type cv U, where U is X or a class derived from
5787 // X, the implicit conversion sequence is the one required to convert the
5788 // element to the parameter type.
5789 //
5790 // Otherwise, if the parameter type is a character array [... ]
5791 // and the initializer list has a single element that is an
5792 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5793 // implicit conversion sequence is the identity conversion.
5794 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5795 if (ToType->isRecordType() && ToType->isAggregateType()) {
5796 QualType InitType = From->getInit(Init: 0)->getType();
5797 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5798 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5799 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5800 SuppressUserConversions,
5801 InOverloadResolution,
5802 AllowObjCWritebackConversion);
5803 }
5804
5805 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5806 InitializedEntity Entity =
5807 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5808 /*Consumed=*/false);
5809 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5810 Result.setStandard();
5811 Result.Standard.setAsIdentityConversion();
5812 Result.Standard.setFromType(ToType);
5813 Result.Standard.setAllToTypes(ToType);
5814 return Result;
5815 }
5816 }
5817 }
5818
5819 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5820 // C++11 [over.ics.list]p2:
5821 // If the parameter type is std::initializer_list<X> or "array of X" and
5822 // all the elements can be implicitly converted to X, the implicit
5823 // conversion sequence is the worst conversion necessary to convert an
5824 // element of the list to X.
5825 //
5826 // C++14 [over.ics.list]p3:
5827 // Otherwise, if the parameter type is "array of N X", if the initializer
5828 // list has exactly N elements or if it has fewer than N elements and X is
5829 // default-constructible, and if all the elements of the initializer list
5830 // can be implicitly converted to X, the implicit conversion sequence is
5831 // the worst conversion necessary to convert an element of the list to X.
5832 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5833 unsigned e = From->getNumInits();
5834 ImplicitConversionSequence DfltElt;
5835 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5836 ToType: QualType());
5837 QualType ContTy = ToType;
5838 bool IsUnbounded = false;
5839 if (AT) {
5840 InitTy = AT->getElementType();
5841 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5842 if (CT->getSize().ult(RHS: e)) {
5843 // Too many inits, fatally bad
5844 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5845 ToType);
5846 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5847 return Result;
5848 }
5849 if (CT->getSize().ugt(RHS: e)) {
5850 // Need an init from empty {}, is there one?
5851 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5852 From->getEndLoc(), /*isExplicit=*/false);
5853 EmptyList.setType(S.Context.VoidTy);
5854 DfltElt = TryListConversion(
5855 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5856 InOverloadResolution, AllowObjCWritebackConversion);
5857 if (DfltElt.isBad()) {
5858 // No {} init, fatally bad
5859 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5860 ToType);
5861 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5862 return Result;
5863 }
5864 }
5865 } else {
5866 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5867 IsUnbounded = true;
5868 if (!e) {
5869 // Cannot convert to zero-sized.
5870 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5871 ToType);
5872 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5873 return Result;
5874 }
5875 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5876 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5877 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5878 }
5879 }
5880
5881 Result.setStandard();
5882 Result.Standard.setAsIdentityConversion();
5883 Result.Standard.setFromType(InitTy);
5884 Result.Standard.setAllToTypes(InitTy);
5885 for (unsigned i = 0; i < e; ++i) {
5886 Expr *Init = From->getInit(Init: i);
5887 ImplicitConversionSequence ICS = TryCopyInitialization(
5888 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5889 AllowObjCWritebackConversion);
5890
5891 // Keep the worse conversion seen so far.
5892 // FIXME: Sequences are not totally ordered, so 'worse' can be
5893 // ambiguous. CWG has been informed.
5894 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5895 ICS2: Result) ==
5896 ImplicitConversionSequence::Worse) {
5897 Result = ICS;
5898 // Bail as soon as we find something unconvertible.
5899 if (Result.isBad()) {
5900 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5901 return Result;
5902 }
5903 }
5904 }
5905
5906 // If we needed any implicit {} initialization, compare that now.
5907 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5908 // has been informed that this might not be the best thing.
5909 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5910 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5911 ImplicitConversionSequence::Worse)
5912 Result = DfltElt;
5913 // Record the type being initialized so that we may compare sequences
5914 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5915 return Result;
5916 }
5917
5918 // C++14 [over.ics.list]p4:
5919 // C++11 [over.ics.list]p3:
5920 // Otherwise, if the parameter is a non-aggregate class X and overload
5921 // resolution chooses a single best constructor [...] the implicit
5922 // conversion sequence is a user-defined conversion sequence. If multiple
5923 // constructors are viable but none is better than the others, the
5924 // implicit conversion sequence is a user-defined conversion sequence.
5925 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5926 // This function can deal with initializer lists.
5927 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5928 AllowExplicit: AllowedExplicit::None,
5929 InOverloadResolution, /*CStyle=*/false,
5930 AllowObjCWritebackConversion,
5931 /*AllowObjCConversionOnExplicit=*/false);
5932 }
5933
5934 // C++14 [over.ics.list]p5:
5935 // C++11 [over.ics.list]p4:
5936 // Otherwise, if the parameter has an aggregate type which can be
5937 // initialized from the initializer list [...] the implicit conversion
5938 // sequence is a user-defined conversion sequence.
5939 if (ToType->isAggregateType()) {
5940 // Type is an aggregate, argument is an init list. At this point it comes
5941 // down to checking whether the initialization works.
5942 // FIXME: Find out whether this parameter is consumed or not.
5943 InitializedEntity Entity =
5944 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5945 /*Consumed=*/false);
5946 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5947 From)) {
5948 Result.setUserDefined();
5949 Result.UserDefined.Before.setAsIdentityConversion();
5950 // Initializer lists don't have a type.
5951 Result.UserDefined.Before.setFromType(QualType());
5952 Result.UserDefined.Before.setAllToTypes(QualType());
5953
5954 Result.UserDefined.After.setAsIdentityConversion();
5955 Result.UserDefined.After.setFromType(ToType);
5956 Result.UserDefined.After.setAllToTypes(ToType);
5957 Result.UserDefined.ConversionFunction = nullptr;
5958 }
5959 return Result;
5960 }
5961
5962 // C++14 [over.ics.list]p6:
5963 // C++11 [over.ics.list]p5:
5964 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5965 if (ToType->isReferenceType()) {
5966 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5967 // mention initializer lists in any way. So we go by what list-
5968 // initialization would do and try to extrapolate from that.
5969
5970 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5971
5972 // If the initializer list has a single element that is reference-related
5973 // to the parameter type, we initialize the reference from that.
5974 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5975 Expr *Init = From->getInit(Init: 0);
5976
5977 QualType T2 = Init->getType();
5978
5979 // If the initializer is the address of an overloaded function, try
5980 // to resolve the overloaded function. If all goes well, T2 is the
5981 // type of the resulting function.
5982 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5983 DeclAccessPair Found;
5984 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5985 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5986 T2 = Fn->getType();
5987 }
5988
5989 // Compute some basic properties of the types and the initializer.
5990 Sema::ReferenceCompareResult RefRelationship =
5991 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5992
5993 if (RefRelationship >= Sema::Ref_Related) {
5994 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5995 SuppressUserConversions,
5996 /*AllowExplicit=*/false);
5997 }
5998 }
5999
6000 // Otherwise, we bind the reference to a temporary created from the
6001 // initializer list.
6002 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
6003 InOverloadResolution,
6004 AllowObjCWritebackConversion);
6005 if (Result.isFailure())
6006 return Result;
6007 assert(!Result.isEllipsis() &&
6008 "Sub-initialization cannot result in ellipsis conversion.");
6009
6010 // Can we even bind to a temporary?
6011 if (ToType->isRValueReferenceType() ||
6012 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6013 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6014 Result.UserDefined.After;
6015 SCS.ReferenceBinding = true;
6016 SCS.IsLvalueReference = ToType->isLValueReferenceType();
6017 SCS.BindsToRvalue = true;
6018 SCS.BindsToFunctionLvalue = false;
6019 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
6020 SCS.ObjCLifetimeConversionBinding = false;
6021 SCS.FromBracedInitList = false;
6022
6023 } else
6024 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6025 FromExpr: From, ToType);
6026 return Result;
6027 }
6028
6029 // C++14 [over.ics.list]p7:
6030 // C++11 [over.ics.list]p6:
6031 // Otherwise, if the parameter type is not a class:
6032 if (!ToType->isRecordType()) {
6033 // - if the initializer list has one element that is not itself an
6034 // initializer list, the implicit conversion sequence is the one
6035 // required to convert the element to the parameter type.
6036 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6037 // single integer.
6038 unsigned NumInits = From->getNumInits();
6039 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6040 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6041 Result = TryCopyInitialization(
6042 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6043 InOverloadResolution, AllowObjCWritebackConversion);
6044 if (Result.isStandard())
6045 Result.Standard.FromBracedInitList = true;
6046 }
6047 // - if the initializer list has no elements, the implicit conversion
6048 // sequence is the identity conversion.
6049 else if (NumInits == 0) {
6050 Result.setStandard();
6051 Result.Standard.setAsIdentityConversion();
6052 Result.Standard.setFromType(ToType);
6053 Result.Standard.setAllToTypes(ToType);
6054 }
6055 return Result;
6056 }
6057
6058 // C++14 [over.ics.list]p8:
6059 // C++11 [over.ics.list]p7:
6060 // In all cases other than those enumerated above, no conversion is possible
6061 return Result;
6062}
6063
6064/// TryCopyInitialization - Try to copy-initialize a value of type
6065/// ToType from the expression From. Return the implicit conversion
6066/// sequence required to pass this argument, which may be a bad
6067/// conversion sequence (meaning that the argument cannot be passed to
6068/// a parameter of this type). If @p SuppressUserConversions, then we
6069/// do not permit any user-defined conversion sequences.
6070static ImplicitConversionSequence
6071TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6072 bool SuppressUserConversions,
6073 bool InOverloadResolution,
6074 bool AllowObjCWritebackConversion,
6075 bool AllowExplicit) {
6076 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6077 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6078 InOverloadResolution,AllowObjCWritebackConversion);
6079
6080 if (ToType->isReferenceType())
6081 return TryReferenceInit(S, Init: From, DeclType: ToType,
6082 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6083 SuppressUserConversions, AllowExplicit);
6084
6085 return TryImplicitConversion(S, From, ToType,
6086 SuppressUserConversions,
6087 AllowExplicit: AllowedExplicit::None,
6088 InOverloadResolution,
6089 /*CStyle=*/false,
6090 AllowObjCWritebackConversion,
6091 /*AllowObjCConversionOnExplicit=*/false);
6092}
6093
6094static bool TryCopyInitialization(const CanQualType FromQTy,
6095 const CanQualType ToQTy,
6096 Sema &S,
6097 SourceLocation Loc,
6098 ExprValueKind FromVK) {
6099 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6100 ImplicitConversionSequence ICS =
6101 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6102
6103 return !ICS.isBad();
6104}
6105
6106/// TryObjectArgumentInitialization - Try to initialize the object
6107/// parameter of the given member function (@c Method) from the
6108/// expression @p From.
6109static ImplicitConversionSequence TryObjectArgumentInitialization(
6110 Sema &S, SourceLocation Loc, QualType FromType,
6111 Expr::Classification FromClassification, CXXMethodDecl *Method,
6112 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6113 QualType ExplicitParameterType = QualType(),
6114 bool SuppressUserConversion = false) {
6115
6116 // We need to have an object of class type.
6117 if (const auto *PT = FromType->getAs<PointerType>()) {
6118 FromType = PT->getPointeeType();
6119
6120 // When we had a pointer, it's implicitly dereferenced, so we
6121 // better have an lvalue.
6122 assert(FromClassification.isLValue());
6123 }
6124
6125 auto ValueKindFromClassification = [](Expr::Classification C) {
6126 if (C.isPRValue())
6127 return clang::VK_PRValue;
6128 if (C.isXValue())
6129 return VK_XValue;
6130 return clang::VK_LValue;
6131 };
6132
6133 if (Method->isExplicitObjectMemberFunction()) {
6134 if (ExplicitParameterType.isNull())
6135 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6136 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6137 ValueKindFromClassification(FromClassification));
6138 ImplicitConversionSequence ICS = TryCopyInitialization(
6139 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6140 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6141 if (ICS.isBad())
6142 ICS.Bad.FromExpr = nullptr;
6143 return ICS;
6144 }
6145
6146 assert(FromType->isRecordType());
6147
6148 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6149 // C++98 [class.dtor]p2:
6150 // A destructor can be invoked for a const, volatile or const volatile
6151 // object.
6152 // C++98 [over.match.funcs]p4:
6153 // For static member functions, the implicit object parameter is considered
6154 // to match any object (since if the function is selected, the object is
6155 // discarded).
6156 Qualifiers Quals = Method->getMethodQualifiers();
6157 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6158 Quals.addConst();
6159 Quals.addVolatile();
6160 }
6161
6162 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6163
6164 // Set up the conversion sequence as a "bad" conversion, to allow us
6165 // to exit early.
6166 ImplicitConversionSequence ICS;
6167
6168 // C++0x [over.match.funcs]p4:
6169 // For non-static member functions, the type of the implicit object
6170 // parameter is
6171 //
6172 // - "lvalue reference to cv X" for functions declared without a
6173 // ref-qualifier or with the & ref-qualifier
6174 // - "rvalue reference to cv X" for functions declared with the &&
6175 // ref-qualifier
6176 //
6177 // where X is the class of which the function is a member and cv is the
6178 // cv-qualification on the member function declaration.
6179 //
6180 // However, when finding an implicit conversion sequence for the argument, we
6181 // are not allowed to perform user-defined conversions
6182 // (C++ [over.match.funcs]p5). We perform a simplified version of
6183 // reference binding here, that allows class rvalues to bind to
6184 // non-constant references.
6185
6186 // First check the qualifiers.
6187 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6188 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6189 if (ImplicitParamType.getCVRQualifiers() !=
6190 FromTypeCanon.getLocalCVRQualifiers() &&
6191 !ImplicitParamType.isAtLeastAsQualifiedAs(
6192 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6193 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6194 FromType, ToType: ImplicitParamType);
6195 return ICS;
6196 }
6197
6198 if (FromTypeCanon.hasAddressSpace()) {
6199 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6200 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6201 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6202 Ctx: S.getASTContext())) {
6203 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6204 FromType, ToType: ImplicitParamType);
6205 return ICS;
6206 }
6207 }
6208
6209 // Check that we have either the same type or a derived type. It
6210 // affects the conversion rank.
6211 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6212 ImplicitConversionKind SecondKind;
6213 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6214 SecondKind = ICK_Identity;
6215 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6216 SecondKind = ICK_Derived_To_Base;
6217 } else if (!Method->isExplicitObjectMemberFunction()) {
6218 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6219 FromType, ToType: ImplicitParamType);
6220 return ICS;
6221 }
6222
6223 // Check the ref-qualifier.
6224 switch (Method->getRefQualifier()) {
6225 case RQ_None:
6226 // Do nothing; we don't care about lvalueness or rvalueness.
6227 break;
6228
6229 case RQ_LValue:
6230 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6231 // non-const lvalue reference cannot bind to an rvalue
6232 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6233 ToType: ImplicitParamType);
6234 return ICS;
6235 }
6236 break;
6237
6238 case RQ_RValue:
6239 if (!FromClassification.isRValue()) {
6240 // rvalue reference cannot bind to an lvalue
6241 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6242 ToType: ImplicitParamType);
6243 return ICS;
6244 }
6245 break;
6246 }
6247
6248 // Success. Mark this as a reference binding.
6249 ICS.setStandard();
6250 ICS.Standard.setAsIdentityConversion();
6251 ICS.Standard.Second = SecondKind;
6252 ICS.Standard.setFromType(FromType);
6253 ICS.Standard.setAllToTypes(ImplicitParamType);
6254 ICS.Standard.ReferenceBinding = true;
6255 ICS.Standard.DirectBinding = true;
6256 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6257 ICS.Standard.BindsToFunctionLvalue = false;
6258 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6259 ICS.Standard.FromBracedInitList = false;
6260 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6261 = (Method->getRefQualifier() == RQ_None);
6262 return ICS;
6263}
6264
6265/// PerformObjectArgumentInitialization - Perform initialization of
6266/// the implicit object parameter for the given Method with the given
6267/// expression.
6268ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6269 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6270 CXXMethodDecl *Method) {
6271 QualType FromRecordType, DestType;
6272 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6273
6274 if (getLangOpts().HLSL &&
6275 From->getType().getAddressSpace() == LangAS::hlsl_constant) {
6276 QualType CastType = From->getType().getLocalUnqualifiedType().withConst();
6277 From = ImplicitCastExpr::Create(Context, T: CastType, Kind: CK_LValueToRValue, Operand: From,
6278 /*BasePath=*/nullptr, Cat: VK_PRValue,
6279 FPO: FPOptionsOverride());
6280 }
6281
6282 Expr::Classification FromClassification;
6283 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6284 FromRecordType = PT->getPointeeType();
6285 DestType = Method->getThisType();
6286 FromClassification = Expr::Classification::makeSimpleLValue();
6287 } else {
6288 FromRecordType = From->getType();
6289 DestType = ImplicitParamRecordType;
6290 FromClassification = From->Classify(Ctx&: Context);
6291
6292 // CWG2813 [expr.call]p6:
6293 // If the function is an implicit object member function, the object
6294 // expression of the class member access shall be a glvalue [...]
6295 if (From->isPRValue()) {
6296 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6297 BoundToLvalueReference: Method->getRefQualifier() !=
6298 RefQualifierKind::RQ_RValue);
6299 }
6300 }
6301
6302 // Note that we always use the true parent context when performing
6303 // the actual argument initialization.
6304 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6305 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6306 ActingContext: Method->getParent());
6307 if (ICS.isBad()) {
6308 switch (ICS.Bad.Kind) {
6309 case BadConversionSequence::bad_qualifiers: {
6310 Qualifiers FromQs = FromRecordType.getQualifiers();
6311 Qualifiers ToQs = DestType.getQualifiers();
6312 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6313 if (CVR) {
6314 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6315 << Method->getDeclName() << FromRecordType << (CVR - 1)
6316 << From->getSourceRange();
6317 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6318 << Method->getDeclName();
6319 return ExprError();
6320 }
6321 break;
6322 }
6323
6324 case BadConversionSequence::lvalue_ref_to_rvalue:
6325 case BadConversionSequence::rvalue_ref_to_lvalue: {
6326 bool IsRValueQualified =
6327 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6328 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6329 << Method->getDeclName() << FromClassification.isRValue()
6330 << IsRValueQualified;
6331 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6332 << Method->getDeclName();
6333 return ExprError();
6334 }
6335
6336 case BadConversionSequence::no_conversion:
6337 case BadConversionSequence::unrelated_class:
6338 break;
6339
6340 case BadConversionSequence::too_few_initializers:
6341 case BadConversionSequence::too_many_initializers:
6342 llvm_unreachable("Lists are not objects");
6343 }
6344
6345 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6346 << ImplicitParamRecordType << FromRecordType
6347 << From->getSourceRange();
6348 }
6349
6350 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6351 ExprResult FromRes =
6352 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6353 if (FromRes.isInvalid())
6354 return ExprError();
6355 From = FromRes.get();
6356 }
6357
6358 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6359 CastKind CK;
6360 QualType PteeTy = DestType->getPointeeType();
6361 LangAS DestAS =
6362 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6363 if (FromRecordType.getAddressSpace() != DestAS)
6364 CK = CK_AddressSpaceConversion;
6365 else
6366 CK = CK_NoOp;
6367 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6368 }
6369 return From;
6370}
6371
6372/// TryContextuallyConvertToBool - Attempt to contextually convert the
6373/// expression From to bool (C++0x [conv]p3).
6374static ImplicitConversionSequence
6375TryContextuallyConvertToBool(Sema &S, Expr *From) {
6376 // C++ [dcl.init]/17.8:
6377 // - Otherwise, if the initialization is direct-initialization, the source
6378 // type is std::nullptr_t, and the destination type is bool, the initial
6379 // value of the object being initialized is false.
6380 if (From->getType()->isNullPtrType())
6381 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6382 DestType: S.Context.BoolTy,
6383 NeedLValToRVal: From->isGLValue());
6384
6385 // All other direct-initialization of bool is equivalent to an implicit
6386 // conversion to bool in which explicit conversions are permitted.
6387 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6388 /*SuppressUserConversions=*/false,
6389 AllowExplicit: AllowedExplicit::Conversions,
6390 /*InOverloadResolution=*/false,
6391 /*CStyle=*/false,
6392 /*AllowObjCWritebackConversion=*/false,
6393 /*AllowObjCConversionOnExplicit=*/false);
6394}
6395
6396ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6397 if (checkPlaceholderForOverload(S&: *this, E&: From))
6398 return ExprError();
6399 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6400 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6401
6402 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6403 if (!ICS.isBad())
6404 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6405 Action: AssignmentAction::Converting);
6406 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6407 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6408 << From->getType() << From->getSourceRange();
6409 return ExprError();
6410}
6411
6412/// Check that the specified conversion is permitted in a converted constant
6413/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6414/// is acceptable.
6415static bool CheckConvertedConstantConversions(Sema &S,
6416 StandardConversionSequence &SCS) {
6417 // Since we know that the target type is an integral or unscoped enumeration
6418 // type, most conversion kinds are impossible. All possible First and Third
6419 // conversions are fine.
6420 switch (SCS.Second) {
6421 case ICK_Identity:
6422 case ICK_Integral_Promotion:
6423 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6424 case ICK_Zero_Queue_Conversion:
6425 return true;
6426
6427 case ICK_Boolean_Conversion:
6428 // Conversion from an integral or unscoped enumeration type to bool is
6429 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6430 // conversion, so we allow it in a converted constant expression.
6431 //
6432 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6433 // a lot of popular code. We should at least add a warning for this
6434 // (non-conforming) extension.
6435 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6436 SCS.getToType(Idx: 2)->isBooleanType();
6437
6438 case ICK_Pointer_Conversion:
6439 case ICK_Pointer_Member:
6440 // C++1z: null pointer conversions and null member pointer conversions are
6441 // only permitted if the source type is std::nullptr_t.
6442 return SCS.getFromType()->isNullPtrType();
6443
6444 case ICK_Floating_Promotion:
6445 case ICK_Complex_Promotion:
6446 case ICK_Floating_Conversion:
6447 case ICK_Complex_Conversion:
6448 case ICK_Floating_Integral:
6449 case ICK_Compatible_Conversion:
6450 case ICK_Derived_To_Base:
6451 case ICK_Vector_Conversion:
6452 case ICK_SVE_Vector_Conversion:
6453 case ICK_RVV_Vector_Conversion:
6454 case ICK_HLSL_Vector_Splat:
6455 case ICK_HLSL_Matrix_Splat:
6456 case ICK_Vector_Splat:
6457 case ICK_Complex_Real:
6458 case ICK_Block_Pointer_Conversion:
6459 case ICK_TransparentUnionConversion:
6460 case ICK_Writeback_Conversion:
6461 case ICK_Zero_Event_Conversion:
6462 case ICK_C_Only_Conversion:
6463 case ICK_Incompatible_Pointer_Conversion:
6464 case ICK_Fixed_Point_Conversion:
6465 case ICK_HLSL_Vector_Truncation:
6466 case ICK_HLSL_Matrix_Truncation:
6467 return false;
6468
6469 case ICK_Lvalue_To_Rvalue:
6470 case ICK_Array_To_Pointer:
6471 case ICK_Function_To_Pointer:
6472 case ICK_HLSL_Array_RValue:
6473 llvm_unreachable("found a first conversion kind in Second");
6474
6475 case ICK_Function_Conversion:
6476 case ICK_Qualification:
6477 llvm_unreachable("found a third conversion kind in Second");
6478
6479 case ICK_Num_Conversion_Kinds:
6480 break;
6481 }
6482
6483 llvm_unreachable("unknown conversion kind");
6484}
6485
6486/// BuildConvertedConstantExpression - Check that the expression From is a
6487/// converted constant expression of type T, perform the conversion but
6488/// does not evaluate the expression
6489static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6490 QualType T, CCEKind CCE,
6491 NamedDecl *Dest,
6492 APValue &PreNarrowingValue) {
6493 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6494 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6495 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6496 "converted constant expression outside C++11 or TTP matching");
6497
6498 if (checkPlaceholderForOverload(S, E&: From))
6499 return ExprError();
6500
6501 if (From->containsErrors()) {
6502 if (S.Context.hasSameType(T1: From->getType(), T2: T))
6503 return From;
6504
6505 // The expression already has errors, so the correct cast kind can't be
6506 // determined. Use RecoveryExpr to keep the expected type T and mark the
6507 // result as invalid, preventing further cascading errors.
6508 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6509 T);
6510 }
6511
6512 // C++1z [expr.const]p3:
6513 // A converted constant expression of type T is an expression,
6514 // implicitly converted to type T, where the converted
6515 // expression is a constant expression and the implicit conversion
6516 // sequence contains only [... list of conversions ...].
6517 ImplicitConversionSequence ICS =
6518 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6519 ? TryContextuallyConvertToBool(S, From)
6520 : TryCopyInitialization(S, From, ToType: T,
6521 /*SuppressUserConversions=*/false,
6522 /*InOverloadResolution=*/false,
6523 /*AllowObjCWritebackConversion=*/false,
6524 /*AllowExplicit=*/false);
6525 StandardConversionSequence *SCS = nullptr;
6526 switch (ICS.getKind()) {
6527 case ImplicitConversionSequence::StandardConversion:
6528 SCS = &ICS.Standard;
6529 break;
6530 case ImplicitConversionSequence::UserDefinedConversion:
6531 if (T->isRecordType())
6532 SCS = &ICS.UserDefined.Before;
6533 else
6534 SCS = &ICS.UserDefined.After;
6535 break;
6536 case ImplicitConversionSequence::AmbiguousConversion:
6537 case ImplicitConversionSequence::BadConversion:
6538 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6539 return S.Diag(Loc: From->getBeginLoc(),
6540 DiagID: diag::err_typecheck_converted_constant_expression)
6541 << From->getType() << From->getSourceRange() << T;
6542 return ExprError();
6543
6544 case ImplicitConversionSequence::EllipsisConversion:
6545 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6546 llvm_unreachable("bad conversion in converted constant expression");
6547 }
6548
6549 // Check that we would only use permitted conversions.
6550 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6551 return S.Diag(Loc: From->getBeginLoc(),
6552 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6553 << From->getType() << From->getSourceRange() << T;
6554 }
6555 // [...] and where the reference binding (if any) binds directly.
6556 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6557 return S.Diag(Loc: From->getBeginLoc(),
6558 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6559 << From->getType() << From->getSourceRange() << T;
6560 }
6561 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6562 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6563 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6564 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6565 // case explicitly.
6566 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6567 return S.Diag(Loc: From->getBeginLoc(),
6568 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6569 << From->getSourceRange();
6570 }
6571
6572 // Usually we can simply apply the ImplicitConversionSequence we formed
6573 // earlier, but that's not guaranteed to work when initializing an object of
6574 // class type.
6575 ExprResult Result;
6576 bool IsTemplateArgument =
6577 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6578 if (T->isRecordType()) {
6579 assert(IsTemplateArgument &&
6580 "unexpected class type converted constant expr");
6581 Result = S.PerformCopyInitialization(
6582 Entity: InitializedEntity::InitializeTemplateParameter(
6583 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6584 EqualLoc: SourceLocation(), Init: From);
6585 } else {
6586 Result =
6587 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6588 }
6589 if (Result.isInvalid())
6590 return Result;
6591
6592 // C++2a [intro.execution]p5:
6593 // A full-expression is [...] a constant-expression [...]
6594 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6595 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6596 IsTemplateArgument);
6597 if (Result.isInvalid())
6598 return Result;
6599
6600 // Check for a narrowing implicit conversion.
6601 bool ReturnPreNarrowingValue = false;
6602 QualType PreNarrowingType;
6603 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6604 ConstantType&: PreNarrowingType)) {
6605 case NK_Variable_Narrowing:
6606 // Implicit conversion to a narrower type, and the value is not a constant
6607 // expression. We'll diagnose this in a moment.
6608 case NK_Not_Narrowing:
6609 break;
6610
6611 case NK_Constant_Narrowing:
6612 if (CCE == CCEKind::ArrayBound &&
6613 PreNarrowingType->isIntegralOrEnumerationType() &&
6614 PreNarrowingValue.isInt()) {
6615 // Don't diagnose array bound narrowing here; we produce more precise
6616 // errors by allowing the un-narrowed value through.
6617 ReturnPreNarrowingValue = true;
6618 break;
6619 }
6620 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6621 << CCE << /*Constant*/ 1
6622 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6623 // If this is an SFINAE Context, treat the result as invalid so it stops
6624 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6625 // FIXME: Should do this whenever the above diagnostic is an error, but
6626 // without further changes this would degrade some other diagnostics.
6627 if (S.isSFINAEContext())
6628 return ExprError();
6629 break;
6630
6631 case NK_Dependent_Narrowing:
6632 // Implicit conversion to a narrower type, but the expression is
6633 // value-dependent so we can't tell whether it's actually narrowing.
6634 // For matching the parameters of a TTP, the conversion is ill-formed
6635 // if it may narrow.
6636 if (CCE != CCEKind::TempArgStrict)
6637 break;
6638 [[fallthrough]];
6639 case NK_Type_Narrowing:
6640 // FIXME: It would be better to diagnose that the expression is not a
6641 // constant expression.
6642 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6643 << CCE << /*Constant*/ 0 << From->getType() << T;
6644 if (S.isSFINAEContext())
6645 return ExprError();
6646 break;
6647 }
6648 if (!ReturnPreNarrowingValue)
6649 PreNarrowingValue = {};
6650
6651 return Result;
6652}
6653
6654/// CheckConvertedConstantExpression - Check that the expression From is a
6655/// converted constant expression of type T, perform the conversion and produce
6656/// the converted expression, per C++11 [expr.const]p3.
6657static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6658 QualType T, APValue &Value,
6659 CCEKind CCE, bool RequireInt,
6660 NamedDecl *Dest) {
6661
6662 APValue PreNarrowingValue;
6663 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6664 PreNarrowingValue);
6665 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6666 Value = APValue();
6667 return Result;
6668 }
6669 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6670 RequireInt, PreNarrowingValue);
6671}
6672
6673ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6674 CCEKind CCE,
6675 NamedDecl *Dest) {
6676 APValue PreNarrowingValue;
6677 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6678 PreNarrowingValue);
6679}
6680
6681ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6682 APValue &Value, CCEKind CCE,
6683 NamedDecl *Dest) {
6684 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6685 Dest);
6686}
6687
6688ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6689 llvm::APSInt &Value,
6690 CCEKind CCE) {
6691 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6692
6693 APValue V;
6694 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6695 /*Dest=*/nullptr);
6696 if (!R.isInvalid() && !R.get()->isValueDependent())
6697 Value = V.getInt();
6698 return R;
6699}
6700
6701ExprResult
6702Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6703 CCEKind CCE, bool RequireInt,
6704 const APValue &PreNarrowingValue) {
6705
6706 ExprResult Result = E;
6707 // Check the expression is a constant expression.
6708 SmallVector<PartialDiagnosticAt, 8> Notes;
6709 Expr::EvalResult Eval;
6710 Eval.Diag = &Notes;
6711
6712 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6713
6714 ConstantExprKind Kind;
6715 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6716 Kind = ConstantExprKind::ClassTemplateArgument;
6717 else if (CCE == CCEKind::TemplateArg)
6718 Kind = ConstantExprKind::NonClassTemplateArgument;
6719 else
6720 Kind = ConstantExprKind::Normal;
6721
6722 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6723 (RequireInt && !Eval.Val.isInt())) {
6724 // The expression can't be folded, so we can't keep it at this position in
6725 // the AST.
6726 Result = ExprError();
6727 } else {
6728 Value = Eval.Val;
6729
6730 if (Notes.empty()) {
6731 // It's a constant expression.
6732 Expr *E = Result.get();
6733 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6734 // We expect a ConstantExpr to have a value associated with it
6735 // by this point.
6736 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6737 "ConstantExpr has no value associated with it");
6738 (void)CE;
6739 } else {
6740 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6741 }
6742 if (!PreNarrowingValue.isAbsent())
6743 Value = std::move(PreNarrowingValue);
6744 return E;
6745 }
6746 }
6747
6748 // It's not a constant expression. Produce an appropriate diagnostic.
6749 if (Notes.size() == 1 &&
6750 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6751 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6752 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6753 diag::note_constexpr_invalid_template_arg) {
6754 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6755 for (unsigned I = 0; I < Notes.size(); ++I)
6756 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6757 } else {
6758 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6759 << CCE << E->getSourceRange();
6760 for (unsigned I = 0; I < Notes.size(); ++I)
6761 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6762 }
6763 return ExprError();
6764}
6765
6766/// dropPointerConversions - If the given standard conversion sequence
6767/// involves any pointer conversions, remove them. This may change
6768/// the result type of the conversion sequence.
6769static void dropPointerConversion(StandardConversionSequence &SCS) {
6770 if (SCS.Second == ICK_Pointer_Conversion) {
6771 SCS.Second = ICK_Identity;
6772 SCS.Dimension = ICK_Identity;
6773 SCS.Third = ICK_Identity;
6774 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6775 }
6776}
6777
6778/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6779/// convert the expression From to an Objective-C pointer type.
6780static ImplicitConversionSequence
6781TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6782 // Do an implicit conversion to 'id'.
6783 QualType Ty = S.Context.getObjCIdType();
6784 ImplicitConversionSequence ICS
6785 = TryImplicitConversion(S, From, ToType: Ty,
6786 // FIXME: Are these flags correct?
6787 /*SuppressUserConversions=*/false,
6788 AllowExplicit: AllowedExplicit::Conversions,
6789 /*InOverloadResolution=*/false,
6790 /*CStyle=*/false,
6791 /*AllowObjCWritebackConversion=*/false,
6792 /*AllowObjCConversionOnExplicit=*/true);
6793
6794 // Strip off any final conversions to 'id'.
6795 switch (ICS.getKind()) {
6796 case ImplicitConversionSequence::BadConversion:
6797 case ImplicitConversionSequence::AmbiguousConversion:
6798 case ImplicitConversionSequence::EllipsisConversion:
6799 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6800 break;
6801
6802 case ImplicitConversionSequence::UserDefinedConversion:
6803 dropPointerConversion(SCS&: ICS.UserDefined.After);
6804 break;
6805
6806 case ImplicitConversionSequence::StandardConversion:
6807 dropPointerConversion(SCS&: ICS.Standard);
6808 break;
6809 }
6810
6811 return ICS;
6812}
6813
6814ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6815 if (checkPlaceholderForOverload(S&: *this, E&: From))
6816 return ExprError();
6817
6818 QualType Ty = Context.getObjCIdType();
6819 ImplicitConversionSequence ICS =
6820 TryContextuallyConvertToObjCPointer(S&: *this, From);
6821 if (!ICS.isBad())
6822 return PerformImplicitConversion(From, ToType: Ty, ICS,
6823 Action: AssignmentAction::Converting);
6824 return ExprResult();
6825}
6826
6827static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6828 const Expr *Base = nullptr;
6829 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6830 "expected a member expression");
6831
6832 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6833 M && !M->isImplicitAccess())
6834 Base = M->getBase();
6835 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6836 M && !M->isImplicitAccess())
6837 Base = M->getBase();
6838
6839 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6840
6841 if (T->isPointerType())
6842 T = T->getPointeeType();
6843
6844 return T;
6845}
6846
6847static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6848 const FunctionDecl *Fun) {
6849 QualType ObjType = Obj->getType();
6850 if (ObjType->isPointerType()) {
6851 ObjType = ObjType->getPointeeType();
6852 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6853 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6854 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6855 }
6856 return Obj;
6857}
6858
6859ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6860 FunctionDecl *Fun) {
6861 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6862 return S.PerformCopyInitialization(
6863 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6864 EqualLoc: Obj->getExprLoc(), Init: Obj);
6865}
6866
6867static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6868 Expr *Object, MultiExprArg &Args,
6869 SmallVectorImpl<Expr *> &NewArgs) {
6870 assert(Method->isExplicitObjectMemberFunction() &&
6871 "Method is not an explicit member function");
6872 assert(NewArgs.empty() && "NewArgs should be empty");
6873
6874 NewArgs.reserve(N: Args.size() + 1);
6875 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6876 NewArgs.push_back(Elt: This);
6877 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6878 Args = NewArgs;
6879 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6880 Method, CallLoc: Object->getBeginLoc());
6881}
6882
6883/// Determine whether the provided type is an integral type, or an enumeration
6884/// type of a permitted flavor.
6885bool Sema::ICEConvertDiagnoser::match(QualType T) {
6886 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6887 : T->isIntegralOrUnscopedEnumerationType();
6888}
6889
6890static ExprResult
6891diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6892 Sema::ContextualImplicitConverter &Converter,
6893 QualType T, UnresolvedSetImpl &ViableConversions) {
6894
6895 if (Converter.Suppress)
6896 return ExprError();
6897
6898 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6899 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6900 CXXConversionDecl *Conv =
6901 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6902 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6903 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6904 }
6905 return From;
6906}
6907
6908static bool
6909diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6910 Sema::ContextualImplicitConverter &Converter,
6911 QualType T, bool HadMultipleCandidates,
6912 UnresolvedSetImpl &ExplicitConversions) {
6913 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6914 DeclAccessPair Found = ExplicitConversions[0];
6915 CXXConversionDecl *Conversion =
6916 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6917
6918 // The user probably meant to invoke the given explicit
6919 // conversion; use it.
6920 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6921 std::string TypeStr;
6922 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6923
6924 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6925 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6926 Code: "static_cast<" + TypeStr + ">(")
6927 << FixItHint::CreateInsertion(
6928 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6929 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6930
6931 // If we aren't in a SFINAE context, build a call to the
6932 // explicit conversion function.
6933 if (SemaRef.isSFINAEContext())
6934 return true;
6935
6936 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6937 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6938 HadMultipleCandidates);
6939 if (Result.isInvalid())
6940 return true;
6941
6942 // Replace the conversion with a RecoveryExpr, so we don't try to
6943 // instantiate it later, but can further diagnose here.
6944 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6945 SubExprs: From, T: Result.get()->getType());
6946 if (Result.isInvalid())
6947 return true;
6948 From = Result.get();
6949 }
6950 return false;
6951}
6952
6953static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6954 Sema::ContextualImplicitConverter &Converter,
6955 QualType T, bool HadMultipleCandidates,
6956 DeclAccessPair &Found) {
6957 CXXConversionDecl *Conversion =
6958 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6959 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6960
6961 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6962 if (!Converter.SuppressConversion) {
6963 if (SemaRef.isSFINAEContext())
6964 return true;
6965
6966 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6967 << From->getSourceRange();
6968 }
6969
6970 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6971 HadMultipleCandidates);
6972 if (Result.isInvalid())
6973 return true;
6974 // Record usage of conversion in an implicit cast.
6975 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6976 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6977 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6978 FPO: SemaRef.CurFPFeatureOverrides());
6979 return false;
6980}
6981
6982static ExprResult finishContextualImplicitConversion(
6983 Sema &SemaRef, SourceLocation Loc, Expr *From,
6984 Sema::ContextualImplicitConverter &Converter) {
6985 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6986 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6987 << From->getSourceRange();
6988
6989 return SemaRef.DefaultLvalueConversion(E: From);
6990}
6991
6992static void
6993collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6994 UnresolvedSetImpl &ViableConversions,
6995 OverloadCandidateSet &CandidateSet) {
6996 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6997 NamedDecl *D = FoundDecl.getDecl();
6998 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6999 if (isa<UsingShadowDecl>(Val: D))
7000 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
7001
7002 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
7003 SemaRef.AddTemplateConversionCandidate(
7004 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7005 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7006 continue;
7007 }
7008 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
7009 SemaRef.AddConversionCandidate(
7010 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7011 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7012 }
7013}
7014
7015/// Attempt to convert the given expression to a type which is accepted
7016/// by the given converter.
7017///
7018/// This routine will attempt to convert an expression of class type to a
7019/// type accepted by the specified converter. In C++11 and before, the class
7020/// must have a single non-explicit conversion function converting to a matching
7021/// type. In C++1y, there can be multiple such conversion functions, but only
7022/// one target type.
7023///
7024/// \param Loc The source location of the construct that requires the
7025/// conversion.
7026///
7027/// \param From The expression we're converting from.
7028///
7029/// \param Converter Used to control and diagnose the conversion process.
7030///
7031/// \returns The expression, converted to an integral or enumeration type if
7032/// successful.
7033ExprResult Sema::PerformContextualImplicitConversion(
7034 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7035 // We can't perform any more checking for type-dependent expressions.
7036 if (From->isTypeDependent())
7037 return From;
7038
7039 // Process placeholders immediately.
7040 if (From->hasPlaceholderType()) {
7041 ExprResult result = CheckPlaceholderExpr(E: From);
7042 if (result.isInvalid())
7043 return result;
7044 From = result.get();
7045 }
7046
7047 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7048 ExprResult Converted = DefaultLvalueConversion(E: From);
7049 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7050 From = Converted.isUsable() ? Converted.get() : nullptr;
7051 // If the expression already has a matching type, we're golden.
7052 if (Converter.match(T))
7053 return Converted;
7054
7055 // FIXME: Check for missing '()' if T is a function type?
7056
7057 // We can only perform contextual implicit conversions on objects of class
7058 // type.
7059 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7060 if (!RecordTy || !getLangOpts().CPlusPlus) {
7061 if (!Converter.Suppress)
7062 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7063 return From;
7064 }
7065
7066 // We must have a complete class type.
7067 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7068 ContextualImplicitConverter &Converter;
7069 Expr *From;
7070
7071 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7072 : Converter(Converter), From(From) {}
7073
7074 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7075 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7076 }
7077 } IncompleteDiagnoser(Converter, From);
7078
7079 if (Converter.Suppress ? !isCompleteType(Loc, T)
7080 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7081 return From;
7082
7083 // Look for a conversion to an integral or enumeration type.
7084 UnresolvedSet<4>
7085 ViableConversions; // These are *potentially* viable in C++1y.
7086 UnresolvedSet<4> ExplicitConversions;
7087 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7088 ->getDefinitionOrSelf()
7089 ->getVisibleConversionFunctions();
7090
7091 bool HadMultipleCandidates =
7092 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7093
7094 // To check that there is only one target type, in C++1y:
7095 QualType ToType;
7096 bool HasUniqueTargetType = true;
7097
7098 // Collect explicit or viable (potentially in C++1y) conversions.
7099 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7100 NamedDecl *D = (*I)->getUnderlyingDecl();
7101 CXXConversionDecl *Conversion;
7102 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7103 if (ConvTemplate) {
7104 if (getLangOpts().CPlusPlus14)
7105 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7106 else
7107 continue; // C++11 does not consider conversion operator templates(?).
7108 } else
7109 Conversion = cast<CXXConversionDecl>(Val: D);
7110
7111 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7112 "Conversion operator templates are considered potentially "
7113 "viable in C++1y");
7114
7115 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7116 if (Converter.match(T: CurToType) || ConvTemplate) {
7117
7118 if (Conversion->isExplicit()) {
7119 // FIXME: For C++1y, do we need this restriction?
7120 // cf. diagnoseNoViableConversion()
7121 if (!ConvTemplate)
7122 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7123 } else {
7124 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7125 if (ToType.isNull())
7126 ToType = CurToType.getUnqualifiedType();
7127 else if (HasUniqueTargetType &&
7128 (CurToType.getUnqualifiedType() != ToType))
7129 HasUniqueTargetType = false;
7130 }
7131 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7132 }
7133 }
7134 }
7135
7136 if (getLangOpts().CPlusPlus14) {
7137 // C++1y [conv]p6:
7138 // ... An expression e of class type E appearing in such a context
7139 // is said to be contextually implicitly converted to a specified
7140 // type T and is well-formed if and only if e can be implicitly
7141 // converted to a type T that is determined as follows: E is searched
7142 // for conversion functions whose return type is cv T or reference to
7143 // cv T such that T is allowed by the context. There shall be
7144 // exactly one such T.
7145
7146 // If no unique T is found:
7147 if (ToType.isNull()) {
7148 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7149 HadMultipleCandidates,
7150 ExplicitConversions))
7151 return ExprError();
7152 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7153 }
7154
7155 // If more than one unique Ts are found:
7156 if (!HasUniqueTargetType)
7157 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7158 ViableConversions);
7159
7160 // If one unique T is found:
7161 // First, build a candidate set from the previously recorded
7162 // potentially viable conversions.
7163 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7164 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7165 CandidateSet);
7166
7167 // Then, perform overload resolution over the candidate set.
7168 OverloadCandidateSet::iterator Best;
7169 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7170 case OR_Success: {
7171 // Apply this conversion.
7172 DeclAccessPair Found =
7173 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7174 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7175 HadMultipleCandidates, Found))
7176 return ExprError();
7177 break;
7178 }
7179 case OR_Ambiguous:
7180 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7181 ViableConversions);
7182 case OR_No_Viable_Function:
7183 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7184 HadMultipleCandidates,
7185 ExplicitConversions))
7186 return ExprError();
7187 [[fallthrough]];
7188 case OR_Deleted:
7189 // We'll complain below about a non-integral condition type.
7190 break;
7191 }
7192 } else {
7193 switch (ViableConversions.size()) {
7194 case 0: {
7195 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7196 HadMultipleCandidates,
7197 ExplicitConversions))
7198 return ExprError();
7199
7200 // We'll complain below about a non-integral condition type.
7201 break;
7202 }
7203 case 1: {
7204 // Apply this conversion.
7205 DeclAccessPair Found = ViableConversions[0];
7206 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7207 HadMultipleCandidates, Found))
7208 return ExprError();
7209 break;
7210 }
7211 default:
7212 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7213 ViableConversions);
7214 }
7215 }
7216
7217 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7218}
7219
7220/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7221/// an acceptable non-member overloaded operator for a call whose
7222/// arguments have types T1 (and, if non-empty, T2). This routine
7223/// implements the check in C++ [over.match.oper]p3b2 concerning
7224/// enumeration types.
7225static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7226 FunctionDecl *Fn,
7227 ArrayRef<Expr *> Args) {
7228 QualType T1 = Args[0]->getType();
7229 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7230
7231 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7232 return true;
7233
7234 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7235 return true;
7236
7237 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7238 if (Proto->getNumParams() < 1)
7239 return false;
7240
7241 if (T1->isEnumeralType()) {
7242 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7243 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7244 return true;
7245 }
7246
7247 if (Proto->getNumParams() < 2)
7248 return false;
7249
7250 if (!T2.isNull() && T2->isEnumeralType()) {
7251 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7252 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7253 return true;
7254 }
7255
7256 return false;
7257}
7258
7259static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7260 if (FD->isTargetMultiVersionDefault())
7261 return false;
7262
7263 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7264 return FD->isTargetMultiVersion();
7265
7266 if (!FD->isMultiVersion())
7267 return false;
7268
7269 // Among multiple target versions consider either the default,
7270 // or the first non-default in the absence of default version.
7271 unsigned SeenAt = 0;
7272 unsigned I = 0;
7273 bool HasDefault = false;
7274 FD->getASTContext().forEachMultiversionedFunctionVersion(
7275 FD, Pred: [&](const FunctionDecl *CurFD) {
7276 if (FD == CurFD)
7277 SeenAt = I;
7278 else if (CurFD->isTargetMultiVersionDefault())
7279 HasDefault = true;
7280 ++I;
7281 });
7282 return HasDefault || SeenAt != 0;
7283}
7284
7285void Sema::AddOverloadCandidate(
7286 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7287 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7288 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7289 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7290 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7291 bool StrictPackMatch) {
7292 const FunctionProtoType *Proto
7293 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7294 assert(Proto && "Functions without a prototype cannot be overloaded");
7295 assert(!Function->getDescribedFunctionTemplate() &&
7296 "Use AddTemplateOverloadCandidate for function templates");
7297
7298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7299 if (!isa<CXXConstructorDecl>(Val: Method)) {
7300 // If we get here, it's because we're calling a member function
7301 // that is named without a member access expression (e.g.,
7302 // "this->f") that was either written explicitly or created
7303 // implicitly. This can happen with a qualified call to a member
7304 // function, e.g., X::f(). We use an empty type for the implied
7305 // object argument (C++ [over.call.func]p3), and the acting context
7306 // is irrelevant.
7307 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7308 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7309 CandidateSet, SuppressUserConversions,
7310 PartialOverloading, EarlyConversions, PO,
7311 StrictPackMatch);
7312 return;
7313 }
7314 // We treat a constructor like a non-member function, since its object
7315 // argument doesn't participate in overload resolution.
7316 }
7317
7318 if (!CandidateSet.isNewCandidate(F: Function, PO))
7319 return;
7320
7321 // C++11 [class.copy]p11: [DR1402]
7322 // A defaulted move constructor that is defined as deleted is ignored by
7323 // overload resolution.
7324 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7325 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7326 Constructor->isMoveConstructor())
7327 return;
7328
7329 // Overload resolution is always an unevaluated context.
7330 EnterExpressionEvaluationContext Unevaluated(
7331 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7332
7333 // C++ [over.match.oper]p3:
7334 // if no operand has a class type, only those non-member functions in the
7335 // lookup set that have a first parameter of type T1 or "reference to
7336 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7337 // is a right operand) a second parameter of type T2 or "reference to
7338 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7339 // candidate functions.
7340 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7341 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7342 return;
7343
7344 // Add this candidate
7345 OverloadCandidate &Candidate =
7346 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7347 Candidate.FoundDecl = FoundDecl;
7348 Candidate.Function = Function;
7349 Candidate.Viable = true;
7350 Candidate.RewriteKind =
7351 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7352 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7353 Candidate.ExplicitCallArguments = Args.size();
7354 Candidate.StrictPackMatch = StrictPackMatch;
7355
7356 // Explicit functions are not actually candidates at all if we're not
7357 // allowing them in this context, but keep them around so we can point
7358 // to them in diagnostics.
7359 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7360 Candidate.Viable = false;
7361 Candidate.FailureKind = ovl_fail_explicit;
7362 return;
7363 }
7364
7365 // Functions with internal linkage are only viable in the same module unit.
7366 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7367 /// FIXME: Currently, the semantics of linkage in clang is slightly
7368 /// different from the semantics in C++ spec. In C++ spec, only names
7369 /// have linkage. So that all entities of the same should share one
7370 /// linkage. But in clang, different entities of the same could have
7371 /// different linkage.
7372 const NamedDecl *ND = Function;
7373 bool IsImplicitlyInstantiated = false;
7374 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7375 ND = SpecInfo->getTemplate();
7376 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7377 TSK_ImplicitInstantiation;
7378 }
7379
7380 /// Don't remove inline functions with internal linkage from the overload
7381 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7382 /// However:
7383 /// - Inline functions with internal linkage are a common pattern in
7384 /// headers to avoid ODR issues.
7385 /// - The global module is meant to be a transition mechanism for C and C++
7386 /// headers, and the current rules as written work against that goal.
7387 const bool IsInlineFunctionInGMF =
7388 Function->isFromGlobalModule() &&
7389 (IsImplicitlyInstantiated || Function->isInlined());
7390
7391 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7392 Candidate.Viable = false;
7393 Candidate.FailureKind = ovl_fail_module_mismatched;
7394 return;
7395 }
7396 }
7397
7398 if (isNonViableMultiVersionOverload(FD: Function)) {
7399 Candidate.Viable = false;
7400 Candidate.FailureKind = ovl_non_default_multiversion_function;
7401 return;
7402 }
7403
7404 if (Constructor) {
7405 // C++ [class.copy]p3:
7406 // A member function template is never instantiated to perform the copy
7407 // of a class object to an object of its class type.
7408 CanQualType ClassType =
7409 Context.getCanonicalTagType(TD: Constructor->getParent());
7410 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7411 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7412 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7413 Base: ClassType))) {
7414 Candidate.Viable = false;
7415 Candidate.FailureKind = ovl_fail_illegal_constructor;
7416 return;
7417 }
7418
7419 // C++ [over.match.funcs]p8: (proposed DR resolution)
7420 // A constructor inherited from class type C that has a first parameter
7421 // of type "reference to P" (including such a constructor instantiated
7422 // from a template) is excluded from the set of candidate functions when
7423 // constructing an object of type cv D if the argument list has exactly
7424 // one argument and D is reference-related to P and P is reference-related
7425 // to C.
7426 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7427 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7428 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7429 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7430 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7431 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7432 SourceLocation Loc = Args.front()->getExprLoc();
7433 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7434 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7435 Candidate.Viable = false;
7436 Candidate.FailureKind = ovl_fail_inhctor_slice;
7437 return;
7438 }
7439 }
7440
7441 // Check that the constructor is capable of constructing an object in the
7442 // destination address space.
7443 if (!Qualifiers::isAddressSpaceSupersetOf(
7444 A: Constructor->getMethodQualifiers().getAddressSpace(),
7445 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7446 Candidate.Viable = false;
7447 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7448 }
7449 }
7450
7451 unsigned NumParams = Proto->getNumParams();
7452
7453 // (C++ 13.3.2p2): A candidate function having fewer than m
7454 // parameters is viable only if it has an ellipsis in its parameter
7455 // list (8.3.5).
7456 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7457 !Proto->isVariadic() &&
7458 shouldEnforceArgLimit(PartialOverloading, Function)) {
7459 Candidate.Viable = false;
7460 Candidate.FailureKind = ovl_fail_too_many_arguments;
7461 return;
7462 }
7463
7464 // (C++ 13.3.2p2): A candidate function having more than m parameters
7465 // is viable only if the (m+1)st parameter has a default argument
7466 // (8.3.6). For the purposes of overload resolution, the
7467 // parameter list is truncated on the right, so that there are
7468 // exactly m parameters.
7469 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7470 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7471 !PartialOverloading) {
7472 // Not enough arguments.
7473 Candidate.Viable = false;
7474 Candidate.FailureKind = ovl_fail_too_few_arguments;
7475 return;
7476 }
7477
7478 // (CUDA B.1): Check for invalid calls between targets.
7479 if (getLangOpts().CUDA) {
7480 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7481 // Skip the check for callers that are implicit members, because in this
7482 // case we may not yet know what the member's target is; the target is
7483 // inferred for the member automatically, based on the bases and fields of
7484 // the class.
7485 if (!(Caller && Caller->isImplicit()) &&
7486 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7487 Candidate.Viable = false;
7488 Candidate.FailureKind = ovl_fail_bad_target;
7489 return;
7490 }
7491 }
7492
7493 if (Function->getTrailingRequiresClause()) {
7494 ConstraintSatisfaction Satisfaction;
7495 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7496 /*ForOverloadResolution*/ true) ||
7497 !Satisfaction.IsSatisfied) {
7498 Candidate.Viable = false;
7499 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7500 return;
7501 }
7502 }
7503
7504 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7505 // Determine the implicit conversion sequences for each of the
7506 // arguments.
7507 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7508 unsigned ConvIdx =
7509 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7510 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7511 // We already formed a conversion sequence for this parameter during
7512 // template argument deduction.
7513 } else if (ArgIdx < NumParams) {
7514 // (C++ 13.3.2p3): for F to be a viable function, there shall
7515 // exist for each argument an implicit conversion sequence
7516 // (13.3.3.1) that converts that argument to the corresponding
7517 // parameter of F.
7518 QualType ParamType = Proto->getParamType(i: ArgIdx);
7519 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7520 if (ParamABI == ParameterABI::HLSLOut ||
7521 ParamABI == ParameterABI::HLSLInOut) {
7522 ParamType = ParamType.getNonReferenceType();
7523 if (ParamABI == ParameterABI::HLSLInOut &&
7524 Args[ArgIdx]->getType().getAddressSpace() ==
7525 LangAS::hlsl_groupshared)
7526 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7527 }
7528 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7529 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7530 /*InOverloadResolution=*/true,
7531 /*AllowObjCWritebackConversion=*/
7532 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7533 if (Candidate.Conversions[ConvIdx].isBad()) {
7534 Candidate.Viable = false;
7535 Candidate.FailureKind = ovl_fail_bad_conversion;
7536 return;
7537 }
7538 } else {
7539 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7540 // argument for which there is no corresponding parameter is
7541 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7542 Candidate.Conversions[ConvIdx].setEllipsis();
7543 }
7544 }
7545
7546 if (EnableIfAttr *FailedAttr =
7547 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7548 Candidate.Viable = false;
7549 Candidate.FailureKind = ovl_fail_enable_if;
7550 Candidate.DeductionFailure.Data = FailedAttr;
7551 return;
7552 }
7553}
7554
7555ObjCMethodDecl *
7556Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7557 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7558 if (Methods.size() <= 1)
7559 return nullptr;
7560
7561 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7562 bool Match = true;
7563 ObjCMethodDecl *Method = Methods[b];
7564 unsigned NumNamedArgs = Sel.getNumArgs();
7565 // Method might have more arguments than selector indicates. This is due
7566 // to addition of c-style arguments in method.
7567 if (Method->param_size() > NumNamedArgs)
7568 NumNamedArgs = Method->param_size();
7569 if (Args.size() < NumNamedArgs)
7570 continue;
7571
7572 for (unsigned i = 0; i < NumNamedArgs; i++) {
7573 // We can't do any type-checking on a type-dependent argument.
7574 if (Args[i]->isTypeDependent()) {
7575 Match = false;
7576 break;
7577 }
7578
7579 ParmVarDecl *param = Method->parameters()[i];
7580 Expr *argExpr = Args[i];
7581 assert(argExpr && "SelectBestMethod(): missing expression");
7582
7583 // Strip the unbridged-cast placeholder expression off unless it's
7584 // a consumed argument.
7585 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7586 !param->hasAttr<CFConsumedAttr>())
7587 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7588
7589 // If the parameter is __unknown_anytype, move on to the next method.
7590 if (param->getType() == Context.UnknownAnyTy) {
7591 Match = false;
7592 break;
7593 }
7594
7595 ImplicitConversionSequence ConversionState
7596 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7597 /*SuppressUserConversions*/false,
7598 /*InOverloadResolution=*/true,
7599 /*AllowObjCWritebackConversion=*/
7600 getLangOpts().ObjCAutoRefCount,
7601 /*AllowExplicit*/false);
7602 // This function looks for a reasonably-exact match, so we consider
7603 // incompatible pointer conversions to be a failure here.
7604 if (ConversionState.isBad() ||
7605 (ConversionState.isStandard() &&
7606 ConversionState.Standard.Second ==
7607 ICK_Incompatible_Pointer_Conversion)) {
7608 Match = false;
7609 break;
7610 }
7611 }
7612 // Promote additional arguments to variadic methods.
7613 if (Match && Method->isVariadic()) {
7614 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7615 if (Args[i]->isTypeDependent()) {
7616 Match = false;
7617 break;
7618 }
7619 ExprResult Arg = DefaultVariadicArgumentPromotion(
7620 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7621 if (Arg.isInvalid()) {
7622 Match = false;
7623 break;
7624 }
7625 }
7626 } else {
7627 // Check for extra arguments to non-variadic methods.
7628 if (Args.size() != NumNamedArgs)
7629 Match = false;
7630 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7631 // Special case when selectors have no argument. In this case, select
7632 // one with the most general result type of 'id'.
7633 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7634 QualType ReturnT = Methods[b]->getReturnType();
7635 if (ReturnT->isObjCIdType())
7636 return Methods[b];
7637 }
7638 }
7639 }
7640
7641 if (Match)
7642 return Method;
7643 }
7644 return nullptr;
7645}
7646
7647static bool convertArgsForAvailabilityChecks(
7648 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7649 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7650 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7651 if (ThisArg) {
7652 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7653 assert(!isa<CXXConstructorDecl>(Method) &&
7654 "Shouldn't have `this` for ctors!");
7655 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7656 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7657 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7658 if (R.isInvalid())
7659 return false;
7660 ConvertedThis = R.get();
7661 } else {
7662 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7663 (void)MD;
7664 assert((MissingImplicitThis || MD->isStatic() ||
7665 isa<CXXConstructorDecl>(MD)) &&
7666 "Expected `this` for non-ctor instance methods");
7667 }
7668 ConvertedThis = nullptr;
7669 }
7670
7671 // Ignore any variadic arguments. Converting them is pointless, since the
7672 // user can't refer to them in the function condition.
7673 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7674
7675 // Convert the arguments.
7676 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7677 ExprResult R;
7678 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7679 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7680 EqualLoc: SourceLocation(), Init: Args[I]);
7681
7682 if (R.isInvalid())
7683 return false;
7684
7685 ConvertedArgs.push_back(Elt: R.get());
7686 }
7687
7688 if (Trap.hasErrorOccurred())
7689 return false;
7690
7691 // Push default arguments if needed.
7692 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7693 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7694 ParmVarDecl *P = Function->getParamDecl(i);
7695 if (!P->hasDefaultArg())
7696 return false;
7697 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7698 if (R.isInvalid())
7699 return false;
7700 ConvertedArgs.push_back(Elt: R.get());
7701 }
7702
7703 if (Trap.hasErrorOccurred())
7704 return false;
7705 }
7706 return true;
7707}
7708
7709EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7710 SourceLocation CallLoc,
7711 ArrayRef<Expr *> Args,
7712 bool MissingImplicitThis) {
7713 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7714 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7715 return nullptr;
7716
7717 SFINAETrap Trap(*this);
7718 // Perform the access checking immediately so any access diagnostics are
7719 // caught by the SFINAE trap.
7720 llvm::scope_exit UndelayDiags(
7721 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7722 DelayedDiagnostics.popUndelayed(state: CurrentState);
7723 });
7724 SmallVector<Expr *, 16> ConvertedArgs;
7725 // FIXME: We should look into making enable_if late-parsed.
7726 Expr *DiscardedThis;
7727 if (!convertArgsForAvailabilityChecks(
7728 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7729 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7730 return *EnableIfAttrs.begin();
7731
7732 for (auto *EIA : EnableIfAttrs) {
7733 APValue Result;
7734 // FIXME: This doesn't consider value-dependent cases, because doing so is
7735 // very difficult. Ideally, we should handle them more gracefully.
7736 if (EIA->getCond()->isValueDependent() ||
7737 !EIA->getCond()->EvaluateWithSubstitution(
7738 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7739 return EIA;
7740
7741 if (!Result.isInt() || !Result.getInt().getBoolValue())
7742 return EIA;
7743 }
7744 return nullptr;
7745}
7746
7747template <typename CheckFn>
7748static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7749 bool ArgDependent, SourceLocation Loc,
7750 CheckFn &&IsSuccessful) {
7751 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7752 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7753 if (ArgDependent == DIA->getArgDependent())
7754 Attrs.push_back(Elt: DIA);
7755 }
7756
7757 // Common case: No diagnose_if attributes, so we can quit early.
7758 if (Attrs.empty())
7759 return false;
7760
7761 auto WarningBegin = std::stable_partition(
7762 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7763 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7764 DIA->getWarningGroup().empty();
7765 });
7766
7767 // Note that diagnose_if attributes are late-parsed, so they appear in the
7768 // correct order (unlike enable_if attributes).
7769 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7770 IsSuccessful);
7771 if (ErrAttr != WarningBegin) {
7772 const DiagnoseIfAttr *DIA = *ErrAttr;
7773 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7774 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7775 << DIA->getParent() << DIA->getCond()->getSourceRange();
7776 return true;
7777 }
7778
7779 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7780 switch (Sev) {
7781 case DiagnoseIfAttr::DS_warning:
7782 return diag::Severity::Warning;
7783 case DiagnoseIfAttr::DS_error:
7784 return diag::Severity::Error;
7785 }
7786 llvm_unreachable("Fully covered switch above!");
7787 };
7788
7789 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7790 if (IsSuccessful(DIA)) {
7791 if (DIA->getWarningGroup().empty() &&
7792 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7793 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7794 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7795 << DIA->getParent() << DIA->getCond()->getSourceRange();
7796 } else {
7797 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7798 DIA->getWarningGroup());
7799 assert(DiagGroup);
7800 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7801 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7802 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7803 S.Diag(Loc, DiagID) << DIA->getMessage();
7804 }
7805 }
7806
7807 return false;
7808}
7809
7810bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7811 const Expr *ThisArg,
7812 ArrayRef<const Expr *> Args,
7813 SourceLocation Loc) {
7814 return diagnoseDiagnoseIfAttrsWith(
7815 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7816 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7817 APValue Result;
7818 // It's sane to use the same Args for any redecl of this function, since
7819 // EvaluateWithSubstitution only cares about the position of each
7820 // argument in the arg list, not the ParmVarDecl* it maps to.
7821 if (!DIA->getCond()->EvaluateWithSubstitution(
7822 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7823 return false;
7824 return Result.isInt() && Result.getInt().getBoolValue();
7825 });
7826}
7827
7828bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7829 SourceLocation Loc) {
7830 return diagnoseDiagnoseIfAttrsWith(
7831 S&: *this, ND, /*ArgDependent=*/false, Loc,
7832 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7833 bool Result;
7834 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7835 Result;
7836 });
7837}
7838
7839void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7840 ArrayRef<Expr *> Args,
7841 OverloadCandidateSet &CandidateSet,
7842 TemplateArgumentListInfo *ExplicitTemplateArgs,
7843 bool SuppressUserConversions,
7844 bool PartialOverloading,
7845 bool FirstArgumentIsBase) {
7846 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7847 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7848 ArrayRef<Expr *> FunctionArgs = Args;
7849
7850 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7851 FunctionDecl *FD =
7852 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7853
7854 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7855 QualType ObjectType;
7856 Expr::Classification ObjectClassification;
7857 if (Args.size() > 0) {
7858 if (Expr *E = Args[0]) {
7859 // Use the explicit base to restrict the lookup:
7860 ObjectType = E->getType();
7861 // Pointers in the object arguments are implicitly dereferenced, so we
7862 // always classify them as l-values.
7863 if (!ObjectType.isNull() && ObjectType->isPointerType())
7864 ObjectClassification = Expr::Classification::makeSimpleLValue();
7865 else
7866 ObjectClassification = E->Classify(Ctx&: Context);
7867 } // .. else there is an implicit base.
7868 FunctionArgs = Args.slice(N: 1);
7869 }
7870 if (FunTmpl) {
7871 AddMethodTemplateCandidate(
7872 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7873 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7874 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7875 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7876 PartialOverloading);
7877 } else {
7878 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7879 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7880 ObjectClassification, Args: FunctionArgs, CandidateSet,
7881 SuppressUserConversions, PartialOverloading);
7882 }
7883 } else {
7884 // This branch handles both standalone functions and static methods.
7885
7886 // Slice the first argument (which is the base) when we access
7887 // static method as non-static.
7888 if (Args.size() > 0 &&
7889 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7890 !isa<CXXConstructorDecl>(Val: FD)))) {
7891 assert(cast<CXXMethodDecl>(FD)->isStatic());
7892 FunctionArgs = Args.slice(N: 1);
7893 }
7894 if (FunTmpl) {
7895 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7896 ExplicitTemplateArgs, Args: FunctionArgs,
7897 CandidateSet, SuppressUserConversions,
7898 PartialOverloading);
7899 } else {
7900 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7901 SuppressUserConversions, PartialOverloading);
7902 }
7903 }
7904 }
7905}
7906
7907void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7908 Expr::Classification ObjectClassification,
7909 ArrayRef<Expr *> Args,
7910 OverloadCandidateSet &CandidateSet,
7911 bool SuppressUserConversions,
7912 OverloadCandidateParamOrder PO) {
7913 NamedDecl *Decl = FoundDecl.getDecl();
7914 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7915
7916 if (isa<UsingShadowDecl>(Val: Decl))
7917 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7918
7919 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7920 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7921 "Expected a member function template");
7922 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7923 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7924 ObjectClassification, Args, CandidateSet,
7925 SuppressUserConversions, PartialOverloading: false, PO);
7926 } else {
7927 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7928 ObjectType, ObjectClassification, Args, CandidateSet,
7929 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7930 }
7931}
7932
7933void Sema::AddMethodCandidate(
7934 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7935 CXXRecordDecl *ActingContext, QualType ObjectType,
7936 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7937 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7938 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7939 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7940 const FunctionProtoType *Proto
7941 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7942 assert(Proto && "Methods without a prototype cannot be overloaded");
7943 assert(!isa<CXXConstructorDecl>(Method) &&
7944 "Use AddOverloadCandidate for constructors");
7945
7946 if (!CandidateSet.isNewCandidate(F: Method, PO))
7947 return;
7948
7949 // C++11 [class.copy]p23: [DR1402]
7950 // A defaulted move assignment operator that is defined as deleted is
7951 // ignored by overload resolution.
7952 if (Method->isDefaulted() && Method->isDeleted() &&
7953 Method->isMoveAssignmentOperator())
7954 return;
7955
7956 // Overload resolution is always an unevaluated context.
7957 EnterExpressionEvaluationContext Unevaluated(
7958 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7959
7960 bool IgnoreExplicitObject =
7961 (Method->isExplicitObjectMemberFunction() &&
7962 CandidateSet.getKind() ==
7963 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7964 bool ImplicitObjectMethodTreatedAsStatic =
7965 CandidateSet.getKind() ==
7966 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7967 Method->isImplicitObjectMemberFunction();
7968
7969 unsigned ExplicitOffset =
7970 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7971
7972 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7973 int(ImplicitObjectMethodTreatedAsStatic);
7974
7975 unsigned ExtraArgs =
7976 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7977 ? 0
7978 : 1;
7979
7980 // Add this candidate
7981 OverloadCandidate &Candidate =
7982 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
7983 Candidate.FoundDecl = FoundDecl;
7984 Candidate.Function = Method;
7985 Candidate.RewriteKind =
7986 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7987 Candidate.TookAddressOfOverload =
7988 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7989 Candidate.ExplicitCallArguments = Args.size();
7990 Candidate.StrictPackMatch = StrictPackMatch;
7991
7992 // (C++ 13.3.2p2): A candidate function having fewer than m
7993 // parameters is viable only if it has an ellipsis in its parameter
7994 // list (8.3.5).
7995 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7996 !Proto->isVariadic() &&
7997 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7998 Candidate.Viable = false;
7999 Candidate.FailureKind = ovl_fail_too_many_arguments;
8000 return;
8001 }
8002
8003 // (C++ 13.3.2p2): A candidate function having more than m parameters
8004 // is viable only if the (m+1)st parameter has a default argument
8005 // (8.3.6). For the purposes of overload resolution, the
8006 // parameter list is truncated on the right, so that there are
8007 // exactly m parameters.
8008 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8009 ExplicitOffset +
8010 int(ImplicitObjectMethodTreatedAsStatic);
8011
8012 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8013 // Not enough arguments.
8014 Candidate.Viable = false;
8015 Candidate.FailureKind = ovl_fail_too_few_arguments;
8016 return;
8017 }
8018
8019 Candidate.Viable = true;
8020
8021 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8022 if (!IgnoreExplicitObject) {
8023 if (ObjectType.isNull())
8024 Candidate.IgnoreObjectArgument = true;
8025 else if (Method->isStatic()) {
8026 // [over.best.ics.general]p8
8027 // When the parameter is the implicit object parameter of a static member
8028 // function, the implicit conversion sequence is a standard conversion
8029 // sequence that is neither better nor worse than any other standard
8030 // conversion sequence.
8031 //
8032 // This is a rule that was introduced in C++23 to support static lambdas.
8033 // We apply it retroactively because we want to support static lambdas as
8034 // an extension and it doesn't hurt previous code.
8035 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8036 } else {
8037 // Determine the implicit conversion sequence for the object
8038 // parameter.
8039 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8040 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8041 Method, ActingContext, /*InOverloadResolution=*/true);
8042 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8043 Candidate.Viable = false;
8044 Candidate.FailureKind = ovl_fail_bad_conversion;
8045 return;
8046 }
8047 }
8048 }
8049
8050 // (CUDA B.1): Check for invalid calls between targets.
8051 if (getLangOpts().CUDA)
8052 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8053 Callee: Method)) {
8054 Candidate.Viable = false;
8055 Candidate.FailureKind = ovl_fail_bad_target;
8056 return;
8057 }
8058
8059 if (Method->getTrailingRequiresClause()) {
8060 ConstraintSatisfaction Satisfaction;
8061 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8062 /*ForOverloadResolution*/ true) ||
8063 !Satisfaction.IsSatisfied) {
8064 Candidate.Viable = false;
8065 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8066 return;
8067 }
8068 }
8069
8070 // Determine the implicit conversion sequences for each of the
8071 // arguments.
8072 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8073 unsigned ConvIdx =
8074 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8075 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8076 // We already formed a conversion sequence for this parameter during
8077 // template argument deduction.
8078 } else if (ArgIdx < NumParams) {
8079 // (C++ 13.3.2p3): for F to be a viable function, there shall
8080 // exist for each argument an implicit conversion sequence
8081 // (13.3.3.1) that converts that argument to the corresponding
8082 // parameter of F.
8083 QualType ParamType;
8084 if (ImplicitObjectMethodTreatedAsStatic) {
8085 ParamType = ArgIdx == 0
8086 ? Method->getFunctionObjectParameterReferenceType()
8087 : Proto->getParamType(i: ArgIdx - 1);
8088 } else {
8089 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8090 }
8091 Candidate.Conversions[ConvIdx]
8092 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8093 SuppressUserConversions,
8094 /*InOverloadResolution=*/true,
8095 /*AllowObjCWritebackConversion=*/
8096 getLangOpts().ObjCAutoRefCount);
8097 if (Candidate.Conversions[ConvIdx].isBad()) {
8098 Candidate.Viable = false;
8099 Candidate.FailureKind = ovl_fail_bad_conversion;
8100 return;
8101 }
8102 } else {
8103 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8104 // argument for which there is no corresponding parameter is
8105 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8106 Candidate.Conversions[ConvIdx].setEllipsis();
8107 }
8108 }
8109
8110 if (EnableIfAttr *FailedAttr =
8111 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8112 Candidate.Viable = false;
8113 Candidate.FailureKind = ovl_fail_enable_if;
8114 Candidate.DeductionFailure.Data = FailedAttr;
8115 return;
8116 }
8117
8118 if (isNonViableMultiVersionOverload(FD: Method)) {
8119 Candidate.Viable = false;
8120 Candidate.FailureKind = ovl_non_default_multiversion_function;
8121 }
8122}
8123
8124static void AddMethodTemplateCandidateImmediately(
8125 Sema &S, OverloadCandidateSet &CandidateSet,
8126 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8127 CXXRecordDecl *ActingContext,
8128 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8129 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8130 bool SuppressUserConversions, bool PartialOverloading,
8131 OverloadCandidateParamOrder PO) {
8132
8133 // C++ [over.match.funcs]p7:
8134 // In each case where a candidate is a function template, candidate
8135 // function template specializations are generated using template argument
8136 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8137 // candidate functions in the usual way.113) A given name can refer to one
8138 // or more function templates and also to a set of overloaded non-template
8139 // functions. In such a case, the candidate functions generated from each
8140 // function template are combined with the set of non-template candidate
8141 // functions.
8142 TemplateDeductionInfo Info(CandidateSet.getLocation());
8143 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8144 FunctionDecl *Specialization = nullptr;
8145 ConversionSequenceList Conversions;
8146 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8147 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8148 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8149 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8150 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8151 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8152 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8153 bool OnlyInitializeNonUserDefinedConversions) {
8154 return S.CheckNonDependentConversions(
8155 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8156 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8157 SuppressUserConversions,
8158 OnlyInitializeNonUserDefinedConversions),
8159 ActingContext, ObjectType, ObjectClassification, PO);
8160 });
8161 Result != TemplateDeductionResult::Success) {
8162 OverloadCandidate &Candidate =
8163 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8164 Candidate.FoundDecl = FoundDecl;
8165 Candidate.Function = Method;
8166 Candidate.Viable = false;
8167 Candidate.RewriteKind =
8168 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8169 Candidate.IsSurrogate = false;
8170 Candidate.TookAddressOfOverload =
8171 CandidateSet.getKind() ==
8172 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8173
8174 Candidate.IgnoreObjectArgument =
8175 Method->isStatic() ||
8176 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8177 Candidate.ExplicitCallArguments = Args.size();
8178 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8179 Candidate.FailureKind = ovl_fail_bad_conversion;
8180 else {
8181 Candidate.FailureKind = ovl_fail_bad_deduction;
8182 Candidate.DeductionFailure =
8183 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8184 }
8185 return;
8186 }
8187
8188 // Add the function template specialization produced by template argument
8189 // deduction as a candidate.
8190 assert(Specialization && "Missing member function template specialization?");
8191 assert(isa<CXXMethodDecl>(Specialization) &&
8192 "Specialization is not a member function?");
8193 S.AddMethodCandidate(
8194 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8195 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8196 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8197}
8198
8199void Sema::AddMethodTemplateCandidate(
8200 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8201 CXXRecordDecl *ActingContext,
8202 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8203 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8204 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8205 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8206 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8207 return;
8208
8209 if (ExplicitTemplateArgs ||
8210 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this)) {
8211 AddMethodTemplateCandidateImmediately(
8212 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8213 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8214 SuppressUserConversions, PartialOverloading, PO);
8215 return;
8216 }
8217
8218 CandidateSet.AddDeferredMethodTemplateCandidate(
8219 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8220 Args, SuppressUserConversions, PartialOverloading, PO);
8221}
8222
8223/// Determine whether a given function template has a simple explicit specifier
8224/// or a non-value-dependent explicit-specification that evaluates to true.
8225static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8226 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8227}
8228
8229static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8230 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8231 ExplicitSpecKind::Unresolved;
8232}
8233
8234static void AddTemplateOverloadCandidateImmediately(
8235 Sema &S, OverloadCandidateSet &CandidateSet,
8236 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8237 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8238 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8239 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8240 bool AggregateCandidateDeduction) {
8241
8242 // If the function template has a non-dependent explicit specification,
8243 // exclude it now if appropriate; we are not permitted to perform deduction
8244 // and substitution in this case.
8245 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8246 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8247 Candidate.FoundDecl = FoundDecl;
8248 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8249 Candidate.Viable = false;
8250 Candidate.FailureKind = ovl_fail_explicit;
8251 return;
8252 }
8253
8254 // C++ [over.match.funcs]p7:
8255 // In each case where a candidate is a function template, candidate
8256 // function template specializations are generated using template argument
8257 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8258 // candidate functions in the usual way.113) A given name can refer to one
8259 // or more function templates and also to a set of overloaded non-template
8260 // functions. In such a case, the candidate functions generated from each
8261 // function template are combined with the set of non-template candidate
8262 // functions.
8263 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8264 FunctionTemplate->getTemplateDepth());
8265 FunctionDecl *Specialization = nullptr;
8266 ConversionSequenceList Conversions;
8267 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8268 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8269 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8270 /*PartialOrdering=*/false,
8271 /*ObjectType=*/QualType(),
8272 /*ObjectClassification=*/Expr::Classification(),
8273 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8274 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8275 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8276 bool OnlyInitializeNonUserDefinedConversions) {
8277 return S.CheckNonDependentConversions(
8278 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8279 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8280 SuppressUserConversions,
8281 OnlyInitializeNonUserDefinedConversions),
8282 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8283 });
8284 Result != TemplateDeductionResult::Success) {
8285 OverloadCandidate &Candidate =
8286 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8287 Candidate.FoundDecl = FoundDecl;
8288 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8289 Candidate.Viable = false;
8290 Candidate.RewriteKind =
8291 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8292 Candidate.IsSurrogate = false;
8293 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8294 // Ignore the object argument if there is one, since we don't have an object
8295 // type.
8296 Candidate.TookAddressOfOverload =
8297 CandidateSet.getKind() ==
8298 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8299
8300 Candidate.IgnoreObjectArgument =
8301 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8302 !cast<CXXMethodDecl>(Val: Candidate.Function)
8303 ->isExplicitObjectMemberFunction() &&
8304 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8305
8306 Candidate.ExplicitCallArguments = Args.size();
8307 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8308 Candidate.FailureKind = ovl_fail_bad_conversion;
8309 else {
8310 Candidate.FailureKind = ovl_fail_bad_deduction;
8311 Candidate.DeductionFailure =
8312 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8313 }
8314 return;
8315 }
8316
8317 // Add the function template specialization produced by template argument
8318 // deduction as a candidate.
8319 assert(Specialization && "Missing function template specialization?");
8320 S.AddOverloadCandidate(
8321 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8322 PartialOverloading, AllowExplicit,
8323 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8324 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8325 StrictPackMatch: Info.hasStrictPackMatch());
8326}
8327
8328void Sema::AddTemplateOverloadCandidate(
8329 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8330 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8331 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8332 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8333 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8334 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8335 return;
8336
8337 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8338
8339 if (ExplicitTemplateArgs ||
8340 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8341 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8342 DependentExplicitSpecifier)) {
8343
8344 AddTemplateOverloadCandidateImmediately(
8345 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8346 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8347 IsADLCandidate, PO, AggregateCandidateDeduction);
8348
8349 if (DependentExplicitSpecifier)
8350 CandidateSet.DisableResolutionByPerfectCandidate();
8351 return;
8352 }
8353
8354 CandidateSet.AddDeferredTemplateCandidate(
8355 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8356 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8357 AggregateCandidateDeduction);
8358}
8359
8360bool Sema::CheckNonDependentConversions(
8361 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8362 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8363 ConversionSequenceList &Conversions,
8364 CheckNonDependentConversionsFlag UserConversionFlag,
8365 CXXRecordDecl *ActingContext, QualType ObjectType,
8366 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8367 // FIXME: The cases in which we allow explicit conversions for constructor
8368 // arguments never consider calling a constructor template. It's not clear
8369 // that is correct.
8370 const bool AllowExplicit = false;
8371
8372 bool ForOverloadSetAddressResolution =
8373 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8374 auto *FD = FunctionTemplate->getTemplatedDecl();
8375 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8376 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8377 !isa<CXXConstructorDecl>(Val: Method);
8378 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8379
8380 if (Conversions.empty())
8381 Conversions =
8382 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8383
8384 // Overload resolution is always an unevaluated context.
8385 EnterExpressionEvaluationContext Unevaluated(
8386 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8387
8388 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8389 // require that, but this check should never result in a hard error, and
8390 // overload resolution is permitted to sidestep instantiations.
8391 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8392 !ObjectType.isNull()) {
8393 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8394 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8395 !ParamTypes[0]->isDependentType()) {
8396 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8397 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8398 Method, ActingContext, /*InOverloadResolution=*/true,
8399 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8400 : QualType());
8401 if (Conversions[ConvIdx].isBad())
8402 return true;
8403 }
8404 }
8405
8406 // A speculative workaround for self-dependent constraint bugs that manifest
8407 // after CWG2369.
8408 // FIXME: Add references to the standard once P3606 is adopted.
8409 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8410 QualType ArgType) {
8411 ParamType = ParamType.getNonReferenceType();
8412 ArgType = ArgType.getNonReferenceType();
8413 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8414 if (PointerConv) {
8415 ParamType = ParamType->getPointeeType();
8416 ArgType = ArgType->getPointeeType();
8417 }
8418
8419 if (auto *RD = ParamType->getAsCXXRecordDecl();
8420 RD && RD->hasDefinition() &&
8421 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8422 auto Info = getConstructorInfo(ND);
8423 if (!Info)
8424 return false;
8425 CXXConstructorDecl *Ctor = Info.Constructor;
8426 /// isConvertingConstructor takes copy/move constructors into
8427 /// account!
8428 return !Ctor->isCopyOrMoveConstructor() &&
8429 Ctor->isConvertingConstructor(
8430 /*AllowExplicit=*/true);
8431 }))
8432 return true;
8433 if (auto *RD = ArgType->getAsCXXRecordDecl();
8434 RD && RD->hasDefinition() &&
8435 !RD->getVisibleConversionFunctions().empty())
8436 return true;
8437
8438 return false;
8439 };
8440
8441 unsigned Offset =
8442 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8443 : 0;
8444
8445 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8446 I != N; ++I) {
8447 QualType ParamType = ParamTypes[I + Offset];
8448 if (!ParamType->isDependentType()) {
8449 unsigned ConvIdx;
8450 if (PO == OverloadCandidateParamOrder::Reversed) {
8451 ConvIdx = Args.size() - 1 - I;
8452 assert(Args.size() + ThisConversions == 2 &&
8453 "number of args (including 'this') must be exactly 2 for "
8454 "reversed order");
8455 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8456 // would also be 0. 'this' got ConvIdx = 1 previously.
8457 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8458 } else {
8459 // For members, 'this' got ConvIdx = 0 previously.
8460 ConvIdx = ThisConversions + I;
8461 }
8462 if (Conversions[ConvIdx].isInitialized())
8463 continue;
8464 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8465 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8466 continue;
8467 Conversions[ConvIdx] = TryCopyInitialization(
8468 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8469 /*InOverloadResolution=*/true,
8470 /*AllowObjCWritebackConversion=*/
8471 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8472 if (Conversions[ConvIdx].isBad())
8473 return true;
8474 }
8475 }
8476
8477 return false;
8478}
8479
8480/// Determine whether this is an allowable conversion from the result
8481/// of an explicit conversion operator to the expected type, per C++
8482/// [over.match.conv]p1 and [over.match.ref]p1.
8483///
8484/// \param ConvType The return type of the conversion function.
8485///
8486/// \param ToType The type we are converting to.
8487///
8488/// \param AllowObjCPointerConversion Allow a conversion from one
8489/// Objective-C pointer to another.
8490///
8491/// \returns true if the conversion is allowable, false otherwise.
8492static bool isAllowableExplicitConversion(Sema &S,
8493 QualType ConvType, QualType ToType,
8494 bool AllowObjCPointerConversion) {
8495 QualType ToNonRefType = ToType.getNonReferenceType();
8496
8497 // Easy case: the types are the same.
8498 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8499 return true;
8500
8501 // Allow qualification conversions.
8502 bool ObjCLifetimeConversion;
8503 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8504 ObjCLifetimeConversion))
8505 return true;
8506
8507 // If we're not allowed to consider Objective-C pointer conversions,
8508 // we're done.
8509 if (!AllowObjCPointerConversion)
8510 return false;
8511
8512 // Is this an Objective-C pointer conversion?
8513 bool IncompatibleObjC = false;
8514 QualType ConvertedType;
8515 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8516 IncompatibleObjC);
8517}
8518
8519void Sema::AddConversionCandidate(
8520 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8521 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8522 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8523 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8524 assert(!Conversion->getDescribedFunctionTemplate() &&
8525 "Conversion function templates use AddTemplateConversionCandidate");
8526 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8527 if (!CandidateSet.isNewCandidate(F: Conversion))
8528 return;
8529
8530 // If the conversion function has an undeduced return type, trigger its
8531 // deduction now.
8532 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8533 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8534 return;
8535 ConvType = Conversion->getConversionType().getNonReferenceType();
8536 }
8537
8538 // If we don't allow any conversion of the result type, ignore conversion
8539 // functions that don't convert to exactly (possibly cv-qualified) T.
8540 if (!AllowResultConversion &&
8541 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8542 return;
8543
8544 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8545 // operator is only a candidate if its return type is the target type or
8546 // can be converted to the target type with a qualification conversion.
8547 //
8548 // FIXME: Include such functions in the candidate list and explain why we
8549 // can't select them.
8550 if (Conversion->isExplicit() &&
8551 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8552 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8553 return;
8554
8555 // Overload resolution is always an unevaluated context.
8556 EnterExpressionEvaluationContext Unevaluated(
8557 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8558
8559 // Add this candidate
8560 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8561 Candidate.FoundDecl = FoundDecl;
8562 Candidate.Function = Conversion;
8563 Candidate.FinalConversion.setAsIdentityConversion();
8564 Candidate.FinalConversion.setFromType(ConvType);
8565 Candidate.FinalConversion.setAllToTypes(ToType);
8566 Candidate.HasFinalConversion = true;
8567 Candidate.Viable = true;
8568 Candidate.ExplicitCallArguments = 1;
8569 Candidate.StrictPackMatch = StrictPackMatch;
8570
8571 // Explicit functions are not actually candidates at all if we're not
8572 // allowing them in this context, but keep them around so we can point
8573 // to them in diagnostics.
8574 if (!AllowExplicit && Conversion->isExplicit()) {
8575 Candidate.Viable = false;
8576 Candidate.FailureKind = ovl_fail_explicit;
8577 return;
8578 }
8579
8580 // C++ [over.match.funcs]p4:
8581 // For conversion functions, the function is considered to be a member of
8582 // the class of the implicit implied object argument for the purpose of
8583 // defining the type of the implicit object parameter.
8584 //
8585 // Determine the implicit conversion sequence for the implicit
8586 // object parameter.
8587 QualType ObjectType = From->getType();
8588 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8589 ObjectType = FromPtrType->getPointeeType();
8590 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8591 // C++23 [over.best.ics.general]
8592 // However, if the target is [...]
8593 // - the object parameter of a user-defined conversion function
8594 // [...] user-defined conversion sequences are not considered.
8595 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8596 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8597 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8598 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8599 /*SuppressUserConversion*/ true);
8600
8601 if (Candidate.Conversions[0].isBad()) {
8602 Candidate.Viable = false;
8603 Candidate.FailureKind = ovl_fail_bad_conversion;
8604 return;
8605 }
8606
8607 if (Conversion->getTrailingRequiresClause()) {
8608 ConstraintSatisfaction Satisfaction;
8609 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8610 !Satisfaction.IsSatisfied) {
8611 Candidate.Viable = false;
8612 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8613 return;
8614 }
8615 }
8616
8617 // We won't go through a user-defined type conversion function to convert a
8618 // derived to base as such conversions are given Conversion Rank. They only
8619 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8620 QualType FromCanon
8621 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8622 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8623 if (FromCanon == ToCanon ||
8624 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8625 Candidate.Viable = false;
8626 Candidate.FailureKind = ovl_fail_trivial_conversion;
8627 return;
8628 }
8629
8630 // To determine what the conversion from the result of calling the
8631 // conversion function to the type we're eventually trying to
8632 // convert to (ToType), we need to synthesize a call to the
8633 // conversion function and attempt copy initialization from it. This
8634 // makes sure that we get the right semantics with respect to
8635 // lvalues/rvalues and the type. Fortunately, we can allocate this
8636 // call on the stack and we don't need its arguments to be
8637 // well-formed.
8638 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8639 VK_LValue, From->getBeginLoc());
8640 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8641 Context.getPointerType(T: Conversion->getType()),
8642 CK_FunctionToPointerDecay, &ConversionRef,
8643 VK_PRValue, FPOptionsOverride());
8644
8645 QualType ConversionType = Conversion->getConversionType();
8646 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8647 Candidate.Viable = false;
8648 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8649 return;
8650 }
8651
8652 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8653
8654 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8655
8656 // Introduce a temporary expression with the right type and value category
8657 // that we can use for deduction purposes.
8658 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8659
8660 ImplicitConversionSequence ICS =
8661 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8662 /*SuppressUserConversions=*/true,
8663 /*InOverloadResolution=*/false,
8664 /*AllowObjCWritebackConversion=*/false);
8665
8666 switch (ICS.getKind()) {
8667 case ImplicitConversionSequence::StandardConversion:
8668 Candidate.FinalConversion = ICS.Standard;
8669 Candidate.HasFinalConversion = true;
8670
8671 // C++ [over.ics.user]p3:
8672 // If the user-defined conversion is specified by a specialization of a
8673 // conversion function template, the second standard conversion sequence
8674 // shall have exact match rank.
8675 if (Conversion->getPrimaryTemplate() &&
8676 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8677 Candidate.Viable = false;
8678 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8679 return;
8680 }
8681
8682 // C++0x [dcl.init.ref]p5:
8683 // In the second case, if the reference is an rvalue reference and
8684 // the second standard conversion sequence of the user-defined
8685 // conversion sequence includes an lvalue-to-rvalue conversion, the
8686 // program is ill-formed.
8687 if (ToType->isRValueReferenceType() &&
8688 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8689 Candidate.Viable = false;
8690 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8691 return;
8692 }
8693 break;
8694
8695 case ImplicitConversionSequence::BadConversion:
8696 Candidate.Viable = false;
8697 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8698 return;
8699
8700 default:
8701 llvm_unreachable(
8702 "Can only end up with a standard conversion sequence or failure");
8703 }
8704
8705 if (EnableIfAttr *FailedAttr =
8706 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8707 Candidate.Viable = false;
8708 Candidate.FailureKind = ovl_fail_enable_if;
8709 Candidate.DeductionFailure.Data = FailedAttr;
8710 return;
8711 }
8712
8713 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8714 Candidate.Viable = false;
8715 Candidate.FailureKind = ovl_non_default_multiversion_function;
8716 }
8717}
8718
8719static void AddTemplateConversionCandidateImmediately(
8720 Sema &S, OverloadCandidateSet &CandidateSet,
8721 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8722 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8723 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8724 bool AllowResultConversion) {
8725
8726 // If the function template has a non-dependent explicit specification,
8727 // exclude it now if appropriate; we are not permitted to perform deduction
8728 // and substitution in this case.
8729 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8730 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8731 Candidate.FoundDecl = FoundDecl;
8732 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8733 Candidate.Viable = false;
8734 Candidate.FailureKind = ovl_fail_explicit;
8735 return;
8736 }
8737
8738 QualType ObjectType = From->getType();
8739 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8740
8741 TemplateDeductionInfo Info(CandidateSet.getLocation());
8742 CXXConversionDecl *Specialization = nullptr;
8743 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8744 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8745 Specialization, Info);
8746 Result != TemplateDeductionResult::Success) {
8747 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8748 Candidate.FoundDecl = FoundDecl;
8749 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8750 Candidate.Viable = false;
8751 Candidate.FailureKind = ovl_fail_bad_deduction;
8752 Candidate.ExplicitCallArguments = 1;
8753 Candidate.DeductionFailure =
8754 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8755 return;
8756 }
8757
8758 // Add the conversion function template specialization produced by
8759 // template argument deduction as a candidate.
8760 assert(Specialization && "Missing function template specialization?");
8761 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8762 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8763 AllowExplicit, AllowResultConversion,
8764 StrictPackMatch: Info.hasStrictPackMatch());
8765}
8766
8767void Sema::AddTemplateConversionCandidate(
8768 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8769 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8770 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8771 bool AllowExplicit, bool AllowResultConversion) {
8772 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8773 "Only conversion function templates permitted here");
8774
8775 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8776 return;
8777
8778 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8779 CandidateSet.getKind() ==
8780 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8781 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8782 AddTemplateConversionCandidateImmediately(
8783 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8784 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8785 AllowResultConversion);
8786
8787 CandidateSet.DisableResolutionByPerfectCandidate();
8788 return;
8789 }
8790
8791 CandidateSet.AddDeferredConversionTemplateCandidate(
8792 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8793 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8794}
8795
8796void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8797 DeclAccessPair FoundDecl,
8798 CXXRecordDecl *ActingContext,
8799 const FunctionProtoType *Proto,
8800 Expr *Object,
8801 ArrayRef<Expr *> Args,
8802 OverloadCandidateSet& CandidateSet) {
8803 if (!CandidateSet.isNewCandidate(F: Conversion))
8804 return;
8805
8806 // Overload resolution is always an unevaluated context.
8807 EnterExpressionEvaluationContext Unevaluated(
8808 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8809
8810 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8811 Candidate.FoundDecl = FoundDecl;
8812 Candidate.Function = nullptr;
8813 Candidate.Surrogate = Conversion;
8814 Candidate.IsSurrogate = true;
8815 Candidate.Viable = true;
8816 Candidate.ExplicitCallArguments = Args.size();
8817
8818 // Determine the implicit conversion sequence for the implicit
8819 // object parameter.
8820 ImplicitConversionSequence ObjectInit;
8821 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8822 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8823 ToType: Conversion->getParamDecl(i: 0)->getType(),
8824 /*SuppressUserConversions=*/false,
8825 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8826 } else {
8827 ObjectInit = TryObjectArgumentInitialization(
8828 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8829 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8830 }
8831
8832 if (ObjectInit.isBad()) {
8833 Candidate.Viable = false;
8834 Candidate.FailureKind = ovl_fail_bad_conversion;
8835 Candidate.Conversions[0] = ObjectInit;
8836 return;
8837 }
8838
8839 // The first conversion is actually a user-defined conversion whose
8840 // first conversion is ObjectInit's standard conversion (which is
8841 // effectively a reference binding). Record it as such.
8842 Candidate.Conversions[0].setUserDefined();
8843 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8844 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8845 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8846 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8847 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8848 Candidate.Conversions[0].UserDefined.After
8849 = Candidate.Conversions[0].UserDefined.Before;
8850 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8851
8852 // Find the
8853 unsigned NumParams = Proto->getNumParams();
8854
8855 // (C++ 13.3.2p2): A candidate function having fewer than m
8856 // parameters is viable only if it has an ellipsis in its parameter
8857 // list (8.3.5).
8858 if (Args.size() > NumParams && !Proto->isVariadic()) {
8859 Candidate.Viable = false;
8860 Candidate.FailureKind = ovl_fail_too_many_arguments;
8861 return;
8862 }
8863
8864 // Function types don't have any default arguments, so just check if
8865 // we have enough arguments.
8866 if (Args.size() < NumParams) {
8867 // Not enough arguments.
8868 Candidate.Viable = false;
8869 Candidate.FailureKind = ovl_fail_too_few_arguments;
8870 return;
8871 }
8872
8873 // Determine the implicit conversion sequences for each of the
8874 // arguments.
8875 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8876 if (ArgIdx < NumParams) {
8877 // (C++ 13.3.2p3): for F to be a viable function, there shall
8878 // exist for each argument an implicit conversion sequence
8879 // (13.3.3.1) that converts that argument to the corresponding
8880 // parameter of F.
8881 QualType ParamType = Proto->getParamType(i: ArgIdx);
8882 Candidate.Conversions[ArgIdx + 1]
8883 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8884 /*SuppressUserConversions=*/false,
8885 /*InOverloadResolution=*/false,
8886 /*AllowObjCWritebackConversion=*/
8887 getLangOpts().ObjCAutoRefCount);
8888 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8889 Candidate.Viable = false;
8890 Candidate.FailureKind = ovl_fail_bad_conversion;
8891 return;
8892 }
8893 } else {
8894 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8895 // argument for which there is no corresponding parameter is
8896 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8897 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8898 }
8899 }
8900
8901 if (Conversion->getTrailingRequiresClause()) {
8902 ConstraintSatisfaction Satisfaction;
8903 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8904 /*ForOverloadResolution*/ true) ||
8905 !Satisfaction.IsSatisfied) {
8906 Candidate.Viable = false;
8907 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8908 return;
8909 }
8910 }
8911
8912 if (EnableIfAttr *FailedAttr =
8913 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8914 Candidate.Viable = false;
8915 Candidate.FailureKind = ovl_fail_enable_if;
8916 Candidate.DeductionFailure.Data = FailedAttr;
8917 return;
8918 }
8919}
8920
8921void Sema::AddNonMemberOperatorCandidates(
8922 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8923 OverloadCandidateSet &CandidateSet,
8924 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8925 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8926 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8927 ArrayRef<Expr *> FunctionArgs = Args;
8928
8929 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8930 FunctionDecl *FD =
8931 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8932
8933 // Don't consider rewritten functions if we're not rewriting.
8934 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8935 continue;
8936
8937 assert(!isa<CXXMethodDecl>(FD) &&
8938 "unqualified operator lookup found a member function");
8939
8940 if (FunTmpl) {
8941 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8942 Args: FunctionArgs, CandidateSet);
8943 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8944
8945 // As template candidates are not deduced immediately,
8946 // persist the array in the overload set.
8947 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8948 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8949 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8950 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8951 IsADLCandidate: ADLCallKind::NotADL,
8952 PO: OverloadCandidateParamOrder::Reversed);
8953 }
8954 } else {
8955 if (ExplicitTemplateArgs)
8956 continue;
8957 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8958 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8959 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8960 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8961 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8962 PO: OverloadCandidateParamOrder::Reversed);
8963 }
8964 }
8965}
8966
8967void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8968 SourceLocation OpLoc,
8969 ArrayRef<Expr *> Args,
8970 OverloadCandidateSet &CandidateSet,
8971 OverloadCandidateParamOrder PO) {
8972 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8973
8974 // C++ [over.match.oper]p3:
8975 // For a unary operator @ with an operand of a type whose
8976 // cv-unqualified version is T1, and for a binary operator @ with
8977 // a left operand of a type whose cv-unqualified version is T1 and
8978 // a right operand of a type whose cv-unqualified version is T2,
8979 // three sets of candidate functions, designated member
8980 // candidates, non-member candidates and built-in candidates, are
8981 // constructed as follows:
8982 QualType T1 = Args[0]->getType();
8983
8984 // -- If T1 is a complete class type or a class currently being
8985 // defined, the set of member candidates is the result of the
8986 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8987 // the set of member candidates is empty.
8988 if (T1->isRecordType()) {
8989 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
8990 auto *T1RD = T1->getAsCXXRecordDecl();
8991 // Complete the type if it can be completed.
8992 // If the type is neither complete nor being defined, bail out now.
8993 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8994 return;
8995
8996 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8997 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
8998 Operators.suppressAccessDiagnostics();
8999
9000 for (LookupResult::iterator Oper = Operators.begin(),
9001 OperEnd = Operators.end();
9002 Oper != OperEnd; ++Oper) {
9003 if (Oper->getAsFunction() &&
9004 PO == OverloadCandidateParamOrder::Reversed &&
9005 !CandidateSet.getRewriteInfo().shouldAddReversed(
9006 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
9007 continue;
9008 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
9009 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
9010 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
9011 }
9012 }
9013}
9014
9015void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
9016 OverloadCandidateSet& CandidateSet,
9017 bool IsAssignmentOperator,
9018 unsigned NumContextualBoolArguments) {
9019 // Overload resolution is always an unevaluated context.
9020 EnterExpressionEvaluationContext Unevaluated(
9021 *this, Sema::ExpressionEvaluationContext::Unevaluated);
9022
9023 // Add this candidate
9024 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
9025 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
9026 Candidate.Function = nullptr;
9027 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
9028
9029 // Determine the implicit conversion sequences for each of the
9030 // arguments.
9031 Candidate.Viable = true;
9032 Candidate.ExplicitCallArguments = Args.size();
9033 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9034 // C++ [over.match.oper]p4:
9035 // For the built-in assignment operators, conversions of the
9036 // left operand are restricted as follows:
9037 // -- no temporaries are introduced to hold the left operand, and
9038 // -- no user-defined conversions are applied to the left
9039 // operand to achieve a type match with the left-most
9040 // parameter of a built-in candidate.
9041 //
9042 // We block these conversions by turning off user-defined
9043 // conversions, since that is the only way that initialization of
9044 // a reference to a non-class type can occur from something that
9045 // is not of the same type.
9046 if (ArgIdx < NumContextualBoolArguments) {
9047 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9048 "Contextual conversion to bool requires bool type");
9049 Candidate.Conversions[ArgIdx]
9050 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9051 } else {
9052 Candidate.Conversions[ArgIdx]
9053 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9054 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9055 /*InOverloadResolution=*/false,
9056 /*AllowObjCWritebackConversion=*/
9057 getLangOpts().ObjCAutoRefCount);
9058 }
9059 if (Candidate.Conversions[ArgIdx].isBad()) {
9060 Candidate.Viable = false;
9061 Candidate.FailureKind = ovl_fail_bad_conversion;
9062 break;
9063 }
9064 }
9065}
9066
9067namespace {
9068
9069/// BuiltinCandidateTypeSet - A set of types that will be used for the
9070/// candidate operator functions for built-in operators (C++
9071/// [over.built]). The types are separated into pointer types and
9072/// enumeration types.
9073class BuiltinCandidateTypeSet {
9074 /// TypeSet - A set of types.
9075 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9076
9077 /// PointerTypes - The set of pointer types that will be used in the
9078 /// built-in candidates.
9079 TypeSet PointerTypes;
9080
9081 /// MemberPointerTypes - The set of member pointer types that will be
9082 /// used in the built-in candidates.
9083 TypeSet MemberPointerTypes;
9084
9085 /// EnumerationTypes - The set of enumeration types that will be
9086 /// used in the built-in candidates.
9087 TypeSet EnumerationTypes;
9088
9089 /// The set of vector types that will be used in the built-in
9090 /// candidates.
9091 TypeSet VectorTypes;
9092
9093 /// The set of matrix types that will be used in the built-in
9094 /// candidates.
9095 TypeSet MatrixTypes;
9096
9097 /// The set of _BitInt types that will be used in the built-in candidates.
9098 TypeSet BitIntTypes;
9099
9100 /// A flag indicating non-record types are viable candidates
9101 bool HasNonRecordTypes;
9102
9103 /// A flag indicating whether either arithmetic or enumeration types
9104 /// were present in the candidate set.
9105 bool HasArithmeticOrEnumeralTypes;
9106
9107 /// A flag indicating whether the nullptr type was present in the
9108 /// candidate set.
9109 bool HasNullPtrType;
9110
9111 /// Sema - The semantic analysis instance where we are building the
9112 /// candidate type set.
9113 Sema &SemaRef;
9114
9115 /// Context - The AST context in which we will build the type sets.
9116 ASTContext &Context;
9117
9118 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9119 const Qualifiers &VisibleQuals);
9120 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9121
9122public:
9123 /// iterator - Iterates through the types that are part of the set.
9124 typedef TypeSet::iterator iterator;
9125
9126 BuiltinCandidateTypeSet(Sema &SemaRef)
9127 : HasNonRecordTypes(false),
9128 HasArithmeticOrEnumeralTypes(false),
9129 HasNullPtrType(false),
9130 SemaRef(SemaRef),
9131 Context(SemaRef.Context) { }
9132
9133 void AddTypesConvertedFrom(QualType Ty,
9134 SourceLocation Loc,
9135 bool AllowUserConversions,
9136 bool AllowExplicitConversions,
9137 const Qualifiers &VisibleTypeConversionsQuals);
9138
9139 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9140 llvm::iterator_range<iterator> member_pointer_types() {
9141 return MemberPointerTypes;
9142 }
9143 llvm::iterator_range<iterator> enumeration_types() {
9144 return EnumerationTypes;
9145 }
9146 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9147 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9148 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9149
9150 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9151 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9152 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9153 bool hasNullPtrType() const { return HasNullPtrType; }
9154};
9155
9156} // end anonymous namespace
9157
9158/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9159/// the set of pointer types along with any more-qualified variants of
9160/// that type. For example, if @p Ty is "int const *", this routine
9161/// will add "int const *", "int const volatile *", "int const
9162/// restrict *", and "int const volatile restrict *" to the set of
9163/// pointer types. Returns true if the add of @p Ty itself succeeded,
9164/// false otherwise.
9165///
9166/// FIXME: what to do about extended qualifiers?
9167bool
9168BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9169 const Qualifiers &VisibleQuals) {
9170
9171 // Insert this type.
9172 if (!PointerTypes.insert(X: Ty))
9173 return false;
9174
9175 QualType PointeeTy;
9176 const PointerType *PointerTy = Ty->getAs<PointerType>();
9177 bool buildObjCPtr = false;
9178 if (!PointerTy) {
9179 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9180 PointeeTy = PTy->getPointeeType();
9181 buildObjCPtr = true;
9182 } else {
9183 PointeeTy = PointerTy->getPointeeType();
9184 }
9185
9186 // Don't add qualified variants of arrays. For one, they're not allowed
9187 // (the qualifier would sink to the element type), and for another, the
9188 // only overload situation where it matters is subscript or pointer +- int,
9189 // and those shouldn't have qualifier variants anyway.
9190 if (PointeeTy->isArrayType())
9191 return true;
9192
9193 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9194 bool hasVolatile = VisibleQuals.hasVolatile();
9195 bool hasRestrict = VisibleQuals.hasRestrict();
9196
9197 // Iterate through all strict supersets of BaseCVR.
9198 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9199 if ((CVR | BaseCVR) != CVR) continue;
9200 // Skip over volatile if no volatile found anywhere in the types.
9201 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9202
9203 // Skip over restrict if no restrict found anywhere in the types, or if
9204 // the type cannot be restrict-qualified.
9205 if ((CVR & Qualifiers::Restrict) &&
9206 (!hasRestrict ||
9207 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9208 continue;
9209
9210 // Build qualified pointee type.
9211 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9212
9213 // Build qualified pointer type.
9214 QualType QPointerTy;
9215 if (!buildObjCPtr)
9216 QPointerTy = Context.getPointerType(T: QPointeeTy);
9217 else
9218 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9219
9220 // Insert qualified pointer type.
9221 PointerTypes.insert(X: QPointerTy);
9222 }
9223
9224 return true;
9225}
9226
9227/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9228/// to the set of pointer types along with any more-qualified variants of
9229/// that type. For example, if @p Ty is "int const *", this routine
9230/// will add "int const *", "int const volatile *", "int const
9231/// restrict *", and "int const volatile restrict *" to the set of
9232/// pointer types. Returns true if the add of @p Ty itself succeeded,
9233/// false otherwise.
9234///
9235/// FIXME: what to do about extended qualifiers?
9236bool
9237BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9238 QualType Ty) {
9239 // Insert this type.
9240 if (!MemberPointerTypes.insert(X: Ty))
9241 return false;
9242
9243 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9244 assert(PointerTy && "type was not a member pointer type!");
9245
9246 QualType PointeeTy = PointerTy->getPointeeType();
9247 // Don't add qualified variants of arrays. For one, they're not allowed
9248 // (the qualifier would sink to the element type), and for another, the
9249 // only overload situation where it matters is subscript or pointer +- int,
9250 // and those shouldn't have qualifier variants anyway.
9251 if (PointeeTy->isArrayType())
9252 return true;
9253 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9254
9255 // Iterate through all strict supersets of the pointee type's CVR
9256 // qualifiers.
9257 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9258 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9259 if ((CVR | BaseCVR) != CVR) continue;
9260
9261 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9262 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9263 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9264 }
9265
9266 return true;
9267}
9268
9269/// AddTypesConvertedFrom - Add each of the types to which the type @p
9270/// Ty can be implicit converted to the given set of @p Types. We're
9271/// primarily interested in pointer types and enumeration types. We also
9272/// take member pointer types, for the conditional operator.
9273/// AllowUserConversions is true if we should look at the conversion
9274/// functions of a class type, and AllowExplicitConversions if we
9275/// should also include the explicit conversion functions of a class
9276/// type.
9277void
9278BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9279 SourceLocation Loc,
9280 bool AllowUserConversions,
9281 bool AllowExplicitConversions,
9282 const Qualifiers &VisibleQuals) {
9283 // Only deal with canonical types.
9284 Ty = Context.getCanonicalType(T: Ty);
9285
9286 // Look through reference types; they aren't part of the type of an
9287 // expression for the purposes of conversions.
9288 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9289 Ty = RefTy->getPointeeType();
9290
9291 // If we're dealing with an array type, decay to the pointer.
9292 if (Ty->isArrayType())
9293 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9294
9295 // Otherwise, we don't care about qualifiers on the type.
9296 Ty = Ty.getLocalUnqualifiedType();
9297
9298 // Flag if we ever add a non-record type.
9299 bool TyIsRec = Ty->isRecordType();
9300 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9301
9302 // Flag if we encounter an arithmetic type.
9303 HasArithmeticOrEnumeralTypes =
9304 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9305
9306 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9307 PointerTypes.insert(X: Ty);
9308 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9309 // Insert our type, and its more-qualified variants, into the set
9310 // of types.
9311 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9312 return;
9313 } else if (Ty->isMemberPointerType()) {
9314 // Member pointers are far easier, since the pointee can't be converted.
9315 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9316 return;
9317 } else if (Ty->isEnumeralType()) {
9318 HasArithmeticOrEnumeralTypes = true;
9319 EnumerationTypes.insert(X: Ty);
9320 } else if (Ty->isBitIntType()) {
9321 HasArithmeticOrEnumeralTypes = true;
9322 BitIntTypes.insert(X: Ty);
9323 } else if (Ty->isVectorType()) {
9324 // We treat vector types as arithmetic types in many contexts as an
9325 // extension.
9326 HasArithmeticOrEnumeralTypes = true;
9327 VectorTypes.insert(X: Ty);
9328 } else if (Ty->isMatrixType()) {
9329 // Similar to vector types, we treat vector types as arithmetic types in
9330 // many contexts as an extension.
9331 HasArithmeticOrEnumeralTypes = true;
9332 MatrixTypes.insert(X: Ty);
9333 } else if (Ty->isNullPtrType()) {
9334 HasNullPtrType = true;
9335 } else if (AllowUserConversions && TyIsRec) {
9336 // No conversion functions in incomplete types.
9337 if (!SemaRef.isCompleteType(Loc, T: Ty))
9338 return;
9339
9340 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9341 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9342 if (isa<UsingShadowDecl>(Val: D))
9343 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9344
9345 // Skip conversion function templates; they don't tell us anything
9346 // about which builtin types we can convert to.
9347 if (isa<FunctionTemplateDecl>(Val: D))
9348 continue;
9349
9350 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9351 if (AllowExplicitConversions || !Conv->isExplicit()) {
9352 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9353 VisibleQuals);
9354 }
9355 }
9356 }
9357}
9358/// Helper function for adjusting address spaces for the pointer or reference
9359/// operands of builtin operators depending on the argument.
9360static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9361 Expr *Arg) {
9362 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9363}
9364
9365/// Helper function for AddBuiltinOperatorCandidates() that adds
9366/// the volatile- and non-volatile-qualified assignment operators for the
9367/// given type to the candidate set.
9368static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9369 QualType T,
9370 ArrayRef<Expr *> Args,
9371 OverloadCandidateSet &CandidateSet) {
9372 QualType ParamTypes[2];
9373
9374 // T& operator=(T&, T)
9375 ParamTypes[0] = S.Context.getLValueReferenceType(
9376 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9377 ParamTypes[1] = T;
9378 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9379 /*IsAssignmentOperator=*/true);
9380
9381 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9382 // volatile T& operator=(volatile T&, T)
9383 ParamTypes[0] = S.Context.getLValueReferenceType(
9384 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9385 Arg: Args[0]));
9386 ParamTypes[1] = T;
9387 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9388 /*IsAssignmentOperator=*/true);
9389 }
9390}
9391
9392/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9393/// if any, found in visible type conversion functions found in ArgExpr's type.
9394static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9395 Qualifiers VRQuals;
9396 CXXRecordDecl *ClassDecl;
9397 if (const MemberPointerType *RHSMPType =
9398 ArgExpr->getType()->getAs<MemberPointerType>())
9399 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9400 else
9401 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9402 if (!ClassDecl) {
9403 // Just to be safe, assume the worst case.
9404 VRQuals.addVolatile();
9405 VRQuals.addRestrict();
9406 return VRQuals;
9407 }
9408 if (!ClassDecl->hasDefinition())
9409 return VRQuals;
9410
9411 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9412 if (isa<UsingShadowDecl>(Val: D))
9413 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9414 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9415 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9416 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9417 CanTy = ResTypeRef->getPointeeType();
9418 // Need to go down the pointer/mempointer chain and add qualifiers
9419 // as see them.
9420 bool done = false;
9421 while (!done) {
9422 if (CanTy.isRestrictQualified())
9423 VRQuals.addRestrict();
9424 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9425 CanTy = ResTypePtr->getPointeeType();
9426 else if (const MemberPointerType *ResTypeMPtr =
9427 CanTy->getAs<MemberPointerType>())
9428 CanTy = ResTypeMPtr->getPointeeType();
9429 else
9430 done = true;
9431 if (CanTy.isVolatileQualified())
9432 VRQuals.addVolatile();
9433 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9434 return VRQuals;
9435 }
9436 }
9437 }
9438 return VRQuals;
9439}
9440
9441// Note: We're currently only handling qualifiers that are meaningful for the
9442// LHS of compound assignment overloading.
9443static void forAllQualifierCombinationsImpl(
9444 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9445 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9446 // _Atomic
9447 if (Available.hasAtomic()) {
9448 Available.removeAtomic();
9449 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9450 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9451 return;
9452 }
9453
9454 // volatile
9455 if (Available.hasVolatile()) {
9456 Available.removeVolatile();
9457 assert(!Applied.hasVolatile());
9458 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9459 Callback);
9460 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9461 return;
9462 }
9463
9464 Callback(Applied);
9465}
9466
9467static void forAllQualifierCombinations(
9468 QualifiersAndAtomic Quals,
9469 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9470 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9471 Callback);
9472}
9473
9474static QualType makeQualifiedLValueReferenceType(QualType Base,
9475 QualifiersAndAtomic Quals,
9476 Sema &S) {
9477 if (Quals.hasAtomic())
9478 Base = S.Context.getAtomicType(T: Base);
9479 if (Quals.hasVolatile())
9480 Base = S.Context.getVolatileType(T: Base);
9481 return S.Context.getLValueReferenceType(T: Base);
9482}
9483
9484namespace {
9485
9486/// Helper class to manage the addition of builtin operator overload
9487/// candidates. It provides shared state and utility methods used throughout
9488/// the process, as well as a helper method to add each group of builtin
9489/// operator overloads from the standard to a candidate set.
9490class BuiltinOperatorOverloadBuilder {
9491 // Common instance state available to all overload candidate addition methods.
9492 Sema &S;
9493 ArrayRef<Expr *> Args;
9494 QualifiersAndAtomic VisibleTypeConversionsQuals;
9495 bool HasArithmeticOrEnumeralCandidateType;
9496 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9497 OverloadCandidateSet &CandidateSet;
9498
9499 static constexpr int ArithmeticTypesCap = 26;
9500 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9501
9502 // Define some indices used to iterate over the arithmetic types in
9503 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9504 // types are that preserved by promotion (C++ [over.built]p2).
9505 unsigned FirstIntegralType,
9506 LastIntegralType;
9507 unsigned FirstPromotedIntegralType,
9508 LastPromotedIntegralType;
9509 unsigned FirstPromotedArithmeticType,
9510 LastPromotedArithmeticType;
9511 unsigned NumArithmeticTypes;
9512
9513 void InitArithmeticTypes() {
9514 // Start of promoted types.
9515 FirstPromotedArithmeticType = 0;
9516 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9517 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9518 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9519 if (S.Context.getTargetInfo().hasFloat128Type())
9520 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9521 if (S.Context.getTargetInfo().hasIbm128Type())
9522 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9523
9524 // Start of integral types.
9525 FirstIntegralType = ArithmeticTypes.size();
9526 FirstPromotedIntegralType = ArithmeticTypes.size();
9527 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9528 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9529 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9530 if (S.Context.getTargetInfo().hasInt128Type() ||
9531 (S.Context.getAuxTargetInfo() &&
9532 S.Context.getAuxTargetInfo()->hasInt128Type()))
9533 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9534 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9535 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9536 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9537 if (S.Context.getTargetInfo().hasInt128Type() ||
9538 (S.Context.getAuxTargetInfo() &&
9539 S.Context.getAuxTargetInfo()->hasInt128Type()))
9540 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9541
9542 /// We add candidates for the unique, unqualified _BitInt types present in
9543 /// the candidate type set. The candidate set already handled ensuring the
9544 /// type is unqualified and canonical, but because we're adding from N
9545 /// different sets, we need to do some extra work to unique things. Insert
9546 /// the candidates into a unique set, then move from that set into the list
9547 /// of arithmetic types.
9548 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9549 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9550 for (QualType BitTy : Candidate.bitint_types())
9551 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9552 }
9553 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9554 LastPromotedIntegralType = ArithmeticTypes.size();
9555 LastPromotedArithmeticType = ArithmeticTypes.size();
9556 // End of promoted types.
9557
9558 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9559 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9560 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9561 if (S.Context.getLangOpts().Char8)
9562 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9563 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9564 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9565 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9566 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9567 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9568 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9569 LastIntegralType = ArithmeticTypes.size();
9570 NumArithmeticTypes = ArithmeticTypes.size();
9571 // End of integral types.
9572 // FIXME: What about complex? What about half?
9573
9574 // We don't know for sure how many bit-precise candidates were involved, so
9575 // we subtract those from the total when testing whether we're under the
9576 // cap or not.
9577 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9578 ArithmeticTypesCap &&
9579 "Enough inline storage for all arithmetic types.");
9580 }
9581
9582 /// Helper method to factor out the common pattern of adding overloads
9583 /// for '++' and '--' builtin operators.
9584 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9585 bool HasVolatile,
9586 bool HasRestrict) {
9587 QualType ParamTypes[2] = {
9588 S.Context.getLValueReferenceType(T: CandidateTy),
9589 S.Context.IntTy
9590 };
9591
9592 // Non-volatile version.
9593 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9594
9595 // Use a heuristic to reduce number of builtin candidates in the set:
9596 // add volatile version only if there are conversions to a volatile type.
9597 if (HasVolatile) {
9598 ParamTypes[0] =
9599 S.Context.getLValueReferenceType(
9600 T: S.Context.getVolatileType(T: CandidateTy));
9601 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9602 }
9603
9604 // Add restrict version only if there are conversions to a restrict type
9605 // and our candidate type is a non-restrict-qualified pointer.
9606 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9607 !CandidateTy.isRestrictQualified()) {
9608 ParamTypes[0]
9609 = S.Context.getLValueReferenceType(
9610 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9611 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9612
9613 if (HasVolatile) {
9614 ParamTypes[0]
9615 = S.Context.getLValueReferenceType(
9616 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9617 CVR: (Qualifiers::Volatile |
9618 Qualifiers::Restrict)));
9619 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9620 }
9621 }
9622
9623 }
9624
9625 /// Helper to add an overload candidate for a binary builtin with types \p L
9626 /// and \p R.
9627 void AddCandidate(QualType L, QualType R) {
9628 QualType LandR[2] = {L, R};
9629 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9630 }
9631
9632public:
9633 BuiltinOperatorOverloadBuilder(
9634 Sema &S, ArrayRef<Expr *> Args,
9635 QualifiersAndAtomic VisibleTypeConversionsQuals,
9636 bool HasArithmeticOrEnumeralCandidateType,
9637 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9638 OverloadCandidateSet &CandidateSet)
9639 : S(S), Args(Args),
9640 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9641 HasArithmeticOrEnumeralCandidateType(
9642 HasArithmeticOrEnumeralCandidateType),
9643 CandidateTypes(CandidateTypes),
9644 CandidateSet(CandidateSet) {
9645
9646 InitArithmeticTypes();
9647 }
9648
9649 // Increment is deprecated for bool since C++17.
9650 //
9651 // C++ [over.built]p3:
9652 //
9653 // For every pair (T, VQ), where T is an arithmetic type other
9654 // than bool, and VQ is either volatile or empty, there exist
9655 // candidate operator functions of the form
9656 //
9657 // VQ T& operator++(VQ T&);
9658 // T operator++(VQ T&, int);
9659 //
9660 // C++ [over.built]p4:
9661 //
9662 // For every pair (T, VQ), where T is an arithmetic type other
9663 // than bool, and VQ is either volatile or empty, there exist
9664 // candidate operator functions of the form
9665 //
9666 // VQ T& operator--(VQ T&);
9667 // T operator--(VQ T&, int);
9668 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9669 if (!HasArithmeticOrEnumeralCandidateType)
9670 return;
9671
9672 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9673 const auto TypeOfT = ArithmeticTypes[Arith];
9674 if (TypeOfT == S.Context.BoolTy) {
9675 if (Op == OO_MinusMinus)
9676 continue;
9677 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9678 continue;
9679 }
9680 addPlusPlusMinusMinusStyleOverloads(
9681 CandidateTy: TypeOfT,
9682 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9683 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9684 }
9685 }
9686
9687 // C++ [over.built]p5:
9688 //
9689 // For every pair (T, VQ), where T is a cv-qualified or
9690 // cv-unqualified object type, and VQ is either volatile or
9691 // empty, there exist candidate operator functions of the form
9692 //
9693 // T*VQ& operator++(T*VQ&);
9694 // T*VQ& operator--(T*VQ&);
9695 // T* operator++(T*VQ&, int);
9696 // T* operator--(T*VQ&, int);
9697 void addPlusPlusMinusMinusPointerOverloads() {
9698 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9699 // Skip pointer types that aren't pointers to object types.
9700 if (!PtrTy->getPointeeType()->isObjectType())
9701 continue;
9702
9703 addPlusPlusMinusMinusStyleOverloads(
9704 CandidateTy: PtrTy,
9705 HasVolatile: (!PtrTy.isVolatileQualified() &&
9706 VisibleTypeConversionsQuals.hasVolatile()),
9707 HasRestrict: (!PtrTy.isRestrictQualified() &&
9708 VisibleTypeConversionsQuals.hasRestrict()));
9709 }
9710 }
9711
9712 // C++ [over.built]p6:
9713 // For every cv-qualified or cv-unqualified object type T, there
9714 // exist candidate operator functions of the form
9715 //
9716 // T& operator*(T*);
9717 //
9718 // C++ [over.built]p7:
9719 // For every function type T that does not have cv-qualifiers or a
9720 // ref-qualifier, there exist candidate operator functions of the form
9721 // T& operator*(T*);
9722 void addUnaryStarPointerOverloads() {
9723 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9724 QualType PointeeTy = ParamTy->getPointeeType();
9725 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9726 continue;
9727
9728 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9729 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9730 continue;
9731
9732 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9733 }
9734 }
9735
9736 // C++ [over.built]p9:
9737 // For every promoted arithmetic type T, there exist candidate
9738 // operator functions of the form
9739 //
9740 // T operator+(T);
9741 // T operator-(T);
9742 void addUnaryPlusOrMinusArithmeticOverloads() {
9743 if (!HasArithmeticOrEnumeralCandidateType)
9744 return;
9745
9746 for (unsigned Arith = FirstPromotedArithmeticType;
9747 Arith < LastPromotedArithmeticType; ++Arith) {
9748 QualType ArithTy = ArithmeticTypes[Arith];
9749 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9750 }
9751
9752 // Extension: We also add these operators for vector types.
9753 for (QualType VecTy : CandidateTypes[0].vector_types())
9754 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9755 }
9756
9757 // C++ [over.built]p8:
9758 // For every type T, there exist candidate operator functions of
9759 // the form
9760 //
9761 // T* operator+(T*);
9762 void addUnaryPlusPointerOverloads() {
9763 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9764 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9765 }
9766
9767 // C++ [over.built]p10:
9768 // For every promoted integral type T, there exist candidate
9769 // operator functions of the form
9770 //
9771 // T operator~(T);
9772 void addUnaryTildePromotedIntegralOverloads() {
9773 if (!HasArithmeticOrEnumeralCandidateType)
9774 return;
9775
9776 for (unsigned Int = FirstPromotedIntegralType;
9777 Int < LastPromotedIntegralType; ++Int) {
9778 QualType IntTy = ArithmeticTypes[Int];
9779 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9780 }
9781
9782 // Extension: We also add this operator for vector types.
9783 for (QualType VecTy : CandidateTypes[0].vector_types())
9784 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9785 }
9786
9787 // C++ [over.match.oper]p16:
9788 // For every pointer to member type T or type std::nullptr_t, there
9789 // exist candidate operator functions of the form
9790 //
9791 // bool operator==(T,T);
9792 // bool operator!=(T,T);
9793 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9794 /// Set of (canonical) types that we've already handled.
9795 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9796
9797 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9798 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9799 // Don't add the same builtin candidate twice.
9800 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9801 continue;
9802
9803 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9804 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9805 }
9806
9807 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9808 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9809 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9810 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9811 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9812 }
9813 }
9814 }
9815 }
9816
9817 // C++ [over.built]p15:
9818 //
9819 // For every T, where T is an enumeration type or a pointer type,
9820 // there exist candidate operator functions of the form
9821 //
9822 // bool operator<(T, T);
9823 // bool operator>(T, T);
9824 // bool operator<=(T, T);
9825 // bool operator>=(T, T);
9826 // bool operator==(T, T);
9827 // bool operator!=(T, T);
9828 // R operator<=>(T, T)
9829 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9830 // C++ [over.match.oper]p3:
9831 // [...]the built-in candidates include all of the candidate operator
9832 // functions defined in 13.6 that, compared to the given operator, [...]
9833 // do not have the same parameter-type-list as any non-template non-member
9834 // candidate.
9835 //
9836 // Note that in practice, this only affects enumeration types because there
9837 // aren't any built-in candidates of record type, and a user-defined operator
9838 // must have an operand of record or enumeration type. Also, the only other
9839 // overloaded operator with enumeration arguments, operator=,
9840 // cannot be overloaded for enumeration types, so this is the only place
9841 // where we must suppress candidates like this.
9842 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9843 UserDefinedBinaryOperators;
9844
9845 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9846 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9847 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9848 CEnd = CandidateSet.end();
9849 C != CEnd; ++C) {
9850 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9851 continue;
9852
9853 if (C->Function->isFunctionTemplateSpecialization())
9854 continue;
9855
9856 // We interpret "same parameter-type-list" as applying to the
9857 // "synthesized candidate, with the order of the two parameters
9858 // reversed", not to the original function.
9859 bool Reversed = C->isReversed();
9860 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9861 ->getType()
9862 .getUnqualifiedType();
9863 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9864 ->getType()
9865 .getUnqualifiedType();
9866
9867 // Skip if either parameter isn't of enumeral type.
9868 if (!FirstParamType->isEnumeralType() ||
9869 !SecondParamType->isEnumeralType())
9870 continue;
9871
9872 // Add this operator to the set of known user-defined operators.
9873 UserDefinedBinaryOperators.insert(
9874 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9875 y: S.Context.getCanonicalType(T: SecondParamType)));
9876 }
9877 }
9878 }
9879
9880 /// Set of (canonical) types that we've already handled.
9881 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9882
9883 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9884 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9885 // Don't add the same builtin candidate twice.
9886 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9887 continue;
9888 if (IsSpaceship && PtrTy->isFunctionPointerType())
9889 continue;
9890
9891 QualType ParamTypes[2] = {PtrTy, PtrTy};
9892 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9893 }
9894 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9895 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9896
9897 // Don't add the same builtin candidate twice, or if a user defined
9898 // candidate exists.
9899 if (!AddedTypes.insert(Ptr: CanonType).second ||
9900 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9901 y&: CanonType)))
9902 continue;
9903 QualType ParamTypes[2] = {EnumTy, EnumTy};
9904 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9905 }
9906 }
9907 }
9908
9909 // C++ [over.built]p13:
9910 //
9911 // For every cv-qualified or cv-unqualified object type T
9912 // there exist candidate operator functions of the form
9913 //
9914 // T* operator+(T*, ptrdiff_t);
9915 // T& operator[](T*, ptrdiff_t); [BELOW]
9916 // T* operator-(T*, ptrdiff_t);
9917 // T* operator+(ptrdiff_t, T*);
9918 // T& operator[](ptrdiff_t, T*); [BELOW]
9919 //
9920 // C++ [over.built]p14:
9921 //
9922 // For every T, where T is a pointer to object type, there
9923 // exist candidate operator functions of the form
9924 //
9925 // ptrdiff_t operator-(T, T);
9926 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9927 /// Set of (canonical) types that we've already handled.
9928 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9929
9930 for (int Arg = 0; Arg < 2; ++Arg) {
9931 QualType AsymmetricParamTypes[2] = {
9932 S.Context.getPointerDiffType(),
9933 S.Context.getPointerDiffType(),
9934 };
9935 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9936 QualType PointeeTy = PtrTy->getPointeeType();
9937 if (!PointeeTy->isObjectType())
9938 continue;
9939
9940 AsymmetricParamTypes[Arg] = PtrTy;
9941 if (Arg == 0 || Op == OO_Plus) {
9942 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9943 // T* operator+(ptrdiff_t, T*);
9944 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9945 }
9946 if (Op == OO_Minus) {
9947 // ptrdiff_t operator-(T, T);
9948 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9949 continue;
9950
9951 QualType ParamTypes[2] = {PtrTy, PtrTy};
9952 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9953 }
9954 }
9955 }
9956 }
9957
9958 // C++ [over.built]p12:
9959 //
9960 // For every pair of promoted arithmetic types L and R, there
9961 // exist candidate operator functions of the form
9962 //
9963 // LR operator*(L, R);
9964 // LR operator/(L, R);
9965 // LR operator+(L, R);
9966 // LR operator-(L, R);
9967 // bool operator<(L, R);
9968 // bool operator>(L, R);
9969 // bool operator<=(L, R);
9970 // bool operator>=(L, R);
9971 // bool operator==(L, R);
9972 // bool operator!=(L, R);
9973 //
9974 // where LR is the result of the usual arithmetic conversions
9975 // between types L and R.
9976 //
9977 // C++ [over.built]p24:
9978 //
9979 // For every pair of promoted arithmetic types L and R, there exist
9980 // candidate operator functions of the form
9981 //
9982 // LR operator?(bool, L, R);
9983 //
9984 // where LR is the result of the usual arithmetic conversions
9985 // between types L and R.
9986 // Our candidates ignore the first parameter.
9987 void addGenericBinaryArithmeticOverloads() {
9988 if (!HasArithmeticOrEnumeralCandidateType)
9989 return;
9990
9991 for (unsigned Left = FirstPromotedArithmeticType;
9992 Left < LastPromotedArithmeticType; ++Left) {
9993 for (unsigned Right = FirstPromotedArithmeticType;
9994 Right < LastPromotedArithmeticType; ++Right) {
9995 QualType LandR[2] = { ArithmeticTypes[Left],
9996 ArithmeticTypes[Right] };
9997 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9998 }
9999 }
10000
10001 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10002 // conditional operator for vector types.
10003 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10004 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10005 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10006 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10007 }
10008 }
10009
10010 /// Add binary operator overloads for each candidate matrix type M1, M2:
10011 /// * (M1, M1) -> M1
10012 /// * (M1, M1.getElementType()) -> M1
10013 /// * (M2.getElementType(), M2) -> M2
10014 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10015 void addMatrixBinaryArithmeticOverloads() {
10016 if (!HasArithmeticOrEnumeralCandidateType)
10017 return;
10018
10019 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10020 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
10021 AddCandidate(L: M1, R: M1);
10022 }
10023
10024 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10025 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
10026 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
10027 AddCandidate(L: M2, R: M2);
10028 }
10029 }
10030
10031 // C++2a [over.built]p14:
10032 //
10033 // For every integral type T there exists a candidate operator function
10034 // of the form
10035 //
10036 // std::strong_ordering operator<=>(T, T)
10037 //
10038 // C++2a [over.built]p15:
10039 //
10040 // For every pair of floating-point types L and R, there exists a candidate
10041 // operator function of the form
10042 //
10043 // std::partial_ordering operator<=>(L, R);
10044 //
10045 // FIXME: The current specification for integral types doesn't play nice with
10046 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10047 // comparisons. Under the current spec this can lead to ambiguity during
10048 // overload resolution. For example:
10049 //
10050 // enum A : int {a};
10051 // auto x = (a <=> (long)42);
10052 //
10053 // error: call is ambiguous for arguments 'A' and 'long'.
10054 // note: candidate operator<=>(int, int)
10055 // note: candidate operator<=>(long, long)
10056 //
10057 // To avoid this error, this function deviates from the specification and adds
10058 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10059 // arithmetic types (the same as the generic relational overloads).
10060 //
10061 // For now this function acts as a placeholder.
10062 void addThreeWayArithmeticOverloads() {
10063 addGenericBinaryArithmeticOverloads();
10064 }
10065
10066 // C++ [over.built]p17:
10067 //
10068 // For every pair of promoted integral types L and R, there
10069 // exist candidate operator functions of the form
10070 //
10071 // LR operator%(L, R);
10072 // LR operator&(L, R);
10073 // LR operator^(L, R);
10074 // LR operator|(L, R);
10075 // L operator<<(L, R);
10076 // L operator>>(L, R);
10077 //
10078 // where LR is the result of the usual arithmetic conversions
10079 // between types L and R.
10080 void addBinaryBitwiseArithmeticOverloads() {
10081 if (!HasArithmeticOrEnumeralCandidateType)
10082 return;
10083
10084 for (unsigned Left = FirstPromotedIntegralType;
10085 Left < LastPromotedIntegralType; ++Left) {
10086 for (unsigned Right = FirstPromotedIntegralType;
10087 Right < LastPromotedIntegralType; ++Right) {
10088 QualType LandR[2] = { ArithmeticTypes[Left],
10089 ArithmeticTypes[Right] };
10090 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10091 }
10092 }
10093 }
10094
10095 // C++ [over.built]p20:
10096 //
10097 // For every pair (T, VQ), where T is an enumeration or
10098 // pointer to member type and VQ is either volatile or
10099 // empty, there exist candidate operator functions of the form
10100 //
10101 // VQ T& operator=(VQ T&, T);
10102 void addAssignmentMemberPointerOrEnumeralOverloads() {
10103 /// Set of (canonical) types that we've already handled.
10104 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10105
10106 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10107 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10108 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10109 continue;
10110
10111 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10112 }
10113
10114 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10115 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10116 continue;
10117
10118 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10119 }
10120 }
10121 }
10122
10123 // C++ [over.built]p19:
10124 //
10125 // For every pair (T, VQ), where T is any type and VQ is either
10126 // volatile or empty, there exist candidate operator functions
10127 // of the form
10128 //
10129 // T*VQ& operator=(T*VQ&, T*);
10130 //
10131 // C++ [over.built]p21:
10132 //
10133 // For every pair (T, VQ), where T is a cv-qualified or
10134 // cv-unqualified object type and VQ is either volatile or
10135 // empty, there exist candidate operator functions of the form
10136 //
10137 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10138 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10139 void addAssignmentPointerOverloads(bool isEqualOp) {
10140 /// Set of (canonical) types that we've already handled.
10141 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10142
10143 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10144 // If this is operator=, keep track of the builtin candidates we added.
10145 if (isEqualOp)
10146 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10147 else if (!PtrTy->getPointeeType()->isObjectType())
10148 continue;
10149
10150 // non-volatile version
10151 QualType ParamTypes[2] = {
10152 S.Context.getLValueReferenceType(T: PtrTy),
10153 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10154 };
10155 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10156 /*IsAssignmentOperator=*/ isEqualOp);
10157
10158 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10159 VisibleTypeConversionsQuals.hasVolatile();
10160 if (NeedVolatile) {
10161 // volatile version
10162 ParamTypes[0] =
10163 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10164 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10165 /*IsAssignmentOperator=*/isEqualOp);
10166 }
10167
10168 if (!PtrTy.isRestrictQualified() &&
10169 VisibleTypeConversionsQuals.hasRestrict()) {
10170 // restrict version
10171 ParamTypes[0] =
10172 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10173 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10174 /*IsAssignmentOperator=*/isEqualOp);
10175
10176 if (NeedVolatile) {
10177 // volatile restrict version
10178 ParamTypes[0] =
10179 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10180 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10181 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10182 /*IsAssignmentOperator=*/isEqualOp);
10183 }
10184 }
10185 }
10186
10187 if (isEqualOp) {
10188 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10189 // Make sure we don't add the same candidate twice.
10190 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10191 continue;
10192
10193 QualType ParamTypes[2] = {
10194 S.Context.getLValueReferenceType(T: PtrTy),
10195 PtrTy,
10196 };
10197
10198 // non-volatile version
10199 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10200 /*IsAssignmentOperator=*/true);
10201
10202 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10203 VisibleTypeConversionsQuals.hasVolatile();
10204 if (NeedVolatile) {
10205 // volatile version
10206 ParamTypes[0] = S.Context.getLValueReferenceType(
10207 T: S.Context.getVolatileType(T: PtrTy));
10208 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10209 /*IsAssignmentOperator=*/true);
10210 }
10211
10212 if (!PtrTy.isRestrictQualified() &&
10213 VisibleTypeConversionsQuals.hasRestrict()) {
10214 // restrict version
10215 ParamTypes[0] = S.Context.getLValueReferenceType(
10216 T: S.Context.getRestrictType(T: PtrTy));
10217 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10218 /*IsAssignmentOperator=*/true);
10219
10220 if (NeedVolatile) {
10221 // volatile restrict version
10222 ParamTypes[0] =
10223 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10224 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10225 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10226 /*IsAssignmentOperator=*/true);
10227 }
10228 }
10229 }
10230 }
10231 }
10232
10233 // C++ [over.built]p18:
10234 //
10235 // For every triple (L, VQ, R), where L is an arithmetic type,
10236 // VQ is either volatile or empty, and R is a promoted
10237 // arithmetic type, there exist candidate operator functions of
10238 // the form
10239 //
10240 // VQ L& operator=(VQ L&, R);
10241 // VQ L& operator*=(VQ L&, R);
10242 // VQ L& operator/=(VQ L&, R);
10243 // VQ L& operator+=(VQ L&, R);
10244 // VQ L& operator-=(VQ L&, R);
10245 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10246 if (!HasArithmeticOrEnumeralCandidateType)
10247 return;
10248
10249 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10250 for (unsigned Right = FirstPromotedArithmeticType;
10251 Right < LastPromotedArithmeticType; ++Right) {
10252 QualType ParamTypes[2];
10253 ParamTypes[1] = ArithmeticTypes[Right];
10254 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10255 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10256
10257 forAllQualifierCombinations(
10258 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10259 ParamTypes[0] =
10260 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10261 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10262 /*IsAssignmentOperator=*/isEqualOp);
10263 });
10264 }
10265 }
10266
10267 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10268 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10269 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10270 QualType ParamTypes[2];
10271 ParamTypes[1] = Vec2Ty;
10272 // Add this built-in operator as a candidate (VQ is empty).
10273 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10274 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10275 /*IsAssignmentOperator=*/isEqualOp);
10276
10277 // Add this built-in operator as a candidate (VQ is 'volatile').
10278 if (VisibleTypeConversionsQuals.hasVolatile()) {
10279 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10280 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10281 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10282 /*IsAssignmentOperator=*/isEqualOp);
10283 }
10284 }
10285 }
10286
10287 // C++ [over.built]p22:
10288 //
10289 // For every triple (L, VQ, R), where L is an integral type, VQ
10290 // is either volatile or empty, and R is a promoted integral
10291 // type, there exist candidate operator functions of the form
10292 //
10293 // VQ L& operator%=(VQ L&, R);
10294 // VQ L& operator<<=(VQ L&, R);
10295 // VQ L& operator>>=(VQ L&, R);
10296 // VQ L& operator&=(VQ L&, R);
10297 // VQ L& operator^=(VQ L&, R);
10298 // VQ L& operator|=(VQ L&, R);
10299 void addAssignmentIntegralOverloads() {
10300 if (!HasArithmeticOrEnumeralCandidateType)
10301 return;
10302
10303 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10304 for (unsigned Right = FirstPromotedIntegralType;
10305 Right < LastPromotedIntegralType; ++Right) {
10306 QualType ParamTypes[2];
10307 ParamTypes[1] = ArithmeticTypes[Right];
10308 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10309 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10310
10311 forAllQualifierCombinations(
10312 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10313 ParamTypes[0] =
10314 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10315 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10316 });
10317 }
10318 }
10319 }
10320
10321 // C++ [over.operator]p23:
10322 //
10323 // There also exist candidate operator functions of the form
10324 //
10325 // bool operator!(bool);
10326 // bool operator&&(bool, bool);
10327 // bool operator||(bool, bool);
10328 void addExclaimOverload() {
10329 QualType ParamTy = S.Context.BoolTy;
10330 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10331 /*IsAssignmentOperator=*/false,
10332 /*NumContextualBoolArguments=*/1);
10333 }
10334 void addAmpAmpOrPipePipeOverload() {
10335 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10336 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10337 /*IsAssignmentOperator=*/false,
10338 /*NumContextualBoolArguments=*/2);
10339 }
10340
10341 // C++ [over.built]p13:
10342 //
10343 // For every cv-qualified or cv-unqualified object type T there
10344 // exist candidate operator functions of the form
10345 //
10346 // T* operator+(T*, ptrdiff_t); [ABOVE]
10347 // T& operator[](T*, ptrdiff_t);
10348 // T* operator-(T*, ptrdiff_t); [ABOVE]
10349 // T* operator+(ptrdiff_t, T*); [ABOVE]
10350 // T& operator[](ptrdiff_t, T*);
10351 void addSubscriptOverloads() {
10352 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10353 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10354 QualType PointeeType = PtrTy->getPointeeType();
10355 if (!PointeeType->isObjectType())
10356 continue;
10357
10358 // T& operator[](T*, ptrdiff_t)
10359 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10360 }
10361
10362 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10363 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10364 QualType PointeeType = PtrTy->getPointeeType();
10365 if (!PointeeType->isObjectType())
10366 continue;
10367
10368 // T& operator[](ptrdiff_t, T*)
10369 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10370 }
10371 }
10372
10373 // C++ [over.built]p11:
10374 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10375 // C1 is the same type as C2 or is a derived class of C2, T is an object
10376 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10377 // there exist candidate operator functions of the form
10378 //
10379 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10380 //
10381 // where CV12 is the union of CV1 and CV2.
10382 void addArrowStarOverloads() {
10383 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10384 QualType C1Ty = PtrTy;
10385 QualType C1;
10386 QualifierCollector Q1;
10387 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10388 if (!isa<RecordType>(Val: C1))
10389 continue;
10390 // heuristic to reduce number of builtin candidates in the set.
10391 // Add volatile/restrict version only if there are conversions to a
10392 // volatile/restrict type.
10393 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10394 continue;
10395 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10396 continue;
10397 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10398 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10399 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10400 *D2 = mptr->getMostRecentCXXRecordDecl();
10401 if (!declaresSameEntity(D1, D2) &&
10402 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10403 break;
10404 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10405 // build CV12 T&
10406 QualType T = mptr->getPointeeType();
10407 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10408 T.isVolatileQualified())
10409 continue;
10410 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10411 T.isRestrictQualified())
10412 continue;
10413 T = Q1.apply(Context: S.Context, QT: T);
10414 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10415 }
10416 }
10417 }
10418
10419 // Note that we don't consider the first argument, since it has been
10420 // contextually converted to bool long ago. The candidates below are
10421 // therefore added as binary.
10422 //
10423 // C++ [over.built]p25:
10424 // For every type T, where T is a pointer, pointer-to-member, or scoped
10425 // enumeration type, there exist candidate operator functions of the form
10426 //
10427 // T operator?(bool, T, T);
10428 //
10429 void addConditionalOperatorOverloads() {
10430 /// Set of (canonical) types that we've already handled.
10431 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10432
10433 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10434 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10435 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10436 continue;
10437
10438 QualType ParamTypes[2] = {PtrTy, PtrTy};
10439 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10440 }
10441
10442 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10443 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10444 continue;
10445
10446 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10447 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10448 }
10449
10450 if (S.getLangOpts().CPlusPlus11) {
10451 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10452 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10453 continue;
10454
10455 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10456 continue;
10457
10458 QualType ParamTypes[2] = {EnumTy, EnumTy};
10459 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10460 }
10461 }
10462 }
10463 }
10464};
10465
10466} // end anonymous namespace
10467
10468void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10469 SourceLocation OpLoc,
10470 ArrayRef<Expr *> Args,
10471 OverloadCandidateSet &CandidateSet) {
10472 // Find all of the types that the arguments can convert to, but only
10473 // if the operator we're looking at has built-in operator candidates
10474 // that make use of these types. Also record whether we encounter non-record
10475 // candidate types or either arithmetic or enumeral candidate types.
10476 QualifiersAndAtomic VisibleTypeConversionsQuals;
10477 VisibleTypeConversionsQuals.addConst();
10478 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10479 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10480 if (Args[ArgIdx]->getType()->isAtomicType())
10481 VisibleTypeConversionsQuals.addAtomic();
10482 }
10483
10484 bool HasNonRecordCandidateType = false;
10485 bool HasArithmeticOrEnumeralCandidateType = false;
10486 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10487 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10488 CandidateTypes.emplace_back(Args&: *this);
10489 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10490 Loc: OpLoc,
10491 AllowUserConversions: true,
10492 AllowExplicitConversions: (Op == OO_Exclaim ||
10493 Op == OO_AmpAmp ||
10494 Op == OO_PipePipe),
10495 VisibleQuals: VisibleTypeConversionsQuals);
10496 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10497 CandidateTypes[ArgIdx].hasNonRecordTypes();
10498 HasArithmeticOrEnumeralCandidateType =
10499 HasArithmeticOrEnumeralCandidateType ||
10500 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10501 }
10502
10503 // Exit early when no non-record types have been added to the candidate set
10504 // for any of the arguments to the operator.
10505 //
10506 // We can't exit early for !, ||, or &&, since there we have always have
10507 // 'bool' overloads.
10508 if (!HasNonRecordCandidateType &&
10509 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10510 return;
10511
10512 // Setup an object to manage the common state for building overloads.
10513 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10514 VisibleTypeConversionsQuals,
10515 HasArithmeticOrEnumeralCandidateType,
10516 CandidateTypes, CandidateSet);
10517
10518 // Dispatch over the operation to add in only those overloads which apply.
10519 switch (Op) {
10520 case OO_None:
10521 case NUM_OVERLOADED_OPERATORS:
10522 llvm_unreachable("Expected an overloaded operator");
10523
10524 case OO_New:
10525 case OO_Delete:
10526 case OO_Array_New:
10527 case OO_Array_Delete:
10528 case OO_Call:
10529 llvm_unreachable(
10530 "Special operators don't use AddBuiltinOperatorCandidates");
10531
10532 case OO_Comma:
10533 case OO_Arrow:
10534 case OO_Coawait:
10535 // C++ [over.match.oper]p3:
10536 // -- For the operator ',', the unary operator '&', the
10537 // operator '->', or the operator 'co_await', the
10538 // built-in candidates set is empty.
10539 break;
10540
10541 case OO_Plus: // '+' is either unary or binary
10542 if (Args.size() == 1)
10543 OpBuilder.addUnaryPlusPointerOverloads();
10544 [[fallthrough]];
10545
10546 case OO_Minus: // '-' is either unary or binary
10547 if (Args.size() == 1) {
10548 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10549 } else {
10550 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10551 OpBuilder.addGenericBinaryArithmeticOverloads();
10552 OpBuilder.addMatrixBinaryArithmeticOverloads();
10553 }
10554 break;
10555
10556 case OO_Star: // '*' is either unary or binary
10557 if (Args.size() == 1)
10558 OpBuilder.addUnaryStarPointerOverloads();
10559 else {
10560 OpBuilder.addGenericBinaryArithmeticOverloads();
10561 OpBuilder.addMatrixBinaryArithmeticOverloads();
10562 }
10563 break;
10564
10565 case OO_Slash:
10566 OpBuilder.addGenericBinaryArithmeticOverloads();
10567 break;
10568
10569 case OO_PlusPlus:
10570 case OO_MinusMinus:
10571 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10572 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10573 break;
10574
10575 case OO_EqualEqual:
10576 case OO_ExclaimEqual:
10577 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10578 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10579 OpBuilder.addGenericBinaryArithmeticOverloads();
10580 break;
10581
10582 case OO_Less:
10583 case OO_Greater:
10584 case OO_LessEqual:
10585 case OO_GreaterEqual:
10586 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10587 OpBuilder.addGenericBinaryArithmeticOverloads();
10588 break;
10589
10590 case OO_Spaceship:
10591 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10592 OpBuilder.addThreeWayArithmeticOverloads();
10593 break;
10594
10595 case OO_Percent:
10596 case OO_Caret:
10597 case OO_Pipe:
10598 case OO_LessLess:
10599 case OO_GreaterGreater:
10600 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10601 break;
10602
10603 case OO_Amp: // '&' is either unary or binary
10604 if (Args.size() == 1)
10605 // C++ [over.match.oper]p3:
10606 // -- For the operator ',', the unary operator '&', or the
10607 // operator '->', the built-in candidates set is empty.
10608 break;
10609
10610 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10611 break;
10612
10613 case OO_Tilde:
10614 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10615 break;
10616
10617 case OO_Equal:
10618 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10619 [[fallthrough]];
10620
10621 case OO_PlusEqual:
10622 case OO_MinusEqual:
10623 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10624 [[fallthrough]];
10625
10626 case OO_StarEqual:
10627 case OO_SlashEqual:
10628 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10629 break;
10630
10631 case OO_PercentEqual:
10632 case OO_LessLessEqual:
10633 case OO_GreaterGreaterEqual:
10634 case OO_AmpEqual:
10635 case OO_CaretEqual:
10636 case OO_PipeEqual:
10637 OpBuilder.addAssignmentIntegralOverloads();
10638 break;
10639
10640 case OO_Exclaim:
10641 OpBuilder.addExclaimOverload();
10642 break;
10643
10644 case OO_AmpAmp:
10645 case OO_PipePipe:
10646 OpBuilder.addAmpAmpOrPipePipeOverload();
10647 break;
10648
10649 case OO_Subscript:
10650 if (Args.size() == 2)
10651 OpBuilder.addSubscriptOverloads();
10652 break;
10653
10654 case OO_ArrowStar:
10655 OpBuilder.addArrowStarOverloads();
10656 break;
10657
10658 case OO_Conditional:
10659 OpBuilder.addConditionalOperatorOverloads();
10660 OpBuilder.addGenericBinaryArithmeticOverloads();
10661 break;
10662 }
10663}
10664
10665void
10666Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10667 SourceLocation Loc,
10668 ArrayRef<Expr *> Args,
10669 TemplateArgumentListInfo *ExplicitTemplateArgs,
10670 OverloadCandidateSet& CandidateSet,
10671 bool PartialOverloading) {
10672 ADLResult Fns;
10673
10674 // FIXME: This approach for uniquing ADL results (and removing
10675 // redundant candidates from the set) relies on pointer-equality,
10676 // which means we need to key off the canonical decl. However,
10677 // always going back to the canonical decl might not get us the
10678 // right set of default arguments. What default arguments are
10679 // we supposed to consider on ADL candidates, anyway?
10680
10681 // FIXME: Pass in the explicit template arguments?
10682 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10683
10684 ArrayRef<Expr *> ReversedArgs;
10685
10686 // Erase all of the candidates we already knew about.
10687 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10688 CandEnd = CandidateSet.end();
10689 Cand != CandEnd; ++Cand)
10690 if (Cand->Function) {
10691 FunctionDecl *Fn = Cand->Function;
10692 Fns.erase(D: Fn);
10693 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10694 Fns.erase(D: FunTmpl);
10695 }
10696
10697 // For each of the ADL candidates we found, add it to the overload
10698 // set.
10699 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10700 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10701
10702 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10703 if (ExplicitTemplateArgs)
10704 continue;
10705
10706 AddOverloadCandidate(
10707 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10708 PartialOverloading, /*AllowExplicit=*/true,
10709 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10710 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10711 AddOverloadCandidate(
10712 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10713 /*SuppressUserConversions=*/false, PartialOverloading,
10714 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10715 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10716 }
10717 } else {
10718 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10719 AddTemplateOverloadCandidate(
10720 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10721 /*SuppressUserConversions=*/false, PartialOverloading,
10722 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10723 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10724 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10725
10726 // As template candidates are not deduced immediately,
10727 // persist the array in the overload set.
10728 if (ReversedArgs.empty())
10729 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10730
10731 AddTemplateOverloadCandidate(
10732 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10733 /*SuppressUserConversions=*/false, PartialOverloading,
10734 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10735 PO: OverloadCandidateParamOrder::Reversed);
10736 }
10737 }
10738 }
10739}
10740
10741namespace {
10742enum class Comparison { Equal, Better, Worse };
10743}
10744
10745/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10746/// overload resolution.
10747///
10748/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10749/// Cand1's first N enable_if attributes have precisely the same conditions as
10750/// Cand2's first N enable_if attributes (where N = the number of enable_if
10751/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10752///
10753/// Note that you can have a pair of candidates such that Cand1's enable_if
10754/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10755/// worse than Cand1's.
10756static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10757 const FunctionDecl *Cand2) {
10758 // Common case: One (or both) decls don't have enable_if attrs.
10759 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10760 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10761 if (!Cand1Attr || !Cand2Attr) {
10762 if (Cand1Attr == Cand2Attr)
10763 return Comparison::Equal;
10764 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10765 }
10766
10767 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10768 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10769
10770 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10771 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10772 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10773 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10774
10775 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10776 // has fewer enable_if attributes than Cand2, and vice versa.
10777 if (!Cand1A)
10778 return Comparison::Worse;
10779 if (!Cand2A)
10780 return Comparison::Better;
10781
10782 Cand1ID.clear();
10783 Cand2ID.clear();
10784
10785 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10786 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10787 if (Cand1ID != Cand2ID)
10788 return Comparison::Worse;
10789 }
10790
10791 return Comparison::Equal;
10792}
10793
10794static Comparison
10795isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10796 const OverloadCandidate &Cand2) {
10797 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10798 !Cand2.Function->isMultiVersion())
10799 return Comparison::Equal;
10800
10801 // If both are invalid, they are equal. If one of them is invalid, the other
10802 // is better.
10803 if (Cand1.Function->isInvalidDecl()) {
10804 if (Cand2.Function->isInvalidDecl())
10805 return Comparison::Equal;
10806 return Comparison::Worse;
10807 }
10808 if (Cand2.Function->isInvalidDecl())
10809 return Comparison::Better;
10810
10811 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10812 // cpu_dispatch, else arbitrarily based on the identifiers.
10813 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10814 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10815 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10816 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10817
10818 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10819 return Comparison::Equal;
10820
10821 if (Cand1CPUDisp && !Cand2CPUDisp)
10822 return Comparison::Better;
10823 if (Cand2CPUDisp && !Cand1CPUDisp)
10824 return Comparison::Worse;
10825
10826 if (Cand1CPUSpec && Cand2CPUSpec) {
10827 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10828 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10829 ? Comparison::Better
10830 : Comparison::Worse;
10831
10832 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10833 FirstDiff = std::mismatch(
10834 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10835 first2: Cand2CPUSpec->cpus_begin(),
10836 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10837 return LHS->getName() == RHS->getName();
10838 });
10839
10840 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10841 "Two different cpu-specific versions should not have the same "
10842 "identifier list, otherwise they'd be the same decl!");
10843 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10844 ? Comparison::Better
10845 : Comparison::Worse;
10846 }
10847 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10848}
10849
10850/// Compute the type of the implicit object parameter for the given function,
10851/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10852/// null QualType if there is a 'matches anything' implicit object parameter.
10853static std::optional<QualType>
10854getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10855 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10856 return std::nullopt;
10857
10858 auto *M = cast<CXXMethodDecl>(Val: F);
10859 // Static member functions' object parameters match all types.
10860 if (M->isStatic())
10861 return QualType();
10862 return M->getFunctionObjectParameterReferenceType();
10863}
10864
10865// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10866// represent the same entity.
10867static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10868 const FunctionDecl *F2) {
10869 if (declaresSameEntity(D1: F1, D2: F2))
10870 return true;
10871 auto PT1 = F1->getPrimaryTemplate();
10872 auto PT2 = F2->getPrimaryTemplate();
10873 if (PT1 && PT2) {
10874 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10875 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10876 D2: PT2->getInstantiatedFromMemberTemplate()))
10877 return true;
10878 }
10879 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10880 // different functions with same params). Consider removing this (as no test
10881 // fail w/o it).
10882 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10883 if (First) {
10884 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10885 return *T;
10886 }
10887 assert(I < F->getNumParams());
10888 return F->getParamDecl(i: I++)->getType();
10889 };
10890
10891 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10892 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10893
10894 if (F1NumParams != F2NumParams)
10895 return false;
10896
10897 unsigned I1 = 0, I2 = 0;
10898 for (unsigned I = 0; I != F1NumParams; ++I) {
10899 QualType T1 = NextParam(F1, I1, I == 0);
10900 QualType T2 = NextParam(F2, I2, I == 0);
10901 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10902 if (!Context.hasSameUnqualifiedType(T1, T2))
10903 return false;
10904 }
10905 return true;
10906}
10907
10908/// We're allowed to use constraints partial ordering only if the candidates
10909/// have the same parameter types:
10910/// [over.match.best.general]p2.6
10911/// F1 and F2 are non-template functions with the same
10912/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10913static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10914 FunctionDecl *Fn2,
10915 bool IsFn1Reversed,
10916 bool IsFn2Reversed) {
10917 assert(Fn1 && Fn2);
10918 if (Fn1->isVariadic() != Fn2->isVariadic())
10919 return false;
10920
10921 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10922 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10923 return false;
10924
10925 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10926 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10927 if (Mem1 && Mem2) {
10928 // if they are member functions, both are direct members of the same class,
10929 // and
10930 if (Mem1->getParent() != Mem2->getParent())
10931 return false;
10932 // if both are non-static member functions, they have the same types for
10933 // their object parameters
10934 if (Mem1->isInstance() && Mem2->isInstance() &&
10935 !S.getASTContext().hasSameType(
10936 T1: Mem1->getFunctionObjectParameterReferenceType(),
10937 T2: Mem1->getFunctionObjectParameterReferenceType()))
10938 return false;
10939 }
10940 return true;
10941}
10942
10943static FunctionDecl *
10944getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10945 bool IsFn1Reversed, bool IsFn2Reversed) {
10946 if (!Fn1 || !Fn2)
10947 return nullptr;
10948
10949 // C++ [temp.constr.order]:
10950 // A non-template function F1 is more partial-ordering-constrained than a
10951 // non-template function F2 if:
10952 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10953 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10954
10955 if (Cand1IsSpecialization || Cand2IsSpecialization)
10956 return nullptr;
10957
10958 // - they have the same non-object-parameter-type-lists, and [...]
10959 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10960 IsFn2Reversed))
10961 return nullptr;
10962
10963 // - the declaration of F1 is more constrained than the declaration of F2.
10964 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10965}
10966
10967/// isBetterOverloadCandidate - Determines whether the first overload
10968/// candidate is a better candidate than the second (C++ 13.3.3p1).
10969bool clang::isBetterOverloadCandidate(
10970 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10971 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10972 bool PartialOverloading) {
10973 // Define viable functions to be better candidates than non-viable
10974 // functions.
10975 if (!Cand2.Viable)
10976 return Cand1.Viable;
10977 else if (!Cand1.Viable)
10978 return false;
10979
10980 // [CUDA] A function with 'never' preference is marked not viable, therefore
10981 // is never shown up here. The worst preference shown up here is 'wrong side',
10982 // e.g. an H function called by a HD function in device compilation. This is
10983 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10984 // function which is called only by an H function. A deferred diagnostic will
10985 // be triggered if it is emitted. However a wrong-sided function is still
10986 // a viable candidate here.
10987 //
10988 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10989 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10990 // can be emitted, Cand1 is not better than Cand2. This rule should have
10991 // precedence over other rules.
10992 //
10993 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10994 // other rules should be used to determine which is better. This is because
10995 // host/device based overloading resolution is mostly for determining
10996 // viability of a function. If two functions are both viable, other factors
10997 // should take precedence in preference, e.g. the standard-defined preferences
10998 // like argument conversion ranks or enable_if partial-ordering. The
10999 // preference for pass-object-size parameters is probably most similar to a
11000 // type-based-overloading decision and so should take priority.
11001 //
11002 // If other rules cannot determine which is better, CUDA preference will be
11003 // used again to determine which is better.
11004 //
11005 // TODO: Currently IdentifyPreference does not return correct values
11006 // for functions called in global variable initializers due to missing
11007 // correct context about device/host. Therefore we can only enforce this
11008 // rule when there is a caller. We should enforce this rule for functions
11009 // in global variable initializers once proper context is added.
11010 //
11011 // TODO: We can only enable the hostness based overloading resolution when
11012 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11013 // overloading resolution diagnostics.
11014 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11015 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11016 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11017 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
11018 bool IsCand1ImplicitHD =
11019 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
11020 bool IsCand2ImplicitHD =
11021 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
11022 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
11023 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11024 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11025 // The implicit HD function may be a function in a system header which
11026 // is forced by pragma. In device compilation, if we prefer HD candidates
11027 // over wrong-sided candidates, overloading resolution may change, which
11028 // may result in non-deferrable diagnostics. As a workaround, we let
11029 // implicit HD candidates take equal preference as wrong-sided candidates.
11030 // This will preserve the overloading resolution.
11031 // TODO: We still need special handling of implicit HD functions since
11032 // they may incur other diagnostics to be deferred. We should make all
11033 // host/device related diagnostics deferrable and remove special handling
11034 // of implicit HD functions.
11035 auto EmitThreshold =
11036 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11037 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11038 ? SemaCUDA::CFP_Never
11039 : SemaCUDA::CFP_WrongSide;
11040 auto Cand1Emittable = P1 > EmitThreshold;
11041 auto Cand2Emittable = P2 > EmitThreshold;
11042 if (Cand1Emittable && !Cand2Emittable)
11043 return true;
11044 if (!Cand1Emittable && Cand2Emittable)
11045 return false;
11046 }
11047 }
11048
11049 // C++ [over.match.best]p1: (Changed in C++23)
11050 //
11051 // -- if F is a static member function, ICS1(F) is defined such
11052 // that ICS1(F) is neither better nor worse than ICS1(G) for
11053 // any function G, and, symmetrically, ICS1(G) is neither
11054 // better nor worse than ICS1(F).
11055 unsigned StartArg = 0;
11056 if (!Cand1.TookAddressOfOverload &&
11057 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11058 StartArg = 1;
11059
11060 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11061 // We don't allow incompatible pointer conversions in C++.
11062 if (!S.getLangOpts().CPlusPlus)
11063 return ICS.isStandard() &&
11064 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11065
11066 // The only ill-formed conversion we allow in C++ is the string literal to
11067 // char* conversion, which is only considered ill-formed after C++11.
11068 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11069 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11070 };
11071
11072 // Define functions that don't require ill-formed conversions for a given
11073 // argument to be better candidates than functions that do.
11074 unsigned NumArgs = Cand1.Conversions.size();
11075 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11076 bool HasBetterConversion = false;
11077 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11078 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11079 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11080 if (Cand1Bad != Cand2Bad) {
11081 if (Cand1Bad)
11082 return false;
11083 HasBetterConversion = true;
11084 }
11085 }
11086
11087 if (HasBetterConversion)
11088 return true;
11089
11090 // C++ [over.match.best]p1:
11091 // A viable function F1 is defined to be a better function than another
11092 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11093 // conversion sequence than ICSi(F2), and then...
11094 bool HasWorseConversion = false;
11095 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11096 switch (CompareImplicitConversionSequences(S, Loc,
11097 ICS1: Cand1.Conversions[ArgIdx],
11098 ICS2: Cand2.Conversions[ArgIdx])) {
11099 case ImplicitConversionSequence::Better:
11100 // Cand1 has a better conversion sequence.
11101 HasBetterConversion = true;
11102 break;
11103
11104 case ImplicitConversionSequence::Worse:
11105 if (Cand1.Function && Cand2.Function &&
11106 Cand1.isReversed() != Cand2.isReversed() &&
11107 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11108 // Work around large-scale breakage caused by considering reversed
11109 // forms of operator== in C++20:
11110 //
11111 // When comparing a function against a reversed function, if we have a
11112 // better conversion for one argument and a worse conversion for the
11113 // other, the implicit conversion sequences are treated as being equally
11114 // good.
11115 //
11116 // This prevents a comparison function from being considered ambiguous
11117 // with a reversed form that is written in the same way.
11118 //
11119 // We diagnose this as an extension from CreateOverloadedBinOp.
11120 HasWorseConversion = true;
11121 break;
11122 }
11123
11124 // Cand1 can't be better than Cand2.
11125 return false;
11126
11127 case ImplicitConversionSequence::Indistinguishable:
11128 // Do nothing.
11129 break;
11130 }
11131 }
11132
11133 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11134 // ICSj(F2), or, if not that,
11135 if (HasBetterConversion && !HasWorseConversion)
11136 return true;
11137
11138 // -- the context is an initialization by user-defined conversion
11139 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11140 // from the return type of F1 to the destination type (i.e.,
11141 // the type of the entity being initialized) is a better
11142 // conversion sequence than the standard conversion sequence
11143 // from the return type of F2 to the destination type.
11144 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11145 Cand1.Function && Cand2.Function &&
11146 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11147 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11148
11149 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11150 // First check whether we prefer one of the conversion functions over the
11151 // other. This only distinguishes the results in non-standard, extension
11152 // cases such as the conversion from a lambda closure type to a function
11153 // pointer or block.
11154 ImplicitConversionSequence::CompareKind Result =
11155 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11156 if (Result == ImplicitConversionSequence::Indistinguishable)
11157 Result = CompareStandardConversionSequences(S, Loc,
11158 SCS1: Cand1.FinalConversion,
11159 SCS2: Cand2.FinalConversion);
11160
11161 if (Result != ImplicitConversionSequence::Indistinguishable)
11162 return Result == ImplicitConversionSequence::Better;
11163
11164 // FIXME: Compare kind of reference binding if conversion functions
11165 // convert to a reference type used in direct reference binding, per
11166 // C++14 [over.match.best]p1 section 2 bullet 3.
11167 }
11168
11169 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11170 // as combined with the resolution to CWG issue 243.
11171 //
11172 // When the context is initialization by constructor ([over.match.ctor] or
11173 // either phase of [over.match.list]), a constructor is preferred over
11174 // a conversion function.
11175 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11176 Cand1.Function && Cand2.Function &&
11177 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11178 isa<CXXConstructorDecl>(Val: Cand2.Function))
11179 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11180
11181 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11182 return Cand2.StrictPackMatch;
11183
11184 // -- F1 is a non-template function and F2 is a function template
11185 // specialization, or, if not that,
11186 bool Cand1IsSpecialization = Cand1.Function &&
11187 Cand1.Function->getPrimaryTemplate();
11188 bool Cand2IsSpecialization = Cand2.Function &&
11189 Cand2.Function->getPrimaryTemplate();
11190 if (Cand1IsSpecialization != Cand2IsSpecialization)
11191 return Cand2IsSpecialization;
11192
11193 // -- F1 and F2 are function template specializations, and the function
11194 // template for F1 is more specialized than the template for F2
11195 // according to the partial ordering rules described in 14.5.5.2, or,
11196 // if not that,
11197 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11198 const auto *Obj1Context =
11199 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11200 const auto *Obj2Context =
11201 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11202 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11203 FT1: Cand1.Function->getPrimaryTemplate(),
11204 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11205 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11206 : TPOC_Call,
11207 NumCallArguments1: Cand1.ExplicitCallArguments,
11208 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11209 : QualType{},
11210 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11211 : QualType{},
11212 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11213 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11214 }
11215 }
11216
11217 // -— F1 and F2 are non-template functions and F1 is more
11218 // partial-ordering-constrained than F2 [...],
11219 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11220 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11221 IsFn2Reversed: Cand2.isReversed());
11222 F && F == Cand1.Function)
11223 return true;
11224
11225 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11226 // class B of D, and for all arguments the corresponding parameters of
11227 // F1 and F2 have the same type.
11228 // FIXME: Implement the "all parameters have the same type" check.
11229 bool Cand1IsInherited =
11230 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11231 bool Cand2IsInherited =
11232 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11233 if (Cand1IsInherited != Cand2IsInherited)
11234 return Cand2IsInherited;
11235 else if (Cand1IsInherited) {
11236 assert(Cand2IsInherited);
11237 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11238 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11239 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11240 return true;
11241 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11242 return false;
11243 // Inherited from sibling base classes: still ambiguous.
11244 }
11245
11246 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11247 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11248 // with reversed order of parameters and F1 is not
11249 //
11250 // We rank reversed + different operator as worse than just reversed, but
11251 // that comparison can never happen, because we only consider reversing for
11252 // the maximally-rewritten operator (== or <=>).
11253 if (Cand1.RewriteKind != Cand2.RewriteKind)
11254 return Cand1.RewriteKind < Cand2.RewriteKind;
11255
11256 // Check C++17 tie-breakers for deduction guides.
11257 {
11258 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11259 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11260 if (Guide1 && Guide2) {
11261 // -- F1 is generated from a deduction-guide and F2 is not
11262 if (Guide1->isImplicit() != Guide2->isImplicit())
11263 return Guide2->isImplicit();
11264
11265 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11266 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11267 return true;
11268 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11269 return false;
11270
11271 // --F1 is generated from a non-template constructor and F2 is generated
11272 // from a constructor template
11273 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11274 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11275 if (Constructor1 && Constructor2) {
11276 bool isC1Templated = Constructor1->getTemplatedKind() !=
11277 FunctionDecl::TemplatedKind::TK_NonTemplate;
11278 bool isC2Templated = Constructor2->getTemplatedKind() !=
11279 FunctionDecl::TemplatedKind::TK_NonTemplate;
11280 if (isC1Templated != isC2Templated)
11281 return isC2Templated;
11282 }
11283 }
11284 }
11285
11286 // Check for enable_if value-based overload resolution.
11287 if (Cand1.Function && Cand2.Function) {
11288 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11289 if (Cmp != Comparison::Equal)
11290 return Cmp == Comparison::Better;
11291 }
11292
11293 bool HasPS1 = Cand1.Function != nullptr &&
11294 functionHasPassObjectSizeParams(FD: Cand1.Function);
11295 bool HasPS2 = Cand2.Function != nullptr &&
11296 functionHasPassObjectSizeParams(FD: Cand2.Function);
11297 if (HasPS1 != HasPS2 && HasPS1)
11298 return true;
11299
11300 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11301 if (MV == Comparison::Better)
11302 return true;
11303 if (MV == Comparison::Worse)
11304 return false;
11305
11306 // If other rules cannot determine which is better, CUDA preference is used
11307 // to determine which is better.
11308 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11309 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11310 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11311 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11312 }
11313
11314 // General member function overloading is handled above, so this only handles
11315 // constructors with address spaces.
11316 // This only handles address spaces since C++ has no other
11317 // qualifier that can be used with constructors.
11318 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11319 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11320 if (CD1 && CD2) {
11321 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11322 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11323 if (AS1 != AS2) {
11324 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11325 return true;
11326 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11327 return false;
11328 }
11329 }
11330
11331 return false;
11332}
11333
11334/// Determine whether two declarations are "equivalent" for the purposes of
11335/// name lookup and overload resolution. This applies when the same internal/no
11336/// linkage entity is defined by two modules (probably by textually including
11337/// the same header). In such a case, we don't consider the declarations to
11338/// declare the same entity, but we also don't want lookups with both
11339/// declarations visible to be ambiguous in some cases (this happens when using
11340/// a modularized libstdc++).
11341bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11342 const NamedDecl *B) {
11343 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11344 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11345 if (!VA || !VB)
11346 return false;
11347
11348 // The declarations must be declaring the same name as an internal linkage
11349 // entity in different modules.
11350 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11351 DC: VB->getDeclContext()->getRedeclContext()) ||
11352 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11353 VA->isExternallyVisible() || VB->isExternallyVisible())
11354 return false;
11355
11356 // Check that the declarations appear to be equivalent.
11357 //
11358 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11359 // For constants and functions, we should check the initializer or body is
11360 // the same. For non-constant variables, we shouldn't allow it at all.
11361 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11362 return true;
11363
11364 // Enum constants within unnamed enumerations will have different types, but
11365 // may still be similar enough to be interchangeable for our purposes.
11366 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11367 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11368 // Only handle anonymous enums. If the enumerations were named and
11369 // equivalent, they would have been merged to the same type.
11370 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11371 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11372 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11373 !Context.hasSameType(T1: EnumA->getIntegerType(),
11374 T2: EnumB->getIntegerType()))
11375 return false;
11376 // Allow this only if the value is the same for both enumerators.
11377 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11378 }
11379 }
11380
11381 // Nothing else is sufficiently similar.
11382 return false;
11383}
11384
11385void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11386 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11387 assert(D && "Unknown declaration");
11388 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11389
11390 Module *M = getOwningModule(Entity: D);
11391 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11392 << !M << (M ? M->getFullModuleName() : "");
11393
11394 for (auto *E : Equiv) {
11395 Module *M = getOwningModule(Entity: E);
11396 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11397 << !M << (M ? M->getFullModuleName() : "");
11398 }
11399}
11400
11401bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11402 return FailureKind == ovl_fail_bad_deduction &&
11403 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11404 TemplateDeductionResult::ConstraintsNotSatisfied &&
11405 static_cast<CNSInfo *>(DeductionFailure.Data)
11406 ->Satisfaction.ContainsErrors;
11407}
11408
11409void OverloadCandidateSet::AddDeferredTemplateCandidate(
11410 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11411 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11412 bool PartialOverloading, bool AllowExplicit,
11413 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11414 bool AggregateCandidateDeduction) {
11415
11416 auto *C =
11417 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11418
11419 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11420 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11421 /*AllowObjCConversionOnExplicit=*/false,
11422 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11423 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11424 .FunctionTemplate: FunctionTemplate,
11425 .FoundDecl: FoundDecl,
11426 .Args: Args,
11427 .IsADLCandidate: IsADLCandidate,
11428 .PO: PO};
11429
11430 HasDeferredTemplateConstructors |=
11431 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11432}
11433
11434void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11435 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11436 CXXRecordDecl *ActingContext, QualType ObjectType,
11437 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11438 bool SuppressUserConversions, bool PartialOverloading,
11439 OverloadCandidateParamOrder PO) {
11440
11441 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11442
11443 auto *C =
11444 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11445
11446 C = new (C) DeferredMethodTemplateOverloadCandidate{
11447 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11448 /*AllowObjCConversionOnExplicit=*/false,
11449 /*AllowResultConversion=*/false,
11450 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11451 /*AggregateCandidateDeduction=*/false},
11452 .FunctionTemplate: MethodTmpl,
11453 .FoundDecl: FoundDecl,
11454 .Args: Args,
11455 .ActingContext: ActingContext,
11456 .ObjectClassification: ObjectClassification,
11457 .ObjectType: ObjectType,
11458 .PO: PO};
11459}
11460
11461void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11462 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11463 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11464 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11465 bool AllowResultConversion) {
11466
11467 auto *C =
11468 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11469
11470 C = new (C) DeferredConversionTemplateOverloadCandidate{
11471 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11472 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11473 /*AllowExplicit=*/false,
11474 /*SuppressUserConversions=*/false,
11475 /*PartialOverloading*/ false,
11476 /*AggregateCandidateDeduction=*/false},
11477 .FunctionTemplate: FunctionTemplate,
11478 .FoundDecl: FoundDecl,
11479 .ActingContext: ActingContext,
11480 .From: From,
11481 .ToType: ToType};
11482}
11483
11484static void
11485AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11486 DeferredMethodTemplateOverloadCandidate &C) {
11487
11488 AddMethodTemplateCandidateImmediately(
11489 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11490 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11491 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11492}
11493
11494static void
11495AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11496 DeferredFunctionTemplateOverloadCandidate &C) {
11497 AddTemplateOverloadCandidateImmediately(
11498 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11499 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11500 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11501 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11502}
11503
11504static void
11505AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11506 DeferredConversionTemplateOverloadCandidate &C) {
11507 return AddTemplateConversionCandidateImmediately(
11508 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11509 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11510 AllowResultConversion: C.AllowResultConversion);
11511}
11512
11513void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11514 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11515 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11516 while (Cand) {
11517 switch (Cand->Kind) {
11518 case DeferredTemplateOverloadCandidate::Function:
11519 AddTemplateOverloadCandidate(
11520 S, CandidateSet&: *this,
11521 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11522 break;
11523 case DeferredTemplateOverloadCandidate::Method:
11524 AddTemplateOverloadCandidate(
11525 S, CandidateSet&: *this,
11526 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11527 break;
11528 case DeferredTemplateOverloadCandidate::Conversion:
11529 AddTemplateOverloadCandidate(
11530 S, CandidateSet&: *this,
11531 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11532 break;
11533 }
11534 Cand = Cand->Next;
11535 }
11536 FirstDeferredCandidate = nullptr;
11537 DeferredCandidatesCount = 0;
11538}
11539
11540OverloadingResult
11541OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11542 Best->Best = true;
11543 if (Best->Function && Best->Function->isDeleted())
11544 return OR_Deleted;
11545 return OR_Success;
11546}
11547
11548void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11549 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11550 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11551 // are accepted by both clang and NVCC. However, during a particular
11552 // compilation mode only one call variant is viable. We need to
11553 // exclude non-viable overload candidates from consideration based
11554 // only on their host/device attributes. Specifically, if one
11555 // candidate call is WrongSide and the other is SameSide, we ignore
11556 // the WrongSide candidate.
11557 // We only need to remove wrong-sided candidates here if
11558 // -fgpu-exclude-wrong-side-overloads is off. When
11559 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11560 // uniformly in isBetterOverloadCandidate.
11561 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11562 return;
11563 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11564
11565 bool ContainsSameSideCandidate =
11566 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11567 // Check viable function only.
11568 return Cand->Viable && Cand->Function &&
11569 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11570 SemaCUDA::CFP_SameSide;
11571 });
11572
11573 if (!ContainsSameSideCandidate)
11574 return;
11575
11576 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11577 // Check viable function only to avoid unnecessary data copying/moving.
11578 return Cand->Viable && Cand->Function &&
11579 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11580 SemaCUDA::CFP_WrongSide;
11581 };
11582 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11583}
11584
11585/// Computes the best viable function (C++ 13.3.3)
11586/// within an overload candidate set.
11587///
11588/// \param Loc The location of the function name (or operator symbol) for
11589/// which overload resolution occurs.
11590///
11591/// \param Best If overload resolution was successful or found a deleted
11592/// function, \p Best points to the candidate function found.
11593///
11594/// \returns The result of overload resolution.
11595OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11596 SourceLocation Loc,
11597 iterator &Best) {
11598
11599 assert((shouldDeferTemplateArgumentDeduction(S) ||
11600 DeferredCandidatesCount == 0) &&
11601 "Unexpected deferred template candidates");
11602
11603 bool TwoPhaseResolution =
11604 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11605
11606 if (TwoPhaseResolution) {
11607 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11608 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11609 if (!(HasDeferredTemplateConstructors &&
11610 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11611 return Res;
11612 }
11613 }
11614
11615 InjectNonDeducedTemplateCandidates(S);
11616 return BestViableFunctionImpl(S, Loc, Best);
11617}
11618
11619OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11620 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11621
11622 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11623 Candidates.reserve(N: this->Candidates.size());
11624 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11625 result: std::back_inserter(x&: Candidates),
11626 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11627
11628 if (S.getLangOpts().CUDA)
11629 CudaExcludeWrongSideCandidates(S, Candidates);
11630
11631 Best = end();
11632 for (auto *Cand : Candidates) {
11633 Cand->Best = false;
11634 if (Cand->Viable) {
11635 if (Best == end() ||
11636 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11637 Best = Cand;
11638 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11639 // This candidate has constraint that we were unable to evaluate because
11640 // it referenced an expression that contained an error. Rather than fall
11641 // back onto a potentially unintended candidate (made worse by
11642 // subsuming constraints), treat this as 'no viable candidate'.
11643 Best = end();
11644 return OR_No_Viable_Function;
11645 }
11646 }
11647
11648 // If we didn't find any viable functions, abort.
11649 if (Best == end())
11650 return OR_No_Viable_Function;
11651
11652 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11653 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11654 PendingBest.push_back(Elt: &*Best);
11655 Best->Best = true;
11656
11657 // Make sure that this function is better than every other viable
11658 // function. If not, we have an ambiguity.
11659 while (!PendingBest.empty()) {
11660 auto *Curr = PendingBest.pop_back_val();
11661 for (auto *Cand : Candidates) {
11662 if (Cand->Viable && !Cand->Best &&
11663 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11664 PendingBest.push_back(Elt: Cand);
11665 Cand->Best = true;
11666
11667 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11668 B: Curr->Function))
11669 EquivalentCands.push_back(Elt: Cand->Function);
11670 else
11671 Best = end();
11672 }
11673 }
11674 }
11675
11676 if (Best == end())
11677 return OR_Ambiguous;
11678
11679 OverloadingResult R = ResultForBestCandidate(Best);
11680
11681 if (!EquivalentCands.empty())
11682 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11683 Equiv: EquivalentCands);
11684 return R;
11685}
11686
11687namespace {
11688
11689enum OverloadCandidateKind {
11690 oc_function,
11691 oc_method,
11692 oc_reversed_binary_operator,
11693 oc_constructor,
11694 oc_implicit_default_constructor,
11695 oc_implicit_copy_constructor,
11696 oc_implicit_move_constructor,
11697 oc_implicit_copy_assignment,
11698 oc_implicit_move_assignment,
11699 oc_implicit_equality_comparison,
11700 oc_inherited_constructor
11701};
11702
11703enum OverloadCandidateSelect {
11704 ocs_non_template,
11705 ocs_template,
11706 ocs_described_template,
11707};
11708
11709static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11710ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11711 const FunctionDecl *Fn,
11712 OverloadCandidateRewriteKind CRK,
11713 std::string &Description) {
11714
11715 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11716 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11717 isTemplate = true;
11718 Description = S.getTemplateArgumentBindingsText(
11719 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11720 }
11721
11722 OverloadCandidateSelect Select = [&]() {
11723 if (!Description.empty())
11724 return ocs_described_template;
11725 return isTemplate ? ocs_template : ocs_non_template;
11726 }();
11727
11728 OverloadCandidateKind Kind = [&]() {
11729 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11730 return oc_implicit_equality_comparison;
11731
11732 if (CRK & CRK_Reversed)
11733 return oc_reversed_binary_operator;
11734
11735 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11736 if (!Ctor->isImplicit()) {
11737 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11738 return oc_inherited_constructor;
11739 else
11740 return oc_constructor;
11741 }
11742
11743 if (Ctor->isDefaultConstructor())
11744 return oc_implicit_default_constructor;
11745
11746 if (Ctor->isMoveConstructor())
11747 return oc_implicit_move_constructor;
11748
11749 assert(Ctor->isCopyConstructor() &&
11750 "unexpected sort of implicit constructor");
11751 return oc_implicit_copy_constructor;
11752 }
11753
11754 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11755 // This actually gets spelled 'candidate function' for now, but
11756 // it doesn't hurt to split it out.
11757 if (!Meth->isImplicit())
11758 return oc_method;
11759
11760 if (Meth->isMoveAssignmentOperator())
11761 return oc_implicit_move_assignment;
11762
11763 if (Meth->isCopyAssignmentOperator())
11764 return oc_implicit_copy_assignment;
11765
11766 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11767 return oc_method;
11768 }
11769
11770 return oc_function;
11771 }();
11772
11773 return std::make_pair(x&: Kind, y&: Select);
11774}
11775
11776void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11777 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11778 // set.
11779 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11780 S.Diag(Loc: FoundDecl->getLocation(),
11781 DiagID: diag::note_ovl_candidate_inherited_constructor)
11782 << Shadow->getNominatedBaseClass();
11783}
11784
11785} // end anonymous namespace
11786
11787static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11788 const FunctionDecl *FD) {
11789 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11790 bool AlwaysTrue;
11791 if (EnableIf->getCond()->isValueDependent() ||
11792 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11793 return false;
11794 if (!AlwaysTrue)
11795 return false;
11796 }
11797 return true;
11798}
11799
11800/// Returns true if we can take the address of the function.
11801///
11802/// \param Complain - If true, we'll emit a diagnostic
11803/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11804/// we in overload resolution?
11805/// \param Loc - The location of the statement we're complaining about. Ignored
11806/// if we're not complaining, or if we're in overload resolution.
11807static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11808 bool Complain,
11809 bool InOverloadResolution,
11810 SourceLocation Loc) {
11811 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11812 if (Complain) {
11813 if (InOverloadResolution)
11814 S.Diag(Loc: FD->getBeginLoc(),
11815 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11816 else
11817 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11818 }
11819 return false;
11820 }
11821
11822 if (FD->getTrailingRequiresClause()) {
11823 ConstraintSatisfaction Satisfaction;
11824 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11825 return false;
11826 if (!Satisfaction.IsSatisfied) {
11827 if (Complain) {
11828 if (InOverloadResolution) {
11829 SmallString<128> TemplateArgString;
11830 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11831 TemplateArgString += " ";
11832 TemplateArgString += S.getTemplateArgumentBindingsText(
11833 Params: FunTmpl->getTemplateParameters(),
11834 Args: *FD->getTemplateSpecializationArgs());
11835 }
11836
11837 S.Diag(Loc: FD->getBeginLoc(),
11838 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11839 << TemplateArgString;
11840 } else
11841 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11842 << FD;
11843 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11844 }
11845 return false;
11846 }
11847 }
11848
11849 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11850 return P->hasAttr<PassObjectSizeAttr>();
11851 });
11852 if (I == FD->param_end())
11853 return true;
11854
11855 if (Complain) {
11856 // Add one to ParamNo because it's user-facing
11857 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11858 if (InOverloadResolution)
11859 S.Diag(Loc: FD->getLocation(),
11860 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11861 << ParamNo;
11862 else
11863 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11864 << FD << ParamNo;
11865 }
11866 return false;
11867}
11868
11869static bool checkAddressOfCandidateIsAvailable(Sema &S,
11870 const FunctionDecl *FD) {
11871 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11872 /*InOverloadResolution=*/true,
11873 /*Loc=*/SourceLocation());
11874}
11875
11876bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11877 bool Complain,
11878 SourceLocation Loc) {
11879 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11880 /*InOverloadResolution=*/false,
11881 Loc);
11882}
11883
11884// Don't print candidates other than the one that matches the calling
11885// convention of the call operator, since that is guaranteed to exist.
11886static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11887 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11888
11889 if (!ConvD)
11890 return false;
11891 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11892 if (!RD->isLambda())
11893 return false;
11894
11895 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11896 CallingConv CallOpCC =
11897 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11898 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11899 CallingConv ConvToCC =
11900 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11901
11902 return ConvToCC != CallOpCC;
11903}
11904
11905// Notes the location of an overload candidate.
11906void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11907 OverloadCandidateRewriteKind RewriteKind,
11908 QualType DestType, bool TakingAddress) {
11909 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11910 return;
11911 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11912 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11913 return;
11914 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11915 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11916 return;
11917 if (shouldSkipNotingLambdaConversionDecl(Fn))
11918 return;
11919
11920 std::string FnDesc;
11921 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11922 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11923 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11924 << (unsigned)KSPair.first << (unsigned)KSPair.second
11925 << Fn << FnDesc;
11926
11927 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11928 Diag(Loc: Fn->getLocation(), PD);
11929 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11930}
11931
11932static void
11933MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11934 // Perhaps the ambiguity was caused by two atomic constraints that are
11935 // 'identical' but not equivalent:
11936 //
11937 // void foo() requires (sizeof(T) > 4) { } // #1
11938 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11939 //
11940 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11941 // #2 to subsume #1, but these constraint are not considered equivalent
11942 // according to the subsumption rules because they are not the same
11943 // source-level construct. This behavior is quite confusing and we should try
11944 // to help the user figure out what happened.
11945
11946 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11947 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11948 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11949 if (!I->Function)
11950 continue;
11951 SmallVector<AssociatedConstraint, 3> AC;
11952 if (auto *Template = I->Function->getPrimaryTemplate())
11953 Template->getAssociatedConstraints(AC);
11954 else
11955 I->Function->getAssociatedConstraints(ACs&: AC);
11956 if (AC.empty())
11957 continue;
11958 if (FirstCand == nullptr) {
11959 FirstCand = I->Function;
11960 FirstAC = AC;
11961 } else if (SecondCand == nullptr) {
11962 SecondCand = I->Function;
11963 SecondAC = AC;
11964 } else {
11965 // We have more than one pair of constrained functions - this check is
11966 // expensive and we'd rather not try to diagnose it.
11967 return;
11968 }
11969 }
11970 if (!SecondCand)
11971 return;
11972 // The diagnostic can only happen if there are associated constraints on
11973 // both sides (there needs to be some identical atomic constraint).
11974 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11975 D2: SecondCand, AC2: SecondAC))
11976 // Just show the user one diagnostic, they'll probably figure it out
11977 // from here.
11978 return;
11979}
11980
11981// Notes the location of all overload candidates designated through
11982// OverloadedExpr
11983void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11984 bool TakingAddress) {
11985 assert(OverloadedExpr->getType() == Context.OverloadTy);
11986
11987 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11988 OverloadExpr *OvlExpr = Ovl.Expression;
11989
11990 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11991 IEnd = OvlExpr->decls_end();
11992 I != IEnd; ++I) {
11993 if (FunctionTemplateDecl *FunTmpl =
11994 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11995 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11996 TakingAddress);
11997 } else if (FunctionDecl *Fun
11998 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11999 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
12000 }
12001 }
12002}
12003
12004/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12005/// "lead" diagnostic; it will be given two arguments, the source and
12006/// target types of the conversion.
12007void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
12008 Sema &S,
12009 SourceLocation CaretLoc,
12010 const PartialDiagnostic &PDiag) const {
12011 S.Diag(Loc: CaretLoc, PD: PDiag)
12012 << Ambiguous.getFromType() << Ambiguous.getToType();
12013 unsigned CandsShown = 0;
12014 AmbiguousConversionSequence::const_iterator I, E;
12015 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12016 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12017 break;
12018 ++CandsShown;
12019 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
12020 }
12021 S.Diags.overloadCandidatesShown(N: CandsShown);
12022 if (I != E)
12023 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12024}
12025
12026static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
12027 unsigned I, bool TakingCandidateAddress) {
12028 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12029 assert(Conv.isBad());
12030 assert(Cand->Function && "for now, candidate must be a function");
12031 FunctionDecl *Fn = Cand->Function;
12032
12033 // There's a conversion slot for the object argument if this is a
12034 // non-constructor method. Note that 'I' corresponds the
12035 // conversion-slot index.
12036 bool isObjectArgument = false;
12037 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12038 !isa<CXXConstructorDecl>(Val: Fn)) {
12039 if (I == 0)
12040 isObjectArgument = true;
12041 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12042 I--;
12043 }
12044
12045 std::string FnDesc;
12046 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12047 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12048 Description&: FnDesc);
12049
12050 Expr *FromExpr = Conv.Bad.FromExpr;
12051 QualType FromTy = Conv.Bad.getFromType();
12052 QualType ToTy = Conv.Bad.getToType();
12053 SourceRange ToParamRange;
12054
12055 // FIXME: In presence of parameter packs we can't determine parameter range
12056 // reliably, as we don't have access to instantiation.
12057 bool HasParamPack =
12058 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12059 return Parm->isParameterPack();
12060 });
12061 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12062 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12063
12064 if (FromTy == S.Context.OverloadTy) {
12065 assert(FromExpr && "overload set argument came from implicit argument?");
12066 Expr *E = FromExpr->IgnoreParens();
12067 if (isa<UnaryOperator>(Val: E))
12068 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12069 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12070
12071 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12072 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12073 << ToParamRange << ToTy << Name << I + 1;
12074 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12075 return;
12076 }
12077
12078 // Do some hand-waving analysis to see if the non-viability is due
12079 // to a qualifier mismatch.
12080 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12081 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12082 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12083 CToTy = RT->getPointeeType();
12084 else {
12085 // TODO: detect and diagnose the full richness of const mismatches.
12086 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12087 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12088 CFromTy = FromPT->getPointeeType();
12089 CToTy = ToPT->getPointeeType();
12090 }
12091 }
12092
12093 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12094 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12095 Qualifiers FromQs = CFromTy.getQualifiers();
12096 Qualifiers ToQs = CToTy.getQualifiers();
12097
12098 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12099 if (isObjectArgument)
12100 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12101 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12102 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12103 else
12104 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12105 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12106 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12107 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12108 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12109 return;
12110 }
12111
12112 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12113 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12114 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12115 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12116 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12117 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12118 return;
12119 }
12120
12121 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12122 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12123 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12124 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12125 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12126 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12127 return;
12128 }
12129
12130 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12131 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12132 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12133 << FromTy << !!FromQs.getPointerAuth()
12134 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12135 << ToQs.getPointerAuth().getAsString() << I + 1
12136 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12137 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12138 return;
12139 }
12140
12141 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12142 assert(CVR && "expected qualifiers mismatch");
12143
12144 if (isObjectArgument) {
12145 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12146 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12147 << FromTy << (CVR - 1);
12148 } else {
12149 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12150 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12151 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12152 }
12153 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12154 return;
12155 }
12156
12157 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12158 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12159 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12160 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12161 << (unsigned)isObjectArgument << I + 1
12162 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12163 << ToParamRange;
12164 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12165 return;
12166 }
12167
12168 // Special diagnostic for failure to convert an initializer list, since
12169 // telling the user that it has type void is not useful.
12170 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12171 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12172 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12173 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12174 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12175 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12176 ? 2
12177 : 0);
12178 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12179 return;
12180 }
12181
12182 // Diagnose references or pointers to incomplete types differently,
12183 // since it's far from impossible that the incompleteness triggered
12184 // the failure.
12185 QualType TempFromTy = FromTy.getNonReferenceType();
12186 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12187 TempFromTy = PTy->getPointeeType();
12188 if (TempFromTy->isIncompleteType()) {
12189 // Emit the generic diagnostic and, optionally, add the hints to it.
12190 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12191 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12192 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12193 << (unsigned)(Cand->Fix.Kind);
12194
12195 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12196 return;
12197 }
12198
12199 // Diagnose base -> derived pointer conversions.
12200 unsigned BaseToDerivedConversion = 0;
12201 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12202 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12203 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12204 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12205 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12206 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12207 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12208 Base: FromPtrTy->getPointeeType()))
12209 BaseToDerivedConversion = 1;
12210 }
12211 } else if (const ObjCObjectPointerType *FromPtrTy
12212 = FromTy->getAs<ObjCObjectPointerType>()) {
12213 if (const ObjCObjectPointerType *ToPtrTy
12214 = ToTy->getAs<ObjCObjectPointerType>())
12215 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12216 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12217 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12218 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12219 FromIface->isSuperClassOf(I: ToIface))
12220 BaseToDerivedConversion = 2;
12221 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12222 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12223 Ctx: S.getASTContext()) &&
12224 !FromTy->isIncompleteType() &&
12225 !ToRefTy->getPointeeType()->isIncompleteType() &&
12226 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12227 BaseToDerivedConversion = 3;
12228 }
12229 }
12230
12231 if (BaseToDerivedConversion) {
12232 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12233 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12234 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12235 << I + 1;
12236 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12237 return;
12238 }
12239
12240 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12241 isa<PointerType>(Val: CToTy)) {
12242 Qualifiers FromQs = CFromTy.getQualifiers();
12243 Qualifiers ToQs = CToTy.getQualifiers();
12244 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12245 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12246 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12247 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12248 << I + 1;
12249 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12250 return;
12251 }
12252 }
12253
12254 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12255 return;
12256
12257 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12258 // although this is almost always an error and we advise against it.
12259 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12260 ToTy == S.Context.getLogicalOperationType()) {
12261 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12262 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12263 << Conv.Bad.FromExpr << ToTy;
12264 return;
12265 }
12266
12267 // Emit the generic diagnostic and, optionally, add the hints to it.
12268 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12269 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12270 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12271 << (unsigned)(Cand->Fix.Kind);
12272
12273 // Check that location of Fn is not in system header.
12274 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12275 // If we can fix the conversion, suggest the FixIts.
12276 for (const FixItHint &HI : Cand->Fix.Hints)
12277 FDiag << HI;
12278 }
12279
12280 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12281
12282 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12283}
12284
12285/// Additional arity mismatch diagnosis specific to a function overload
12286/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12287/// over a candidate in any candidate set.
12288static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12289 unsigned NumArgs, bool IsAddressOf = false) {
12290 assert(Cand->Function && "Candidate is required to be a function.");
12291 FunctionDecl *Fn = Cand->Function;
12292 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12293 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12294
12295 // With invalid overloaded operators, it's possible that we think we
12296 // have an arity mismatch when in fact it looks like we have the
12297 // right number of arguments, because only overloaded operators have
12298 // the weird behavior of overloading member and non-member functions.
12299 // Just don't report anything.
12300 if (Fn->isInvalidDecl() &&
12301 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12302 return true;
12303
12304 if (NumArgs < MinParams) {
12305 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12306 (Cand->FailureKind == ovl_fail_bad_deduction &&
12307 Cand->DeductionFailure.getResult() ==
12308 TemplateDeductionResult::TooFewArguments));
12309 } else {
12310 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12311 (Cand->FailureKind == ovl_fail_bad_deduction &&
12312 Cand->DeductionFailure.getResult() ==
12313 TemplateDeductionResult::TooManyArguments));
12314 }
12315
12316 return false;
12317}
12318
12319/// General arity mismatch diagnosis over a candidate in a candidate set.
12320static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12321 unsigned NumFormalArgs,
12322 bool IsAddressOf = false) {
12323 assert(isa<FunctionDecl>(D) &&
12324 "The templated declaration should at least be a function"
12325 " when diagnosing bad template argument deduction due to too many"
12326 " or too few arguments");
12327
12328 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12329
12330 // TODO: treat calls to a missing default constructor as a special case
12331 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12332 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12333 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12334
12335 // at least / at most / exactly
12336 bool HasExplicitObjectParam =
12337 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12338
12339 unsigned ParamCount =
12340 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12341 unsigned mode, modeCount;
12342
12343 if (NumFormalArgs < MinParams) {
12344 if (MinParams != ParamCount || FnTy->isVariadic() ||
12345 FnTy->isTemplateVariadic())
12346 mode = 0; // "at least"
12347 else
12348 mode = 2; // "exactly"
12349 modeCount = MinParams;
12350 } else {
12351 if (MinParams != ParamCount)
12352 mode = 1; // "at most"
12353 else
12354 mode = 2; // "exactly"
12355 modeCount = ParamCount;
12356 }
12357
12358 std::string Description;
12359 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12360 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12361
12362 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12363 if (modeCount == 1 && !IsAddressOf &&
12364 FirstNonObjectParamIdx < Fn->getNumParams() &&
12365 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12366 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12367 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12368 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12369 << NumFormalArgs << HasExplicitObjectParam
12370 << Fn->getParametersSourceRange();
12371 else
12372 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12373 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12374 << Description << mode << modeCount << NumFormalArgs
12375 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12376
12377 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12378}
12379
12380/// Arity mismatch diagnosis specific to a function overload candidate.
12381static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12382 unsigned NumFormalArgs) {
12383 assert(Cand->Function && "Candidate must be a function");
12384 FunctionDecl *Fn = Cand->Function;
12385 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12386 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12387 IsAddressOf: Cand->TookAddressOfOverload);
12388}
12389
12390static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12391 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12392 return TD;
12393 llvm_unreachable("Unsupported: Getting the described template declaration"
12394 " for bad deduction diagnosis");
12395}
12396
12397/// Diagnose a failed template-argument deduction.
12398static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12399 DeductionFailureInfo &DeductionFailure,
12400 unsigned NumArgs,
12401 bool TakingCandidateAddress) {
12402 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12403 NamedDecl *ParamD;
12404 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12405 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12406 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12407 switch (DeductionFailure.getResult()) {
12408 case TemplateDeductionResult::Success:
12409 llvm_unreachable(
12410 "TemplateDeductionResult::Success while diagnosing bad deduction");
12411 case TemplateDeductionResult::NonDependentConversionFailure:
12412 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12413 "while diagnosing bad deduction");
12414 case TemplateDeductionResult::Invalid:
12415 case TemplateDeductionResult::AlreadyDiagnosed:
12416 return;
12417
12418 case TemplateDeductionResult::Incomplete: {
12419 assert(ParamD && "no parameter found for incomplete deduction result");
12420 S.Diag(Loc: Templated->getLocation(),
12421 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12422 << ParamD->getDeclName();
12423 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12424 return;
12425 }
12426
12427 case TemplateDeductionResult::IncompletePack: {
12428 assert(ParamD && "no parameter found for incomplete deduction result");
12429 S.Diag(Loc: Templated->getLocation(),
12430 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12431 << ParamD->getDeclName()
12432 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12433 << *DeductionFailure.getFirstArg();
12434 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12435 return;
12436 }
12437
12438 case TemplateDeductionResult::Underqualified: {
12439 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12440 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12441
12442 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12443
12444 // Param will have been canonicalized, but it should just be a
12445 // qualified version of ParamD, so move the qualifiers to that.
12446 QualifierCollector Qs;
12447 Qs.strip(type: Param);
12448 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12449 assert(S.Context.hasSameType(Param, NonCanonParam));
12450
12451 // Arg has also been canonicalized, but there's nothing we can do
12452 // about that. It also doesn't matter as much, because it won't
12453 // have any template parameters in it (because deduction isn't
12454 // done on dependent types).
12455 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12456
12457 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12458 << ParamD->getDeclName() << Arg << NonCanonParam;
12459 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12460 return;
12461 }
12462
12463 case TemplateDeductionResult::Inconsistent: {
12464 assert(ParamD && "no parameter found for inconsistent deduction result");
12465 int which = 0;
12466 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12467 which = 0;
12468 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12469 // Deduction might have failed because we deduced arguments of two
12470 // different types for a non-type template parameter.
12471 // FIXME: Use a different TDK value for this.
12472 QualType T1 =
12473 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12474 QualType T2 =
12475 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12476 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12477 S.Diag(Loc: Templated->getLocation(),
12478 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12479 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12480 << *DeductionFailure.getSecondArg() << T2;
12481 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12482 return;
12483 }
12484
12485 which = 1;
12486 } else {
12487 which = 2;
12488 }
12489
12490 // Tweak the diagnostic if the problem is that we deduced packs of
12491 // different arities. We'll print the actual packs anyway in case that
12492 // includes additional useful information.
12493 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12494 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12495 DeductionFailure.getFirstArg()->pack_size() !=
12496 DeductionFailure.getSecondArg()->pack_size()) {
12497 which = 3;
12498 }
12499
12500 S.Diag(Loc: Templated->getLocation(),
12501 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12502 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12503 << *DeductionFailure.getSecondArg();
12504 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12505 return;
12506 }
12507
12508 case TemplateDeductionResult::InvalidExplicitArguments: {
12509 assert(ParamD && "no parameter found for invalid explicit arguments");
12510
12511 auto Diag = S.Diag(Loc: Templated->getLocation(),
12512 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch);
12513 if (ParamD->getDeclName())
12514 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12515 else
12516 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12517 << (getDepthAndIndex(ND: ParamD).second + 1);
12518 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12519 SmallString<128> DiagContent;
12520 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: DiagContent);
12521 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12522 } else {
12523 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12524 }
12525
12526 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12527 return;
12528 }
12529 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12530 // Format the template argument list into the argument string.
12531 SmallString<128> TemplateArgString;
12532 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12533 TemplateArgString = " ";
12534 TemplateArgString += S.getTemplateArgumentBindingsText(
12535 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12536 if (TemplateArgString.size() == 1)
12537 TemplateArgString.clear();
12538 S.Diag(Loc: Templated->getLocation(),
12539 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12540 << TemplateArgString;
12541
12542 S.DiagnoseUnsatisfiedConstraint(
12543 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12544 return;
12545 }
12546 case TemplateDeductionResult::TooManyArguments:
12547 case TemplateDeductionResult::TooFewArguments:
12548 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12549 return;
12550
12551 case TemplateDeductionResult::InstantiationDepth:
12552 S.Diag(Loc: Templated->getLocation(),
12553 DiagID: diag::note_ovl_candidate_instantiation_depth);
12554 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12555 return;
12556
12557 case TemplateDeductionResult::SubstitutionFailure: {
12558 // Format the template argument list into the argument string.
12559 SmallString<128> TemplateArgString;
12560 if (TemplateArgumentList *Args =
12561 DeductionFailure.getTemplateArgumentList()) {
12562 TemplateArgString = " ";
12563 TemplateArgString += S.getTemplateArgumentBindingsText(
12564 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12565 if (TemplateArgString.size() == 1)
12566 TemplateArgString.clear();
12567 }
12568
12569 // If this candidate was disabled by enable_if, say so.
12570 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12571 if (PDiag && PDiag->second.getDiagID() ==
12572 diag::err_typename_nested_not_found_enable_if) {
12573 // FIXME: Use the source range of the condition, and the fully-qualified
12574 // name of the enable_if template. These are both present in PDiag.
12575 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12576 << "'enable_if'" << TemplateArgString;
12577 return;
12578 }
12579
12580 // We found a specific requirement that disabled the enable_if.
12581 if (PDiag && PDiag->second.getDiagID() ==
12582 diag::err_typename_nested_not_found_requirement) {
12583 S.Diag(Loc: Templated->getLocation(),
12584 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12585 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12586 return;
12587 }
12588
12589 // Format the SFINAE diagnostic into the argument string.
12590 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12591 // formatted message in another diagnostic.
12592 SmallString<128> SFINAEArgString;
12593 SourceRange R;
12594 if (PDiag) {
12595 SFINAEArgString = ": ";
12596 R = SourceRange(PDiag->first, PDiag->first);
12597 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12598 }
12599
12600 S.Diag(Loc: Templated->getLocation(),
12601 DiagID: diag::note_ovl_candidate_substitution_failure)
12602 << TemplateArgString << SFINAEArgString << R;
12603 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12604 return;
12605 }
12606
12607 case TemplateDeductionResult::DeducedMismatch:
12608 case TemplateDeductionResult::DeducedMismatchNested: {
12609 // Format the template argument list into the argument string.
12610 SmallString<128> TemplateArgString;
12611 if (TemplateArgumentList *Args =
12612 DeductionFailure.getTemplateArgumentList()) {
12613 TemplateArgString = " ";
12614 TemplateArgString += S.getTemplateArgumentBindingsText(
12615 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12616 if (TemplateArgString.size() == 1)
12617 TemplateArgString.clear();
12618 }
12619
12620 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12621 << (*DeductionFailure.getCallArgIndex() + 1)
12622 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12623 << TemplateArgString
12624 << (DeductionFailure.getResult() ==
12625 TemplateDeductionResult::DeducedMismatchNested);
12626 break;
12627 }
12628
12629 case TemplateDeductionResult::NonDeducedMismatch: {
12630 // FIXME: Provide a source location to indicate what we couldn't match.
12631 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12632 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12633 if (FirstTA.getKind() == TemplateArgument::Template &&
12634 SecondTA.getKind() == TemplateArgument::Template) {
12635 TemplateName FirstTN = FirstTA.getAsTemplate();
12636 TemplateName SecondTN = SecondTA.getAsTemplate();
12637 if (FirstTN.getKind() == TemplateName::Template &&
12638 SecondTN.getKind() == TemplateName::Template) {
12639 if (FirstTN.getAsTemplateDecl()->getName() ==
12640 SecondTN.getAsTemplateDecl()->getName()) {
12641 // FIXME: This fixes a bad diagnostic where both templates are named
12642 // the same. This particular case is a bit difficult since:
12643 // 1) It is passed as a string to the diagnostic printer.
12644 // 2) The diagnostic printer only attempts to find a better
12645 // name for types, not decls.
12646 // Ideally, this should folded into the diagnostic printer.
12647 S.Diag(Loc: Templated->getLocation(),
12648 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12649 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12650 return;
12651 }
12652 }
12653 }
12654
12655 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12656 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12657 return;
12658
12659 // FIXME: For generic lambda parameters, check if the function is a lambda
12660 // call operator, and if so, emit a prettier and more informative
12661 // diagnostic that mentions 'auto' and lambda in addition to
12662 // (or instead of?) the canonical template type parameters.
12663 S.Diag(Loc: Templated->getLocation(),
12664 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12665 << FirstTA << SecondTA;
12666 return;
12667 }
12668 // TODO: diagnose these individually, then kill off
12669 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12670 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12671 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12672 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12673 return;
12674 case TemplateDeductionResult::CUDATargetMismatch:
12675 S.Diag(Loc: Templated->getLocation(),
12676 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12677 return;
12678 }
12679}
12680
12681/// Diagnose a failed template-argument deduction, for function calls.
12682static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12683 unsigned NumArgs,
12684 bool TakingCandidateAddress) {
12685 assert(Cand->Function && "Candidate must be a function");
12686 FunctionDecl *Fn = Cand->Function;
12687 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12688 if (TDK == TemplateDeductionResult::TooFewArguments ||
12689 TDK == TemplateDeductionResult::TooManyArguments) {
12690 if (CheckArityMismatch(S, Cand, NumArgs))
12691 return;
12692 }
12693 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12694 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12695}
12696
12697/// CUDA: diagnose an invalid call across targets.
12698static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12699 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12700 assert(Cand->Function && "Candidate must be a Function.");
12701 FunctionDecl *Callee = Cand->Function;
12702
12703 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12704 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12705
12706 std::string FnDesc;
12707 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12708 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12709 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12710
12711 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12712 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12713 << FnDesc /* Ignored */
12714 << CalleeTarget << CallerTarget;
12715
12716 // This could be an implicit constructor for which we could not infer the
12717 // target due to a collsion. Diagnose that case.
12718 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12719 if (Meth != nullptr && Meth->isImplicit()) {
12720 CXXRecordDecl *ParentClass = Meth->getParent();
12721 CXXSpecialMemberKind CSM;
12722
12723 switch (FnKindPair.first) {
12724 default:
12725 return;
12726 case oc_implicit_default_constructor:
12727 CSM = CXXSpecialMemberKind::DefaultConstructor;
12728 break;
12729 case oc_implicit_copy_constructor:
12730 CSM = CXXSpecialMemberKind::CopyConstructor;
12731 break;
12732 case oc_implicit_move_constructor:
12733 CSM = CXXSpecialMemberKind::MoveConstructor;
12734 break;
12735 case oc_implicit_copy_assignment:
12736 CSM = CXXSpecialMemberKind::CopyAssignment;
12737 break;
12738 case oc_implicit_move_assignment:
12739 CSM = CXXSpecialMemberKind::MoveAssignment;
12740 break;
12741 };
12742
12743 bool ConstRHS = false;
12744 if (Meth->getNumParams()) {
12745 if (const ReferenceType *RT =
12746 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12747 ConstRHS = RT->getPointeeType().isConstQualified();
12748 }
12749 }
12750
12751 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12752 /* ConstRHS */ ConstRHS,
12753 /* Diagnose */ true);
12754 }
12755}
12756
12757static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12758 assert(Cand->Function && "Candidate must be a function");
12759 FunctionDecl *Callee = Cand->Function;
12760 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12761
12762 S.Diag(Loc: Callee->getLocation(),
12763 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12764 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12765}
12766
12767static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12768 assert(Cand->Function && "Candidate must be a function");
12769 FunctionDecl *Fn = Cand->Function;
12770 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12771 assert(ES.isExplicit() && "not an explicit candidate");
12772
12773 unsigned Kind;
12774 switch (Fn->getDeclKind()) {
12775 case Decl::Kind::CXXConstructor:
12776 Kind = 0;
12777 break;
12778 case Decl::Kind::CXXConversion:
12779 Kind = 1;
12780 break;
12781 case Decl::Kind::CXXDeductionGuide:
12782 Kind = Fn->isImplicit() ? 0 : 2;
12783 break;
12784 default:
12785 llvm_unreachable("invalid Decl");
12786 }
12787
12788 // Note the location of the first (in-class) declaration; a redeclaration
12789 // (particularly an out-of-class definition) will typically lack the
12790 // 'explicit' specifier.
12791 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12792 FunctionDecl *First = Fn->getFirstDecl();
12793 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12794 First = Pattern->getFirstDecl();
12795
12796 S.Diag(Loc: First->getLocation(),
12797 DiagID: diag::note_ovl_candidate_explicit)
12798 << Kind << (ES.getExpr() ? 1 : 0)
12799 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12800}
12801
12802static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12803 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12804 if (!DG)
12805 return;
12806 TemplateDecl *OriginTemplate =
12807 DG->getDeclName().getCXXDeductionGuideTemplate();
12808 // We want to always print synthesized deduction guides for type aliases.
12809 // They would retain the explicit bit of the corresponding constructor.
12810 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12811 return;
12812 std::string FunctionProto;
12813 llvm::raw_string_ostream OS(FunctionProto);
12814 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12815 if (!Template) {
12816 // This also could be an instantiation. Find out the primary template.
12817 FunctionDecl *Pattern =
12818 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12819 if (!Pattern) {
12820 // The implicit deduction guide is built on an explicit non-template
12821 // deduction guide. Currently, this might be the case only for type
12822 // aliases.
12823 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12824 // gets merged.
12825 assert(OriginTemplate->isTypeAlias() &&
12826 "Non-template implicit deduction guides are only possible for "
12827 "type aliases");
12828 DG->print(Out&: OS);
12829 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12830 << FunctionProto;
12831 return;
12832 }
12833 Template = Pattern->getDescribedFunctionTemplate();
12834 assert(Template && "Cannot find the associated function template of "
12835 "CXXDeductionGuideDecl?");
12836 }
12837 Template->print(Out&: OS);
12838 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12839 << FunctionProto;
12840}
12841
12842/// Generates a 'note' diagnostic for an overload candidate. We've
12843/// already generated a primary error at the call site.
12844///
12845/// It really does need to be a single diagnostic with its caret
12846/// pointed at the candidate declaration. Yes, this creates some
12847/// major challenges of technical writing. Yes, this makes pointing
12848/// out problems with specific arguments quite awkward. It's still
12849/// better than generating twenty screens of text for every failed
12850/// overload.
12851///
12852/// It would be great to be able to express per-candidate problems
12853/// more richly for those diagnostic clients that cared, but we'd
12854/// still have to be just as careful with the default diagnostics.
12855/// \param CtorDestAS Addr space of object being constructed (for ctor
12856/// candidates only).
12857static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12858 unsigned NumArgs,
12859 bool TakingCandidateAddress,
12860 LangAS CtorDestAS = LangAS::Default) {
12861 assert(Cand->Function && "Candidate must be a function");
12862 FunctionDecl *Fn = Cand->Function;
12863 if (shouldSkipNotingLambdaConversionDecl(Fn))
12864 return;
12865
12866 // There is no physical candidate declaration to point to for OpenCL builtins.
12867 // Except for failed conversions, the notes are identical for each candidate,
12868 // so do not generate such notes.
12869 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12870 Cand->FailureKind != ovl_fail_bad_conversion)
12871 return;
12872
12873 // Skip implicit member functions when trying to resolve
12874 // the address of a an overload set for a function pointer.
12875 if (Cand->TookAddressOfOverload &&
12876 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12877 return;
12878
12879 // Note deleted candidates, but only if they're viable.
12880 if (Cand->Viable) {
12881 if (Fn->isDeleted()) {
12882 std::string FnDesc;
12883 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12884 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12885 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12886
12887 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12888 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12889 << (Fn->isDeleted()
12890 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12891 : 0);
12892 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12893 return;
12894 }
12895
12896 // We don't really have anything else to say about viable candidates.
12897 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12898 return;
12899 }
12900
12901 // If this is a synthesized deduction guide we're deducing against, add a note
12902 // for it. These deduction guides are not explicitly spelled in the source
12903 // code, so simply printing a deduction failure note mentioning synthesized
12904 // template parameters or pointing to the header of the surrounding RecordDecl
12905 // would be confusing.
12906 //
12907 // We prefer adding such notes at the end of the deduction failure because
12908 // duplicate code snippets appearing in the diagnostic would likely become
12909 // noisy.
12910 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12911
12912 switch (Cand->FailureKind) {
12913 case ovl_fail_too_many_arguments:
12914 case ovl_fail_too_few_arguments:
12915 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12916
12917 case ovl_fail_bad_deduction:
12918 return DiagnoseBadDeduction(S, Cand, NumArgs,
12919 TakingCandidateAddress);
12920
12921 case ovl_fail_illegal_constructor: {
12922 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12923 << (Fn->getPrimaryTemplate() ? 1 : 0);
12924 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12925 return;
12926 }
12927
12928 case ovl_fail_object_addrspace_mismatch: {
12929 Qualifiers QualsForPrinting;
12930 QualsForPrinting.setAddressSpace(CtorDestAS);
12931 S.Diag(Loc: Fn->getLocation(),
12932 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12933 << QualsForPrinting;
12934 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12935 return;
12936 }
12937
12938 case ovl_fail_trivial_conversion:
12939 case ovl_fail_bad_final_conversion:
12940 case ovl_fail_final_conversion_not_exact:
12941 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12942
12943 case ovl_fail_bad_conversion: {
12944 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12945 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12946 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12947 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12948
12949 // FIXME: this currently happens when we're called from SemaInit
12950 // when user-conversion overload fails. Figure out how to handle
12951 // those conditions and diagnose them well.
12952 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12953 }
12954
12955 case ovl_fail_bad_target:
12956 return DiagnoseBadTarget(S, Cand);
12957
12958 case ovl_fail_enable_if:
12959 return DiagnoseFailedEnableIfAttr(S, Cand);
12960
12961 case ovl_fail_explicit:
12962 return DiagnoseFailedExplicitSpec(S, Cand);
12963
12964 case ovl_fail_inhctor_slice:
12965 // It's generally not interesting to note copy/move constructors here.
12966 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12967 return;
12968 S.Diag(Loc: Fn->getLocation(),
12969 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12970 << (Fn->getPrimaryTemplate() ? 1 : 0)
12971 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12972 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12973 return;
12974
12975 case ovl_fail_addr_not_available: {
12976 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12977 (void)Available;
12978 assert(!Available);
12979 break;
12980 }
12981 case ovl_non_default_multiversion_function:
12982 // Do nothing, these should simply be ignored.
12983 break;
12984
12985 case ovl_fail_constraints_not_satisfied: {
12986 std::string FnDesc;
12987 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12988 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12989 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12990
12991 S.Diag(Loc: Fn->getLocation(),
12992 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12993 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12994 << FnDesc /* Ignored */;
12995 ConstraintSatisfaction Satisfaction;
12996 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
12997 /*ForOverloadResolution=*/true))
12998 break;
12999 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13000 }
13001 }
13002}
13003
13004static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
13005 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
13006 return;
13007
13008 // Desugar the type of the surrogate down to a function type,
13009 // retaining as many typedefs as possible while still showing
13010 // the function type (and, therefore, its parameter types).
13011 QualType FnType = Cand->Surrogate->getConversionType();
13012 bool isLValueReference = false;
13013 bool isRValueReference = false;
13014 bool isPointer = false;
13015 if (const LValueReferenceType *FnTypeRef =
13016 FnType->getAs<LValueReferenceType>()) {
13017 FnType = FnTypeRef->getPointeeType();
13018 isLValueReference = true;
13019 } else if (const RValueReferenceType *FnTypeRef =
13020 FnType->getAs<RValueReferenceType>()) {
13021 FnType = FnTypeRef->getPointeeType();
13022 isRValueReference = true;
13023 }
13024 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13025 FnType = FnTypePtr->getPointeeType();
13026 isPointer = true;
13027 }
13028 // Desugar down to a function type.
13029 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13030 // Reconstruct the pointer/reference as appropriate.
13031 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
13032 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13033 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13034
13035 if (!Cand->Viable &&
13036 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13037 S.Diag(Loc: Cand->Surrogate->getLocation(),
13038 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13039 << Cand->Surrogate;
13040 ConstraintSatisfaction Satisfaction;
13041 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13042 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13043 } else {
13044 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13045 << FnType;
13046 }
13047}
13048
13049static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13050 SourceLocation OpLoc,
13051 OverloadCandidate *Cand) {
13052 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13053 std::string TypeStr("operator");
13054 TypeStr += Opc;
13055 TypeStr += "(";
13056 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13057 if (Cand->Conversions.size() == 1) {
13058 TypeStr += ")";
13059 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13060 } else {
13061 TypeStr += ", ";
13062 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13063 TypeStr += ")";
13064 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13065 }
13066}
13067
13068static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13069 OverloadCandidate *Cand) {
13070 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13071 if (ICS.isBad()) break; // all meaningless after first invalid
13072 if (!ICS.isAmbiguous()) continue;
13073
13074 ICS.DiagnoseAmbiguousConversion(
13075 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13076 }
13077}
13078
13079static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13080 if (Cand->Function)
13081 return Cand->Function->getLocation();
13082 if (Cand->IsSurrogate)
13083 return Cand->Surrogate->getLocation();
13084 return SourceLocation();
13085}
13086
13087static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13088 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13089 case TemplateDeductionResult::Success:
13090 case TemplateDeductionResult::NonDependentConversionFailure:
13091 case TemplateDeductionResult::AlreadyDiagnosed:
13092 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13093
13094 case TemplateDeductionResult::Invalid:
13095 case TemplateDeductionResult::Incomplete:
13096 case TemplateDeductionResult::IncompletePack:
13097 return 1;
13098
13099 case TemplateDeductionResult::Underqualified:
13100 case TemplateDeductionResult::Inconsistent:
13101 return 2;
13102
13103 case TemplateDeductionResult::SubstitutionFailure:
13104 case TemplateDeductionResult::DeducedMismatch:
13105 case TemplateDeductionResult::ConstraintsNotSatisfied:
13106 case TemplateDeductionResult::DeducedMismatchNested:
13107 case TemplateDeductionResult::NonDeducedMismatch:
13108 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13109 case TemplateDeductionResult::CUDATargetMismatch:
13110 return 3;
13111
13112 case TemplateDeductionResult::InstantiationDepth:
13113 return 4;
13114
13115 case TemplateDeductionResult::InvalidExplicitArguments:
13116 return 5;
13117
13118 case TemplateDeductionResult::TooManyArguments:
13119 case TemplateDeductionResult::TooFewArguments:
13120 return 6;
13121 }
13122 llvm_unreachable("Unhandled deduction result");
13123}
13124
13125namespace {
13126
13127struct CompareOverloadCandidatesForDisplay {
13128 Sema &S;
13129 SourceLocation Loc;
13130 size_t NumArgs;
13131 OverloadCandidateSet::CandidateSetKind CSK;
13132
13133 CompareOverloadCandidatesForDisplay(
13134 Sema &S, SourceLocation Loc, size_t NArgs,
13135 OverloadCandidateSet::CandidateSetKind CSK)
13136 : S(S), NumArgs(NArgs), CSK(CSK) {}
13137
13138 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13139 // If there are too many or too few arguments, that's the high-order bit we
13140 // want to sort by, even if the immediate failure kind was something else.
13141 if (C->FailureKind == ovl_fail_too_many_arguments ||
13142 C->FailureKind == ovl_fail_too_few_arguments)
13143 return static_cast<OverloadFailureKind>(C->FailureKind);
13144
13145 if (C->Function) {
13146 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13147 return ovl_fail_too_many_arguments;
13148 if (NumArgs < C->Function->getMinRequiredArguments())
13149 return ovl_fail_too_few_arguments;
13150 }
13151
13152 return static_cast<OverloadFailureKind>(C->FailureKind);
13153 }
13154
13155 bool operator()(const OverloadCandidate *L,
13156 const OverloadCandidate *R) {
13157 // Fast-path this check.
13158 if (L == R) return false;
13159
13160 // Order first by viability.
13161 if (L->Viable) {
13162 if (!R->Viable) return true;
13163
13164 if (int Ord = CompareConversions(L: *L, R: *R))
13165 return Ord < 0;
13166 // Use other tie breakers.
13167 } else if (R->Viable)
13168 return false;
13169
13170 assert(L->Viable == R->Viable);
13171
13172 // Criteria by which we can sort non-viable candidates:
13173 if (!L->Viable) {
13174 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13175 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13176
13177 // 1. Arity mismatches come after other candidates.
13178 if (LFailureKind == ovl_fail_too_many_arguments ||
13179 LFailureKind == ovl_fail_too_few_arguments) {
13180 if (RFailureKind == ovl_fail_too_many_arguments ||
13181 RFailureKind == ovl_fail_too_few_arguments) {
13182 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13183 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13184 if (LDist == RDist) {
13185 if (LFailureKind == RFailureKind)
13186 // Sort non-surrogates before surrogates.
13187 return !L->IsSurrogate && R->IsSurrogate;
13188 // Sort candidates requiring fewer parameters than there were
13189 // arguments given after candidates requiring more parameters
13190 // than there were arguments given.
13191 return LFailureKind == ovl_fail_too_many_arguments;
13192 }
13193 return LDist < RDist;
13194 }
13195 return false;
13196 }
13197 if (RFailureKind == ovl_fail_too_many_arguments ||
13198 RFailureKind == ovl_fail_too_few_arguments)
13199 return true;
13200
13201 // 2. Bad conversions come first and are ordered by the number
13202 // of bad conversions and quality of good conversions.
13203 if (LFailureKind == ovl_fail_bad_conversion) {
13204 if (RFailureKind != ovl_fail_bad_conversion)
13205 return true;
13206
13207 // The conversion that can be fixed with a smaller number of changes,
13208 // comes first.
13209 unsigned numLFixes = L->Fix.NumConversionsFixed;
13210 unsigned numRFixes = R->Fix.NumConversionsFixed;
13211 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13212 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13213 if (numLFixes != numRFixes) {
13214 return numLFixes < numRFixes;
13215 }
13216
13217 // If there's any ordering between the defined conversions...
13218 if (int Ord = CompareConversions(L: *L, R: *R))
13219 return Ord < 0;
13220 } else if (RFailureKind == ovl_fail_bad_conversion)
13221 return false;
13222
13223 if (LFailureKind == ovl_fail_bad_deduction) {
13224 if (RFailureKind != ovl_fail_bad_deduction)
13225 return true;
13226
13227 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13228 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13229 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13230 if (LRank != RRank)
13231 return LRank < RRank;
13232 }
13233 } else if (RFailureKind == ovl_fail_bad_deduction)
13234 return false;
13235
13236 // TODO: others?
13237 }
13238
13239 // Sort everything else by location.
13240 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13241 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13242
13243 // Put candidates without locations (e.g. builtins) at the end.
13244 if (LLoc.isValid() && RLoc.isValid())
13245 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13246 if (LLoc.isValid() && !RLoc.isValid())
13247 return true;
13248 if (RLoc.isValid() && !LLoc.isValid())
13249 return false;
13250 assert(!LLoc.isValid() && !RLoc.isValid());
13251 // For builtins and other functions without locations, fallback to the order
13252 // in which they were added into the candidate set.
13253 return L < R;
13254 }
13255
13256private:
13257 struct ConversionSignals {
13258 unsigned KindRank = 0;
13259 ImplicitConversionRank Rank = ICR_Exact_Match;
13260
13261 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13262 ConversionSignals Sig;
13263 Sig.KindRank = Seq.getKindRank();
13264 if (Seq.isStandard())
13265 Sig.Rank = Seq.Standard.getRank();
13266 else if (Seq.isUserDefined())
13267 Sig.Rank = Seq.UserDefined.After.getRank();
13268 // We intend StaticObjectArgumentConversion to compare the same as
13269 // StandardConversion with ICR_ExactMatch rank.
13270 return Sig;
13271 }
13272
13273 static ConversionSignals ForObjectArgument() {
13274 // We intend StaticObjectArgumentConversion to compare the same as
13275 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13276 return {};
13277 }
13278 };
13279
13280 // Returns -1 if conversions in L are considered better.
13281 // 0 if they are considered indistinguishable.
13282 // 1 if conversions in R are better.
13283 int CompareConversions(const OverloadCandidate &L,
13284 const OverloadCandidate &R) {
13285 // We cannot use `isBetterOverloadCandidate` because it is defined
13286 // according to the C++ standard and provides a partial order, but we need
13287 // a total order as this function is used in sort.
13288 assert(L.Conversions.size() == R.Conversions.size());
13289 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13290 auto LS = L.IgnoreObjectArgument && I == 0
13291 ? ConversionSignals::ForObjectArgument()
13292 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13293 auto RS = R.IgnoreObjectArgument
13294 ? ConversionSignals::ForObjectArgument()
13295 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13296 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13297 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13298 ? -1
13299 : 1;
13300 }
13301 // FIXME: find a way to compare templates for being more or less
13302 // specialized that provides a strict weak ordering.
13303 return 0;
13304 }
13305};
13306}
13307
13308/// CompleteNonViableCandidate - Normally, overload resolution only
13309/// computes up to the first bad conversion. Produces the FixIt set if
13310/// possible.
13311static void
13312CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13313 ArrayRef<Expr *> Args,
13314 OverloadCandidateSet::CandidateSetKind CSK) {
13315 assert(!Cand->Viable);
13316
13317 // Don't do anything on failures other than bad conversion.
13318 if (Cand->FailureKind != ovl_fail_bad_conversion)
13319 return;
13320
13321 // We only want the FixIts if all the arguments can be corrected.
13322 bool Unfixable = false;
13323 // Use a implicit copy initialization to check conversion fixes.
13324 Cand->Fix.setConversionChecker(TryCopyInitialization);
13325
13326 // Attempt to fix the bad conversion.
13327 unsigned ConvCount = Cand->Conversions.size();
13328 for (unsigned ConvIdx =
13329 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13330 : 0);
13331 /**/; ++ConvIdx) {
13332 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13333 if (Cand->Conversions[ConvIdx].isInitialized() &&
13334 Cand->Conversions[ConvIdx].isBad()) {
13335 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13336 break;
13337 }
13338 }
13339
13340 // FIXME: this should probably be preserved from the overload
13341 // operation somehow.
13342 bool SuppressUserConversions = false;
13343
13344 unsigned ConvIdx = 0;
13345 unsigned ArgIdx = 0;
13346 ArrayRef<QualType> ParamTypes;
13347 bool Reversed = Cand->isReversed();
13348
13349 if (Cand->IsSurrogate) {
13350 QualType ConvType
13351 = Cand->Surrogate->getConversionType().getNonReferenceType();
13352 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13353 ConvType = ConvPtrType->getPointeeType();
13354 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13355 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13356 ConvIdx = 1;
13357 } else if (Cand->Function) {
13358 ParamTypes =
13359 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13360 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13361 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13362 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13363 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13364 ConvIdx = 1;
13365 if (CSK == OverloadCandidateSet::CSK_Operator &&
13366 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13367 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13368 OO_Subscript)
13369 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13370 ArgIdx = 1;
13371 }
13372 } else {
13373 // Builtin operator.
13374 assert(ConvCount <= 3);
13375 ParamTypes = Cand->BuiltinParamTypes;
13376 }
13377
13378 // Fill in the rest of the conversions.
13379 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13380 ConvIdx != ConvCount && ArgIdx < Args.size();
13381 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13382 if (Cand->Conversions[ConvIdx].isInitialized()) {
13383 // We've already checked this conversion.
13384 } else if (ParamIdx < ParamTypes.size()) {
13385 if (ParamTypes[ParamIdx]->isDependentType())
13386 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13387 Args[ArgIdx]->getType());
13388 else {
13389 Cand->Conversions[ConvIdx] =
13390 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13391 SuppressUserConversions,
13392 /*InOverloadResolution=*/true,
13393 /*AllowObjCWritebackConversion=*/
13394 S.getLangOpts().ObjCAutoRefCount);
13395 // Store the FixIt in the candidate if it exists.
13396 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13397 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13398 }
13399 } else
13400 Cand->Conversions[ConvIdx].setEllipsis();
13401 }
13402}
13403
13404SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13405 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13406 SourceLocation OpLoc,
13407 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13408
13409 InjectNonDeducedTemplateCandidates(S);
13410
13411 // Sort the candidates by viability and position. Sorting directly would
13412 // be prohibitive, so we make a set of pointers and sort those.
13413 SmallVector<OverloadCandidate*, 32> Cands;
13414 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13415 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13416 Cand != LastCand; ++Cand) {
13417 if (!Filter(*Cand))
13418 continue;
13419 switch (OCD) {
13420 case OCD_AllCandidates:
13421 if (!Cand->Viable) {
13422 if (!Cand->Function && !Cand->IsSurrogate) {
13423 // This a non-viable builtin candidate. We do not, in general,
13424 // want to list every possible builtin candidate.
13425 continue;
13426 }
13427 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13428 }
13429 break;
13430
13431 case OCD_ViableCandidates:
13432 if (!Cand->Viable)
13433 continue;
13434 break;
13435
13436 case OCD_AmbiguousCandidates:
13437 if (!Cand->Best)
13438 continue;
13439 break;
13440 }
13441
13442 Cands.push_back(Elt: Cand);
13443 }
13444
13445 llvm::stable_sort(
13446 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13447
13448 return Cands;
13449}
13450
13451bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13452 SourceLocation OpLoc) {
13453 bool DeferHint = false;
13454 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13455 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13456 // host device candidates.
13457 auto WrongSidedCands =
13458 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13459 return (Cand.Viable == false &&
13460 Cand.FailureKind == ovl_fail_bad_target) ||
13461 (Cand.Function &&
13462 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13463 Cand.Function->template hasAttr<CUDADeviceAttr>());
13464 });
13465 DeferHint = !WrongSidedCands.empty();
13466 }
13467 return DeferHint;
13468}
13469
13470/// When overload resolution fails, prints diagnostic messages containing the
13471/// candidates in the candidate set.
13472void OverloadCandidateSet::NoteCandidates(
13473 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13474 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13475 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13476
13477 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13478
13479 {
13480 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13481 S.Diag(Loc: PD.first, PD: PD.second);
13482 }
13483
13484 // In WebAssembly we don't want to emit further diagnostics if a table is
13485 // passed as an argument to a function.
13486 bool NoteCands = true;
13487 for (const Expr *Arg : Args) {
13488 if (Arg->getType()->isWebAssemblyTableType())
13489 NoteCands = false;
13490 }
13491
13492 if (NoteCands)
13493 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13494
13495 if (OCD == OCD_AmbiguousCandidates)
13496 MaybeDiagnoseAmbiguousConstraints(S,
13497 Cands: {Candidates.begin(), Candidates.end()});
13498}
13499
13500void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13501 ArrayRef<OverloadCandidate *> Cands,
13502 StringRef Opc, SourceLocation OpLoc) {
13503 bool ReportedAmbiguousConversions = false;
13504
13505 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13506 unsigned CandsShown = 0;
13507 auto I = Cands.begin(), E = Cands.end();
13508 for (; I != E; ++I) {
13509 OverloadCandidate *Cand = *I;
13510
13511 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13512 ShowOverloads == Ovl_Best) {
13513 break;
13514 }
13515 ++CandsShown;
13516
13517 if (Cand->Function)
13518 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13519 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13520 else if (Cand->IsSurrogate)
13521 NoteSurrogateCandidate(S, Cand);
13522 else {
13523 assert(Cand->Viable &&
13524 "Non-viable built-in candidates are not added to Cands.");
13525 // Generally we only see ambiguities including viable builtin
13526 // operators if overload resolution got screwed up by an
13527 // ambiguous user-defined conversion.
13528 //
13529 // FIXME: It's quite possible for different conversions to see
13530 // different ambiguities, though.
13531 if (!ReportedAmbiguousConversions) {
13532 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13533 ReportedAmbiguousConversions = true;
13534 }
13535
13536 // If this is a viable builtin, print it.
13537 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13538 }
13539 }
13540
13541 // Inform S.Diags that we've shown an overload set with N elements. This may
13542 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13543 S.Diags.overloadCandidatesShown(N: CandsShown);
13544
13545 if (I != E) {
13546 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13547 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13548 }
13549}
13550
13551bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
13552 const Sema &S) const {
13553 if (S.getLangOpts().CUDA) {
13554 auto *Caller = S.getCurFunctionDecl(AllowLambda: true);
13555 // Overloading based on __host__ and __device__ attributes takes
13556 // higher priority, HD functions may favor template candidates even when a
13557 // non-template candidate would be a perfect match.
13558 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13559 Caller->hasAttr<CUDADeviceAttr>())
13560 return false;
13561 }
13562
13563 return
13564 // For user defined conversion we need to check against different
13565 // combination of CV qualifiers and look at any explicit specifier, so
13566 // always deduce template candidates.
13567 Kind != CSK_InitByUserDefinedConversion
13568 // When doing code completion, we want to see all the
13569 // viable candidates.
13570 && Kind != CSK_CodeCompletion;
13571}
13572
13573static SourceLocation
13574GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13575 return Cand->Specialization ? Cand->Specialization->getLocation()
13576 : SourceLocation();
13577}
13578
13579namespace {
13580struct CompareTemplateSpecCandidatesForDisplay {
13581 Sema &S;
13582 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13583
13584 bool operator()(const TemplateSpecCandidate *L,
13585 const TemplateSpecCandidate *R) {
13586 // Fast-path this check.
13587 if (L == R)
13588 return false;
13589
13590 // Assuming that both candidates are not matches...
13591
13592 // Sort by the ranking of deduction failures.
13593 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13594 return RankDeductionFailure(DFI: L->DeductionFailure) <
13595 RankDeductionFailure(DFI: R->DeductionFailure);
13596
13597 // Sort everything else by location.
13598 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13599 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13600
13601 // Put candidates without locations (e.g. builtins) at the end.
13602 if (LLoc.isInvalid())
13603 return false;
13604 if (RLoc.isInvalid())
13605 return true;
13606
13607 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13608 }
13609};
13610}
13611
13612/// Diagnose a template argument deduction failure.
13613/// We are treating these failures as overload failures due to bad
13614/// deductions.
13615void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13616 bool ForTakingAddress) {
13617 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13618 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13619}
13620
13621void TemplateSpecCandidateSet::destroyCandidates() {
13622 for (iterator i = begin(), e = end(); i != e; ++i) {
13623 i->DeductionFailure.Destroy();
13624 }
13625}
13626
13627void TemplateSpecCandidateSet::clear() {
13628 destroyCandidates();
13629 Candidates.clear();
13630}
13631
13632/// NoteCandidates - When no template specialization match is found, prints
13633/// diagnostic messages containing the non-matching specializations that form
13634/// the candidate set.
13635/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13636/// OCD == OCD_AllCandidates and Cand->Viable == false.
13637void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13638 // Sort the candidates by position (assuming no candidate is a match).
13639 // Sorting directly would be prohibitive, so we make a set of pointers
13640 // and sort those.
13641 SmallVector<TemplateSpecCandidate *, 32> Cands;
13642 Cands.reserve(N: size());
13643 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13644 if (Cand->Specialization)
13645 Cands.push_back(Elt: Cand);
13646 // Otherwise, this is a non-matching builtin candidate. We do not,
13647 // in general, want to list every possible builtin candidate.
13648 }
13649
13650 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13651
13652 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13653 // for generalization purposes (?).
13654 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13655
13656 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13657 unsigned CandsShown = 0;
13658 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13659 TemplateSpecCandidate *Cand = *I;
13660
13661 // Set an arbitrary limit on the number of candidates we'll spam
13662 // the user with. FIXME: This limit should depend on details of the
13663 // candidate list.
13664 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13665 break;
13666 ++CandsShown;
13667
13668 assert(Cand->Specialization &&
13669 "Non-matching built-in candidates are not added to Cands.");
13670 Cand->NoteDeductionFailure(S, ForTakingAddress);
13671 }
13672
13673 if (I != E)
13674 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13675}
13676
13677// [PossiblyAFunctionType] --> [Return]
13678// NonFunctionType --> NonFunctionType
13679// R (A) --> R(A)
13680// R (*)(A) --> R (A)
13681// R (&)(A) --> R (A)
13682// R (S::*)(A) --> R (A)
13683QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13684 QualType Ret = PossiblyAFunctionType;
13685 if (const PointerType *ToTypePtr =
13686 PossiblyAFunctionType->getAs<PointerType>())
13687 Ret = ToTypePtr->getPointeeType();
13688 else if (const ReferenceType *ToTypeRef =
13689 PossiblyAFunctionType->getAs<ReferenceType>())
13690 Ret = ToTypeRef->getPointeeType();
13691 else if (const MemberPointerType *MemTypePtr =
13692 PossiblyAFunctionType->getAs<MemberPointerType>())
13693 Ret = MemTypePtr->getPointeeType();
13694 Ret =
13695 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13696 return Ret;
13697}
13698
13699static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13700 bool Complain = true) {
13701 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13702 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13703 return true;
13704
13705 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13706 if (S.getLangOpts().CPlusPlus17 &&
13707 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13708 !S.ResolveExceptionSpec(Loc, FPT))
13709 return true;
13710
13711 return false;
13712}
13713
13714namespace {
13715// A helper class to help with address of function resolution
13716// - allows us to avoid passing around all those ugly parameters
13717class AddressOfFunctionResolver {
13718 Sema& S;
13719 Expr* SourceExpr;
13720 const QualType& TargetType;
13721 QualType TargetFunctionType; // Extracted function type from target type
13722
13723 bool Complain;
13724 //DeclAccessPair& ResultFunctionAccessPair;
13725 ASTContext& Context;
13726
13727 bool TargetTypeIsNonStaticMemberFunction;
13728 bool FoundNonTemplateFunction;
13729 bool StaticMemberFunctionFromBoundPointer;
13730 bool HasComplained;
13731
13732 OverloadExpr::FindResult OvlExprInfo;
13733 OverloadExpr *OvlExpr;
13734 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13735 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13736 TemplateSpecCandidateSet FailedCandidates;
13737
13738public:
13739 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13740 const QualType &TargetType, bool Complain)
13741 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13742 Complain(Complain), Context(S.getASTContext()),
13743 TargetTypeIsNonStaticMemberFunction(
13744 !!TargetType->getAs<MemberPointerType>()),
13745 FoundNonTemplateFunction(false),
13746 StaticMemberFunctionFromBoundPointer(false),
13747 HasComplained(false),
13748 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13749 OvlExpr(OvlExprInfo.Expression),
13750 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13751 ExtractUnqualifiedFunctionTypeFromTargetType();
13752
13753 if (TargetFunctionType->isFunctionType()) {
13754 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13755 if (!UME->isImplicitAccess() &&
13756 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13757 StaticMemberFunctionFromBoundPointer = true;
13758 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13759 DeclAccessPair dap;
13760 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13761 ovl: OvlExpr, Complain: false, Found: &dap)) {
13762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13763 if (!Method->isStatic()) {
13764 // If the target type is a non-function type and the function found
13765 // is a non-static member function, pretend as if that was the
13766 // target, it's the only possible type to end up with.
13767 TargetTypeIsNonStaticMemberFunction = true;
13768
13769 // And skip adding the function if its not in the proper form.
13770 // We'll diagnose this due to an empty set of functions.
13771 if (!OvlExprInfo.HasFormOfMemberPointer)
13772 return;
13773 }
13774
13775 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13776 }
13777 return;
13778 }
13779
13780 if (OvlExpr->hasExplicitTemplateArgs())
13781 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13782
13783 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13784 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13785 EliminateSuboptimalCudaMatches();
13786
13787 // C++ [over.over]p4:
13788 // If more than one function is selected, [...]
13789 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13790 if (FoundNonTemplateFunction) {
13791 EliminateAllTemplateMatches();
13792 EliminateLessPartialOrderingConstrainedMatches();
13793 } else
13794 EliminateAllExceptMostSpecializedTemplate();
13795 }
13796 }
13797 }
13798
13799 bool hasComplained() const { return HasComplained; }
13800
13801private:
13802 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13803 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13804 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13805 }
13806
13807 /// \return true if A is considered a better overload candidate for the
13808 /// desired type than B.
13809 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13810 // If A doesn't have exactly the correct type, we don't want to classify it
13811 // as "better" than anything else. This way, the user is required to
13812 // disambiguate for us if there are multiple candidates and no exact match.
13813 return candidateHasExactlyCorrectType(FD: A) &&
13814 (!candidateHasExactlyCorrectType(FD: B) ||
13815 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13816 }
13817
13818 /// \return true if we were able to eliminate all but one overload candidate,
13819 /// false otherwise.
13820 bool eliminiateSuboptimalOverloadCandidates() {
13821 // Same algorithm as overload resolution -- one pass to pick the "best",
13822 // another pass to be sure that nothing is better than the best.
13823 auto Best = Matches.begin();
13824 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13825 if (isBetterCandidate(A: I->second, B: Best->second))
13826 Best = I;
13827
13828 const FunctionDecl *BestFn = Best->second;
13829 auto IsBestOrInferiorToBest = [this, BestFn](
13830 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13831 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13832 };
13833
13834 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13835 // option, so we can potentially give the user a better error
13836 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13837 return false;
13838 Matches[0] = *Best;
13839 Matches.resize(N: 1);
13840 return true;
13841 }
13842
13843 bool isTargetTypeAFunction() const {
13844 return TargetFunctionType->isFunctionType();
13845 }
13846
13847 // [ToType] [Return]
13848
13849 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13850 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13851 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13852 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13853 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13854 }
13855
13856 // return true if any matching specializations were found
13857 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13858 const DeclAccessPair& CurAccessFunPair) {
13859 if (CXXMethodDecl *Method
13860 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13861 // Skip non-static function templates when converting to pointer, and
13862 // static when converting to member pointer.
13863 bool CanConvertToFunctionPointer =
13864 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13865 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13866 return false;
13867 }
13868 else if (TargetTypeIsNonStaticMemberFunction)
13869 return false;
13870
13871 // C++ [over.over]p2:
13872 // If the name is a function template, template argument deduction is
13873 // done (14.8.2.2), and if the argument deduction succeeds, the
13874 // resulting template argument list is used to generate a single
13875 // function template specialization, which is added to the set of
13876 // overloaded functions considered.
13877 FunctionDecl *Specialization = nullptr;
13878 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13879 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13880 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13881 Specialization, Info, /*IsAddressOfFunction*/ true);
13882 Result != TemplateDeductionResult::Success) {
13883 // Make a note of the failed deduction for diagnostics.
13884 FailedCandidates.addCandidate()
13885 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13886 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13887 return false;
13888 }
13889
13890 // Template argument deduction ensures that we have an exact match or
13891 // compatible pointer-to-function arguments that would be adjusted by ICS.
13892 // This function template specicalization works.
13893 assert(S.isSameOrCompatibleFunctionType(
13894 Context.getCanonicalType(Specialization->getType()),
13895 Context.getCanonicalType(TargetFunctionType)));
13896
13897 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13898 return false;
13899
13900 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13901 return true;
13902 }
13903
13904 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13905 const DeclAccessPair& CurAccessFunPair) {
13906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13907 // Skip non-static functions when converting to pointer, and static
13908 // when converting to member pointer.
13909 bool CanConvertToFunctionPointer =
13910 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13911 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13912 return false;
13913 }
13914 else if (TargetTypeIsNonStaticMemberFunction)
13915 return false;
13916
13917 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13918 if (S.getLangOpts().CUDA) {
13919 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13920 if (!(Caller && Caller->isImplicit()) &&
13921 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13922 return false;
13923 }
13924 if (FunDecl->isMultiVersion()) {
13925 const auto *TA = FunDecl->getAttr<TargetAttr>();
13926 if (TA && !TA->isDefaultVersion())
13927 return false;
13928 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13929 if (TVA && !TVA->isDefaultVersion())
13930 return false;
13931 }
13932
13933 // If any candidate has a placeholder return type, trigger its deduction
13934 // now.
13935 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13936 Complain)) {
13937 HasComplained |= Complain;
13938 return false;
13939 }
13940
13941 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13942 return false;
13943
13944 // If we're in C, we need to support types that aren't exactly identical.
13945 if (!S.getLangOpts().CPlusPlus ||
13946 candidateHasExactlyCorrectType(FD: FunDecl)) {
13947 Matches.push_back(Elt: std::make_pair(
13948 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13949 FoundNonTemplateFunction = true;
13950 return true;
13951 }
13952 }
13953
13954 return false;
13955 }
13956
13957 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13958 bool Ret = false;
13959
13960 // If the overload expression doesn't have the form of a pointer to
13961 // member, don't try to convert it to a pointer-to-member type.
13962 if (IsInvalidFormOfPointerToMemberFunction())
13963 return false;
13964
13965 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13966 E = OvlExpr->decls_end();
13967 I != E; ++I) {
13968 // Look through any using declarations to find the underlying function.
13969 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13970
13971 // C++ [over.over]p3:
13972 // Non-member functions and static member functions match
13973 // targets of type "pointer-to-function" or "reference-to-function."
13974 // Nonstatic member functions match targets of
13975 // type "pointer-to-member-function."
13976 // Note that according to DR 247, the containing class does not matter.
13977 if (FunctionTemplateDecl *FunctionTemplate
13978 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13979 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13980 Ret = true;
13981 }
13982 // If we have explicit template arguments supplied, skip non-templates.
13983 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13984 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13985 Ret = true;
13986 }
13987 assert(Ret || Matches.empty());
13988 return Ret;
13989 }
13990
13991 void EliminateAllExceptMostSpecializedTemplate() {
13992 // [...] and any given function template specialization F1 is
13993 // eliminated if the set contains a second function template
13994 // specialization whose function template is more specialized
13995 // than the function template of F1 according to the partial
13996 // ordering rules of 14.5.5.2.
13997
13998 // The algorithm specified above is quadratic. We instead use a
13999 // two-pass algorithm (similar to the one used to identify the
14000 // best viable function in an overload set) that identifies the
14001 // best function template (if it exists).
14002
14003 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14004 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14005 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
14006
14007 // TODO: It looks like FailedCandidates does not serve much purpose
14008 // here, since the no_viable diagnostic has index 0.
14009 UnresolvedSetIterator Result = S.getMostSpecialized(
14010 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
14011 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
14012 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
14013 << Matches[0].second->getDeclName(),
14014 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
14015 << (unsigned)oc_function << (unsigned)ocs_described_template,
14016 Complain, TargetType: TargetFunctionType);
14017
14018 if (Result != MatchesCopy.end()) {
14019 // Make it the first and only element
14020 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14021 Matches[0].second = cast<FunctionDecl>(Val: *Result);
14022 Matches.resize(N: 1);
14023 } else
14024 HasComplained |= Complain;
14025 }
14026
14027 void EliminateAllTemplateMatches() {
14028 // [...] any function template specializations in the set are
14029 // eliminated if the set also contains a non-template function, [...]
14030 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14031 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14032 ++I;
14033 else {
14034 Matches[I] = Matches[--N];
14035 Matches.resize(N);
14036 }
14037 }
14038 }
14039
14040 void EliminateLessPartialOrderingConstrainedMatches() {
14041 // C++ [over.over]p5:
14042 // [...] Any given non-template function F0 is eliminated if the set
14043 // contains a second non-template function that is more
14044 // partial-ordering-constrained than F0. [...]
14045 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14046 "Call EliminateAllTemplateMatches() first");
14047 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14048 Results.push_back(Elt: Matches[0]);
14049 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14050 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14051 FunctionDecl *F = getMorePartialOrderingConstrained(
14052 S, Fn1: Matches[I].second, Fn2: Results[0].second,
14053 /*IsFn1Reversed=*/false,
14054 /*IsFn2Reversed=*/false);
14055 if (!F) {
14056 Results.push_back(Elt: Matches[I]);
14057 continue;
14058 }
14059 if (F == Matches[I].second) {
14060 Results.clear();
14061 Results.push_back(Elt: Matches[I]);
14062 }
14063 }
14064 std::swap(LHS&: Matches, RHS&: Results);
14065 }
14066
14067 void EliminateSuboptimalCudaMatches() {
14068 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14069 Matches);
14070 }
14071
14072public:
14073 void ComplainNoMatchesFound() const {
14074 assert(Matches.empty());
14075 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14076 << OvlExpr->getName() << TargetFunctionType
14077 << OvlExpr->getSourceRange();
14078 if (FailedCandidates.empty())
14079 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14080 /*TakingAddress=*/true);
14081 else {
14082 // We have some deduction failure messages. Use them to diagnose
14083 // the function templates, and diagnose the non-template candidates
14084 // normally.
14085 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14086 IEnd = OvlExpr->decls_end();
14087 I != IEnd; ++I)
14088 if (FunctionDecl *Fun =
14089 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14090 if (!functionHasPassObjectSizeParams(FD: Fun))
14091 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14092 /*TakingAddress=*/true);
14093 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14094 }
14095 }
14096
14097 bool IsInvalidFormOfPointerToMemberFunction() const {
14098 return TargetTypeIsNonStaticMemberFunction &&
14099 !OvlExprInfo.HasFormOfMemberPointer;
14100 }
14101
14102 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14103 // TODO: Should we condition this on whether any functions might
14104 // have matched, or is it more appropriate to do that in callers?
14105 // TODO: a fixit wouldn't hurt.
14106 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14107 << TargetType << OvlExpr->getSourceRange();
14108 }
14109
14110 bool IsStaticMemberFunctionFromBoundPointer() const {
14111 return StaticMemberFunctionFromBoundPointer;
14112 }
14113
14114 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14115 S.Diag(Loc: OvlExpr->getBeginLoc(),
14116 DiagID: diag::err_invalid_form_pointer_member_function)
14117 << OvlExpr->getSourceRange();
14118 }
14119
14120 void ComplainOfInvalidConversion() const {
14121 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14122 << OvlExpr->getName() << TargetType;
14123 }
14124
14125 void ComplainMultipleMatchesFound() const {
14126 assert(Matches.size() > 1);
14127 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14128 << OvlExpr->getName() << OvlExpr->getSourceRange();
14129 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14130 /*TakingAddress=*/true);
14131 }
14132
14133 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14134
14135 int getNumMatches() const { return Matches.size(); }
14136
14137 FunctionDecl* getMatchingFunctionDecl() const {
14138 if (Matches.size() != 1) return nullptr;
14139 return Matches[0].second;
14140 }
14141
14142 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14143 if (Matches.size() != 1) return nullptr;
14144 return &Matches[0].first;
14145 }
14146};
14147}
14148
14149FunctionDecl *
14150Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14151 QualType TargetType,
14152 bool Complain,
14153 DeclAccessPair &FoundResult,
14154 bool *pHadMultipleCandidates) {
14155 assert(AddressOfExpr->getType() == Context.OverloadTy);
14156
14157 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14158 Complain);
14159 int NumMatches = Resolver.getNumMatches();
14160 FunctionDecl *Fn = nullptr;
14161 bool ShouldComplain = Complain && !Resolver.hasComplained();
14162 if (NumMatches == 0 && ShouldComplain) {
14163 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14164 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14165 else
14166 Resolver.ComplainNoMatchesFound();
14167 }
14168 else if (NumMatches > 1 && ShouldComplain)
14169 Resolver.ComplainMultipleMatchesFound();
14170 else if (NumMatches == 1) {
14171 Fn = Resolver.getMatchingFunctionDecl();
14172 assert(Fn);
14173 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14174 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14175 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14176 if (Complain) {
14177 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14178 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14179 else
14180 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14181 }
14182 }
14183
14184 if (pHadMultipleCandidates)
14185 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14186 return Fn;
14187}
14188
14189FunctionDecl *
14190Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14191 OverloadExpr::FindResult R = OverloadExpr::find(E);
14192 OverloadExpr *Ovl = R.Expression;
14193 bool IsResultAmbiguous = false;
14194 FunctionDecl *Result = nullptr;
14195 DeclAccessPair DAP;
14196 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14197
14198 // Return positive for better, negative for worse, 0 for equal preference.
14199 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14200 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14201 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14202 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14203 };
14204
14205 // Don't use the AddressOfResolver because we're specifically looking for
14206 // cases where we have one overload candidate that lacks
14207 // enable_if/pass_object_size/...
14208 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14209 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14210 if (!FD)
14211 return nullptr;
14212
14213 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14214 continue;
14215
14216 // If we found a better result, update Result.
14217 auto FoundBetter = [&]() {
14218 IsResultAmbiguous = false;
14219 DAP = I.getPair();
14220 Result = FD;
14221 };
14222
14223 // We have more than one result - see if it is more
14224 // partial-ordering-constrained than the previous one.
14225 if (Result) {
14226 // Check CUDA preference first. If the candidates have differennt CUDA
14227 // preference, choose the one with higher CUDA preference. Otherwise,
14228 // choose the one with more constraints.
14229 if (getLangOpts().CUDA) {
14230 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14231 // FD has different preference than Result.
14232 if (PreferenceByCUDA != 0) {
14233 // FD is more preferable than Result.
14234 if (PreferenceByCUDA > 0)
14235 FoundBetter();
14236 continue;
14237 }
14238 }
14239 // FD has the same CUDA preference than Result. Continue to check
14240 // constraints.
14241
14242 // C++ [over.over]p5:
14243 // [...] Any given non-template function F0 is eliminated if the set
14244 // contains a second non-template function that is more
14245 // partial-ordering-constrained than F0 [...]
14246 FunctionDecl *MoreConstrained =
14247 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14248 /*IsFn1Reversed=*/false,
14249 /*IsFn2Reversed=*/false);
14250 if (MoreConstrained != FD) {
14251 if (!MoreConstrained) {
14252 IsResultAmbiguous = true;
14253 AmbiguousDecls.push_back(Elt: FD);
14254 }
14255 continue;
14256 }
14257 // FD is more constrained - replace Result with it.
14258 }
14259 FoundBetter();
14260 }
14261
14262 if (IsResultAmbiguous)
14263 return nullptr;
14264
14265 if (Result) {
14266 // We skipped over some ambiguous declarations which might be ambiguous with
14267 // the selected result.
14268 for (FunctionDecl *Skipped : AmbiguousDecls) {
14269 // If skipped candidate has different CUDA preference than the result,
14270 // there is no ambiguity. Otherwise check whether they have different
14271 // constraints.
14272 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14273 continue;
14274 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14275 return nullptr;
14276 }
14277 Pair = DAP;
14278 }
14279 return Result;
14280}
14281
14282bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14283 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14284 Expr *E = SrcExpr.get();
14285 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14286
14287 DeclAccessPair DAP;
14288 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14289 if (!Found || Found->isCPUDispatchMultiVersion() ||
14290 Found->isCPUSpecificMultiVersion())
14291 return false;
14292
14293 // Emitting multiple diagnostics for a function that is both inaccessible and
14294 // unavailable is consistent with our behavior elsewhere. So, always check
14295 // for both.
14296 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14297 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14298 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14299 if (Res.isInvalid())
14300 return false;
14301 Expr *Fixed = Res.get();
14302 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14303 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14304 else
14305 SrcExpr = Fixed;
14306 return true;
14307}
14308
14309FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14310 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14311 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14312 // C++ [over.over]p1:
14313 // [...] [Note: any redundant set of parentheses surrounding the
14314 // overloaded function name is ignored (5.1). ]
14315 // C++ [over.over]p1:
14316 // [...] The overloaded function name can be preceded by the &
14317 // operator.
14318
14319 // If we didn't actually find any template-ids, we're done.
14320 if (!ovl->hasExplicitTemplateArgs())
14321 return nullptr;
14322
14323 TemplateArgumentListInfo ExplicitTemplateArgs;
14324 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14325
14326 // Look through all of the overloaded functions, searching for one
14327 // whose type matches exactly.
14328 FunctionDecl *Matched = nullptr;
14329 for (UnresolvedSetIterator I = ovl->decls_begin(),
14330 E = ovl->decls_end(); I != E; ++I) {
14331 // C++0x [temp.arg.explicit]p3:
14332 // [...] In contexts where deduction is done and fails, or in contexts
14333 // where deduction is not done, if a template argument list is
14334 // specified and it, along with any default template arguments,
14335 // identifies a single function template specialization, then the
14336 // template-id is an lvalue for the function template specialization.
14337 FunctionTemplateDecl *FunctionTemplate =
14338 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14339 if (!FunctionTemplate)
14340 continue;
14341
14342 // C++ [over.over]p2:
14343 // If the name is a function template, template argument deduction is
14344 // done (14.8.2.2), and if the argument deduction succeeds, the
14345 // resulting template argument list is used to generate a single
14346 // function template specialization, which is added to the set of
14347 // overloaded functions considered.
14348 FunctionDecl *Specialization = nullptr;
14349 TemplateDeductionInfo Info(ovl->getNameLoc());
14350 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14351 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14352 /*IsAddressOfFunction*/ true);
14353 Result != TemplateDeductionResult::Success) {
14354 // Make a note of the failed deduction for diagnostics.
14355 if (FailedTSC)
14356 FailedTSC->addCandidate().set(
14357 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14358 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14359 continue;
14360 }
14361
14362 assert(Specialization && "no specialization and no error?");
14363
14364 // C++ [temp.deduct.call]p6:
14365 // [...] If all successful deductions yield the same deduced A, that
14366 // deduced A is the result of deduction; otherwise, the parameter is
14367 // treated as a non-deduced context.
14368 if (Matched) {
14369 if (ForTypeDeduction &&
14370 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14371 Arg: Specialization->getType()))
14372 continue;
14373 // Multiple matches; we can't resolve to a single declaration.
14374 if (Complain) {
14375 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14376 << ovl->getName();
14377 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14378 }
14379 return nullptr;
14380 }
14381
14382 Matched = Specialization;
14383 if (FoundResult) *FoundResult = I.getPair();
14384 }
14385
14386 if (Matched &&
14387 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14388 return nullptr;
14389
14390 return Matched;
14391}
14392
14393bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14394 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14395 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14396 unsigned DiagIDForComplaining) {
14397 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14398
14399 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14400
14401 DeclAccessPair found;
14402 ExprResult SingleFunctionExpression;
14403 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14404 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14405 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14406 SrcExpr = ExprError();
14407 return true;
14408 }
14409
14410 // It is only correct to resolve to an instance method if we're
14411 // resolving a form that's permitted to be a pointer to member.
14412 // Otherwise we'll end up making a bound member expression, which
14413 // is illegal in all the contexts we resolve like this.
14414 if (!ovl.HasFormOfMemberPointer &&
14415 isa<CXXMethodDecl>(Val: fn) &&
14416 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14417 if (!complain) return false;
14418
14419 Diag(Loc: ovl.Expression->getExprLoc(),
14420 DiagID: diag::err_bound_member_function)
14421 << 0 << ovl.Expression->getSourceRange();
14422
14423 // TODO: I believe we only end up here if there's a mix of
14424 // static and non-static candidates (otherwise the expression
14425 // would have 'bound member' type, not 'overload' type).
14426 // Ideally we would note which candidate was chosen and why
14427 // the static candidates were rejected.
14428 SrcExpr = ExprError();
14429 return true;
14430 }
14431
14432 // Fix the expression to refer to 'fn'.
14433 SingleFunctionExpression =
14434 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14435
14436 // If desired, do function-to-pointer decay.
14437 if (doFunctionPointerConversion) {
14438 SingleFunctionExpression =
14439 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14440 if (SingleFunctionExpression.isInvalid()) {
14441 SrcExpr = ExprError();
14442 return true;
14443 }
14444 }
14445 }
14446
14447 if (!SingleFunctionExpression.isUsable()) {
14448 if (complain) {
14449 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14450 << ovl.Expression->getName()
14451 << DestTypeForComplaining
14452 << OpRangeForComplaining
14453 << ovl.Expression->getQualifierLoc().getSourceRange();
14454 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14455
14456 SrcExpr = ExprError();
14457 return true;
14458 }
14459
14460 return false;
14461 }
14462
14463 SrcExpr = SingleFunctionExpression;
14464 return true;
14465}
14466
14467/// Add a single candidate to the overload set.
14468static void AddOverloadedCallCandidate(Sema &S,
14469 DeclAccessPair FoundDecl,
14470 TemplateArgumentListInfo *ExplicitTemplateArgs,
14471 ArrayRef<Expr *> Args,
14472 OverloadCandidateSet &CandidateSet,
14473 bool PartialOverloading,
14474 bool KnownValid) {
14475 NamedDecl *Callee = FoundDecl.getDecl();
14476 if (isa<UsingShadowDecl>(Val: Callee))
14477 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14478
14479 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14480 if (ExplicitTemplateArgs) {
14481 assert(!KnownValid && "Explicit template arguments?");
14482 return;
14483 }
14484 // Prevent ill-formed function decls to be added as overload candidates.
14485 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14486 return;
14487
14488 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14489 /*SuppressUserConversions=*/false,
14490 PartialOverloading);
14491 return;
14492 }
14493
14494 if (FunctionTemplateDecl *FuncTemplate
14495 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14496 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14497 ExplicitTemplateArgs, Args, CandidateSet,
14498 /*SuppressUserConversions=*/false,
14499 PartialOverloading);
14500 return;
14501 }
14502
14503 assert(!KnownValid && "unhandled case in overloaded call candidate");
14504}
14505
14506void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14507 ArrayRef<Expr *> Args,
14508 OverloadCandidateSet &CandidateSet,
14509 bool PartialOverloading) {
14510
14511#ifndef NDEBUG
14512 // Verify that ArgumentDependentLookup is consistent with the rules
14513 // in C++0x [basic.lookup.argdep]p3:
14514 //
14515 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14516 // and let Y be the lookup set produced by argument dependent
14517 // lookup (defined as follows). If X contains
14518 //
14519 // -- a declaration of a class member, or
14520 //
14521 // -- a block-scope function declaration that is not a
14522 // using-declaration, or
14523 //
14524 // -- a declaration that is neither a function or a function
14525 // template
14526 //
14527 // then Y is empty.
14528
14529 if (ULE->requiresADL()) {
14530 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14531 E = ULE->decls_end(); I != E; ++I) {
14532 assert(!(*I)->getDeclContext()->isRecord());
14533 assert(isa<UsingShadowDecl>(*I) ||
14534 !(*I)->getDeclContext()->isFunctionOrMethod());
14535 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14536 }
14537 }
14538#endif
14539
14540 // It would be nice to avoid this copy.
14541 TemplateArgumentListInfo TABuffer;
14542 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14543 if (ULE->hasExplicitTemplateArgs()) {
14544 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14545 ExplicitTemplateArgs = &TABuffer;
14546 }
14547
14548 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14549 E = ULE->decls_end(); I != E; ++I)
14550 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14551 CandidateSet, PartialOverloading,
14552 /*KnownValid*/ true);
14553
14554 if (ULE->requiresADL())
14555 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14556 Args, ExplicitTemplateArgs,
14557 CandidateSet, PartialOverloading);
14558}
14559
14560void Sema::AddOverloadedCallCandidates(
14561 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14562 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14563 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14564 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14565 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14566}
14567
14568/// Determine whether a declaration with the specified name could be moved into
14569/// a different namespace.
14570static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14571 switch (Name.getCXXOverloadedOperator()) {
14572 case OO_New: case OO_Array_New:
14573 case OO_Delete: case OO_Array_Delete:
14574 return false;
14575
14576 default:
14577 return true;
14578 }
14579}
14580
14581/// Attempt to recover from an ill-formed use of a non-dependent name in a
14582/// template, where the non-dependent name was declared after the template
14583/// was defined. This is common in code written for a compilers which do not
14584/// correctly implement two-stage name lookup.
14585///
14586/// Returns true if a viable candidate was found and a diagnostic was issued.
14587static bool DiagnoseTwoPhaseLookup(
14588 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14589 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14590 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14591 CXXRecordDecl **FoundInClass = nullptr) {
14592 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14593 return false;
14594
14595 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14596 if (DC->isTransparentContext())
14597 continue;
14598
14599 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14600
14601 if (!R.empty()) {
14602 R.suppressDiagnostics();
14603
14604 OverloadCandidateSet Candidates(FnLoc, CSK);
14605 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14606 CandidateSet&: Candidates);
14607
14608 OverloadCandidateSet::iterator Best;
14609 OverloadingResult OR =
14610 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14611
14612 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14613 // We either found non-function declarations or a best viable function
14614 // at class scope. A class-scope lookup result disables ADL. Don't
14615 // look past this, but let the caller know that we found something that
14616 // either is, or might be, usable in this class.
14617 if (FoundInClass) {
14618 *FoundInClass = RD;
14619 if (OR == OR_Success) {
14620 R.clear();
14621 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14622 R.resolveKind();
14623 }
14624 }
14625 return false;
14626 }
14627
14628 if (OR != OR_Success) {
14629 // There wasn't a unique best function or function template.
14630 return false;
14631 }
14632
14633 // Find the namespaces where ADL would have looked, and suggest
14634 // declaring the function there instead.
14635 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14636 Sema::AssociatedClassSet AssociatedClasses;
14637 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14638 AssociatedNamespaces,
14639 AssociatedClasses);
14640 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14641 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14642 DeclContext *Std = SemaRef.getStdNamespace();
14643 for (Sema::AssociatedNamespaceSet::iterator
14644 it = AssociatedNamespaces.begin(),
14645 end = AssociatedNamespaces.end(); it != end; ++it) {
14646 // Never suggest declaring a function within namespace 'std'.
14647 if (Std && Std->Encloses(DC: *it))
14648 continue;
14649
14650 // Never suggest declaring a function within a namespace with a
14651 // reserved name, like __gnu_cxx.
14652 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14653 if (NS &&
14654 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14655 continue;
14656
14657 SuggestedNamespaces.insert(X: *it);
14658 }
14659 }
14660
14661 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14662 << R.getLookupName();
14663 if (SuggestedNamespaces.empty()) {
14664 SemaRef.Diag(Loc: Best->Function->getLocation(),
14665 DiagID: diag::note_not_found_by_two_phase_lookup)
14666 << R.getLookupName() << 0;
14667 } else if (SuggestedNamespaces.size() == 1) {
14668 SemaRef.Diag(Loc: Best->Function->getLocation(),
14669 DiagID: diag::note_not_found_by_two_phase_lookup)
14670 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14671 } else {
14672 // FIXME: It would be useful to list the associated namespaces here,
14673 // but the diagnostics infrastructure doesn't provide a way to produce
14674 // a localized representation of a list of items.
14675 SemaRef.Diag(Loc: Best->Function->getLocation(),
14676 DiagID: diag::note_not_found_by_two_phase_lookup)
14677 << R.getLookupName() << 2;
14678 }
14679
14680 // Try to recover by calling this function.
14681 return true;
14682 }
14683
14684 R.clear();
14685 }
14686
14687 return false;
14688}
14689
14690/// Attempt to recover from ill-formed use of a non-dependent operator in a
14691/// template, where the non-dependent operator was declared after the template
14692/// was defined.
14693///
14694/// Returns true if a viable candidate was found and a diagnostic was issued.
14695static bool
14696DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14697 SourceLocation OpLoc,
14698 ArrayRef<Expr *> Args) {
14699 DeclarationName OpName =
14700 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14701 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14702 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14703 CSK: OverloadCandidateSet::CSK_Operator,
14704 /*ExplicitTemplateArgs=*/nullptr, Args);
14705}
14706
14707namespace {
14708class BuildRecoveryCallExprRAII {
14709 Sema &SemaRef;
14710 Sema::SatisfactionStackResetRAII SatStack;
14711
14712public:
14713 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14714 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14715 SemaRef.IsBuildingRecoveryCallExpr = true;
14716 }
14717
14718 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14719};
14720}
14721
14722/// Attempts to recover from a call where no functions were found.
14723///
14724/// This function will do one of three things:
14725/// * Diagnose, recover, and return a recovery expression.
14726/// * Diagnose, fail to recover, and return ExprError().
14727/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14728/// expected to diagnose as appropriate.
14729static ExprResult
14730BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14731 UnresolvedLookupExpr *ULE,
14732 SourceLocation LParenLoc,
14733 MutableArrayRef<Expr *> Args,
14734 SourceLocation RParenLoc,
14735 bool EmptyLookup, bool AllowTypoCorrection) {
14736 // Do not try to recover if it is already building a recovery call.
14737 // This stops infinite loops for template instantiations like
14738 //
14739 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14740 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14741 if (SemaRef.IsBuildingRecoveryCallExpr)
14742 return ExprResult();
14743 BuildRecoveryCallExprRAII RCE(SemaRef);
14744
14745 CXXScopeSpec SS;
14746 SS.Adopt(Other: ULE->getQualifierLoc());
14747 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14748
14749 TemplateArgumentListInfo TABuffer;
14750 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14751 if (ULE->hasExplicitTemplateArgs()) {
14752 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14753 ExplicitTemplateArgs = &TABuffer;
14754 }
14755
14756 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14757 Sema::LookupOrdinaryName);
14758 CXXRecordDecl *FoundInClass = nullptr;
14759 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14760 CSK: OverloadCandidateSet::CSK_Normal,
14761 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14762 // OK, diagnosed a two-phase lookup issue.
14763 } else if (EmptyLookup) {
14764 // Try to recover from an empty lookup with typo correction.
14765 R.clear();
14766 NoTypoCorrectionCCC NoTypoValidator{};
14767 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14768 ExplicitTemplateArgs != nullptr,
14769 dyn_cast<MemberExpr>(Val: Fn));
14770 CorrectionCandidateCallback &Validator =
14771 AllowTypoCorrection
14772 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14773 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14774 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14775 Args))
14776 return ExprError();
14777 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14778 // We found a usable declaration of the name in a dependent base of some
14779 // enclosing class.
14780 // FIXME: We should also explain why the candidates found by name lookup
14781 // were not viable.
14782 if (SemaRef.DiagnoseDependentMemberLookup(R))
14783 return ExprError();
14784 } else {
14785 // We had viable candidates and couldn't recover; let the caller diagnose
14786 // this.
14787 return ExprResult();
14788 }
14789
14790 // If we get here, we should have issued a diagnostic and formed a recovery
14791 // lookup result.
14792 assert(!R.empty() && "lookup results empty despite recovery");
14793
14794 // If recovery created an ambiguity, just bail out.
14795 if (R.isAmbiguous()) {
14796 R.suppressDiagnostics();
14797 return ExprError();
14798 }
14799
14800 // Build an implicit member call if appropriate. Just drop the
14801 // casts and such from the call, we don't really care.
14802 ExprResult NewFn = ExprError();
14803 if ((*R.begin())->isCXXClassMember())
14804 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14805 TemplateArgs: ExplicitTemplateArgs, S);
14806 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14807 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14808 TemplateArgs: ExplicitTemplateArgs);
14809 else
14810 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14811
14812 if (NewFn.isInvalid())
14813 return ExprError();
14814
14815 // This shouldn't cause an infinite loop because we're giving it
14816 // an expression with viable lookup results, which should never
14817 // end up here.
14818 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14819 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14820 RParenLoc);
14821}
14822
14823bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14824 UnresolvedLookupExpr *ULE,
14825 MultiExprArg Args,
14826 SourceLocation RParenLoc,
14827 OverloadCandidateSet *CandidateSet,
14828 ExprResult *Result) {
14829#ifndef NDEBUG
14830 if (ULE->requiresADL()) {
14831 // To do ADL, we must have found an unqualified name.
14832 assert(!ULE->getQualifier() && "qualified name with ADL");
14833
14834 // We don't perform ADL for implicit declarations of builtins.
14835 // Verify that this was correctly set up.
14836 FunctionDecl *F;
14837 if (ULE->decls_begin() != ULE->decls_end() &&
14838 ULE->decls_begin() + 1 == ULE->decls_end() &&
14839 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14840 F->getBuiltinID() && F->isImplicit())
14841 llvm_unreachable("performing ADL for builtin");
14842
14843 // We don't perform ADL in C.
14844 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14845 }
14846#endif
14847
14848 UnbridgedCastsSet UnbridgedCasts;
14849 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14850 *Result = ExprError();
14851 return true;
14852 }
14853
14854 // Add the functions denoted by the callee to the set of candidate
14855 // functions, including those from argument-dependent lookup.
14856 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14857
14858 if (getLangOpts().MSVCCompat &&
14859 CurContext->isDependentContext() && !isSFINAEContext() &&
14860 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14861
14862 OverloadCandidateSet::iterator Best;
14863 if (CandidateSet->empty() ||
14864 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14865 OR_No_Viable_Function) {
14866 // In Microsoft mode, if we are inside a template class member function
14867 // then create a type dependent CallExpr. The goal is to postpone name
14868 // lookup to instantiation time to be able to search into type dependent
14869 // base classes.
14870 CallExpr *CE =
14871 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14872 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14873 CE->markDependentForPostponedNameLookup();
14874 *Result = CE;
14875 return true;
14876 }
14877 }
14878
14879 if (CandidateSet->empty())
14880 return false;
14881
14882 UnbridgedCasts.restore();
14883 return false;
14884}
14885
14886// Guess at what the return type for an unresolvable overload should be.
14887static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14888 OverloadCandidateSet::iterator *Best) {
14889 std::optional<QualType> Result;
14890 // Adjust Type after seeing a candidate.
14891 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14892 if (!Candidate.Function)
14893 return;
14894 if (Candidate.Function->isInvalidDecl())
14895 return;
14896 QualType T = Candidate.Function->getReturnType();
14897 if (T.isNull())
14898 return;
14899 if (!Result)
14900 Result = T;
14901 else if (Result != T)
14902 Result = QualType();
14903 };
14904
14905 // Look for an unambiguous type from a progressively larger subset.
14906 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14907 //
14908 // First, consider only the best candidate.
14909 if (Best && *Best != CS.end())
14910 ConsiderCandidate(**Best);
14911 // Next, consider only viable candidates.
14912 if (!Result)
14913 for (const auto &C : CS)
14914 if (C.Viable)
14915 ConsiderCandidate(C);
14916 // Finally, consider all candidates.
14917 if (!Result)
14918 for (const auto &C : CS)
14919 ConsiderCandidate(C);
14920
14921 if (!Result)
14922 return QualType();
14923 auto Value = *Result;
14924 if (Value.isNull() || Value->isUndeducedType())
14925 return QualType();
14926 return Value;
14927}
14928
14929/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14930/// the completed call expression. If overload resolution fails, emits
14931/// diagnostics and returns ExprError()
14932static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14933 UnresolvedLookupExpr *ULE,
14934 SourceLocation LParenLoc,
14935 MultiExprArg Args,
14936 SourceLocation RParenLoc,
14937 Expr *ExecConfig,
14938 OverloadCandidateSet *CandidateSet,
14939 OverloadCandidateSet::iterator *Best,
14940 OverloadingResult OverloadResult,
14941 bool AllowTypoCorrection) {
14942 switch (OverloadResult) {
14943 case OR_Success: {
14944 FunctionDecl *FDecl = (*Best)->Function;
14945 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14946 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14947 return ExprError();
14948 ExprResult Res =
14949 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14950 if (Res.isInvalid())
14951 return ExprError();
14952 return SemaRef.BuildResolvedCallExpr(
14953 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14954 /*IsExecConfig=*/false,
14955 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14956 }
14957
14958 case OR_No_Viable_Function: {
14959 if (*Best != CandidateSet->end() &&
14960 CandidateSet->getKind() ==
14961 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14962 if (CXXMethodDecl *M =
14963 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14964 M && M->isImplicitObjectMemberFunction()) {
14965 CandidateSet->NoteCandidates(
14966 PD: PartialDiagnosticAt(
14967 Fn->getBeginLoc(),
14968 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14969 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14970 return ExprError();
14971 }
14972 }
14973
14974 // Try to recover by looking for viable functions which the user might
14975 // have meant to call.
14976 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14977 Args, RParenLoc,
14978 EmptyLookup: CandidateSet->empty(),
14979 AllowTypoCorrection);
14980 if (Recovery.isInvalid() || Recovery.isUsable())
14981 return Recovery;
14982
14983 // If the user passes in a function that we can't take the address of, we
14984 // generally end up emitting really bad error messages. Here, we attempt to
14985 // emit better ones.
14986 for (const Expr *Arg : Args) {
14987 if (!Arg->getType()->isFunctionType())
14988 continue;
14989 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14990 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14991 if (FD &&
14992 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14993 Loc: Arg->getExprLoc()))
14994 return ExprError();
14995 }
14996 }
14997
14998 CandidateSet->NoteCandidates(
14999 PD: PartialDiagnosticAt(
15000 Fn->getBeginLoc(),
15001 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
15002 << ULE->getName() << Fn->getSourceRange()),
15003 S&: SemaRef, OCD: OCD_AllCandidates, Args);
15004 break;
15005 }
15006
15007 case OR_Ambiguous:
15008 CandidateSet->NoteCandidates(
15009 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
15010 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
15011 << ULE->getName() << Fn->getSourceRange()),
15012 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15013 break;
15014
15015 case OR_Deleted: {
15016 FunctionDecl *FDecl = (*Best)->Function;
15017 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
15018 Range: Fn->getSourceRange(), Name: ULE->getName(),
15019 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
15020
15021 // We emitted an error for the unavailable/deleted function call but keep
15022 // the call in the AST.
15023 ExprResult Res =
15024 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15025 if (Res.isInvalid())
15026 return ExprError();
15027 return SemaRef.BuildResolvedCallExpr(
15028 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15029 /*IsExecConfig=*/false,
15030 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15031 }
15032 }
15033
15034 // Overload resolution failed, try to recover.
15035 SmallVector<Expr *, 8> SubExprs = {Fn};
15036 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
15037 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
15038 T: chooseRecoveryType(CS&: *CandidateSet, Best));
15039}
15040
15041static void markUnaddressableCandidatesUnviable(Sema &S,
15042 OverloadCandidateSet &CS) {
15043 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15044 if (I->Viable &&
15045 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
15046 I->Viable = false;
15047 I->FailureKind = ovl_fail_addr_not_available;
15048 }
15049 }
15050}
15051
15052ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
15053 UnresolvedLookupExpr *ULE,
15054 SourceLocation LParenLoc,
15055 MultiExprArg Args,
15056 SourceLocation RParenLoc,
15057 Expr *ExecConfig,
15058 bool AllowTypoCorrection,
15059 bool CalleesAddressIsTaken) {
15060
15061 OverloadCandidateSet::CandidateSetKind CSK =
15062 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15063 : OverloadCandidateSet::CSK_Normal;
15064
15065 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15066 ExprResult result;
15067
15068 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15069 Result: &result))
15070 return result;
15071
15072 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15073 // functions that aren't addressible are considered unviable.
15074 if (CalleesAddressIsTaken)
15075 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15076
15077 OverloadCandidateSet::iterator Best;
15078 OverloadingResult OverloadResult =
15079 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15080
15081 // [C++23][over.call.func]
15082 // if overload resolution selects a non-static member function,
15083 // the call is ill-formed;
15084 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15085 Best != CandidateSet.end()) {
15086 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15087 M && M->isImplicitObjectMemberFunction()) {
15088 OverloadResult = OR_No_Viable_Function;
15089 }
15090 }
15091
15092 // Model the case with a call to a templated function whose definition
15093 // encloses the call and whose return type contains a placeholder type as if
15094 // the UnresolvedLookupExpr was type-dependent.
15095 if (OverloadResult == OR_Success) {
15096 const FunctionDecl *FDecl = Best->Function;
15097 if (LangOpts.CUDA)
15098 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15099 if (FDecl && FDecl->isTemplateInstantiation() &&
15100 FDecl->getReturnType()->isUndeducedType()) {
15101
15102 // Creating dependent CallExpr is not okay if the enclosing context itself
15103 // is not dependent. This situation notably arises if a non-dependent
15104 // member function calls the later-defined overloaded static function.
15105 //
15106 // For example, in
15107 // class A {
15108 // void c() { callee(1); }
15109 // static auto callee(auto x) { }
15110 // };
15111 //
15112 // Here callee(1) is unresolved at the call site, but is not inside a
15113 // dependent context. There will be no further attempt to resolve this
15114 // call if it is made dependent.
15115
15116 if (const auto *TP =
15117 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15118 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15119 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15120 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15121 }
15122 }
15123 }
15124
15125 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15126 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15127 OverloadResult, AllowTypoCorrection);
15128}
15129
15130ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15131 NestedNameSpecifierLoc NNSLoc,
15132 DeclarationNameInfo DNI,
15133 const UnresolvedSetImpl &Fns,
15134 bool PerformADL) {
15135 return UnresolvedLookupExpr::Create(
15136 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15137 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15138}
15139
15140ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15141 CXXConversionDecl *Method,
15142 bool HadMultipleCandidates) {
15143 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15144 // the FoundDecl as it impedes TransformMemberExpr.
15145 // We go a bit further here: if there's no difference in UnderlyingDecl,
15146 // then using FoundDecl vs Method shouldn't make a difference either.
15147 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15148 FoundDecl = Method;
15149 // Convert the expression to match the conversion function's implicit object
15150 // parameter.
15151 ExprResult Exp;
15152 if (Method->isExplicitObjectMemberFunction())
15153 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15154 else
15155 Exp = PerformImplicitObjectArgumentInitialization(
15156 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15157 if (Exp.isInvalid())
15158 return true;
15159
15160 if (Method->getParent()->isLambda() &&
15161 Method->getConversionType()->isBlockPointerType()) {
15162 // This is a lambda conversion to block pointer; check if the argument
15163 // was a LambdaExpr.
15164 Expr *SubE = E;
15165 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15166 if (CE && CE->getCastKind() == CK_NoOp)
15167 SubE = CE->getSubExpr();
15168 SubE = SubE->IgnoreParens();
15169 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15170 SubE = BE->getSubExpr();
15171 if (isa<LambdaExpr>(Val: SubE)) {
15172 // For the conversion to block pointer on a lambda expression, we
15173 // construct a special BlockLiteral instead; this doesn't really make
15174 // a difference in ARC, but outside of ARC the resulting block literal
15175 // follows the normal lifetime rules for block literals instead of being
15176 // autoreleased.
15177 PushExpressionEvaluationContext(
15178 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15179 ExprResult BlockExp = BuildBlockForLambdaConversion(
15180 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15181 PopExpressionEvaluationContext();
15182
15183 // FIXME: This note should be produced by a CodeSynthesisContext.
15184 if (BlockExp.isInvalid())
15185 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15186 return BlockExp;
15187 }
15188 }
15189 CallExpr *CE;
15190 QualType ResultType = Method->getReturnType();
15191 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15192 ResultType = ResultType.getNonLValueExprType(Context);
15193 if (Method->isExplicitObjectMemberFunction()) {
15194 ExprResult FnExpr =
15195 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15196 HadMultipleCandidates, Loc: E->getBeginLoc());
15197 if (FnExpr.isInvalid())
15198 return ExprError();
15199 Expr *ObjectParam = Exp.get();
15200 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15201 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15202 FPFeatures: CurFPFeatureOverrides());
15203 CE->setUsesMemberSyntax(true);
15204 } else {
15205 MemberExpr *ME =
15206 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15207 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15208 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15209 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15210 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15211
15212 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15213 RP: Exp.get()->getEndLoc(),
15214 FPFeatures: CurFPFeatureOverrides());
15215 }
15216
15217 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15218 Proto: Method->getType()->castAs<FunctionProtoType>()))
15219 return ExprError();
15220
15221 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15222}
15223
15224void Sema::LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
15225 OverloadedOperatorKind Op,
15226 const UnresolvedSetImpl &Fns,
15227 ArrayRef<Expr *> Args, bool PerformADL) {
15228 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15229
15230 SourceLocation OpLoc = CandidateSet.getLocation();
15231 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15232
15233 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15234 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15235 if (PerformADL)
15236 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15237 /*ExplicitTemplateArgs*/ nullptr,
15238 CandidateSet);
15239 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15240}
15241
15242ExprResult
15243Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15244 const UnresolvedSetImpl &Fns,
15245 Expr *Input, bool PerformADL) {
15246 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15247 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15248 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15249 // TODO: provide better source location info.
15250 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15251
15252 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15253 return ExprError();
15254
15255 Expr *Args[2] = { Input, nullptr };
15256 unsigned NumArgs = 1;
15257
15258 // For post-increment and post-decrement, add the implicit '0' as
15259 // the second argument, so that we know this is a post-increment or
15260 // post-decrement.
15261 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15262 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15263 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15264 l: SourceLocation());
15265 NumArgs = 2;
15266 }
15267
15268 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15269
15270 if (Input->isTypeDependent()) {
15271 ExprValueKind VK = ExprValueKind::VK_PRValue;
15272 // [C++26][expr.unary.op][expr.pre.incr]
15273 // The * operator yields an lvalue of type
15274 // The pre/post increment operators yied an lvalue.
15275 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15276 VK = VK_LValue;
15277
15278 if (Fns.empty())
15279 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15280 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15281 FPFeatures: CurFPFeatureOverrides());
15282
15283 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15284 ExprResult Fn = CreateUnresolvedLookupExpr(
15285 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15286 if (Fn.isInvalid())
15287 return ExprError();
15288 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15289 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15290 FPFeatures: CurFPFeatureOverrides());
15291 }
15292
15293 // Build an empty overload set.
15294 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15295 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, Args: ArgsArray, PerformADL);
15296
15297 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15298
15299 // Perform overload resolution.
15300 OverloadCandidateSet::iterator Best;
15301 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15302 case OR_Success: {
15303 // We found a built-in operator or an overloaded operator.
15304 FunctionDecl *FnDecl = Best->Function;
15305
15306 if (FnDecl) {
15307 Expr *Base = nullptr;
15308 // We matched an overloaded operator. Build a call to that
15309 // operator.
15310
15311 // Convert the arguments.
15312 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15313 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15314
15315 ExprResult InputInit;
15316 if (Method->isExplicitObjectMemberFunction())
15317 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15318 else
15319 InputInit = PerformImplicitObjectArgumentInitialization(
15320 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15321 if (InputInit.isInvalid())
15322 return ExprError();
15323 Base = Input = InputInit.get();
15324 } else {
15325 // Convert the arguments.
15326 ExprResult InputInit
15327 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15328 Context,
15329 Parm: FnDecl->getParamDecl(i: 0)),
15330 EqualLoc: SourceLocation(),
15331 Init: Input);
15332 if (InputInit.isInvalid())
15333 return ExprError();
15334 Input = InputInit.get();
15335 }
15336
15337 // Build the actual expression node.
15338 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15339 Base, HadMultipleCandidates,
15340 Loc: OpLoc);
15341 if (FnExpr.isInvalid())
15342 return ExprError();
15343
15344 // Determine the result type.
15345 QualType ResultTy = FnDecl->getReturnType();
15346 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15347 ResultTy = ResultTy.getNonLValueExprType(Context);
15348
15349 Args[0] = Input;
15350 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15351 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15352 FPFeatures: CurFPFeatureOverrides(),
15353 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15354
15355 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15356 return ExprError();
15357
15358 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15359 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15360 return ExprError();
15361 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15362 } else {
15363 // We matched a built-in operator. Convert the arguments, then
15364 // break out so that we will build the appropriate built-in
15365 // operator node.
15366 ExprResult InputRes = PerformImplicitConversion(
15367 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15368 Action: AssignmentAction::Passing,
15369 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15370 if (InputRes.isInvalid())
15371 return ExprError();
15372 Input = InputRes.get();
15373 break;
15374 }
15375 }
15376
15377 case OR_No_Viable_Function:
15378 // This is an erroneous use of an operator which can be overloaded by
15379 // a non-member function. Check for non-member operators which were
15380 // defined too late to be candidates.
15381 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15382 // FIXME: Recover by calling the found function.
15383 return ExprError();
15384
15385 // No viable function; fall through to handling this as a
15386 // built-in operator, which will produce an error message for us.
15387 break;
15388
15389 case OR_Ambiguous:
15390 CandidateSet.NoteCandidates(
15391 PD: PartialDiagnosticAt(OpLoc,
15392 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15393 << UnaryOperator::getOpcodeStr(Op: Opc)
15394 << Input->getType() << Input->getSourceRange()),
15395 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15396 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15397 return ExprError();
15398
15399 case OR_Deleted: {
15400 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15401 // object whose method was called. Later in NoteCandidates size of ArgsArray
15402 // is passed further and it eventually ends up compared to number of
15403 // function candidate parameters which never includes the object parameter,
15404 // so slice ArgsArray to make sure apples are compared to apples.
15405 StringLiteral *Msg = Best->Function->getDeletedMessage();
15406 CandidateSet.NoteCandidates(
15407 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15408 << UnaryOperator::getOpcodeStr(Op: Opc)
15409 << (Msg != nullptr)
15410 << (Msg ? Msg->getString() : StringRef())
15411 << Input->getSourceRange()),
15412 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15413 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15414 return ExprError();
15415 }
15416 }
15417
15418 // Either we found no viable overloaded operator or we matched a
15419 // built-in operator. In either case, fall through to trying to
15420 // build a built-in operation.
15421 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15422}
15423
15424void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15425 OverloadedOperatorKind Op,
15426 const UnresolvedSetImpl &Fns,
15427 ArrayRef<Expr *> Args, bool PerformADL) {
15428 SourceLocation OpLoc = CandidateSet.getLocation();
15429
15430 OverloadedOperatorKind ExtraOp =
15431 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15432 ? getRewrittenOverloadedOperator(Kind: Op)
15433 : OO_None;
15434
15435 // Add the candidates from the given function set. This also adds the
15436 // rewritten candidates using these functions if necessary.
15437 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15438
15439 // As template candidates are not deduced immediately,
15440 // persist the array in the overload set.
15441 ArrayRef<Expr *> ReversedArgs;
15442 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15443 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15444 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15445
15446 // Add operator candidates that are member functions.
15447 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15448 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15449 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15450 PO: OverloadCandidateParamOrder::Reversed);
15451
15452 // In C++20, also add any rewritten member candidates.
15453 if (ExtraOp) {
15454 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15455 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15456 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15457 PO: OverloadCandidateParamOrder::Reversed);
15458 }
15459
15460 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15461 // performed for an assignment operator (nor for operator[] nor operator->,
15462 // which don't get here).
15463 if (Op != OO_Equal && PerformADL) {
15464 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15465 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15466 /*ExplicitTemplateArgs*/ nullptr,
15467 CandidateSet);
15468 if (ExtraOp) {
15469 DeclarationName ExtraOpName =
15470 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15471 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15472 /*ExplicitTemplateArgs*/ nullptr,
15473 CandidateSet);
15474 }
15475 }
15476
15477 // Add builtin operator candidates.
15478 //
15479 // FIXME: We don't add any rewritten candidates here. This is strictly
15480 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15481 // resulting in our selecting a rewritten builtin candidate. For example:
15482 //
15483 // enum class E { e };
15484 // bool operator!=(E, E) requires false;
15485 // bool k = E::e != E::e;
15486 //
15487 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15488 // it seems unreasonable to consider rewritten builtin candidates. A core
15489 // issue has been filed proposing to removed this requirement.
15490 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15491}
15492
15493ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15494 BinaryOperatorKind Opc,
15495 const UnresolvedSetImpl &Fns, Expr *LHS,
15496 Expr *RHS, bool PerformADL,
15497 bool AllowRewrittenCandidates,
15498 FunctionDecl *DefaultedFn) {
15499 Expr *Args[2] = { LHS, RHS };
15500 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15501
15502 if (!getLangOpts().CPlusPlus20)
15503 AllowRewrittenCandidates = false;
15504
15505 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15506
15507 // If either side is type-dependent, create an appropriate dependent
15508 // expression.
15509 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15510 if (Fns.empty()) {
15511 // If there are no functions to store, just build a dependent
15512 // BinaryOperator or CompoundAssignment.
15513 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15514 return CompoundAssignOperator::Create(
15515 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15516 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15517 CompResultType: Context.DependentTy);
15518 return BinaryOperator::Create(
15519 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15520 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15521 }
15522
15523 // FIXME: save results of ADL from here?
15524 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15525 // TODO: provide better source location info in DNLoc component.
15526 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15527 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15528 ExprResult Fn = CreateUnresolvedLookupExpr(
15529 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15530 if (Fn.isInvalid())
15531 return ExprError();
15532 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15533 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15534 FPFeatures: CurFPFeatureOverrides());
15535 }
15536
15537 // If this is the .* operator, which is not overloadable, just
15538 // create a built-in binary operator.
15539 if (Opc == BO_PtrMemD) {
15540 auto CheckPlaceholder = [&](Expr *&Arg) {
15541 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15542 if (Res.isUsable())
15543 Arg = Res.get();
15544 return !Res.isUsable();
15545 };
15546
15547 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15548 // expression that contains placeholders (in either the LHS or RHS).
15549 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15550 return ExprError();
15551 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15552 }
15553
15554 // Always do placeholder-like conversions on the RHS.
15555 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15556 return ExprError();
15557
15558 // Do placeholder-like conversion on the LHS; note that we should
15559 // not get here with a PseudoObject LHS.
15560 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15561 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15562 return ExprError();
15563
15564 // If this is the assignment operator, we only perform overload resolution
15565 // if the left-hand side is a class or enumeration type. This is actually
15566 // a hack. The standard requires that we do overload resolution between the
15567 // various built-in candidates, but as DR507 points out, this can lead to
15568 // problems. So we do it this way, which pretty much follows what GCC does.
15569 // Note that we go the traditional code path for compound assignment forms.
15570 // In HLSL, user-defined structs/classes do not have constructors or
15571 // overloadable assignment operators, so we can take this shortcut too.
15572 const Type *LHSTy = Args[0]->getType().getTypePtr();
15573 if (Opc == BO_Assign &&
15574 (!LHSTy->isOverloadableType() ||
15575 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15576 !LHSTy->getAsCXXRecordDecl()->isHLSLBuiltinRecord())))
15577 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15578
15579 // Build the overload set.
15580 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15581 OverloadCandidateSet::OperatorRewriteInfo(
15582 Op, OpLoc, AllowRewrittenCandidates));
15583 if (DefaultedFn)
15584 CandidateSet.exclude(F: DefaultedFn);
15585 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15586
15587 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15588
15589 // Perform overload resolution.
15590 OverloadCandidateSet::iterator Best;
15591 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15592 case OR_Success: {
15593 // We found a built-in operator or an overloaded operator.
15594 FunctionDecl *FnDecl = Best->Function;
15595
15596 bool IsReversed = Best->isReversed();
15597 if (IsReversed)
15598 std::swap(a&: Args[0], b&: Args[1]);
15599
15600 if (FnDecl) {
15601
15602 if (FnDecl->isInvalidDecl())
15603 return ExprError();
15604
15605 Expr *Base = nullptr;
15606 // We matched an overloaded operator. Build a call to that
15607 // operator.
15608
15609 OverloadedOperatorKind ChosenOp =
15610 FnDecl->getDeclName().getCXXOverloadedOperator();
15611
15612 // C++2a [over.match.oper]p9:
15613 // If a rewritten operator== candidate is selected by overload
15614 // resolution for an operator@, its return type shall be cv bool
15615 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15616 !FnDecl->getReturnType()->isBooleanType()) {
15617 bool IsExtension =
15618 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15619 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15620 : diag::err_ovl_rewrite_equalequal_not_bool)
15621 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15622 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15623 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15624 if (!IsExtension)
15625 return ExprError();
15626 }
15627
15628 if (AllowRewrittenCandidates && !IsReversed &&
15629 CandidateSet.getRewriteInfo().isReversible()) {
15630 // We could have reversed this operator, but didn't. Check if some
15631 // reversed form was a viable candidate, and if so, if it had a
15632 // better conversion for either parameter. If so, this call is
15633 // formally ambiguous, and allowing it is an extension.
15634 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15635 for (OverloadCandidate &Cand : CandidateSet) {
15636 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15637 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15638 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15639 if (CompareImplicitConversionSequences(
15640 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15641 ICS2: Best->Conversions[ArgIdx]) ==
15642 ImplicitConversionSequence::Better) {
15643 AmbiguousWith.push_back(Elt: Cand.Function);
15644 break;
15645 }
15646 }
15647 }
15648 }
15649
15650 if (!AmbiguousWith.empty()) {
15651 bool AmbiguousWithSelf =
15652 AmbiguousWith.size() == 1 &&
15653 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15654 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15655 << BinaryOperator::getOpcodeStr(Op: Opc)
15656 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15657 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15658 if (AmbiguousWithSelf) {
15659 Diag(Loc: FnDecl->getLocation(),
15660 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15661 // Mark member== const or provide matching != to disallow reversed
15662 // args. Eg.
15663 // struct S { bool operator==(const S&); };
15664 // S()==S();
15665 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15666 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15667 !MD->isConst() &&
15668 !MD->hasCXXExplicitFunctionObjectParameter() &&
15669 Context.hasSameUnqualifiedType(
15670 T1: MD->getFunctionObjectParameterType(),
15671 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15672 Context.hasSameUnqualifiedType(
15673 T1: MD->getFunctionObjectParameterType(),
15674 T2: Args[0]->getType()) &&
15675 Context.hasSameUnqualifiedType(
15676 T1: MD->getFunctionObjectParameterType(),
15677 T2: Args[1]->getType()))
15678 Diag(Loc: FnDecl->getLocation(),
15679 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15680 } else {
15681 Diag(Loc: FnDecl->getLocation(),
15682 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15683 for (auto *F : AmbiguousWith)
15684 Diag(Loc: F->getLocation(),
15685 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15686 }
15687 }
15688 }
15689
15690 // Check for nonnull = nullable.
15691 // This won't be caught in the arg's initialization: the parameter to
15692 // the assignment operator is not marked nonnull.
15693 if (Op == OO_Equal)
15694 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15695 SrcType: Args[1]->getType(), Loc: OpLoc);
15696
15697 // Convert the arguments.
15698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15699 // Best->Access is only meaningful for class members.
15700 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15701
15702 ExprResult Arg0, Arg1;
15703 unsigned ParamIdx = 0;
15704 if (Method->isExplicitObjectMemberFunction()) {
15705 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15706 ParamIdx = 1;
15707 } else {
15708 Arg0 = PerformImplicitObjectArgumentInitialization(
15709 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15710 }
15711 Arg1 = PerformCopyInitialization(
15712 Entity: InitializedEntity::InitializeParameter(
15713 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15714 EqualLoc: SourceLocation(), Init: Args[1]);
15715 if (Arg0.isInvalid() || Arg1.isInvalid())
15716 return ExprError();
15717
15718 Base = Args[0] = Arg0.getAs<Expr>();
15719 Args[1] = RHS = Arg1.getAs<Expr>();
15720 } else {
15721 // Convert the arguments.
15722 ExprResult Arg0 = PerformCopyInitialization(
15723 Entity: InitializedEntity::InitializeParameter(Context,
15724 Parm: FnDecl->getParamDecl(i: 0)),
15725 EqualLoc: SourceLocation(), Init: Args[0]);
15726 if (Arg0.isInvalid())
15727 return ExprError();
15728
15729 ExprResult Arg1 =
15730 PerformCopyInitialization(
15731 Entity: InitializedEntity::InitializeParameter(Context,
15732 Parm: FnDecl->getParamDecl(i: 1)),
15733 EqualLoc: SourceLocation(), Init: Args[1]);
15734 if (Arg1.isInvalid())
15735 return ExprError();
15736 Args[0] = LHS = Arg0.getAs<Expr>();
15737 Args[1] = RHS = Arg1.getAs<Expr>();
15738 }
15739
15740 // Build the actual expression node.
15741 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15742 FoundDecl: Best->FoundDecl, Base,
15743 HadMultipleCandidates, Loc: OpLoc);
15744 if (FnExpr.isInvalid())
15745 return ExprError();
15746
15747 // Determine the result type.
15748 QualType ResultTy = FnDecl->getReturnType();
15749 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15750 ResultTy = ResultTy.getNonLValueExprType(Context);
15751
15752 CallExpr *TheCall;
15753 ArrayRef<const Expr *> ArgsArray(Args, 2);
15754 const Expr *ImplicitThis = nullptr;
15755
15756 // We always create a CXXOperatorCallExpr, even for explicit object
15757 // members; CodeGen should take care not to emit the this pointer.
15758 TheCall = CXXOperatorCallExpr::Create(
15759 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15760 FPFeatures: CurFPFeatureOverrides(),
15761 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15762 IsReversed);
15763
15764 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15765 Method && Method->isImplicitObjectMemberFunction()) {
15766 // Cut off the implicit 'this'.
15767 ImplicitThis = ArgsArray[0];
15768 ArgsArray = ArgsArray.slice(N: 1);
15769 }
15770
15771 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15772 FD: FnDecl))
15773 return ExprError();
15774
15775 if (Op == OO_Equal) {
15776 // Check for a self move.
15777 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15778 // lifetime check.
15779 checkAssignmentLifetime(
15780 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15781 Init: Args[1]);
15782 }
15783 if (ImplicitThis) {
15784 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15785 QualType ThisTypeFromDecl = Context.getPointerType(
15786 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15787
15788 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15789 ParamTy: ThisTypeFromDecl);
15790 }
15791
15792 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15793 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15794 CallType: VariadicCallType::DoesNotApply);
15795
15796 ExprResult R = MaybeBindToTemporary(E: TheCall);
15797 if (R.isInvalid())
15798 return ExprError();
15799
15800 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15801 if (R.isInvalid())
15802 return ExprError();
15803
15804 // For a rewritten candidate, we've already reversed the arguments
15805 // if needed. Perform the rest of the rewrite now.
15806 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15807 (Op == OO_Spaceship && IsReversed)) {
15808 if (Op == OO_ExclaimEqual) {
15809 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15810 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15811 } else {
15812 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15813 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15814 Expr *ZeroLiteral =
15815 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15816
15817 Sema::CodeSynthesisContext Ctx;
15818 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15819 Ctx.Entity = FnDecl;
15820 pushCodeSynthesisContext(Ctx);
15821
15822 R = CreateOverloadedBinOp(
15823 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15824 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15825 /*AllowRewrittenCandidates=*/false);
15826
15827 popCodeSynthesisContext();
15828 }
15829 if (R.isInvalid())
15830 return ExprError();
15831 } else {
15832 assert(ChosenOp == Op && "unexpected operator name");
15833 }
15834
15835 // Make a note in the AST if we did any rewriting.
15836 if (Best->RewriteKind != CRK_None)
15837 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15838
15839 return R;
15840 } else {
15841 // We matched a built-in operator. Convert the arguments, then
15842 // break out so that we will build the appropriate built-in
15843 // operator node.
15844 ExprResult ArgsRes0 = PerformImplicitConversion(
15845 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15846 Action: AssignmentAction::Passing,
15847 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15848 if (ArgsRes0.isInvalid())
15849 return ExprError();
15850 Args[0] = ArgsRes0.get();
15851
15852 ExprResult ArgsRes1 = PerformImplicitConversion(
15853 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15854 Action: AssignmentAction::Passing,
15855 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15856 if (ArgsRes1.isInvalid())
15857 return ExprError();
15858 Args[1] = ArgsRes1.get();
15859 break;
15860 }
15861 }
15862
15863 case OR_No_Viable_Function: {
15864 // C++ [over.match.oper]p9:
15865 // If the operator is the operator , [...] and there are no
15866 // viable functions, then the operator is assumed to be the
15867 // built-in operator and interpreted according to clause 5.
15868 if (Opc == BO_Comma)
15869 break;
15870
15871 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15872 // compare result using '==' and '<'.
15873 if (DefaultedFn && Opc == BO_Cmp) {
15874 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15875 RHS: Args[1], DefaultedFn);
15876 if (E.isInvalid() || E.isUsable())
15877 return E;
15878 }
15879
15880 // For class as left operand for assignment or compound assignment
15881 // operator do not fall through to handling in built-in, but report that
15882 // no overloaded assignment operator found
15883 ExprResult Result = ExprError();
15884 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15885 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15886 Args, OpLoc);
15887 DeferDiagsRAII DDR(*this,
15888 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15889 if (Args[0]->getType()->isRecordType() &&
15890 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15891 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15892 << BinaryOperator::getOpcodeStr(Op: Opc)
15893 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15894 if (Args[0]->getType()->isIncompleteType()) {
15895 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15896 << Args[0]->getType()
15897 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15898 }
15899 } else {
15900 // This is an erroneous use of an operator which can be overloaded by
15901 // a non-member function. Check for non-member operators which were
15902 // defined too late to be candidates.
15903 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15904 // FIXME: Recover by calling the found function.
15905 return ExprError();
15906
15907 // No viable function; try to create a built-in operation, which will
15908 // produce an error. Then, show the non-viable candidates.
15909 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15910 }
15911 assert(Result.isInvalid() &&
15912 "C++ binary operator overloading is missing candidates!");
15913 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15914 return Result;
15915 }
15916
15917 case OR_Ambiguous:
15918 CandidateSet.NoteCandidates(
15919 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15920 << BinaryOperator::getOpcodeStr(Op: Opc)
15921 << Args[0]->getType()
15922 << Args[1]->getType()
15923 << Args[0]->getSourceRange()
15924 << Args[1]->getSourceRange()),
15925 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15926 OpLoc);
15927 return ExprError();
15928
15929 case OR_Deleted: {
15930 if (isImplicitlyDeleted(FD: Best->Function)) {
15931 FunctionDecl *DeletedFD = Best->Function;
15932 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15933 if (DFK.isSpecialMember()) {
15934 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15935 << Args[0]->getType() << DFK.asSpecialMember();
15936 } else {
15937 assert(DFK.isComparison());
15938 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15939 << Args[0]->getType() << DeletedFD;
15940 }
15941
15942 // The user probably meant to call this special member. Just
15943 // explain why it's deleted.
15944 NoteDeletedFunction(FD: DeletedFD);
15945 return ExprError();
15946 }
15947
15948 StringLiteral *Msg = Best->Function->getDeletedMessage();
15949 CandidateSet.NoteCandidates(
15950 PD: PartialDiagnosticAt(
15951 OpLoc,
15952 PDiag(DiagID: diag::err_ovl_deleted_oper)
15953 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15954 .getCXXOverloadedOperator())
15955 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15956 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15957 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15958 OpLoc);
15959 return ExprError();
15960 }
15961 }
15962
15963 // We matched a built-in operator; build it.
15964 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15965}
15966
15967ExprResult Sema::BuildSynthesizedThreeWayComparison(
15968 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15969 FunctionDecl *DefaultedFn) {
15970 const ComparisonCategoryInfo *Info =
15971 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15972 // If we're not producing a known comparison category type, we can't
15973 // synthesize a three-way comparison. Let the caller diagnose this.
15974 if (!Info)
15975 return ExprResult((Expr*)nullptr);
15976
15977 // If we ever want to perform this synthesis more generally, we will need to
15978 // apply the temporary materialization conversion to the operands.
15979 assert(LHS->isGLValue() && RHS->isGLValue() &&
15980 "cannot use prvalue expressions more than once");
15981 Expr *OrigLHS = LHS;
15982 Expr *OrigRHS = RHS;
15983
15984 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15985 // each of them multiple times below.
15986 LHS = new (Context)
15987 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15988 LHS->getObjectKind(), LHS);
15989 RHS = new (Context)
15990 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15991 RHS->getObjectKind(), RHS);
15992
15993 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15994 DefaultedFn);
15995 if (Eq.isInvalid())
15996 return ExprError();
15997
15998 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15999 AllowRewrittenCandidates: true, DefaultedFn);
16000 if (Less.isInvalid())
16001 return ExprError();
16002
16003 ExprResult Greater;
16004 if (Info->isPartial()) {
16005 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
16006 DefaultedFn);
16007 if (Greater.isInvalid())
16008 return ExprError();
16009 }
16010
16011 // Form the list of comparisons we're going to perform.
16012 struct Comparison {
16013 ExprResult Cmp;
16014 ComparisonCategoryResult Result;
16015 } Comparisons[4] =
16016 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
16017 : ComparisonCategoryResult::Equivalent},
16018 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
16019 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
16020 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
16021 };
16022
16023 int I = Info->isPartial() ? 3 : 2;
16024
16025 // Combine the comparisons with suitable conditional expressions.
16026 ExprResult Result;
16027 for (; I >= 0; --I) {
16028 // Build a reference to the comparison category constant.
16029 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
16030 // FIXME: Missing a constant for a comparison category. Diagnose this?
16031 if (!VI)
16032 return ExprResult((Expr*)nullptr);
16033 ExprResult ThisResult =
16034 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
16035 if (ThisResult.isInvalid())
16036 return ExprError();
16037
16038 // Build a conditional unless this is the final case.
16039 if (Result.get()) {
16040 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
16041 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
16042 if (Result.isInvalid())
16043 return ExprError();
16044 } else {
16045 Result = ThisResult;
16046 }
16047 }
16048
16049 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16050 // bind the OpaqueValueExprs before they're (repeatedly) used.
16051 Expr *SyntacticForm = BinaryOperator::Create(
16052 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
16053 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
16054 FPFeatures: CurFPFeatureOverrides());
16055 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16056 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
16057}
16058
16059static bool PrepareArgumentsForCallToObjectOfClassType(
16060 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16061 MultiExprArg Args, SourceLocation LParenLoc) {
16062
16063 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16064 unsigned NumParams = Proto->getNumParams();
16065 unsigned NumArgsSlots =
16066 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16067 // Build the full argument list for the method call (the implicit object
16068 // parameter is placed at the beginning of the list).
16069 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16070 bool IsError = false;
16071 // Initialize the implicit object parameter.
16072 // Check the argument types.
16073 for (unsigned i = 0; i != NumParams; i++) {
16074 Expr *Arg;
16075 if (i < Args.size()) {
16076 Arg = Args[i];
16077 ExprResult InputInit =
16078 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16079 Context&: S.Context, Parm: Method->getParamDecl(i)),
16080 EqualLoc: SourceLocation(), Init: Arg);
16081 IsError |= InputInit.isInvalid();
16082 Arg = InputInit.getAs<Expr>();
16083 } else {
16084 ExprResult DefArg =
16085 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16086 if (DefArg.isInvalid()) {
16087 IsError = true;
16088 break;
16089 }
16090 Arg = DefArg.getAs<Expr>();
16091 }
16092
16093 MethodArgs.push_back(Elt: Arg);
16094 }
16095 return IsError;
16096}
16097
16098ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16099 SourceLocation RLoc,
16100 Expr *Base,
16101 MultiExprArg ArgExpr) {
16102 SmallVector<Expr *, 2> Args;
16103 Args.push_back(Elt: Base);
16104 for (auto *e : ArgExpr) {
16105 Args.push_back(Elt: e);
16106 }
16107 DeclarationName OpName =
16108 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16109
16110 SourceRange Range = ArgExpr.empty()
16111 ? SourceRange{}
16112 : SourceRange(ArgExpr.front()->getBeginLoc(),
16113 ArgExpr.back()->getEndLoc());
16114
16115 // If either side is type-dependent, create an appropriate dependent
16116 // expression.
16117 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16118
16119 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16120 // CHECKME: no 'operator' keyword?
16121 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16122 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16123 ExprResult Fn = CreateUnresolvedLookupExpr(
16124 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16125 if (Fn.isInvalid())
16126 return ExprError();
16127 // Can't add any actual overloads yet
16128
16129 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16130 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16131 FPFeatures: CurFPFeatureOverrides());
16132 }
16133
16134 // Handle placeholders
16135 UnbridgedCastsSet UnbridgedCasts;
16136 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16137 return ExprError();
16138 }
16139 // Build an empty overload set.
16140 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16141
16142 // Subscript can only be overloaded as a member function.
16143
16144 // Add operator candidates that are member functions.
16145 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16146
16147 // Add builtin operator candidates.
16148 if (Args.size() == 2)
16149 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16150
16151 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16152
16153 // Perform overload resolution.
16154 OverloadCandidateSet::iterator Best;
16155 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16156 case OR_Success: {
16157 // We found a built-in operator or an overloaded operator.
16158 FunctionDecl *FnDecl = Best->Function;
16159
16160 if (FnDecl) {
16161 // We matched an overloaded operator. Build a call to that
16162 // operator.
16163
16164 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16165
16166 // Convert the arguments.
16167 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16168 SmallVector<Expr *, 2> MethodArgs;
16169
16170 // Initialize the object parameter.
16171 if (Method->isExplicitObjectMemberFunction()) {
16172 ExprResult Res =
16173 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16174 if (Res.isInvalid())
16175 return ExprError();
16176 Args[0] = Res.get();
16177 ArgExpr = Args;
16178 } else {
16179 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16180 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16181 if (Arg0.isInvalid())
16182 return ExprError();
16183
16184 MethodArgs.push_back(Elt: Arg0.get());
16185 }
16186
16187 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16188 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16189 if (IsError)
16190 return ExprError();
16191
16192 // Build the actual expression node.
16193 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16194 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16195 ExprResult FnExpr = CreateFunctionRefExpr(
16196 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
16197 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
16198 if (FnExpr.isInvalid())
16199 return ExprError();
16200
16201 // Determine the result type
16202 QualType ResultTy = FnDecl->getReturnType();
16203 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16204 ResultTy = ResultTy.getNonLValueExprType(Context);
16205
16206 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16207 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16208 FPFeatures: CurFPFeatureOverrides());
16209
16210 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16211 return ExprError();
16212
16213 if (CheckFunctionCall(FDecl: Method, TheCall,
16214 Proto: Method->getType()->castAs<FunctionProtoType>()))
16215 return ExprError();
16216
16217 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16218 Decl: FnDecl);
16219 } else {
16220 // We matched a built-in operator. Convert the arguments, then
16221 // break out so that we will build the appropriate built-in
16222 // operator node.
16223 ExprResult ArgsRes0 = PerformImplicitConversion(
16224 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16225 Action: AssignmentAction::Passing,
16226 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16227 if (ArgsRes0.isInvalid())
16228 return ExprError();
16229 Args[0] = ArgsRes0.get();
16230
16231 ExprResult ArgsRes1 = PerformImplicitConversion(
16232 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16233 Action: AssignmentAction::Passing,
16234 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16235 if (ArgsRes1.isInvalid())
16236 return ExprError();
16237 Args[1] = ArgsRes1.get();
16238
16239 break;
16240 }
16241 }
16242
16243 case OR_No_Viable_Function: {
16244 PartialDiagnostic PD =
16245 CandidateSet.empty()
16246 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16247 << Args[0]->getType() << /*subscript*/ 0
16248 << Args[0]->getSourceRange() << Range)
16249 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16250 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16251 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16252 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16253 return ExprError();
16254 }
16255
16256 case OR_Ambiguous:
16257 if (Args.size() == 2) {
16258 CandidateSet.NoteCandidates(
16259 PD: PartialDiagnosticAt(
16260 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16261 << "[]" << Args[0]->getType() << Args[1]->getType()
16262 << Args[0]->getSourceRange() << Range),
16263 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16264 } else {
16265 CandidateSet.NoteCandidates(
16266 PD: PartialDiagnosticAt(LLoc,
16267 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16268 << Args[0]->getType()
16269 << Args[0]->getSourceRange() << Range),
16270 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16271 }
16272 return ExprError();
16273
16274 case OR_Deleted: {
16275 StringLiteral *Msg = Best->Function->getDeletedMessage();
16276 CandidateSet.NoteCandidates(
16277 PD: PartialDiagnosticAt(LLoc,
16278 PDiag(DiagID: diag::err_ovl_deleted_oper)
16279 << "[]" << (Msg != nullptr)
16280 << (Msg ? Msg->getString() : StringRef())
16281 << Args[0]->getSourceRange() << Range),
16282 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16283 return ExprError();
16284 }
16285 }
16286
16287 // We matched a built-in operator; build it.
16288 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16289}
16290
16291ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16292 SourceLocation LParenLoc,
16293 MultiExprArg Args,
16294 SourceLocation RParenLoc,
16295 Expr *ExecConfig, bool IsExecConfig,
16296 bool AllowRecovery) {
16297 assert(MemExprE->getType() == Context.BoundMemberTy ||
16298 MemExprE->getType() == Context.OverloadTy);
16299
16300 // Dig out the member expression. This holds both the object
16301 // argument and the member function we're referring to.
16302 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16303
16304 // Determine whether this is a call to a pointer-to-member function.
16305 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16306 assert(op->getType() == Context.BoundMemberTy);
16307 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16308
16309 QualType fnType =
16310 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16311
16312 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16313 QualType resultType = proto->getCallResultType(Context);
16314 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16315
16316 // Check that the object type isn't more qualified than the
16317 // member function we're calling.
16318 Qualifiers funcQuals = proto->getMethodQuals();
16319
16320 QualType objectType = op->getLHS()->getType();
16321 if (op->getOpcode() == BO_PtrMemI)
16322 objectType = objectType->castAs<PointerType>()->getPointeeType();
16323 Qualifiers objectQuals = objectType.getQualifiers();
16324
16325 Qualifiers difference = objectQuals - funcQuals;
16326 difference.removeObjCGCAttr();
16327 difference.removeAddressSpace();
16328 if (difference) {
16329 std::string qualsString = difference.getAsString();
16330 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16331 << fnType.getUnqualifiedType()
16332 << qualsString
16333 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16334 }
16335
16336 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16337 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16338 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16339
16340 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16341 CE: call, FD: nullptr))
16342 return ExprError();
16343
16344 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16345 return ExprError();
16346
16347 if (CheckOtherCall(TheCall: call, Proto: proto))
16348 return ExprError();
16349
16350 return MaybeBindToTemporary(E: call);
16351 }
16352
16353 // We only try to build a recovery expr at this level if we can preserve
16354 // the return type, otherwise we return ExprError() and let the caller
16355 // recover.
16356 auto BuildRecoveryExpr = [&](QualType Type) {
16357 if (!AllowRecovery)
16358 return ExprError();
16359 std::vector<Expr *> SubExprs = {MemExprE};
16360 llvm::append_range(C&: SubExprs, R&: Args);
16361 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16362 T: Type);
16363 };
16364 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16365 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16366 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16367
16368 UnbridgedCastsSet UnbridgedCasts;
16369 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16370 return ExprError();
16371
16372 MemberExpr *MemExpr;
16373 CXXMethodDecl *Method = nullptr;
16374 bool HadMultipleCandidates = false;
16375 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16376 NestedNameSpecifier Qualifier = std::nullopt;
16377 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16378 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16379 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16380 FoundDecl = MemExpr->getFoundDecl();
16381 Qualifier = MemExpr->getQualifier();
16382 UnbridgedCasts.restore();
16383 } else {
16384 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16385 Qualifier = UnresExpr->getQualifier();
16386
16387 QualType ObjectType = UnresExpr->getBaseType();
16388 Expr::Classification ObjectClassification
16389 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16390 : UnresExpr->getBase()->Classify(Ctx&: Context);
16391
16392 // Add overload candidates
16393 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16394 OverloadCandidateSet::CSK_Normal);
16395
16396 // FIXME: avoid copy.
16397 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16398 if (UnresExpr->hasExplicitTemplateArgs()) {
16399 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16400 TemplateArgs = &TemplateArgsBuffer;
16401 }
16402
16403 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16404 E = UnresExpr->decls_end(); I != E; ++I) {
16405
16406 QualType ExplicitObjectType = ObjectType;
16407
16408 NamedDecl *Func = *I;
16409 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16410 if (isa<UsingShadowDecl>(Val: Func))
16411 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16412
16413 bool HasExplicitParameter = false;
16414 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16415 M && M->hasCXXExplicitFunctionObjectParameter())
16416 HasExplicitParameter = true;
16417 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16418 M &&
16419 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16420 HasExplicitParameter = true;
16421
16422 if (HasExplicitParameter)
16423 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16424
16425 // Microsoft supports direct constructor calls.
16426 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16427 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16428 CandidateSet,
16429 /*SuppressUserConversions*/ false);
16430 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16431 // If explicit template arguments were provided, we can't call a
16432 // non-template member function.
16433 if (TemplateArgs)
16434 continue;
16435
16436 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16437 ObjectClassification, Args, CandidateSet,
16438 /*SuppressUserConversions=*/false);
16439 } else {
16440 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16441 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16442 ObjectType: ExplicitObjectType, ObjectClassification,
16443 Args, CandidateSet,
16444 /*SuppressUserConversions=*/false);
16445 }
16446 }
16447
16448 HadMultipleCandidates = (CandidateSet.size() > 1);
16449
16450 DeclarationName DeclName = UnresExpr->getMemberName();
16451
16452 UnbridgedCasts.restore();
16453
16454 OverloadCandidateSet::iterator Best;
16455 bool Succeeded = false;
16456 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16457 Best)) {
16458 case OR_Success:
16459 Method = cast<CXXMethodDecl>(Val: Best->Function);
16460 FoundDecl = Best->FoundDecl;
16461 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16462 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16463 break;
16464 // If FoundDecl is different from Method (such as if one is a template
16465 // and the other a specialization), make sure DiagnoseUseOfDecl is
16466 // called on both.
16467 // FIXME: This would be more comprehensively addressed by modifying
16468 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16469 // being used.
16470 if (Method != FoundDecl.getDecl() &&
16471 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16472 break;
16473 Succeeded = true;
16474 break;
16475
16476 case OR_No_Viable_Function:
16477 CandidateSet.NoteCandidates(
16478 PD: PartialDiagnosticAt(
16479 UnresExpr->getMemberLoc(),
16480 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16481 << DeclName << MemExprE->getSourceRange()),
16482 S&: *this, OCD: OCD_AllCandidates, Args);
16483 break;
16484 case OR_Ambiguous:
16485 CandidateSet.NoteCandidates(
16486 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16487 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16488 << DeclName << MemExprE->getSourceRange()),
16489 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16490 break;
16491 case OR_Deleted:
16492 DiagnoseUseOfDeletedFunction(
16493 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16494 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16495 break;
16496 }
16497 // Overload resolution fails, try to recover.
16498 if (!Succeeded)
16499 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16500
16501 ExprResult Res =
16502 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16503 if (Res.isInvalid())
16504 return ExprError();
16505 MemExprE = Res.get();
16506
16507 // If overload resolution picked a static member
16508 // build a non-member call based on that function.
16509 if (Method->isStatic()) {
16510 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16511 Config: ExecConfig, IsExecConfig);
16512 }
16513
16514 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16515 }
16516
16517 QualType ResultType = Method->getReturnType();
16518 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16519 ResultType = ResultType.getNonLValueExprType(Context);
16520
16521 assert(Method && "Member call to something that isn't a method?");
16522 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16523
16524 CallExpr *TheCall = nullptr;
16525 llvm::SmallVector<Expr *, 8> NewArgs;
16526 if (Method->isExplicitObjectMemberFunction()) {
16527 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16528 NewArgs))
16529 return ExprError();
16530
16531 // Build the actual expression node.
16532 ExprResult FnExpr =
16533 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16534 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16535 if (FnExpr.isInvalid())
16536 return ExprError();
16537
16538 TheCall =
16539 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16540 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16541 TheCall->setUsesMemberSyntax(true);
16542 } else {
16543 // Convert the object argument (for a non-static member function call).
16544 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16545 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16546 if (ObjectArg.isInvalid())
16547 return ExprError();
16548 MemExpr->setBase(ObjectArg.get());
16549 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16550 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16551 MinNumArgs: Proto->getNumParams());
16552 }
16553
16554 // Check for a valid return type.
16555 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16556 CE: TheCall, FD: Method))
16557 return BuildRecoveryExpr(ResultType);
16558
16559 // Convert the rest of the arguments
16560 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16561 RParenLoc))
16562 return BuildRecoveryExpr(ResultType);
16563
16564 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16565
16566 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16567 return ExprError();
16568
16569 // In the case the method to call was not selected by the overloading
16570 // resolution process, we still need to handle the enable_if attribute. Do
16571 // that here, so it will not hide previous -- and more relevant -- errors.
16572 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16573 if (const EnableIfAttr *Attr =
16574 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16575 Diag(Loc: MemE->getMemberLoc(),
16576 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16577 << Method << Method->getSourceRange();
16578 Diag(Loc: Method->getLocation(),
16579 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16580 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16581 return ExprError();
16582 }
16583 }
16584
16585 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16586 TheCall->getDirectCallee()->isPureVirtual()) {
16587 const FunctionDecl *MD = TheCall->getDirectCallee();
16588
16589 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16590 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16591 Diag(Loc: MemExpr->getBeginLoc(),
16592 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16593 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16594 << MD->getParent();
16595
16596 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16597 if (getLangOpts().AppleKext)
16598 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16599 << MD->getParent() << MD->getDeclName();
16600 }
16601 }
16602
16603 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16604 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16605 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16606 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16607 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16608 DtorLoc: MemExpr->getMemberLoc());
16609 }
16610
16611 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16612 Decl: TheCall->getDirectCallee());
16613}
16614
16615ExprResult
16616Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16617 SourceLocation LParenLoc,
16618 MultiExprArg Args,
16619 SourceLocation RParenLoc) {
16620 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16621 return ExprError();
16622 ExprResult Object = Obj;
16623
16624 UnbridgedCastsSet UnbridgedCasts;
16625 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16626 return ExprError();
16627
16628 assert(Object.get()->getType()->isRecordType() &&
16629 "Requires object type argument");
16630
16631 // C++ [over.call.object]p1:
16632 // If the primary-expression E in the function call syntax
16633 // evaluates to a class object of type "cv T", then the set of
16634 // candidate functions includes at least the function call
16635 // operators of T. The function call operators of T are obtained by
16636 // ordinary lookup of the name operator() in the context of
16637 // (E).operator().
16638 OverloadCandidateSet CandidateSet(LParenLoc,
16639 OverloadCandidateSet::CSK_Operator);
16640 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16641
16642 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16643 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16644 return true;
16645
16646 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16647 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16648 LookupQualifiedName(R, LookupCtx: Record);
16649 R.suppressAccessDiagnostics();
16650
16651 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16652 Oper != OperEnd; ++Oper) {
16653 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16654 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16655 /*SuppressUserConversion=*/SuppressUserConversions: false);
16656 }
16657
16658 // When calling a lambda, both the call operator, and
16659 // the conversion operator to function pointer
16660 // are considered. But when constraint checking
16661 // on the call operator fails, it will also fail on the
16662 // conversion operator as the constraints are always the same.
16663 // As the user probably does not intend to perform a surrogate call,
16664 // we filter them out to produce better error diagnostics, ie to avoid
16665 // showing 2 failed overloads instead of one.
16666 bool IgnoreSurrogateFunctions = false;
16667 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16668 const OverloadCandidate &Candidate = *CandidateSet.begin();
16669 if (!Candidate.Viable &&
16670 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16671 IgnoreSurrogateFunctions = true;
16672 }
16673
16674 // C++ [over.call.object]p2:
16675 // In addition, for each (non-explicit in C++0x) conversion function
16676 // declared in T of the form
16677 //
16678 // operator conversion-type-id () cv-qualifier;
16679 //
16680 // where cv-qualifier is the same cv-qualification as, or a
16681 // greater cv-qualification than, cv, and where conversion-type-id
16682 // denotes the type "pointer to function of (P1,...,Pn) returning
16683 // R", or the type "reference to pointer to function of
16684 // (P1,...,Pn) returning R", or the type "reference to function
16685 // of (P1,...,Pn) returning R", a surrogate call function [...]
16686 // is also considered as a candidate function. Similarly,
16687 // surrogate call functions are added to the set of candidate
16688 // functions for each conversion function declared in an
16689 // accessible base class provided the function is not hidden
16690 // within T by another intervening declaration.
16691 const auto &Conversions = Record->getVisibleConversionFunctions();
16692 for (auto I = Conversions.begin(), E = Conversions.end();
16693 !IgnoreSurrogateFunctions && I != E; ++I) {
16694 NamedDecl *D = *I;
16695 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16696 if (isa<UsingShadowDecl>(Val: D))
16697 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16698
16699 // Skip over templated conversion functions; they aren't
16700 // surrogates.
16701 if (isa<FunctionTemplateDecl>(Val: D))
16702 continue;
16703
16704 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16705 if (!Conv->isExplicit()) {
16706 // Strip the reference type (if any) and then the pointer type (if
16707 // any) to get down to what might be a function type.
16708 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16709 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16710 ConvType = ConvPtrType->getPointeeType();
16711
16712 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16713 {
16714 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16715 Object: Object.get(), Args, CandidateSet);
16716 }
16717 }
16718 }
16719
16720 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16721
16722 // Perform overload resolution.
16723 OverloadCandidateSet::iterator Best;
16724 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16725 Best)) {
16726 case OR_Success:
16727 // Overload resolution succeeded; we'll build the appropriate call
16728 // below.
16729 break;
16730
16731 case OR_No_Viable_Function: {
16732 PartialDiagnostic PD =
16733 CandidateSet.empty()
16734 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16735 << Object.get()->getType() << /*call*/ 1
16736 << Object.get()->getSourceRange())
16737 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16738 << Object.get()->getType() << Object.get()->getSourceRange());
16739 CandidateSet.NoteCandidates(
16740 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16741 OCD: OCD_AllCandidates, Args);
16742 break;
16743 }
16744 case OR_Ambiguous:
16745 if (!R.isAmbiguous())
16746 CandidateSet.NoteCandidates(
16747 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16748 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16749 << Object.get()->getType()
16750 << Object.get()->getSourceRange()),
16751 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16752 break;
16753
16754 case OR_Deleted: {
16755 // FIXME: Is this diagnostic here really necessary? It seems that
16756 // 1. we don't have any tests for this diagnostic, and
16757 // 2. we already issue err_deleted_function_use for this later on anyway.
16758 StringLiteral *Msg = Best->Function->getDeletedMessage();
16759 CandidateSet.NoteCandidates(
16760 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16761 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16762 << Object.get()->getType() << (Msg != nullptr)
16763 << (Msg ? Msg->getString() : StringRef())
16764 << Object.get()->getSourceRange()),
16765 S&: *this, OCD: OCD_AllCandidates, Args);
16766 break;
16767 }
16768 }
16769
16770 if (Best == CandidateSet.end())
16771 return true;
16772
16773 UnbridgedCasts.restore();
16774
16775 if (Best->Function == nullptr) {
16776 // Since there is no function declaration, this is one of the
16777 // surrogate candidates. Dig out the conversion function.
16778 CXXConversionDecl *Conv
16779 = cast<CXXConversionDecl>(
16780 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16781
16782 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16783 FoundDecl: Best->FoundDecl);
16784 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16785 return ExprError();
16786 assert(Conv == Best->FoundDecl.getDecl() &&
16787 "Found Decl & conversion-to-functionptr should be same, right?!");
16788 // We selected one of the surrogate functions that converts the
16789 // object parameter to a function pointer. Perform the conversion
16790 // on the object argument, then let BuildCallExpr finish the job.
16791
16792 // Create an implicit member expr to refer to the conversion operator.
16793 // and then call it.
16794 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16795 Method: Conv, HadMultipleCandidates);
16796 if (Call.isInvalid())
16797 return ExprError();
16798 // Record usage of conversion in an implicit cast.
16799 Call = ImplicitCastExpr::Create(
16800 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16801 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16802
16803 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16804 }
16805
16806 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16807
16808 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16809 // that calls this method, using Object for the implicit object
16810 // parameter and passing along the remaining arguments.
16811 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16812
16813 // An error diagnostic has already been printed when parsing the declaration.
16814 if (Method->isInvalidDecl())
16815 return ExprError();
16816
16817 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16818 unsigned NumParams = Proto->getNumParams();
16819
16820 DeclarationNameInfo OpLocInfo(
16821 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16822 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16823 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16824 Base: Obj, HadMultipleCandidates,
16825 Loc: OpLocInfo.getLoc(),
16826 LocInfo: OpLocInfo.getInfo());
16827 if (NewFn.isInvalid())
16828 return true;
16829
16830 SmallVector<Expr *, 8> MethodArgs;
16831 MethodArgs.reserve(N: NumParams + 1);
16832
16833 bool IsError = false;
16834
16835 // Initialize the object parameter.
16836 llvm::SmallVector<Expr *, 8> NewArgs;
16837 if (Method->isExplicitObjectMemberFunction()) {
16838 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16839 } else {
16840 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16841 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16842 if (ObjRes.isInvalid())
16843 IsError = true;
16844 else
16845 Object = ObjRes;
16846 MethodArgs.push_back(Elt: Object.get());
16847 }
16848
16849 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16850 S&: *this, MethodArgs, Method, Args, LParenLoc);
16851
16852 // If this is a variadic call, handle args passed through "...".
16853 if (Proto->isVariadic()) {
16854 // Promote the arguments (C99 6.5.2.2p7).
16855 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16856 ExprResult Arg = DefaultVariadicArgumentPromotion(
16857 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16858 IsError |= Arg.isInvalid();
16859 MethodArgs.push_back(Elt: Arg.get());
16860 }
16861 }
16862
16863 if (IsError)
16864 return true;
16865
16866 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16867
16868 // Once we've built TheCall, all of the expressions are properly owned.
16869 QualType ResultTy = Method->getReturnType();
16870 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16871 ResultTy = ResultTy.getNonLValueExprType(Context);
16872
16873 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16874 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16875 FPFeatures: CurFPFeatureOverrides());
16876
16877 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16878 return true;
16879
16880 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16881 return true;
16882
16883 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16884}
16885
16886ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16887 SourceLocation OpLoc,
16888 bool *NoArrowOperatorFound) {
16889 assert(Base->getType()->isRecordType() &&
16890 "left-hand side must have class type");
16891
16892 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16893 return ExprError();
16894
16895 SourceLocation Loc = Base->getExprLoc();
16896
16897 // C++ [over.ref]p1:
16898 //
16899 // [...] An expression x->m is interpreted as (x.operator->())->m
16900 // for a class object x of type T if T::operator->() exists and if
16901 // the operator is selected as the best match function by the
16902 // overload resolution mechanism (13.3).
16903 DeclarationName OpName =
16904 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16905 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16906
16907 if (RequireCompleteType(Loc, T: Base->getType(),
16908 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16909 return ExprError();
16910
16911 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16912 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16913 R.suppressAccessDiagnostics();
16914
16915 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16916 Oper != OperEnd; ++Oper) {
16917 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16918 Args: {}, CandidateSet,
16919 /*SuppressUserConversion=*/SuppressUserConversions: false);
16920 }
16921
16922 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16923
16924 // Perform overload resolution.
16925 OverloadCandidateSet::iterator Best;
16926 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16927 case OR_Success:
16928 // Overload resolution succeeded; we'll build the call below.
16929 break;
16930
16931 case OR_No_Viable_Function: {
16932 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16933 if (CandidateSet.empty()) {
16934 QualType BaseType = Base->getType();
16935 if (NoArrowOperatorFound) {
16936 // Report this specific error to the caller instead of emitting a
16937 // diagnostic, as requested.
16938 *NoArrowOperatorFound = true;
16939 return ExprError();
16940 }
16941 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16942 << BaseType << Base->getSourceRange();
16943 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16944 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16945 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16946 }
16947 } else
16948 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16949 << "operator->" << Base->getSourceRange();
16950 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16951 return ExprError();
16952 }
16953 case OR_Ambiguous:
16954 if (!R.isAmbiguous())
16955 CandidateSet.NoteCandidates(
16956 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16957 << "->" << Base->getType()
16958 << Base->getSourceRange()),
16959 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16960 return ExprError();
16961
16962 case OR_Deleted: {
16963 StringLiteral *Msg = Best->Function->getDeletedMessage();
16964 CandidateSet.NoteCandidates(
16965 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16966 << "->" << (Msg != nullptr)
16967 << (Msg ? Msg->getString() : StringRef())
16968 << Base->getSourceRange()),
16969 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16970 return ExprError();
16971 }
16972 }
16973
16974 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16975
16976 // Convert the object parameter.
16977 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16978
16979 if (Method->isExplicitObjectMemberFunction()) {
16980 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16981 if (R.isInvalid())
16982 return ExprError();
16983 Base = R.get();
16984 } else {
16985 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16986 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16987 if (BaseResult.isInvalid())
16988 return ExprError();
16989 Base = BaseResult.get();
16990 }
16991
16992 // Build the operator call.
16993 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16994 Base, HadMultipleCandidates, Loc: OpLoc);
16995 if (FnExpr.isInvalid())
16996 return ExprError();
16997
16998 QualType ResultTy = Method->getReturnType();
16999 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17000 ResultTy = ResultTy.getNonLValueExprType(Context);
17001
17002 CallExpr *TheCall =
17003 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
17004 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
17005
17006 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
17007 return ExprError();
17008
17009 if (CheckFunctionCall(FDecl: Method, TheCall,
17010 Proto: Method->getType()->castAs<FunctionProtoType>()))
17011 return ExprError();
17012
17013 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17014}
17015
17016ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
17017 DeclarationNameInfo &SuffixInfo,
17018 ArrayRef<Expr*> Args,
17019 SourceLocation LitEndLoc,
17020 TemplateArgumentListInfo *TemplateArgs) {
17021 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17022
17023 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17024 OverloadCandidateSet::CSK_Normal);
17025 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
17026 ExplicitTemplateArgs: TemplateArgs);
17027
17028 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17029
17030 // Perform overload resolution. This will usually be trivial, but might need
17031 // to perform substitutions for a literal operator template.
17032 OverloadCandidateSet::iterator Best;
17033 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
17034 case OR_Success:
17035 case OR_Deleted:
17036 break;
17037
17038 case OR_No_Viable_Function:
17039 CandidateSet.NoteCandidates(
17040 PD: PartialDiagnosticAt(UDSuffixLoc,
17041 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
17042 << R.getLookupName()),
17043 S&: *this, OCD: OCD_AllCandidates, Args);
17044 return ExprError();
17045
17046 case OR_Ambiguous:
17047 CandidateSet.NoteCandidates(
17048 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
17049 << R.getLookupName()),
17050 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
17051 return ExprError();
17052 }
17053
17054 FunctionDecl *FD = Best->Function;
17055 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
17056 Base: nullptr, HadMultipleCandidates,
17057 Loc: SuffixInfo.getLoc(),
17058 LocInfo: SuffixInfo.getInfo());
17059 if (Fn.isInvalid())
17060 return true;
17061
17062 // Check the argument types. This should almost always be a no-op, except
17063 // that array-to-pointer decay is applied to string literals.
17064 Expr *ConvArgs[2];
17065 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17066 ExprResult InputInit = PerformCopyInitialization(
17067 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17068 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17069 if (InputInit.isInvalid())
17070 return true;
17071 ConvArgs[ArgIdx] = InputInit.get();
17072 }
17073
17074 QualType ResultTy = FD->getReturnType();
17075 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17076 ResultTy = ResultTy.getNonLValueExprType(Context);
17077
17078 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17079 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17080 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17081
17082 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17083 return ExprError();
17084
17085 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17086 return ExprError();
17087
17088 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17089}
17090
17091Sema::ForRangeStatus
17092Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17093 SourceLocation RangeLoc,
17094 const DeclarationNameInfo &NameInfo,
17095 LookupResult &MemberLookup,
17096 OverloadCandidateSet *CandidateSet,
17097 Expr *Range, ExprResult *CallExpr) {
17098 Scope *S = nullptr;
17099
17100 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17101 if (!MemberLookup.empty()) {
17102 ExprResult MemberRef =
17103 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17104 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17105 /*TemplateKWLoc=*/SourceLocation(),
17106 /*FirstQualifierInScope=*/nullptr,
17107 R&: MemberLookup,
17108 /*TemplateArgs=*/nullptr, S);
17109 if (MemberRef.isInvalid()) {
17110 *CallExpr = ExprError();
17111 return FRS_DiagnosticIssued;
17112 }
17113 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17114 if (CallExpr->isInvalid()) {
17115 *CallExpr = ExprError();
17116 return FRS_DiagnosticIssued;
17117 }
17118 } else {
17119 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17120 NNSLoc: NestedNameSpecifierLoc(),
17121 DNI: NameInfo, Fns: UnresolvedSet<0>());
17122 if (FnR.isInvalid())
17123 return FRS_DiagnosticIssued;
17124 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17125
17126 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17127 CandidateSet, Result: CallExpr);
17128 if (CandidateSet->empty() || CandidateSetError) {
17129 *CallExpr = ExprError();
17130 return FRS_NoViableFunction;
17131 }
17132 OverloadCandidateSet::iterator Best;
17133 OverloadingResult OverloadResult =
17134 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17135
17136 if (OverloadResult == OR_No_Viable_Function) {
17137 *CallExpr = ExprError();
17138 return FRS_NoViableFunction;
17139 }
17140 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17141 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17142 OverloadResult,
17143 /*AllowTypoCorrection=*/false);
17144 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17145 *CallExpr = ExprError();
17146 return FRS_DiagnosticIssued;
17147 }
17148 }
17149 return FRS_Success;
17150}
17151
17152ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17153 FunctionDecl *Fn) {
17154 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17155 ExprResult SubExpr =
17156 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17157 if (SubExpr.isInvalid())
17158 return ExprError();
17159 if (SubExpr.get() == PE->getSubExpr())
17160 return PE;
17161
17162 return new (Context)
17163 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17164 }
17165
17166 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17167 ExprResult SubExpr =
17168 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17169 if (SubExpr.isInvalid())
17170 return ExprError();
17171 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17172 SubExpr.get()->getType()) &&
17173 "Implicit cast type cannot be determined from overload");
17174 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17175 if (SubExpr.get() == ICE->getSubExpr())
17176 return ICE;
17177
17178 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17179 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17180 FPO: CurFPFeatureOverrides());
17181 }
17182
17183 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17184 if (!GSE->isResultDependent()) {
17185 ExprResult SubExpr =
17186 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17187 if (SubExpr.isInvalid())
17188 return ExprError();
17189 if (SubExpr.get() == GSE->getResultExpr())
17190 return GSE;
17191
17192 // Replace the resulting type information before rebuilding the generic
17193 // selection expression.
17194 ArrayRef<Expr *> A = GSE->getAssocExprs();
17195 SmallVector<Expr *, 4> AssocExprs(A);
17196 unsigned ResultIdx = GSE->getResultIndex();
17197 AssocExprs[ResultIdx] = SubExpr.get();
17198
17199 if (GSE->isExprPredicate())
17200 return GenericSelectionExpr::Create(
17201 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17202 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17203 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17204 ResultIndex: ResultIdx);
17205 return GenericSelectionExpr::Create(
17206 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17207 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17208 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17209 ResultIndex: ResultIdx);
17210 }
17211 // Rather than fall through to the unreachable, return the original generic
17212 // selection expression.
17213 return GSE;
17214 }
17215
17216 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17217 assert(UnOp->getOpcode() == UO_AddrOf &&
17218 "Can only take the address of an overloaded function");
17219 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17220 if (!Method->isImplicitObjectMemberFunction()) {
17221 // Do nothing: the address of static and
17222 // explicit object member functions is a (non-member) function pointer.
17223 } else {
17224 // Fix the subexpression, which really has to be an
17225 // UnresolvedLookupExpr holding an overloaded member function
17226 // or template.
17227 ExprResult SubExpr =
17228 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17229 if (SubExpr.isInvalid())
17230 return ExprError();
17231 if (SubExpr.get() == UnOp->getSubExpr())
17232 return UnOp;
17233
17234 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17235 Op: SubExpr.get(), MD: Method))
17236 return ExprError();
17237
17238 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17239 "fixed to something other than a decl ref");
17240 NestedNameSpecifier Qualifier =
17241 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17242 assert(Qualifier &&
17243 "fixed to a member ref with no nested name qualifier");
17244
17245 // We have taken the address of a pointer to member
17246 // function. Perform the computation here so that we get the
17247 // appropriate pointer to member type.
17248 QualType MemPtrType = Context.getMemberPointerType(
17249 T: Fn->getType(), Qualifier,
17250 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17251 // Under the MS ABI, lock down the inheritance model now.
17252 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17253 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17254
17255 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17256 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17257 l: UnOp->getOperatorLoc(), CanOverflow: false,
17258 FPFeatures: CurFPFeatureOverrides());
17259 }
17260 }
17261 ExprResult SubExpr =
17262 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17263 if (SubExpr.isInvalid())
17264 return ExprError();
17265 if (SubExpr.get() == UnOp->getSubExpr())
17266 return UnOp;
17267
17268 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17269 InputExpr: SubExpr.get());
17270 }
17271
17272 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17273 if (Found.getAccess() == AS_none) {
17274 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17275 }
17276 // FIXME: avoid copy.
17277 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17278 if (ULE->hasExplicitTemplateArgs()) {
17279 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17280 TemplateArgs = &TemplateArgsBuffer;
17281 }
17282
17283 QualType Type = Fn->getType();
17284 ExprValueKind ValueKind =
17285 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17286 ? VK_LValue
17287 : VK_PRValue;
17288
17289 // FIXME: Duplicated from BuildDeclarationNameExpr.
17290 if (unsigned BID = Fn->getBuiltinID()) {
17291 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17292 Type = Context.BuiltinFnTy;
17293 ValueKind = VK_PRValue;
17294 }
17295 }
17296
17297 DeclRefExpr *DRE = BuildDeclRefExpr(
17298 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17299 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17300 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17301 return DRE;
17302 }
17303
17304 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17305 // FIXME: avoid copy.
17306 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17307 if (MemExpr->hasExplicitTemplateArgs()) {
17308 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17309 TemplateArgs = &TemplateArgsBuffer;
17310 }
17311
17312 Expr *Base;
17313
17314 // If we're filling in a static method where we used to have an
17315 // implicit member access, rewrite to a simple decl ref.
17316 if (MemExpr->isImplicitAccess()) {
17317 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17318 DeclRefExpr *DRE = BuildDeclRefExpr(
17319 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17320 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17321 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17322 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17323 return DRE;
17324 } else {
17325 SourceLocation Loc = MemExpr->getMemberLoc();
17326 if (MemExpr->getQualifier())
17327 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17328 Base =
17329 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17330 }
17331 } else
17332 Base = MemExpr->getBase();
17333
17334 ExprValueKind valueKind;
17335 QualType type;
17336 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17337 valueKind = VK_LValue;
17338 type = Fn->getType();
17339 } else {
17340 valueKind = VK_PRValue;
17341 type = Context.BoundMemberTy;
17342 }
17343
17344 return BuildMemberExpr(
17345 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17346 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17347 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17348 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17349 }
17350
17351 llvm_unreachable("Invalid reference to overloaded function");
17352}
17353
17354ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17355 DeclAccessPair Found,
17356 FunctionDecl *Fn) {
17357 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17358}
17359
17360bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17361 FunctionDecl *Function) {
17362 if (!PartialOverloading || !Function)
17363 return true;
17364 if (Function->isVariadic())
17365 return false;
17366 if (const auto *Proto =
17367 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17368 if (Proto->isTemplateVariadic())
17369 return false;
17370 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17371 if (const auto *Proto =
17372 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17373 if (Proto->isTemplateVariadic())
17374 return false;
17375 return true;
17376}
17377
17378void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17379 DeclarationName Name,
17380 OverloadCandidateSet &CandidateSet,
17381 FunctionDecl *Fn, MultiExprArg Args,
17382 bool IsMember) {
17383 StringLiteral *Msg = Fn->getDeletedMessage();
17384 CandidateSet.NoteCandidates(
17385 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17386 << IsMember << Name << (Msg != nullptr)
17387 << (Msg ? Msg->getString() : StringRef())
17388 << Range),
17389 S&: *this, OCD: OCD_AllCandidates, Args);
17390}
17391