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/ASTDiagnostic.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/DiagnosticOptions.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaAMDGPU.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
40#include "clang/Sema/TemplateDeduction.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
56using AllowedExplicit = Sema::AllowedExplicit;
57
58static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
59 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
65static ExprResult CreateFunctionRefExpr(
66 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
67 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
68 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
69 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
70 return ExprError();
71 // If FoundDecl is different from Fn (such as if one is a template
72 // and the other a specialization), make sure DiagnoseUseOfDecl is
73 // called on both.
74 // FIXME: This would be more comprehensively addressed by modifying
75 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
76 // being used.
77 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
78 return ExprError();
79 DeclRefExpr *DRE = new (S.Context)
80 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
81 if (HadMultipleCandidates)
82 DRE->setHadMultipleCandidates(true);
83
84 S.MarkDeclRefReferenced(E: DRE, Base);
85 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
86 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
87 S.ResolveExceptionSpec(Loc, FPT);
88 DRE->setType(Fn->getType());
89 }
90 }
91 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
92 CK: CK_FunctionToPointerDecay);
93}
94
95static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
96 bool InOverloadResolution,
97 StandardConversionSequence &SCS,
98 bool CStyle,
99 bool AllowObjCWritebackConversion);
100
101static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
102 QualType &ToType,
103 bool InOverloadResolution,
104 StandardConversionSequence &SCS,
105 bool CStyle);
106static OverloadingResult
107IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
108 UserDefinedConversionSequence& User,
109 OverloadCandidateSet& Conversions,
110 AllowedExplicit AllowExplicit,
111 bool AllowObjCConversionOnExplicit);
112
113static ImplicitConversionSequence::CompareKind
114CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
115 const StandardConversionSequence& SCS1,
116 const StandardConversionSequence& SCS2);
117
118static ImplicitConversionSequence::CompareKind
119CompareQualificationConversions(Sema &S,
120 const StandardConversionSequence& SCS1,
121 const StandardConversionSequence& SCS2);
122
123static ImplicitConversionSequence::CompareKind
124CompareOverflowBehaviorConversions(Sema &S,
125 const StandardConversionSequence &SCS1,
126 const StandardConversionSequence &SCS2);
127
128static ImplicitConversionSequence::CompareKind
129CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
130 const StandardConversionSequence& SCS1,
131 const StandardConversionSequence& SCS2);
132
133/// GetConversionRank - Retrieve the implicit conversion rank
134/// corresponding to the given implicit conversion kind.
135ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
136 static const ImplicitConversionRank Rank[] = {
137 ICR_Exact_Match,
138 ICR_Exact_Match,
139 ICR_Exact_Match,
140 ICR_Exact_Match,
141 ICR_Exact_Match,
142 ICR_Exact_Match,
143 ICR_Promotion,
144 ICR_Promotion,
145 ICR_Promotion,
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_Conversion,
158 ICR_OCL_Scalar_Widening,
159 ICR_Complex_Real_Conversion,
160 ICR_Conversion,
161 ICR_Conversion,
162 ICR_Writeback_Conversion,
163 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Event_Conversion
166 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
167 // it was omitted by the patch that added
168 // ICK_Zero_Queue_Conversion
169 ICR_C_Conversion,
170 ICR_C_Conversion_Extension,
171 ICR_Conversion,
172 ICR_HLSL_Dimension_Reduction,
173 ICR_HLSL_Dimension_Reduction,
174 ICR_Conversion,
175 ICR_HLSL_Scalar_Widening,
176 ICR_HLSL_Scalar_Widening,
177 };
178 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
179 return Rank[(int)Kind];
180}
181
182ImplicitConversionRank
183clang::GetDimensionConversionRank(ImplicitConversionRank Base,
184 ImplicitConversionKind Dimension) {
185 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
186 if (Rank == ICR_HLSL_Scalar_Widening) {
187 if (Base == ICR_Promotion)
188 return ICR_HLSL_Scalar_Widening_Promotion;
189 if (Base == ICR_Conversion)
190 return ICR_HLSL_Scalar_Widening_Conversion;
191 }
192 if (Rank == ICR_HLSL_Dimension_Reduction) {
193 if (Base == ICR_Promotion)
194 return ICR_HLSL_Dimension_Reduction_Promotion;
195 if (Base == ICR_Conversion)
196 return ICR_HLSL_Dimension_Reduction_Conversion;
197 }
198 return Rank;
199}
200
201/// GetImplicitConversionName - Return the name of this kind of
202/// implicit conversion.
203static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
204 static const char *const Name[] = {
205 "No conversion",
206 "Lvalue-to-rvalue",
207 "Array-to-pointer",
208 "Function-to-pointer",
209 "Function pointer conversion",
210 "Qualification",
211 "Integral promotion",
212 "Floating point promotion",
213 "Complex promotion",
214 "Integral conversion",
215 "Floating conversion",
216 "Complex conversion",
217 "Floating-integral conversion",
218 "Pointer conversion",
219 "Pointer-to-member conversion",
220 "Boolean conversion",
221 "Compatible-types conversion",
222 "Derived-to-base conversion",
223 "Vector conversion",
224 "SVE Vector conversion",
225 "RVV Vector conversion",
226 "Vector splat",
227 "Complex-real conversion",
228 "Block Pointer conversion",
229 "Transparent Union Conversion",
230 "Writeback conversion",
231 "OpenCL Zero Event Conversion",
232 "OpenCL Zero Queue Conversion",
233 "C specific type conversion",
234 "Incompatible pointer conversion",
235 "Fixed point conversion",
236 "HLSL vector truncation",
237 "HLSL matrix truncation",
238 "Non-decaying array conversion",
239 "HLSL vector splat",
240 "HLSL matrix splat",
241 };
242 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
243 return Name[Kind];
244}
245
246/// StandardConversionSequence - Set the standard conversion
247/// sequence to the identity conversion.
248void StandardConversionSequence::setAsIdentityConversion() {
249 First = ICK_Identity;
250 Second = ICK_Identity;
251 Dimension = ICK_Identity;
252 Third = ICK_Identity;
253 DeprecatedStringLiteralToCharPtr = false;
254 QualificationIncludesObjCLifetime = false;
255 ReferenceBinding = false;
256 DirectBinding = false;
257 IsLvalueReference = true;
258 BindsToFunctionLvalue = false;
259 BindsToRvalue = false;
260 BindsImplicitObjectArgumentWithoutRefQualifier = false;
261 ObjCLifetimeConversionBinding = false;
262 FromBracedInitList = false;
263 CopyConstructor = nullptr;
264}
265
266/// getRank - Retrieve the rank of this standard conversion sequence
267/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
268/// implicit conversions.
269ImplicitConversionRank StandardConversionSequence::getRank() const {
270 ImplicitConversionRank Rank = ICR_Exact_Match;
271 if (GetConversionRank(Kind: First) > Rank)
272 Rank = GetConversionRank(Kind: First);
273 if (GetConversionRank(Kind: Second) > Rank)
274 Rank = GetConversionRank(Kind: Second);
275 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
276 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
277 if (GetConversionRank(Kind: Third) > Rank)
278 Rank = GetConversionRank(Kind: Third);
279 return Rank;
280}
281
282/// isPointerConversionToBool - Determines whether this conversion is
283/// a conversion of a pointer or pointer-to-member to bool. This is
284/// used as part of the ranking of standard conversion sequences
285/// (C++ 13.3.3.2p4).
286bool StandardConversionSequence::isPointerConversionToBool() const {
287 // Note that FromType has not necessarily been transformed by the
288 // array-to-pointer or function-to-pointer implicit conversions, so
289 // check for their presence as well as checking whether FromType is
290 // a pointer.
291 if (getToType(Idx: 1)->isBooleanType() &&
292 (getFromType()->isPointerType() ||
293 getFromType()->isMemberPointerType() ||
294 getFromType()->isObjCObjectPointerType() ||
295 getFromType()->isBlockPointerType() ||
296 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
297 return true;
298
299 return false;
300}
301
302/// isPointerConversionToVoidPointer - Determines whether this
303/// conversion is a conversion of a pointer to a void pointer. This is
304/// used as part of the ranking of standard conversion sequences (C++
305/// 13.3.3.2p4).
306bool
307StandardConversionSequence::
308isPointerConversionToVoidPointer(ASTContext& Context) const {
309 QualType FromType = getFromType();
310 QualType ToType = getToType(Idx: 1);
311
312 // Note that FromType has not necessarily been transformed by the
313 // array-to-pointer implicit conversion, so check for its presence
314 // and redo the conversion to get a pointer.
315 if (First == ICK_Array_To_Pointer)
316 FromType = Context.getArrayDecayedType(T: FromType);
317
318 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
319 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
320 return ToPtrType->getPointeeType()->isVoidType();
321
322 return false;
323}
324
325/// Skip any implicit casts which could be either part of a narrowing conversion
326/// or after one in an implicit conversion.
327static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
328 const Expr *Converted) {
329 // We can have cleanups wrapping the converted expression; these need to be
330 // preserved so that destructors run if necessary.
331 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
332 Expr *Inner =
333 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
334 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
335 objects: EWC->getObjects());
336 }
337
338 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
339 switch (ICE->getCastKind()) {
340 case CK_NoOp:
341 case CK_IntegralCast:
342 case CK_IntegralToBoolean:
343 case CK_IntegralToFloating:
344 case CK_BooleanToSignedIntegral:
345 case CK_FloatingToIntegral:
346 case CK_FloatingToBoolean:
347 case CK_FloatingCast:
348 Converted = ICE->getSubExpr();
349 continue;
350
351 default:
352 return Converted;
353 }
354 }
355
356 return Converted;
357}
358
359/// Check if this standard conversion sequence represents a narrowing
360/// conversion, according to C++11 [dcl.init.list]p7.
361///
362/// \param Ctx The AST context.
363/// \param Converted The result of applying this standard conversion sequence.
364/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
365/// value of the expression prior to the narrowing conversion.
366/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
367/// type of the expression prior to the narrowing conversion.
368/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
369/// from floating point types to integral types should be ignored.
370/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
371/// to conform MSVC compiler behavior.
372NarrowingKind StandardConversionSequence::getNarrowingKind(
373 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
374 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
375 bool AllowRelaxedEval) const {
376 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
377 "narrowing check outside C++");
378
379 // C++11 [dcl.init.list]p7:
380 // A narrowing conversion is an implicit conversion ...
381 QualType FromType = getToType(Idx: 0);
382 QualType ToType = getToType(Idx: 1);
383
384 // A conversion to an enumeration type is narrowing if the conversion to
385 // the underlying type is narrowing. This only arises for expressions of
386 // the form 'Enum{init}'.
387 if (const auto *ED = ToType->getAsEnumDecl())
388 ToType = ED->getIntegerType();
389
390 switch (Second) {
391 // 'bool' is an integral type; dispatch to the right place to handle it.
392 case ICK_Boolean_Conversion:
393 if (FromType->isRealFloatingType())
394 goto FloatingIntegralConversion;
395 if (FromType->isIntegralOrUnscopedEnumerationType())
396 goto IntegralConversion;
397 // -- from a pointer type or pointer-to-member type to bool, or
398 return NK_Type_Narrowing;
399
400 // -- from a floating-point type to an integer type, or
401 //
402 // -- from an integer type or unscoped enumeration type to a floating-point
403 // type, except where the source is a constant expression and the actual
404 // value after conversion will fit into the target type and will produce
405 // the original value when converted back to the original type, or
406 case ICK_Floating_Integral:
407 FloatingIntegralConversion:
408 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
409 return NK_Type_Narrowing;
410 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
411 ToType->isRealFloatingType()) {
412 if (IgnoreFloatToIntegralConversion)
413 return NK_Not_Narrowing;
414 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
415 assert(Initializer && "Unknown conversion expression");
416
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
419 return NK_Dependent_Narrowing;
420
421 if (std::optional<llvm::APSInt> IntConstantValue =
422 Initializer->getIntegerConstantExpr(Ctx)) {
423 // Convert the integer to the floating type.
424 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
425 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
426 RM: llvm::APFloat::rmNearestTiesToEven);
427 // And back.
428 llvm::APSInt ConvertedValue = *IntConstantValue;
429 bool ignored;
430 llvm::APFloat::opStatus Status = Result.convertToInteger(
431 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
432 // If the converted-back integer has unspecified value, or if the
433 // resulting value is different, this was a narrowing conversion.
434 if (Status == llvm::APFloat::opInvalidOp ||
435 *IntConstantValue != ConvertedValue) {
436 ConstantValue = APValue(*IntConstantValue);
437 ConstantType = Initializer->getType();
438 return NK_Constant_Narrowing;
439 }
440 } else {
441 // Variables are always narrowings.
442 return NK_Variable_Narrowing;
443 }
444 }
445 return NK_Not_Narrowing;
446
447 // -- from long double to double or float, or from double to float, except
448 // where the source is a constant expression and the actual value after
449 // conversion is within the range of values that can be represented (even
450 // if it cannot be represented exactly), or
451 case ICK_Floating_Conversion:
452 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
453 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
454 // FromType is larger than ToType.
455 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
456
457 // If it's value-dependent, we can't tell whether it's narrowing.
458 if (Initializer->isValueDependent())
459 return NK_Dependent_Narrowing;
460
461 Expr::EvalResult R;
462 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
463 ((Ctx.getLangOpts().CPlusPlus &&
464 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue,
465 AllowRelaxedEval)))) {
466 // Constant!
467 if (Ctx.getLangOpts().C23)
468 ConstantValue = R.Val;
469 assert(ConstantValue.isFloat());
470 llvm::APFloat FloatVal = ConstantValue.getFloat();
471 // Convert the source value into the target type.
472 bool ignored;
473 llvm::APFloat Converted = FloatVal;
474 llvm::APFloat::opStatus ConvertStatus =
475 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
476 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
477 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
478 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
479 if (Ctx.getLangOpts().C23) {
480 if (FloatVal.isNaN() && Converted.isNaN() &&
481 !FloatVal.isSignaling() && !Converted.isSignaling()) {
482 // Quiet NaNs are considered the same value, regardless of
483 // payloads.
484 return NK_Not_Narrowing;
485 }
486 // For normal values, check exact equality.
487 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
488 ConstantType = Initializer->getType();
489 return NK_Constant_Narrowing;
490 }
491 } else {
492 // If there was no overflow, the source value is within the range of
493 // values that can be represented.
494 if (ConvertStatus & llvm::APFloat::opOverflow) {
495 ConstantType = Initializer->getType();
496 return NK_Constant_Narrowing;
497 }
498 }
499 } else {
500 return NK_Variable_Narrowing;
501 }
502 }
503 return NK_Not_Narrowing;
504
505 // -- from an integer type or unscoped enumeration type to an integer type
506 // that cannot represent all the values of the original type, except where
507 // (CWG2627) -- the source is a bit-field whose width w is less than that
508 // of its type (or, for an enumeration type, its underlying type) and the
509 // target type can represent all the values of a hypothetical extended
510 // integer type with width w and with the same signedness as the original
511 // type or
512 // -- the source is a constant expression and the actual value after
513 // conversion will fit into the target type and will produce the original
514 // value when converted back to the original type.
515 case ICK_Integral_Conversion:
516 IntegralConversion: {
517 assert(FromType->isIntegralOrUnscopedEnumerationType());
518 assert(ToType->isIntegralOrUnscopedEnumerationType());
519 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
520 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
521 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
522 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
523
524 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
525 bool ToSigned, unsigned ToWidth) {
526 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
527 !(FromSigned && !ToSigned);
528 };
529
530 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // Not all values of FromType can be represented in ToType.
534 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
535
536 bool DependentBitField = false;
537 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
538 if (BitField->getBitWidth()->isValueDependent())
539 DependentBitField = true;
540 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
541 BitFieldWidth < FromWidth) {
542 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
543 return NK_Not_Narrowing;
544
545 // The initializer will be truncated to the bit-field width
546 FromWidth = BitFieldWidth;
547 }
548 }
549
550 // If it's value-dependent, we can't tell whether it's narrowing.
551 if (Initializer->isValueDependent())
552 return NK_Dependent_Narrowing;
553
554 std::optional<llvm::APSInt> OptInitializerValue =
555 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
556 if (!OptInitializerValue) {
557 // If the bit-field width was dependent, it might end up being small
558 // enough to fit in the target type (unless the target type is unsigned
559 // and the source type is signed, in which case it will never fit)
560 if (DependentBitField && !(FromSigned && !ToSigned))
561 return NK_Dependent_Narrowing;
562
563 // Otherwise, such a conversion is always narrowing
564 return NK_Variable_Narrowing;
565 }
566 llvm::APSInt &InitializerValue = *OptInitializerValue;
567 bool Narrowing = false;
568 if (FromWidth < ToWidth) {
569 // Negative -> unsigned is narrowing. Otherwise, more bits is never
570 // narrowing.
571 if (InitializerValue.isSigned() && InitializerValue.isNegative())
572 Narrowing = true;
573 } else {
574 // Add a bit to the InitializerValue so we don't have to worry about
575 // signed vs. unsigned comparisons.
576 InitializerValue =
577 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
578 // Convert the initializer to and from the target width and signed-ness.
579 llvm::APSInt ConvertedValue = InitializerValue;
580 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
581 ConvertedValue.setIsSigned(ToSigned);
582 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
583 ConvertedValue.setIsSigned(InitializerValue.isSigned());
584 // If the result is different, this was a narrowing conversion.
585 if (ConvertedValue != InitializerValue)
586 Narrowing = true;
587 }
588 if (Narrowing) {
589 ConstantType = Initializer->getType();
590 ConstantValue = APValue(InitializerValue);
591 return NK_Constant_Narrowing;
592 }
593
594 return NK_Not_Narrowing;
595 }
596 case ICK_Complex_Real:
597 if (FromType->isComplexType() && !ToType->isComplexType())
598 return NK_Type_Narrowing;
599 return NK_Not_Narrowing;
600
601 case ICK_Floating_Promotion:
602 if (Ctx.getLangOpts().C23) {
603 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
604 Expr::EvalResult R;
605 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
606 ConstantValue = R.Val;
607 assert(ConstantValue.isFloat());
608 llvm::APFloat FloatVal = ConstantValue.getFloat();
609 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
610 // value, the unqualified versions of the type of the initializer and
611 // the corresponding real type of the object declared shall be
612 // compatible.
613 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
614 ConstantType = Initializer->getType();
615 return NK_Constant_Narrowing;
616 }
617 }
618 }
619 return NK_Not_Narrowing;
620 default:
621 // Other kinds of conversions are not narrowings.
622 return NK_Not_Narrowing;
623 }
624}
625
626/// dump - Print this standard conversion sequence to standard
627/// error. Useful for debugging overloading issues.
628LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
629 raw_ostream &OS = llvm::errs();
630 bool PrintedSomething = false;
631 if (First != ICK_Identity) {
632 OS << GetImplicitConversionName(Kind: First);
633 PrintedSomething = true;
634 }
635
636 if (Second != ICK_Identity) {
637 if (PrintedSomething) {
638 OS << " -> ";
639 }
640 OS << GetImplicitConversionName(Kind: Second);
641
642 if (CopyConstructor) {
643 OS << " (by copy constructor)";
644 } else if (DirectBinding) {
645 OS << " (direct reference binding)";
646 } else if (ReferenceBinding) {
647 OS << " (reference binding)";
648 }
649 PrintedSomething = true;
650 }
651
652 if (Third != ICK_Identity) {
653 if (PrintedSomething) {
654 OS << " -> ";
655 }
656 OS << GetImplicitConversionName(Kind: Third);
657 PrintedSomething = true;
658 }
659
660 if (!PrintedSomething) {
661 OS << "No conversions required";
662 }
663}
664
665/// dump - Print this user-defined conversion sequence to standard
666/// error. Useful for debugging overloading issues.
667void UserDefinedConversionSequence::dump() const {
668 raw_ostream &OS = llvm::errs();
669 if (Before.First || Before.Second || Before.Third) {
670 Before.dump();
671 OS << " -> ";
672 }
673 if (ConversionFunction)
674 OS << '\'' << *ConversionFunction << '\'';
675 else
676 OS << "aggregate initialization";
677 if (After.First || After.Second || After.Third) {
678 OS << " -> ";
679 After.dump();
680 }
681}
682
683/// dump - Print this implicit conversion sequence to standard
684/// error. Useful for debugging overloading issues.
685void ImplicitConversionSequence::dump() const {
686 raw_ostream &OS = llvm::errs();
687 if (hasInitializerListContainerType())
688 OS << "Worst list element conversion: ";
689 switch (ConversionKind) {
690 case StandardConversion:
691 OS << "Standard conversion: ";
692 Standard.dump();
693 break;
694 case UserDefinedConversion:
695 OS << "User-defined conversion: ";
696 UserDefined.dump();
697 break;
698 case EllipsisConversion:
699 OS << "Ellipsis conversion";
700 break;
701 case AmbiguousConversion:
702 OS << "Ambiguous conversion";
703 break;
704 case BadConversion:
705 OS << "Bad conversion";
706 break;
707 }
708
709 OS << "\n";
710}
711
712void AmbiguousConversionSequence::construct() {
713 new (&conversions()) ConversionSet();
714}
715
716void AmbiguousConversionSequence::destruct() {
717 conversions().~ConversionSet();
718}
719
720void
721AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
722 FromTypePtr = O.FromTypePtr;
723 ToTypePtr = O.ToTypePtr;
724 new (&conversions()) ConversionSet(O.conversions());
725}
726
727namespace {
728 // Structure used by DeductionFailureInfo to store
729 // template argument information.
730 struct DFIArguments {
731 TemplateArgument FirstArg;
732 TemplateArgument SecondArg;
733 };
734 // Structure used by DeductionFailureInfo to store
735 // template parameter and template argument information.
736 struct DFIParamWithArguments : DFIArguments {
737 TemplateParameter Param;
738 };
739 // Structure used by DeductionFailureInfo to store template argument
740 // information and the index of the problematic call argument.
741 struct DFIDeducedMismatchArgs : DFIArguments {
742 TemplateArgumentList *TemplateArgs;
743 unsigned CallArgIndex;
744 };
745 // Structure used by DeductionFailureInfo to store information about
746 // unsatisfied constraints.
747 struct CNSInfo {
748 TemplateArgumentList *TemplateArgs;
749 ConstraintSatisfaction Satisfaction;
750 };
751}
752
753/// Convert from Sema's representation of template deduction information
754/// to the form used in overload-candidate information.
755DeductionFailureInfo
756clang::MakeDeductionFailureInfo(ASTContext &Context,
757 TemplateDeductionResult TDK,
758 TemplateDeductionInfo &Info) {
759 DeductionFailureInfo Result;
760 Result.Result = static_cast<unsigned>(TDK);
761 Result.HasDiagnostic = false;
762 switch (TDK) {
763 case TemplateDeductionResult::Invalid:
764 case TemplateDeductionResult::InstantiationDepth:
765 case TemplateDeductionResult::TooManyArguments:
766 case TemplateDeductionResult::TooFewArguments:
767 case TemplateDeductionResult::MiscellaneousDeductionFailure:
768 case TemplateDeductionResult::CUDATargetMismatch:
769 Result.Data = nullptr;
770 break;
771
772 case TemplateDeductionResult::Incomplete:
773 Result.Data = Info.Param.getOpaqueValue();
774 break;
775 case TemplateDeductionResult::InvalidExplicitArguments:
776 Result.Data = Info.Param.getOpaqueValue();
777 if (Info.hasSFINAEDiagnostic()) {
778 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
779 SourceLocation(), PartialDiagnostic::NullDiagnostic());
780 Info.takeSFINAEDiagnostic(PD&: *Diag);
781 Result.HasDiagnostic = true;
782 }
783 break;
784
785 case TemplateDeductionResult::DeducedMismatch:
786 case TemplateDeductionResult::DeducedMismatchNested: {
787 // FIXME: Should allocate from normal heap so that we can free this later.
788 auto *Saved = new (Context) DFIDeducedMismatchArgs;
789 Saved->FirstArg = Info.FirstArg;
790 Saved->SecondArg = Info.SecondArg;
791 Saved->TemplateArgs = Info.takeSugared();
792 Saved->CallArgIndex = Info.CallArgIndex;
793 Result.Data = Saved;
794 break;
795 }
796
797 case TemplateDeductionResult::NonDeducedMismatch: {
798 // FIXME: Should allocate from normal heap so that we can free this later.
799 DFIArguments *Saved = new (Context) DFIArguments;
800 Saved->FirstArg = Info.FirstArg;
801 Saved->SecondArg = Info.SecondArg;
802 Result.Data = Saved;
803 break;
804 }
805
806 case TemplateDeductionResult::IncompletePack:
807 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
808 case TemplateDeductionResult::Inconsistent:
809 case TemplateDeductionResult::Underqualified: {
810 // FIXME: Should allocate from normal heap so that we can free this later.
811 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
812 Saved->Param = Info.Param;
813 Saved->FirstArg = Info.FirstArg;
814 Saved->SecondArg = Info.SecondArg;
815 Result.Data = Saved;
816 break;
817 }
818
819 case TemplateDeductionResult::SubstitutionFailure:
820 Result.Data = Info.takeSugared();
821 if (Info.hasSFINAEDiagnostic()) {
822 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
823 SourceLocation(), PartialDiagnostic::NullDiagnostic());
824 Info.takeSFINAEDiagnostic(PD&: *Diag);
825 Result.HasDiagnostic = true;
826 }
827 break;
828
829 case TemplateDeductionResult::ConstraintsNotSatisfied: {
830 CNSInfo *Saved = new (Context) CNSInfo;
831 Saved->TemplateArgs = Info.takeSugared();
832 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
833 Result.Data = Saved;
834 break;
835 }
836
837 case TemplateDeductionResult::Success:
838 case TemplateDeductionResult::NonDependentConversionFailure:
839 case TemplateDeductionResult::AlreadyDiagnosed:
840 llvm_unreachable("not a deduction failure");
841 }
842
843 return Result;
844}
845
846void DeductionFailureInfo::Destroy() {
847 switch (static_cast<TemplateDeductionResult>(Result)) {
848 case TemplateDeductionResult::Success:
849 case TemplateDeductionResult::Invalid:
850 case TemplateDeductionResult::InstantiationDepth:
851 case TemplateDeductionResult::Incomplete:
852 case TemplateDeductionResult::TooManyArguments:
853 case TemplateDeductionResult::TooFewArguments:
854 case TemplateDeductionResult::CUDATargetMismatch:
855 case TemplateDeductionResult::NonDependentConversionFailure:
856 break;
857
858 case TemplateDeductionResult::IncompletePack:
859 case TemplateDeductionResult::Inconsistent:
860 case TemplateDeductionResult::Underqualified:
861 case TemplateDeductionResult::DeducedMismatch:
862 case TemplateDeductionResult::DeducedMismatchNested:
863 case TemplateDeductionResult::NonDeducedMismatch:
864 // FIXME: Destroy the data?
865 Data = nullptr;
866 break;
867
868 case TemplateDeductionResult::InvalidExplicitArguments:
869 case TemplateDeductionResult::SubstitutionFailure:
870 // FIXME: Destroy the template argument list?
871 Data = nullptr;
872 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
873 Diag->~PartialDiagnosticAt();
874 HasDiagnostic = false;
875 }
876 break;
877
878 case TemplateDeductionResult::ConstraintsNotSatisfied:
879 // FIXME: Destroy the template argument list?
880 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
881 Data = nullptr;
882 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
883 Diag->~PartialDiagnosticAt();
884 HasDiagnostic = false;
885 }
886 break;
887
888 // Unhandled
889 case TemplateDeductionResult::MiscellaneousDeductionFailure:
890 case TemplateDeductionResult::AlreadyDiagnosed:
891 break;
892 }
893}
894
895PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
896 if (HasDiagnostic)
897 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
898 return nullptr;
899}
900
901TemplateParameter DeductionFailureInfo::getTemplateParameter() {
902 switch (static_cast<TemplateDeductionResult>(Result)) {
903 case TemplateDeductionResult::Success:
904 case TemplateDeductionResult::Invalid:
905 case TemplateDeductionResult::InstantiationDepth:
906 case TemplateDeductionResult::TooManyArguments:
907 case TemplateDeductionResult::TooFewArguments:
908 case TemplateDeductionResult::SubstitutionFailure:
909 case TemplateDeductionResult::DeducedMismatch:
910 case TemplateDeductionResult::DeducedMismatchNested:
911 case TemplateDeductionResult::NonDeducedMismatch:
912 case TemplateDeductionResult::CUDATargetMismatch:
913 case TemplateDeductionResult::NonDependentConversionFailure:
914 case TemplateDeductionResult::ConstraintsNotSatisfied:
915 return TemplateParameter();
916
917 case TemplateDeductionResult::Incomplete:
918 case TemplateDeductionResult::InvalidExplicitArguments:
919 return TemplateParameter::getFromOpaqueValue(VP: Data);
920
921 case TemplateDeductionResult::IncompletePack:
922 case TemplateDeductionResult::Inconsistent:
923 case TemplateDeductionResult::Underqualified:
924 return static_cast<DFIParamWithArguments*>(Data)->Param;
925
926 // Unhandled
927 case TemplateDeductionResult::MiscellaneousDeductionFailure:
928 case TemplateDeductionResult::AlreadyDiagnosed:
929 break;
930 }
931
932 return TemplateParameter();
933}
934
935TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
936 switch (static_cast<TemplateDeductionResult>(Result)) {
937 case TemplateDeductionResult::Success:
938 case TemplateDeductionResult::Invalid:
939 case TemplateDeductionResult::InstantiationDepth:
940 case TemplateDeductionResult::TooManyArguments:
941 case TemplateDeductionResult::TooFewArguments:
942 case TemplateDeductionResult::Incomplete:
943 case TemplateDeductionResult::IncompletePack:
944 case TemplateDeductionResult::InvalidExplicitArguments:
945 case TemplateDeductionResult::Inconsistent:
946 case TemplateDeductionResult::Underqualified:
947 case TemplateDeductionResult::NonDeducedMismatch:
948 case TemplateDeductionResult::CUDATargetMismatch:
949 case TemplateDeductionResult::NonDependentConversionFailure:
950 return nullptr;
951
952 case TemplateDeductionResult::DeducedMismatch:
953 case TemplateDeductionResult::DeducedMismatchNested:
954 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
955
956 case TemplateDeductionResult::SubstitutionFailure:
957 return static_cast<TemplateArgumentList*>(Data);
958
959 case TemplateDeductionResult::ConstraintsNotSatisfied:
960 return static_cast<CNSInfo*>(Data)->TemplateArgs;
961
962 // Unhandled
963 case TemplateDeductionResult::MiscellaneousDeductionFailure:
964 case TemplateDeductionResult::AlreadyDiagnosed:
965 break;
966 }
967
968 return nullptr;
969}
970
971const TemplateArgument *DeductionFailureInfo::getFirstArg() {
972 switch (static_cast<TemplateDeductionResult>(Result)) {
973 case TemplateDeductionResult::Success:
974 case TemplateDeductionResult::Invalid:
975 case TemplateDeductionResult::InstantiationDepth:
976 case TemplateDeductionResult::Incomplete:
977 case TemplateDeductionResult::TooManyArguments:
978 case TemplateDeductionResult::TooFewArguments:
979 case TemplateDeductionResult::InvalidExplicitArguments:
980 case TemplateDeductionResult::SubstitutionFailure:
981 case TemplateDeductionResult::CUDATargetMismatch:
982 case TemplateDeductionResult::NonDependentConversionFailure:
983 case TemplateDeductionResult::ConstraintsNotSatisfied:
984 return nullptr;
985
986 case TemplateDeductionResult::IncompletePack:
987 case TemplateDeductionResult::Inconsistent:
988 case TemplateDeductionResult::Underqualified:
989 case TemplateDeductionResult::DeducedMismatch:
990 case TemplateDeductionResult::DeducedMismatchNested:
991 case TemplateDeductionResult::NonDeducedMismatch:
992 return &static_cast<DFIArguments*>(Data)->FirstArg;
993
994 // Unhandled
995 case TemplateDeductionResult::MiscellaneousDeductionFailure:
996 case TemplateDeductionResult::AlreadyDiagnosed:
997 break;
998 }
999
1000 return nullptr;
1001}
1002
1003const TemplateArgument *DeductionFailureInfo::getSecondArg() {
1004 switch (static_cast<TemplateDeductionResult>(Result)) {
1005 case TemplateDeductionResult::Success:
1006 case TemplateDeductionResult::Invalid:
1007 case TemplateDeductionResult::InstantiationDepth:
1008 case TemplateDeductionResult::Incomplete:
1009 case TemplateDeductionResult::IncompletePack:
1010 case TemplateDeductionResult::TooManyArguments:
1011 case TemplateDeductionResult::TooFewArguments:
1012 case TemplateDeductionResult::InvalidExplicitArguments:
1013 case TemplateDeductionResult::SubstitutionFailure:
1014 case TemplateDeductionResult::CUDATargetMismatch:
1015 case TemplateDeductionResult::NonDependentConversionFailure:
1016 case TemplateDeductionResult::ConstraintsNotSatisfied:
1017 return nullptr;
1018
1019 case TemplateDeductionResult::Inconsistent:
1020 case TemplateDeductionResult::Underqualified:
1021 case TemplateDeductionResult::DeducedMismatch:
1022 case TemplateDeductionResult::DeducedMismatchNested:
1023 case TemplateDeductionResult::NonDeducedMismatch:
1024 return &static_cast<DFIArguments*>(Data)->SecondArg;
1025
1026 // Unhandled
1027 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1028 case TemplateDeductionResult::AlreadyDiagnosed:
1029 break;
1030 }
1031
1032 return nullptr;
1033}
1034
1035UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1036 switch (static_cast<TemplateDeductionResult>(Result)) {
1037 case TemplateDeductionResult::DeducedMismatch:
1038 case TemplateDeductionResult::DeducedMismatchNested:
1039 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1040
1041 default:
1042 return std::nullopt;
1043 }
1044}
1045
1046static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1047 const FunctionDecl *Y) {
1048 if (!X || !Y)
1049 return false;
1050 if (X->getNumParams() != Y->getNumParams())
1051 return false;
1052 // FIXME: when do rewritten comparison operators
1053 // with explicit object parameters correspond?
1054 // https://cplusplus.github.io/CWG/issues/2797.html
1055 for (unsigned I = 0; I < X->getNumParams(); ++I)
1056 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1057 T2: Y->getParamDecl(i: I)->getType()))
1058 return false;
1059 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1060 auto *FTY = Y->getDescribedFunctionTemplate();
1061 if (!FTY)
1062 return false;
1063 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1064 Y: FTY->getTemplateParameters()))
1065 return false;
1066 }
1067 return true;
1068}
1069
1070static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1071 Expr *FirstOperand, FunctionDecl *EqFD) {
1072 assert(EqFD->getOverloadedOperator() ==
1073 OverloadedOperatorKind::OO_EqualEqual);
1074 // C++2a [over.match.oper]p4:
1075 // A non-template function or function template F named operator== is a
1076 // rewrite target with first operand o unless a search for the name operator!=
1077 // in the scope S from the instantiation context of the operator expression
1078 // finds a function or function template that would correspond
1079 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1080 // scope of the class type of o if F is a class member, and the namespace
1081 // scope of which F is a member otherwise. A function template specialization
1082 // named operator== is a rewrite target if its function template is a rewrite
1083 // target.
1084 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1085 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1086 if (isa<CXXMethodDecl>(Val: EqFD)) {
1087 // If F is a class member, search scope is class type of first operand.
1088 QualType RHS = FirstOperand->getType();
1089 auto *RHSRec = RHS->getAsCXXRecordDecl();
1090 if (!RHSRec)
1091 return true;
1092 LookupResult Members(S, NotEqOp, OpLoc,
1093 Sema::LookupNameKind::LookupMemberName);
1094 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1095 Members.suppressAccessDiagnostics();
1096 for (NamedDecl *Op : Members)
1097 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1098 return false;
1099 return true;
1100 }
1101 // Otherwise the search scope is the namespace scope of which F is a member.
1102 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1103 auto *NotEqFD = Op->getAsFunction();
1104 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1105 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1106 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1107 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1108 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1109 return false;
1110 }
1111 return true;
1112}
1113
1114bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1115 OverloadedOperatorKind Op) const {
1116 if (!AllowRewrittenCandidates)
1117 return false;
1118 return Op == OO_EqualEqual || Op == OO_Spaceship;
1119}
1120
1121bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1122 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1123 auto Op = FD->getOverloadedOperator();
1124 if (!allowsReversed(Op))
1125 return false;
1126 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1127 assert(OriginalArgs.size() == 2);
1128 if (!shouldAddReversedEqEq(
1129 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1130 return false;
1131 }
1132 // Don't bother adding a reversed candidate that can never be a better
1133 // match than the non-reversed version.
1134 return FD->getNumNonObjectParams() != 2 ||
1135 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1136 T2: FD->getParamDecl(i: 1)->getType()) ||
1137 FD->hasAttr<EnableIfAttr>();
1138}
1139
1140void OverloadCandidateSet::destroyCandidates() {
1141 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1142 for (auto &C : i->Conversions)
1143 C.~ImplicitConversionSequence();
1144 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1145 i->DeductionFailure.Destroy();
1146 }
1147}
1148
1149void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1150 destroyCandidates();
1151 SlabAllocator.Reset();
1152 NumInlineBytesUsed = 0;
1153 Candidates.clear();
1154 Functions.clear();
1155 Kind = CSK;
1156 FirstDeferredCandidate = nullptr;
1157 DeferredCandidatesCount = 0;
1158 HasDeferredTemplateConstructors = false;
1159 ResolutionByPerfectCandidateIsDisabled = false;
1160}
1161
1162namespace {
1163 class UnbridgedCastsSet {
1164 struct Entry {
1165 Expr **Addr;
1166 Expr *Saved;
1167 };
1168 SmallVector<Entry, 2> Entries;
1169
1170 public:
1171 void save(Sema &S, Expr *&E) {
1172 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1173 Entry entry = { .Addr: &E, .Saved: E };
1174 Entries.push_back(Elt: entry);
1175 E = S.ObjC().stripARCUnbridgedCast(e: E);
1176 }
1177
1178 void restore() {
1179 for (SmallVectorImpl<Entry>::iterator
1180 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1181 *i->Addr = i->Saved;
1182 }
1183 };
1184}
1185
1186/// checkPlaceholderForOverload - Do any interesting placeholder-like
1187/// preprocessing on the given expression.
1188///
1189/// \param unbridgedCasts a collection to which to add unbridged casts;
1190/// without this, they will be immediately diagnosed as errors
1191///
1192/// Return true on unrecoverable error.
1193static bool
1194checkPlaceholderForOverload(Sema &S, Expr *&E,
1195 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1196 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1197 // We can't handle overloaded expressions here because overload
1198 // resolution might reasonably tweak them.
1199 if (placeholder->getKind() == BuiltinType::Overload) return false;
1200
1201 // If the context potentially accepts unbridged ARC casts, strip
1202 // the unbridged cast and add it to the collection for later restoration.
1203 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1204 unbridgedCasts) {
1205 unbridgedCasts->save(S, E);
1206 return false;
1207 }
1208
1209 // Go ahead and check everything else.
1210 ExprResult result = S.CheckPlaceholderExpr(E);
1211 if (result.isInvalid())
1212 return true;
1213
1214 E = result.get();
1215 return false;
1216 }
1217
1218 // Nothing to do.
1219 return false;
1220}
1221
1222/// checkArgPlaceholdersForOverload - Check a set of call operands for
1223/// placeholders.
1224static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1225 UnbridgedCastsSet &unbridged) {
1226 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1227 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1228 return true;
1229
1230 return false;
1231}
1232
1233OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1234 const LookupResult &Old, NamedDecl *&Match,
1235 bool NewIsUsingDecl) {
1236 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1237 I != E; ++I) {
1238 NamedDecl *OldD = *I;
1239
1240 bool OldIsUsingDecl = false;
1241 if (isa<UsingShadowDecl>(Val: OldD)) {
1242 OldIsUsingDecl = true;
1243
1244 // We can always introduce two using declarations into the same
1245 // context, even if they have identical signatures.
1246 if (NewIsUsingDecl) continue;
1247
1248 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1249 }
1250
1251 // A using-declaration does not conflict with another declaration
1252 // if one of them is hidden.
1253 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1254 continue;
1255
1256 // If either declaration was introduced by a using declaration,
1257 // we'll need to use slightly different rules for matching.
1258 // Essentially, these rules are the normal rules, except that
1259 // function templates hide function templates with different
1260 // return types or template parameter lists.
1261 bool UseMemberUsingDeclRules =
1262 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1263 !New->getFriendObjectKind();
1264
1265 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1266 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1267 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1268 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1269 continue;
1270 }
1271
1272 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1273 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1274 continue;
1275
1276 Match = *I;
1277 return OverloadKind::Match;
1278 }
1279
1280 // Builtins that have custom typechecking or have a reference should
1281 // not be overloadable or redeclarable.
1282 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1283 Match = *I;
1284 return OverloadKind::NonFunction;
1285 }
1286 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1287 // We can overload with these, which can show up when doing
1288 // redeclaration checks for UsingDecls.
1289 assert(Old.getLookupKind() == LookupUsingDeclName);
1290 } else if (isa<TagDecl>(Val: OldD)) {
1291 // We can always overload with tags by hiding them.
1292 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1293 // Optimistically assume that an unresolved using decl will
1294 // overload; if it doesn't, we'll have to diagnose during
1295 // template instantiation.
1296 //
1297 // Exception: if the scope is dependent and this is not a class
1298 // member, the using declaration can only introduce an enumerator.
1299 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1300 Match = *I;
1301 return OverloadKind::NonFunction;
1302 }
1303 } else {
1304 // (C++ 13p1):
1305 // Only function declarations can be overloaded; object and type
1306 // declarations cannot be overloaded.
1307 Match = *I;
1308 return OverloadKind::NonFunction;
1309 }
1310 }
1311
1312 // C++ [temp.friend]p1:
1313 // For a friend function declaration that is not a template declaration:
1314 // -- if the name of the friend is a qualified or unqualified template-id,
1315 // [...], otherwise
1316 // -- if the name of the friend is a qualified-id and a matching
1317 // non-template function is found in the specified class or namespace,
1318 // the friend declaration refers to that function, otherwise,
1319 // -- if the name of the friend is a qualified-id and a matching function
1320 // template is found in the specified class or namespace, the friend
1321 // declaration refers to the deduced specialization of that function
1322 // template, otherwise
1323 // -- the name shall be an unqualified-id [...]
1324 // If we get here for a qualified friend declaration, we've just reached the
1325 // third bullet. If the type of the friend is dependent, skip this lookup
1326 // until instantiation.
1327 if (New->getFriendObjectKind() && New->getQualifier() &&
1328 !New->getDescribedFunctionTemplate() &&
1329 !New->getDependentSpecializationInfo() &&
1330 !New->getType()->isDependentType()) {
1331 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1332 TemplateSpecResult.addAllDecls(Other: Old);
1333 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1334 /*QualifiedFriend*/true)) {
1335 New->setInvalidDecl();
1336 return OverloadKind::Overload;
1337 }
1338
1339 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1340 return OverloadKind::Match;
1341 }
1342
1343 return OverloadKind::Overload;
1344}
1345
1346template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1347 assert(D && "function decl should not be null");
1348 if (auto *A = D->getAttr<AttrT>())
1349 return !A->isImplicit();
1350 return false;
1351}
1352
1353static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1354 FunctionDecl *Old,
1355 bool UseMemberUsingDeclRules,
1356 bool ConsiderCudaAttrs,
1357 bool UseOverrideRules = false) {
1358 // C++ [basic.start.main]p2: This function shall not be overloaded.
1359 if (New->isMain())
1360 return false;
1361
1362 // MSVCRT user defined entry points cannot be overloaded.
1363 if (New->isMSVCRTEntryPoint())
1364 return false;
1365
1366 NamedDecl *OldDecl = Old;
1367 NamedDecl *NewDecl = New;
1368 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1369 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1370
1371 // C++ [temp.fct]p2:
1372 // A function template can be overloaded with other function templates
1373 // and with normal (non-template) functions.
1374 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1375 return true;
1376
1377 // Is the function New an overload of the function Old?
1378 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1379 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1380
1381 // Compare the signatures (C++ 1.3.10) of the two functions to
1382 // determine whether they are overloads. If we find any mismatch
1383 // in the signature, they are overloads.
1384
1385 // If either of these functions is a K&R-style function (no
1386 // prototype), then we consider them to have matching signatures.
1387 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1388 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1389 return false;
1390
1391 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1392 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1393
1394 // The signature of a function includes the types of its
1395 // parameters (C++ 1.3.10), which includes the presence or absence
1396 // of the ellipsis; see C++ DR 357).
1397 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1398 return true;
1399
1400 // For member-like friends, the enclosing class is part of the signature.
1401 if ((New->isMemberLikeConstrainedFriend() ||
1402 Old->isMemberLikeConstrainedFriend()) &&
1403 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1404 return true;
1405
1406 // Compare the parameter lists.
1407 // This can only be done once we have establish that friend functions
1408 // inhabit the same context, otherwise we might tried to instantiate
1409 // references to non-instantiated entities during constraint substitution.
1410 // GH78101.
1411 if (NewTemplate) {
1412 OldDecl = OldTemplate;
1413 NewDecl = NewTemplate;
1414 // C++ [temp.over.link]p4:
1415 // The signature of a function template consists of its function
1416 // signature, its return type and its template parameter list. The names
1417 // of the template parameters are significant only for establishing the
1418 // relationship between the template parameters and the rest of the
1419 // signature.
1420 //
1421 // We check the return type and template parameter lists for function
1422 // templates first; the remaining checks follow.
1423 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1424 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1425 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1426 bool SameReturnType = SemaRef.Context.hasSameType(
1427 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1428 // FIXME(GH58571): Match template parameter list even for non-constrained
1429 // template heads. This currently ensures that the code prior to C++20 is
1430 // not newly broken.
1431 bool ConstraintsInTemplateHead =
1432 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1433 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1434 // C++ [namespace.udecl]p11:
1435 // The set of declarations named by a using-declarator that inhabits a
1436 // class C does not include member functions and member function
1437 // templates of a base class that "correspond" to (and thus would
1438 // conflict with) a declaration of a function or function template in
1439 // C.
1440 // Comparing return types is not required for the "correspond" check to
1441 // decide whether a member introduced by a shadow declaration is hidden.
1442 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1443 !SameTemplateParameterList)
1444 return true;
1445 if (!UseMemberUsingDeclRules &&
1446 (!SameTemplateParameterList || !SameReturnType))
1447 return true;
1448 }
1449
1450 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1451 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1452
1453 int OldParamsOffset = 0;
1454 int NewParamsOffset = 0;
1455
1456 // When determining if a method is an overload from a base class, act as if
1457 // the implicit object parameter are of the same type.
1458
1459 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1460 if (M->isExplicitObjectMemberFunction()) {
1461 auto ThisType = M->getFunctionObjectParameterReferenceType();
1462 if (ThisType.isConstQualified())
1463 Q.removeConst();
1464 return Q;
1465 }
1466
1467 // We do not allow overloading based off of '__restrict'.
1468 Q.removeRestrict();
1469
1470 // We may not have applied the implicit const for a constexpr member
1471 // function yet (because we haven't yet resolved whether this is a static
1472 // or non-static member function). Add it now, on the assumption that this
1473 // is a redeclaration of OldMethod.
1474 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1475 (M->isConstexpr() || M->isConsteval()) &&
1476 !isa<CXXConstructorDecl>(Val: NewMethod))
1477 Q.addConst();
1478 return Q;
1479 };
1480
1481 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1482 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1483 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1484
1485 if (OldMethod->isExplicitObjectMemberFunction()) {
1486 BS.Quals.removeVolatile();
1487 DS.Quals.removeVolatile();
1488 }
1489
1490 return BS.Quals == DS.Quals;
1491 };
1492
1493 auto CompareType = [&](QualType Base, QualType D) {
1494 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1495 auto DS = D.getNonReferenceType().getCanonicalType().split();
1496
1497 if (!AreQualifiersEqual(BS, DS))
1498 return false;
1499
1500 if (OldMethod->isImplicitObjectMemberFunction() &&
1501 OldMethod->getParent() != NewMethod->getParent()) {
1502 CanQualType ParentType =
1503 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1504 if (ParentType.getTypePtr() != BS.Ty)
1505 return false;
1506 BS.Ty = DS.Ty;
1507 }
1508
1509 // FIXME: should we ignore some type attributes here?
1510 if (BS.Ty != DS.Ty)
1511 return false;
1512
1513 if (Base->isLValueReferenceType())
1514 return D->isLValueReferenceType();
1515 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1516 };
1517
1518 // If the function is a class member, its signature includes the
1519 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1520 auto DiagnoseInconsistentRefQualifiers = [&]() {
1521 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1522 return false;
1523 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1524 return false;
1525 if (OldMethod->isExplicitObjectMemberFunction() ||
1526 NewMethod->isExplicitObjectMemberFunction())
1527 return false;
1528 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1529 NewMethod->getRefQualifier() == RQ_None)) {
1530 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1531 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1532 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1533 return true;
1534 }
1535 return false;
1536 };
1537
1538 // We look at the parameters first, as it is the common case.
1539 // However we should not emit diagnostic before checking
1540 // the overloads do not differ by constraints or other discriminant.
1541 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1542 bool HaveInconsistentQualifiers = false;
1543
1544 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1545 OldParamsOffset++;
1546 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1547 NewParamsOffset++;
1548
1549 if (OldType->getNumParams() - OldParamsOffset !=
1550 NewType->getNumParams() - NewParamsOffset ||
1551 !SemaRef.FunctionParamTypesAreEqual(
1552 Old: {OldType->param_type_begin() + OldParamsOffset,
1553 OldType->param_type_end()},
1554 New: {NewType->param_type_begin() + NewParamsOffset,
1555 NewType->param_type_end()},
1556 ArgPos: nullptr)) {
1557 return true;
1558 }
1559
1560 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1561 !NewMethod->isStatic()) {
1562 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1563 const CXXMethodDecl *New) {
1564 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1565 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1566
1567 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1568 return F->getRefQualifier() == RQ_None &&
1569 !F->isExplicitObjectMemberFunction();
1570 };
1571
1572 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1573 CompareType(OldObjectType.getNonReferenceType(),
1574 NewObjectType.getNonReferenceType()))
1575 return true;
1576 return CompareType(OldObjectType, NewObjectType);
1577 }(OldMethod, NewMethod);
1578
1579 if (!HaveCorrespondingObjectParameters) {
1580 ShouldDiagnoseInconsistentRefQualifiers = true;
1581 // CWG2554
1582 // and, if at least one is an explicit object member function, ignoring
1583 // object parameters
1584 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1585 !OldMethod->isExplicitObjectMemberFunction()))
1586 HaveInconsistentQualifiers = true;
1587 }
1588 }
1589
1590 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1591 NewMethod->isImplicitObjectMemberFunction())
1592 ShouldDiagnoseInconsistentRefQualifiers = true;
1593
1594 if (!UseOverrideRules &&
1595 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1596 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1597 OldRC = Old->getTrailingRequiresClause();
1598 if (!NewRC != !OldRC)
1599 return true;
1600 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1601 return true;
1602 if (NewRC &&
1603 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1604 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1605 return true;
1606 }
1607
1608 // Though pass_object_size is placed on parameters and takes an argument, we
1609 // consider it to be a function-level modifier for the sake of function
1610 // identity. Either the function has one or more parameters with
1611 // pass_object_size or it doesn't.
1612 if (functionHasPassObjectSizeParams(FD: New) !=
1613 functionHasPassObjectSizeParams(FD: Old))
1614 return true;
1615
1616 // enable_if attributes are an order-sensitive part of the signature.
1617 for (specific_attr_iterator<EnableIfAttr>
1618 NewI = New->specific_attr_begin<EnableIfAttr>(),
1619 NewE = New->specific_attr_end<EnableIfAttr>(),
1620 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1621 OldE = Old->specific_attr_end<EnableIfAttr>();
1622 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1623 if (NewI == NewE || OldI == OldE)
1624 return true;
1625 llvm::FoldingSetNodeID NewID, OldID;
1626 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1627 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1628 if (NewID != OldID)
1629 return true;
1630 }
1631
1632 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1633 DiagnoseInconsistentRefQualifiers()) ||
1634 HaveInconsistentQualifiers)
1635 return true;
1636
1637 // At this point, it is known that the two functions have the same signature.
1638 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1639 // Don't allow overloading of destructors. (In theory we could, but it
1640 // would be a giant change to clang.)
1641 if (!isa<CXXDestructorDecl>(Val: New)) {
1642 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1643 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1644 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1645 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1646 "Unexpected invalid target.");
1647
1648 // Allow overloading of functions with same signature and different CUDA
1649 // target attributes.
1650 if (NewTarget != OldTarget) {
1651 // Special case: non-constexpr function is allowed to override
1652 // constexpr virtual function
1653 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1654 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1655 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1656 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1657 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1658 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1659 return false;
1660 }
1661 return true;
1662 }
1663 }
1664 }
1665 }
1666
1667 // The signatures match; this is not an overload.
1668 return false;
1669}
1670
1671bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1672 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1673 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1674 ConsiderCudaAttrs);
1675}
1676
1677bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1678 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1679 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1680 /*UseMemberUsingDeclRules=*/false,
1681 /*ConsiderCudaAttrs=*/true,
1682 /*UseOverrideRules=*/true);
1683}
1684
1685/// Tries a user-defined conversion from From to ToType.
1686///
1687/// Produces an implicit conversion sequence for when a standard conversion
1688/// is not an option. See TryImplicitConversion for more information.
1689static ImplicitConversionSequence
1690TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1691 bool SuppressUserConversions,
1692 AllowedExplicit AllowExplicit,
1693 bool InOverloadResolution,
1694 bool CStyle,
1695 bool AllowObjCWritebackConversion,
1696 bool AllowObjCConversionOnExplicit) {
1697 ImplicitConversionSequence ICS;
1698
1699 if (SuppressUserConversions) {
1700 // We're not in the case above, so there is no conversion that
1701 // we can perform.
1702 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1703 return ICS;
1704 }
1705
1706 // Attempt user-defined conversion.
1707 OverloadCandidateSet Conversions(From->getExprLoc(),
1708 OverloadCandidateSet::CSK_Normal);
1709 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1710 Conversions, AllowExplicit,
1711 AllowObjCConversionOnExplicit)) {
1712 case OR_Success:
1713 case OR_Deleted:
1714 ICS.setUserDefined();
1715 // C++ [over.ics.user]p4:
1716 // A conversion of an expression of class type to the same class
1717 // type is given Exact Match rank, and a conversion of an
1718 // expression of class type to a base class of that type is
1719 // given Conversion rank, in spite of the fact that a copy
1720 // constructor (i.e., a user-defined conversion function) is
1721 // called for those cases.
1722 if (CXXConstructorDecl *Constructor
1723 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1724 QualType FromType;
1725 SourceLocation FromLoc;
1726 // C++11 [over.ics.list]p6, per DR2137:
1727 // C++17 [over.ics.list]p6:
1728 // If C is not an initializer-list constructor and the initializer list
1729 // has a single element of type cv U, where U is X or a class derived
1730 // from X, the implicit conversion sequence has Exact Match rank if U is
1731 // X, or Conversion rank if U is derived from X.
1732 bool FromListInit = false;
1733 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1734 InitList && InitList->getNumInits() == 1 &&
1735 !S.isInitListConstructor(Ctor: Constructor)) {
1736 const Expr *SingleInit = InitList->getInit(Init: 0);
1737 FromType = SingleInit->getType();
1738 FromLoc = SingleInit->getBeginLoc();
1739 FromListInit = true;
1740 } else {
1741 FromType = From->getType();
1742 FromLoc = From->getBeginLoc();
1743 }
1744 QualType FromCanon =
1745 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1746 QualType ToCanon
1747 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1748 if ((FromCanon == ToCanon ||
1749 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1750 // Turn this into a "standard" conversion sequence, so that it
1751 // gets ranked with standard conversion sequences.
1752 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1753 ICS.setStandard();
1754 ICS.Standard.setAsIdentityConversion();
1755 ICS.Standard.setFromType(FromType);
1756 ICS.Standard.setAllToTypes(ToType);
1757 ICS.Standard.FromBracedInitList = FromListInit;
1758 ICS.Standard.CopyConstructor = Constructor;
1759 ICS.Standard.FoundCopyConstructor = Found;
1760 if (ToCanon != FromCanon)
1761 ICS.Standard.Second = ICK_Derived_To_Base;
1762 }
1763 }
1764 break;
1765
1766 case OR_Ambiguous:
1767 ICS.setAmbiguous();
1768 ICS.Ambiguous.setFromType(From->getType());
1769 ICS.Ambiguous.setToType(ToType);
1770 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1771 Cand != Conversions.end(); ++Cand)
1772 if (Cand->Best)
1773 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1774 break;
1775
1776 // Fall through.
1777 case OR_No_Viable_Function:
1778 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1779 break;
1780 }
1781
1782 return ICS;
1783}
1784
1785/// TryImplicitConversion - Attempt to perform an implicit conversion
1786/// from the given expression (Expr) to the given type (ToType). This
1787/// function returns an implicit conversion sequence that can be used
1788/// to perform the initialization. Given
1789///
1790/// void f(float f);
1791/// void g(int i) { f(i); }
1792///
1793/// this routine would produce an implicit conversion sequence to
1794/// describe the initialization of f from i, which will be a standard
1795/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1796/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1797//
1798/// Note that this routine only determines how the conversion can be
1799/// performed; it does not actually perform the conversion. As such,
1800/// it will not produce any diagnostics if no conversion is available,
1801/// but will instead return an implicit conversion sequence of kind
1802/// "BadConversion".
1803///
1804/// If @p SuppressUserConversions, then user-defined conversions are
1805/// not permitted.
1806/// If @p AllowExplicit, then explicit user-defined conversions are
1807/// permitted.
1808///
1809/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1810/// writeback conversion, which allows __autoreleasing id* parameters to
1811/// be initialized with __strong id* or __weak id* arguments.
1812static ImplicitConversionSequence
1813TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1814 bool SuppressUserConversions,
1815 AllowedExplicit AllowExplicit,
1816 bool InOverloadResolution,
1817 bool CStyle,
1818 bool AllowObjCWritebackConversion,
1819 bool AllowObjCConversionOnExplicit) {
1820 ImplicitConversionSequence ICS;
1821 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1822 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1823 ICS.setStandard();
1824 return ICS;
1825 }
1826
1827 if (!S.getLangOpts().CPlusPlus) {
1828 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1829 return ICS;
1830 }
1831
1832 // C++ [over.ics.user]p4:
1833 // A conversion of an expression of class type to the same class
1834 // type is given Exact Match rank, and a conversion of an
1835 // expression of class type to a base class of that type is
1836 // given Conversion rank, in spite of the fact that a copy/move
1837 // constructor (i.e., a user-defined conversion function) is
1838 // called for those cases.
1839 QualType FromType = From->getType();
1840 if (ToType->isRecordType() &&
1841 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1842 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1843 ICS.setStandard();
1844 ICS.Standard.setAsIdentityConversion();
1845 ICS.Standard.setFromType(FromType);
1846 ICS.Standard.setAllToTypes(ToType);
1847
1848 // We don't actually check at this point whether there is a valid
1849 // copy/move constructor, since overloading just assumes that it
1850 // exists. When we actually perform initialization, we'll find the
1851 // appropriate constructor to copy the returned object, if needed.
1852 ICS.Standard.CopyConstructor = nullptr;
1853
1854 // In HLSL, a conversion of an expression of class type to the same class
1855 // type needs implicit LvaluetoRvalue conversion.
1856 if (S.getLangOpts().HLSL)
1857 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
1858
1859 // Determine whether this is considered a derived-to-base conversion.
1860 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1861 ICS.Standard.Second = ICK_Derived_To_Base;
1862
1863 return ICS;
1864 }
1865
1866 if (S.getLangOpts().HLSL) {
1867 // Handle conversion of the HLSL resource types.
1868 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1869 if (FromTy->isHLSLAttributedResourceType()) {
1870 // Attributed resource types can convert to other attributed
1871 // resource types with the same attributes and contained types,
1872 // or to __hlsl_resource_t without any attributes.
1873 bool CanConvert = false;
1874 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1875 if (ToTy->isHLSLAttributedResourceType()) {
1876 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1877 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1878 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1879 T2: FromResType->getWrappedType()) &&
1880 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1881 T2: FromResType->getContainedType()) &&
1882 ToResType->getAttrs() == FromResType->getAttrs())
1883 CanConvert = true;
1884 } else if (ToTy->isHLSLResourceType()) {
1885 CanConvert = true;
1886 }
1887 if (CanConvert) {
1888 ICS.setStandard();
1889 ICS.Standard.setAsIdentityConversion();
1890 ICS.Standard.setFromType(FromType);
1891 ICS.Standard.setAllToTypes(ToType);
1892 return ICS;
1893 }
1894 }
1895 }
1896
1897 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1898 AllowExplicit, InOverloadResolution, CStyle,
1899 AllowObjCWritebackConversion,
1900 AllowObjCConversionOnExplicit);
1901}
1902
1903ImplicitConversionSequence
1904Sema::TryImplicitConversion(Expr *From, QualType ToType,
1905 bool SuppressUserConversions,
1906 AllowedExplicit AllowExplicit,
1907 bool InOverloadResolution,
1908 bool CStyle,
1909 bool AllowObjCWritebackConversion) {
1910 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1911 AllowExplicit, InOverloadResolution, CStyle,
1912 AllowObjCWritebackConversion,
1913 /*AllowObjCConversionOnExplicit=*/false);
1914}
1915
1916ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1917 AssignmentAction Action,
1918 bool AllowExplicit) {
1919 if (checkPlaceholderForOverload(S&: *this, E&: From))
1920 return ExprError();
1921
1922 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1923 bool AllowObjCWritebackConversion =
1924 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1925 Action == AssignmentAction::Sending);
1926 if (getLangOpts().ObjC)
1927 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1928 SrcType: From->getType(), SrcExpr&: From);
1929 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1930 S&: *this, From, ToType,
1931 /*SuppressUserConversions=*/false,
1932 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1933 /*InOverloadResolution=*/false,
1934 /*CStyle=*/false, AllowObjCWritebackConversion,
1935 /*AllowObjCConversionOnExplicit=*/false);
1936 return PerformImplicitConversion(From, ToType, ICS, Action);
1937}
1938
1939bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1940 QualType &ResultTy) const {
1941 bool Changed = IsFunctionConversion(FromType, ToType);
1942 if (Changed)
1943 ResultTy = ToType;
1944 return Changed;
1945}
1946
1947bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1948 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1949 return false;
1950
1951 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1952 // or F(t noexcept) -> F(t)
1953 // where F adds one of the following at most once:
1954 // - a pointer
1955 // - a member pointer
1956 // - a block pointer
1957 // Changes here need matching changes in FindCompositePointerType.
1958 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1959 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1960 Type::TypeClass TyClass = CanTo->getTypeClass();
1961 if (TyClass != CanFrom->getTypeClass()) return false;
1962 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1963 if (TyClass == Type::Pointer) {
1964 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1965 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1966 } else if (TyClass == Type::BlockPointer) {
1967 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1968 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1969 } else if (TyClass == Type::MemberPointer) {
1970 auto ToMPT = CanTo.castAs<MemberPointerType>();
1971 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1972 // A function pointer conversion cannot change the class of the function.
1973 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1974 D2: FromMPT->getMostRecentCXXRecordDecl()))
1975 return false;
1976 CanTo = ToMPT->getPointeeType();
1977 CanFrom = FromMPT->getPointeeType();
1978 } else {
1979 return false;
1980 }
1981
1982 TyClass = CanTo->getTypeClass();
1983 if (TyClass != CanFrom->getTypeClass()) return false;
1984 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1985 return false;
1986 }
1987
1988 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1989 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1990
1991 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1992 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1993
1994 bool Changed = false;
1995
1996 // Drop 'noreturn' if not present in target type.
1997 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1998 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1999 Changed = true;
2000 }
2001
2002 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
2003 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
2004
2005 if (FromFPT && ToFPT) {
2006 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2007 QualType NewTy = Context.getFunctionType(
2008 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
2009 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2010 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
2011 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
2012 FromFn = FromFPT;
2013 Changed = true;
2014 }
2015 }
2016
2017 // Drop 'noexcept' if not present in target type.
2018 if (FromFPT && ToFPT) {
2019 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2020 FromFn = cast<FunctionType>(
2021 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
2022 ESI: EST_None)
2023 .getTypePtr());
2024 Changed = true;
2025 }
2026
2027 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2028 // only if the ExtParameterInfo lists of the two function prototypes can be
2029 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2030 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2031 bool CanUseToFPT, CanUseFromFPT;
2032 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2033 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2034 CanUseToFPT && !CanUseFromFPT) {
2035 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2036 ExtInfo.ExtParameterInfos =
2037 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2038 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2039 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2040 FromFn = QT->getAs<FunctionType>();
2041 Changed = true;
2042 }
2043
2044 if (Context.hasAnyFunctionEffects()) {
2045 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2046
2047 // Transparently add/drop effects; here we are concerned with
2048 // language rules/canonicalization. Adding/dropping effects is a warning.
2049 const auto FromFX = FromFPT->getFunctionEffects();
2050 const auto ToFX = ToFPT->getFunctionEffects();
2051 if (FromFX != ToFX) {
2052 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2053 ExtInfo.FunctionEffects = ToFX;
2054 QualType QT = Context.getFunctionType(
2055 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2056 FromFn = QT->getAs<FunctionType>();
2057 Changed = true;
2058 }
2059 }
2060 }
2061
2062 if (!Changed)
2063 return false;
2064
2065 assert(QualType(FromFn, 0).isCanonical());
2066 if (QualType(FromFn, 0) != CanTo) return false;
2067
2068 return true;
2069}
2070
2071/// Determine whether the conversion from FromType to ToType is a valid
2072/// floating point conversion.
2073///
2074static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2075 QualType ToType) {
2076 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2077 return false;
2078 // FIXME: disable conversions between long double, __ibm128 and __float128
2079 // if their representation is different until there is back end support
2080 // We of course allow this conversion if long double is really double.
2081
2082 // Conversions between bfloat16 and float16 are currently not supported.
2083 if ((FromType->isBFloat16Type() &&
2084 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2085 (ToType->isBFloat16Type() &&
2086 (FromType->isFloat16Type() || FromType->isHalfType())))
2087 return false;
2088
2089 // Conversions between IEEE-quad and IBM-extended semantics are not
2090 // permitted.
2091 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2092 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2093 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2094 &ToSem == &llvm::APFloat::IEEEquad()) ||
2095 (&FromSem == &llvm::APFloat::IEEEquad() &&
2096 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2097 return false;
2098 return true;
2099}
2100
2101static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2102 QualType ToType,
2103 ImplicitConversionKind &ICK,
2104 Expr *From) {
2105 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2106 return true;
2107
2108 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2109 ICK = ICK_Floating_Promotion;
2110 return true;
2111 }
2112
2113 if (IsFloatingPointConversion(S, FromType, ToType)) {
2114 ICK = ICK_Floating_Conversion;
2115 return true;
2116 }
2117
2118 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2119 ICK = ICK_Boolean_Conversion;
2120 return true;
2121 }
2122
2123 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2124 (FromType->isIntegralOrUnscopedEnumerationType() &&
2125 ToType->isRealFloatingType())) {
2126 ICK = ICK_Floating_Integral;
2127 return true;
2128 }
2129
2130 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2131 ICK = ICK_Integral_Promotion;
2132 return true;
2133 }
2134
2135 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2136 ToType->isIntegralType(Ctx: S.Context)) {
2137 ICK = ICK_Integral_Conversion;
2138 return true;
2139 }
2140
2141 return false;
2142}
2143
2144/// Determine whether the conversion from FromType to ToType is a valid
2145/// matrix conversion.
2146///
2147/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2148/// conversion.
2149static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2150 ImplicitConversionKind &ICK,
2151 ImplicitConversionKind &ElConv, Expr *From,
2152 bool InOverloadResolution, bool CStyle) {
2153 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2154 if (!S.getLangOpts().HLSL)
2155 return false;
2156
2157 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2158 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2159
2160 // If both arguments are matrix, handle possible matrix truncation and
2161 // element conversion.
2162 if (ToMatrixType && FromMatrixType) {
2163 unsigned FromCols = FromMatrixType->getNumColumns();
2164 unsigned ToCols = ToMatrixType->getNumColumns();
2165 if (FromCols < ToCols)
2166 return false;
2167
2168 unsigned FromRows = FromMatrixType->getNumRows();
2169 unsigned ToRows = ToMatrixType->getNumRows();
2170 if (FromRows < ToRows)
2171 return false;
2172
2173 if (FromRows == ToRows && FromCols == ToCols)
2174 ElConv = ICK_Identity;
2175 else
2176 ElConv = ICK_HLSL_Matrix_Truncation;
2177
2178 QualType FromElTy = FromMatrixType->getElementType();
2179 QualType ToElTy = ToMatrixType->getElementType();
2180 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2181 return true;
2182 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2183 }
2184
2185 // Matrix splat from any arithmetic type to a matrix.
2186 if (ToMatrixType && FromType->isArithmeticType()) {
2187 ElConv = ICK_HLSL_Matrix_Splat;
2188 QualType ToElTy = ToMatrixType->getElementType();
2189 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2190 }
2191 if (FromMatrixType && !ToMatrixType) {
2192 ElConv = ICK_HLSL_Matrix_Truncation;
2193 QualType FromElTy = FromMatrixType->getElementType();
2194 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2195 return true;
2196 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2197 }
2198
2199 return false;
2200}
2201
2202/// Determine whether the conversion from FromType to ToType is a valid
2203/// vector conversion.
2204///
2205/// \param ICK Will be set to the vector conversion kind, if this is a vector
2206/// conversion.
2207static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2208 ImplicitConversionKind &ICK,
2209 ImplicitConversionKind &ElConv, Expr *From,
2210 bool InOverloadResolution, bool CStyle) {
2211 // We need at least one of these types to be a vector type to have a vector
2212 // conversion.
2213 if (!ToType->isVectorType() && !FromType->isVectorType())
2214 return false;
2215
2216 // Identical types require no conversions.
2217 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2218 return false;
2219
2220 // HLSL allows implicit truncation of vector types.
2221 if (S.getLangOpts().HLSL) {
2222 auto *ToExtType = ToType->getAs<ExtVectorType>();
2223 auto *FromExtType = FromType->getAs<ExtVectorType>();
2224
2225 // If both arguments are vectors, handle possible vector truncation and
2226 // element conversion.
2227 if (ToExtType && FromExtType) {
2228 unsigned FromElts = FromExtType->getNumElements();
2229 unsigned ToElts = ToExtType->getNumElements();
2230 if (FromElts < ToElts)
2231 return false;
2232 if (FromElts == ToElts)
2233 ElConv = ICK_Identity;
2234 else
2235 ElConv = ICK_HLSL_Vector_Truncation;
2236
2237 QualType FromElTy = FromExtType->getElementType();
2238 QualType ToElTy = ToExtType->getElementType();
2239 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2240 return true;
2241 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2242 }
2243 if (FromExtType && !ToExtType) {
2244 ElConv = ICK_HLSL_Vector_Truncation;
2245 QualType FromElTy = FromExtType->getElementType();
2246 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2247 return true;
2248 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2249 }
2250 // Fallthrough for the case where ToType is a vector and FromType is not.
2251 }
2252
2253 // There are no conversions between extended vector types, only identity.
2254 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2255 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2256 // Implicit conversions require the same number of elements.
2257 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2258 return false;
2259
2260 // Permit implicit conversions from integral values to boolean vectors.
2261 if (ToType->isExtVectorBoolType() &&
2262 FromExtType->getElementType()->isIntegerType()) {
2263 ICK = ICK_Boolean_Conversion;
2264 return true;
2265 }
2266 // There are no other conversions between extended vector types.
2267 return false;
2268 }
2269
2270 // Vector splat from any arithmetic type to a vector.
2271 if (FromType->isArithmeticType()) {
2272 if (S.getLangOpts().HLSL) {
2273 ElConv = ICK_HLSL_Vector_Splat;
2274 QualType ToElTy = ToExtType->getElementType();
2275 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2276 From);
2277 }
2278 ICK = ICK_Vector_Splat;
2279 return true;
2280 }
2281 }
2282
2283 if (ToType->isSVESizelessBuiltinType() ||
2284 FromType->isSVESizelessBuiltinType())
2285 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2286 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2287 ICK = ICK_SVE_Vector_Conversion;
2288 return true;
2289 }
2290
2291 if (ToType->isRVVSizelessBuiltinType() ||
2292 FromType->isRVVSizelessBuiltinType())
2293 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2294 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2295 ICK = ICK_RVV_Vector_Conversion;
2296 return true;
2297 }
2298
2299 // We can perform the conversion between vector types in the following cases:
2300 // 1)vector types are equivalent AltiVec and GCC vector types
2301 // 2)lax vector conversions are permitted and the vector types are of the
2302 // same size
2303 // 3)the destination type does not have the ARM MVE strict-polymorphism
2304 // attribute, which inhibits lax vector conversion for overload resolution
2305 // only
2306 if (ToType->isVectorType() && FromType->isVectorType()) {
2307 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2308 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2309 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2310 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2311 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2312 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2313 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2314 !InOverloadResolution && !CStyle) {
2315 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2316 << FromType << ToType;
2317 }
2318 ICK = ICK_Vector_Conversion;
2319 return true;
2320 }
2321 }
2322
2323 return false;
2324}
2325
2326static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2327 bool InOverloadResolution,
2328 StandardConversionSequence &SCS,
2329 bool CStyle);
2330
2331static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2332 QualType ToType,
2333 bool InOverloadResolution,
2334 StandardConversionSequence &SCS,
2335 bool CStyle);
2336
2337/// IsStandardConversion - Determines whether there is a standard
2338/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2339/// expression From to the type ToType. Standard conversion sequences
2340/// only consider non-class types; for conversions that involve class
2341/// types, use TryImplicitConversion. If a conversion exists, SCS will
2342/// contain the standard conversion sequence required to perform this
2343/// conversion and this routine will return true. Otherwise, this
2344/// routine will return false and the value of SCS is unspecified.
2345static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2346 bool InOverloadResolution,
2347 StandardConversionSequence &SCS,
2348 bool CStyle,
2349 bool AllowObjCWritebackConversion) {
2350 QualType FromType = From->getType();
2351
2352 // Standard conversions (C++ [conv])
2353 SCS.setAsIdentityConversion();
2354 SCS.IncompatibleObjC = false;
2355 SCS.setFromType(FromType);
2356 SCS.CopyConstructor = nullptr;
2357
2358 // There are no standard conversions for class types in C++, so
2359 // abort early. When overloading in C, however, we do permit them.
2360 if (S.getLangOpts().CPlusPlus &&
2361 (FromType->isRecordType() || ToType->isRecordType()))
2362 return false;
2363
2364 // The first conversion can be an lvalue-to-rvalue conversion,
2365 // array-to-pointer conversion, or function-to-pointer conversion
2366 // (C++ 4p1).
2367
2368 if (FromType == S.Context.OverloadTy) {
2369 DeclAccessPair AccessPair;
2370 if (FunctionDecl *Fn
2371 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2372 Found&: AccessPair)) {
2373 // We were able to resolve the address of the overloaded function,
2374 // so we can convert to the type of that function.
2375 FromType = Fn->getType();
2376 SCS.setFromType(FromType);
2377
2378 // we can sometimes resolve &foo<int> regardless of ToType, so check
2379 // if the type matches (identity) or we are converting to bool
2380 if (!S.Context.hasSameUnqualifiedType(
2381 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2382 // if the function type matches except for [[noreturn]], it's ok
2383 if (!S.IsFunctionConversion(FromType,
2384 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2385 // otherwise, only a boolean conversion is standard
2386 if (!ToType->isBooleanType())
2387 return false;
2388 }
2389
2390 // Check if the "from" expression is taking the address of an overloaded
2391 // function and recompute the FromType accordingly. Take advantage of the
2392 // fact that non-static member functions *must* have such an address-of
2393 // expression.
2394 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2395 if (Method && !Method->isStatic() &&
2396 !Method->isExplicitObjectMemberFunction()) {
2397 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2398 "Non-unary operator on non-static member address");
2399 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2400 == UO_AddrOf &&
2401 "Non-address-of operator on non-static member address");
2402 FromType = S.Context.getMemberPointerType(
2403 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2404 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2405 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2406 UO_AddrOf &&
2407 "Non-address-of operator for overloaded function expression");
2408 FromType = S.Context.getPointerType(T: FromType);
2409 }
2410 } else {
2411 return false;
2412 }
2413 }
2414
2415 bool argIsLValue = From->isGLValue();
2416 // To handle conversion from ArrayParameterType to ConstantArrayType
2417 // this block must be above the one below because Array parameters
2418 // do not decay and when handling HLSLOutArgExprs and
2419 // the From expression is an LValue.
2420 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2421 ToType->isConstantArrayType()) {
2422 // HLSL constant array parameters do not decay, so if the argument is a
2423 // constant array and the parameter is an ArrayParameterType we have special
2424 // handling here.
2425 if (ToType->isArrayParameterType()) {
2426 FromType = S.Context.getArrayParameterType(Ty: FromType);
2427 } else if (FromType->isArrayParameterType()) {
2428 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2429 FromType = APT->getConstantArrayType(Ctx: S.Context);
2430 }
2431
2432 SCS.First = ICK_HLSL_Array_RValue;
2433
2434 // Don't consider qualifiers, which include things like address spaces
2435 if (FromType.getCanonicalType().getUnqualifiedType() !=
2436 ToType.getCanonicalType().getUnqualifiedType())
2437 return false;
2438
2439 SCS.setAllToTypes(ToType);
2440 return true;
2441 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2442 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2443 // Lvalue-to-rvalue conversion (C++11 4.1):
2444 // A glvalue (3.10) of a non-function, non-array type T can
2445 // be converted to a prvalue.
2446
2447 SCS.First = ICK_Lvalue_To_Rvalue;
2448
2449 // C11 6.3.2.1p2:
2450 // ... if the lvalue has atomic type, the value has the non-atomic version
2451 // of the type of the lvalue ...
2452 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2453 FromType = Atomic->getValueType();
2454
2455 // If T is a non-class type, the type of the rvalue is the
2456 // cv-unqualified version of T. Otherwise, the type of the rvalue
2457 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2458 // just strip the qualifiers because they don't matter.
2459 FromType = FromType.getUnqualifiedType();
2460 } else if (FromType->isArrayType()) {
2461 // Array-to-pointer conversion (C++ 4.2)
2462 SCS.First = ICK_Array_To_Pointer;
2463
2464 // An lvalue or rvalue of type "array of N T" or "array of unknown
2465 // bound of T" can be converted to an rvalue of type "pointer to
2466 // T" (C++ 4.2p1).
2467 FromType = S.Context.getArrayDecayedType(T: FromType);
2468
2469 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2470 // This conversion is deprecated in C++03 (D.4)
2471 SCS.DeprecatedStringLiteralToCharPtr = true;
2472
2473 // For the purpose of ranking in overload resolution
2474 // (13.3.3.1.1), this conversion is considered an
2475 // array-to-pointer conversion followed by a qualification
2476 // conversion (4.4). (C++ 4.2p2)
2477 SCS.Second = ICK_Identity;
2478 SCS.Third = ICK_Qualification;
2479 SCS.QualificationIncludesObjCLifetime = false;
2480 SCS.setAllToTypes(FromType);
2481 return true;
2482 }
2483 } else if (FromType->isFunctionType() && argIsLValue) {
2484 // Function-to-pointer conversion (C++ 4.3).
2485 SCS.First = ICK_Function_To_Pointer;
2486
2487 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2488 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2489 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2490 return false;
2491
2492 // An lvalue of function type T can be converted to an rvalue of
2493 // type "pointer to T." The result is a pointer to the
2494 // function. (C++ 4.3p1).
2495 FromType = S.Context.getPointerType(T: FromType);
2496 } else {
2497 // We don't require any conversions for the first step.
2498 SCS.First = ICK_Identity;
2499 }
2500 SCS.setToType(Idx: 0, T: FromType);
2501
2502 // The second conversion can be an integral promotion, floating
2503 // point promotion, integral conversion, floating point conversion,
2504 // floating-integral conversion, pointer conversion,
2505 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2506 // For overloading in C, this can also be a "compatible-type"
2507 // conversion.
2508 bool IncompatibleObjC = false;
2509 ImplicitConversionKind SecondICK = ICK_Identity;
2510 ImplicitConversionKind DimensionICK = ICK_Identity;
2511 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2512 // The unqualified versions of the types are the same: there's no
2513 // conversion to do.
2514 SCS.Second = ICK_Identity;
2515 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2516 // Integral promotion (C++ 4.5).
2517 SCS.Second = ICK_Integral_Promotion;
2518 FromType = ToType.getUnqualifiedType();
2519 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2520 // Floating point promotion (C++ 4.6).
2521 SCS.Second = ICK_Floating_Promotion;
2522 FromType = ToType.getUnqualifiedType();
2523 } else if (S.IsComplexPromotion(FromType, ToType)) {
2524 // Complex promotion (Clang extension)
2525 SCS.Second = ICK_Complex_Promotion;
2526 FromType = ToType.getUnqualifiedType();
2527 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2528 // OverflowBehaviorType promotions
2529 SCS.Second = ICK_Integral_Promotion;
2530 FromType = ToType.getUnqualifiedType();
2531 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2532 // OverflowBehaviorType conversions
2533 SCS.Second = ICK_Integral_Conversion;
2534 FromType = ToType.getUnqualifiedType();
2535 } else if (ToType->isBooleanType() &&
2536 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2537 FromType->isBlockPointerType() ||
2538 FromType->isMemberPointerType())) {
2539 // Boolean conversions (C++ 4.12).
2540 SCS.Second = ICK_Boolean_Conversion;
2541 FromType = S.Context.BoolTy;
2542 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2543 ToType->isIntegralType(Ctx: S.Context)) {
2544 // Integral conversions (C++ 4.7).
2545 SCS.Second = ICK_Integral_Conversion;
2546 FromType = ToType.getUnqualifiedType();
2547 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2548 // Complex conversions (C99 6.3.1.6)
2549 SCS.Second = ICK_Complex_Conversion;
2550 FromType = ToType.getUnqualifiedType();
2551 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2552 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2553 // Complex-real conversions (C99 6.3.1.7)
2554 SCS.Second = ICK_Complex_Real;
2555 FromType = ToType.getUnqualifiedType();
2556 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2557 // Floating point conversions (C++ 4.8).
2558 SCS.Second = ICK_Floating_Conversion;
2559 FromType = ToType.getUnqualifiedType();
2560 } else if ((FromType->isRealFloatingType() &&
2561 ToType->isIntegralType(Ctx: S.Context)) ||
2562 (FromType->isIntegralOrUnscopedEnumerationType() &&
2563 ToType->isRealFloatingType())) {
2564
2565 // Floating-integral conversions (C++ 4.9).
2566 SCS.Second = ICK_Floating_Integral;
2567 FromType = ToType.getUnqualifiedType();
2568 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2569 SCS.Second = ICK_Block_Pointer_Conversion;
2570 } else if (AllowObjCWritebackConversion &&
2571 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2572 SCS.Second = ICK_Writeback_Conversion;
2573 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2574 ConvertedType&: FromType, IncompatibleObjC)) {
2575 // Pointer conversions (C++ 4.10).
2576 SCS.Second = ICK_Pointer_Conversion;
2577 SCS.IncompatibleObjC = IncompatibleObjC;
2578 FromType = FromType.getUnqualifiedType();
2579 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2580 InOverloadResolution, ConvertedType&: FromType)) {
2581 // Pointer to member conversions (4.11).
2582 SCS.Second = ICK_Pointer_Member;
2583 } else if (IsVectorConversion(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 (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2589 From, InOverloadResolution, CStyle)) {
2590 SCS.Second = SecondICK;
2591 SCS.Dimension = DimensionICK;
2592 FromType = ToType.getUnqualifiedType();
2593 } else if (!S.getLangOpts().CPlusPlus &&
2594 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2595 // Compatible conversions (Clang extension for C function overloading)
2596 SCS.Second = ICK_Compatible_Conversion;
2597 FromType = ToType.getUnqualifiedType();
2598 } else if (IsTransparentUnionStandardConversion(
2599 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2600 SCS.Second = ICK_TransparentUnionConversion;
2601 FromType = ToType;
2602 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2603 CStyle)) {
2604 // tryAtomicConversion has updated the standard conversion sequence
2605 // appropriately.
2606 return true;
2607 } else if (tryOverflowBehaviorTypeConversion(
2608 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2609 return true;
2610 } else if (ToType->isEventT() &&
2611 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2612 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2613 SCS.Second = ICK_Zero_Event_Conversion;
2614 FromType = ToType;
2615 } else if (ToType->isQueueT() &&
2616 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2617 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2618 SCS.Second = ICK_Zero_Queue_Conversion;
2619 FromType = ToType;
2620 } else if (ToType->isSamplerT() &&
2621 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2622 SCS.Second = ICK_Compatible_Conversion;
2623 FromType = ToType;
2624 } else if ((ToType->isFixedPointType() &&
2625 FromType->isConvertibleToFixedPointType()) ||
2626 (FromType->isFixedPointType() &&
2627 ToType->isConvertibleToFixedPointType())) {
2628 SCS.Second = ICK_Fixed_Point_Conversion;
2629 FromType = ToType;
2630 } else {
2631 // No second conversion required.
2632 SCS.Second = ICK_Identity;
2633 }
2634 SCS.setToType(Idx: 1, T: FromType);
2635
2636 // The third conversion can be a function pointer conversion or a
2637 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2638 bool ObjCLifetimeConversion;
2639 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2640 // Function pointer conversions (removing 'noexcept') including removal of
2641 // 'noreturn' (Clang extension).
2642 SCS.Third = ICK_Function_Conversion;
2643 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2644 ObjCLifetimeConversion)) {
2645 SCS.Third = ICK_Qualification;
2646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2647 FromType = ToType;
2648 } else {
2649 // No conversion required
2650 SCS.Third = ICK_Identity;
2651 }
2652
2653 // C++ [over.best.ics]p6:
2654 // [...] Any difference in top-level cv-qualification is
2655 // subsumed by the initialization itself and does not constitute
2656 // a conversion. [...]
2657 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2658 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2659 if (CanonFrom.getLocalUnqualifiedType()
2660 == CanonTo.getLocalUnqualifiedType() &&
2661 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2662 FromType = ToType;
2663 CanonFrom = CanonTo;
2664 }
2665
2666 SCS.setToType(Idx: 2, T: FromType);
2667
2668 if (CanonFrom == CanonTo)
2669 return true;
2670
2671 // If we have not converted the argument type to the parameter type,
2672 // this is a bad conversion sequence, unless we're resolving an overload in C.
2673 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2674 return false;
2675
2676 ExprResult ER = ExprResult{From};
2677 AssignConvertType Conv =
2678 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2679 /*Diagnose=*/false,
2680 /*DiagnoseCFAudited=*/false,
2681 /*ConvertRHS=*/false);
2682 ImplicitConversionKind SecondConv;
2683 switch (Conv) {
2684 case AssignConvertType::Compatible:
2685 case AssignConvertType::
2686 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2687 SecondConv = ICK_C_Only_Conversion;
2688 break;
2689 // For our purposes, discarding qualifiers is just as bad as using an
2690 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2691 // qualifiers, as well.
2692 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2693 case AssignConvertType::IncompatiblePointer:
2694 case AssignConvertType::IncompatiblePointerSign:
2695 SecondConv = ICK_Incompatible_Pointer_Conversion;
2696 break;
2697 default:
2698 return false;
2699 }
2700
2701 // First can only be an lvalue conversion, so we pretend that this was the
2702 // second conversion. First should already be valid from earlier in the
2703 // function.
2704 SCS.Second = SecondConv;
2705 SCS.setToType(Idx: 1, T: ToType);
2706
2707 // Third is Identity, because Second should rank us worse than any other
2708 // conversion. This could also be ICK_Qualification, but it's simpler to just
2709 // lump everything in with the second conversion, and we don't gain anything
2710 // from making this ICK_Qualification.
2711 SCS.Third = ICK_Identity;
2712 SCS.setToType(Idx: 2, T: ToType);
2713 return true;
2714}
2715
2716static bool
2717IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2718 QualType &ToType,
2719 bool InOverloadResolution,
2720 StandardConversionSequence &SCS,
2721 bool CStyle) {
2722
2723 const RecordType *UT = ToType->getAsUnionType();
2724 if (!UT)
2725 return false;
2726 // The field to initialize within the transparent union.
2727 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2728 if (!UD->hasAttr<TransparentUnionAttr>())
2729 return false;
2730 // It's compatible if the expression matches any of the fields.
2731 for (const auto *it : UD->fields()) {
2732 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2733 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2734 ToType = it->getType();
2735 return true;
2736 }
2737 }
2738 return false;
2739}
2740
2741bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2742 const BuiltinType *To = ToType->getAs<BuiltinType>();
2743 // All integers are built-in.
2744 if (!To) {
2745 return false;
2746 }
2747
2748 // An rvalue of type char, signed char, unsigned char, short int, or
2749 // unsigned short int can be converted to an rvalue of type int if
2750 // int can represent all the values of the source type; otherwise,
2751 // the source rvalue can be converted to an rvalue of type unsigned
2752 // int (C++ 4.5p1).
2753 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2754 !FromType->isEnumeralType()) {
2755 if ( // We can promote any signed, promotable integer type to an int
2756 (FromType->isSignedIntegerType() ||
2757 // We can promote any unsigned integer type whose size is
2758 // less than int to an int.
2759 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2760 return To->getKind() == BuiltinType::Int;
2761 }
2762
2763 return To->getKind() == BuiltinType::UInt;
2764 }
2765
2766 // C++11 [conv.prom]p3:
2767 // A prvalue of an unscoped enumeration type whose underlying type is not
2768 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2769 // following types that can represent all the values of the enumeration
2770 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2771 // unsigned int, long int, unsigned long int, long long int, or unsigned
2772 // long long int. If none of the types in that list can represent all the
2773 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2774 // type can be converted to an rvalue a prvalue of the extended integer type
2775 // with lowest integer conversion rank (4.13) greater than the rank of long
2776 // long in which all the values of the enumeration can be represented. If
2777 // there are two such extended types, the signed one is chosen.
2778 // C++11 [conv.prom]p4:
2779 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2780 // can be converted to a prvalue of its underlying type. Moreover, if
2781 // integral promotion can be applied to its underlying type, a prvalue of an
2782 // unscoped enumeration type whose underlying type is fixed can also be
2783 // converted to a prvalue of the promoted underlying type.
2784 if (const auto *FromED = FromType->getAsEnumDecl()) {
2785 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2786 // provided for a scoped enumeration.
2787 if (FromED->isScoped())
2788 return false;
2789
2790 // We can perform an integral promotion to the underlying type of the enum,
2791 // even if that's not the promoted type. Note that the check for promoting
2792 // the underlying type is based on the type alone, and does not consider
2793 // the bitfield-ness of the actual source expression.
2794 if (FromED->isFixed()) {
2795 QualType Underlying = FromED->getIntegerType();
2796 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2797 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2798 }
2799
2800 // We have already pre-calculated the promotion type, so this is trivial.
2801 if (ToType->isIntegerType() &&
2802 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2803 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2804
2805 // C++ [conv.prom]p5:
2806 // If the bit-field has an enumerated type, it is treated as any other
2807 // value of that type for promotion purposes.
2808 //
2809 // ... so do not fall through into the bit-field checks below in C++.
2810 if (getLangOpts().CPlusPlus)
2811 return false;
2812 }
2813
2814 // C++0x [conv.prom]p2:
2815 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2816 // to an rvalue a prvalue of the first of the following types that can
2817 // represent all the values of its underlying type: int, unsigned int,
2818 // long int, unsigned long int, long long int, or unsigned long long int.
2819 // If none of the types in that list can represent all the values of its
2820 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2821 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2822 // type.
2823 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2824 ToType->isIntegerType()) {
2825 // Determine whether the type we're converting from is signed or
2826 // unsigned.
2827 bool FromIsSigned = FromType->isSignedIntegerType();
2828 uint64_t FromSize = Context.getTypeSize(T: FromType);
2829
2830 // The types we'll try to promote to, in the appropriate
2831 // order. Try each of these types.
2832 QualType PromoteTypes[6] = {
2833 Context.IntTy, Context.UnsignedIntTy,
2834 Context.LongTy, Context.UnsignedLongTy ,
2835 Context.LongLongTy, Context.UnsignedLongLongTy
2836 };
2837 for (int Idx = 0; Idx < 6; ++Idx) {
2838 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2839 if (FromSize < ToSize ||
2840 (FromSize == ToSize &&
2841 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2842 // We found the type that we can promote to. If this is the
2843 // type we wanted, we have a promotion. Otherwise, no
2844 // promotion.
2845 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2846 }
2847 }
2848 }
2849
2850 // An rvalue for an integral bit-field (9.6) can be converted to an
2851 // rvalue of type int if int can represent all the values of the
2852 // bit-field; otherwise, it can be converted to unsigned int if
2853 // unsigned int can represent all the values of the bit-field. If
2854 // the bit-field is larger yet, no integral promotion applies to
2855 // it. If the bit-field has an enumerated type, it is treated as any
2856 // other value of that type for promotion purposes (C++ 4.5p3).
2857 // FIXME: We should delay checking of bit-fields until we actually perform the
2858 // conversion.
2859 //
2860 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2861 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2862 // bit-fields and those whose underlying type is larger than int) for GCC
2863 // compatibility.
2864 if (From) {
2865 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2866 std::optional<llvm::APSInt> BitWidth;
2867 if (FromType->isIntegralType(Ctx: Context) &&
2868 (BitWidth =
2869 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2870 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2871 ToSize = Context.getTypeSize(T: ToType);
2872
2873 // Are we promoting to an int from a bitfield that fits in an int?
2874 if (*BitWidth < ToSize ||
2875 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2876 return To->getKind() == BuiltinType::Int;
2877 }
2878
2879 // Are we promoting to an unsigned int from an unsigned bitfield
2880 // that fits into an unsigned int?
2881 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2882 return To->getKind() == BuiltinType::UInt;
2883 }
2884
2885 return false;
2886 }
2887 }
2888 }
2889
2890 // An rvalue of type bool can be converted to an rvalue of type int,
2891 // with false becoming zero and true becoming one (C++ 4.5p4).
2892 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2893 return true;
2894 }
2895
2896 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2897 // integral type.
2898 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2899 ToType->isIntegerType())
2900 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2901
2902 return false;
2903}
2904
2905bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2906 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2907 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2908 /// An rvalue of type float can be converted to an rvalue of type
2909 /// double. (C++ 4.6p1).
2910 if (FromBuiltin->getKind() == BuiltinType::Float &&
2911 ToBuiltin->getKind() == BuiltinType::Double)
2912 return true;
2913
2914 // C99 6.3.1.5p1:
2915 // When a float is promoted to double or long double, or a
2916 // double is promoted to long double [...].
2917 if (!getLangOpts().CPlusPlus &&
2918 (FromBuiltin->getKind() == BuiltinType::Float ||
2919 FromBuiltin->getKind() == BuiltinType::Double) &&
2920 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2921 ToBuiltin->getKind() == BuiltinType::Float128 ||
2922 ToBuiltin->getKind() == BuiltinType::Ibm128))
2923 return true;
2924
2925 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2926 // or not native half types are enabled.
2927 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2928 (ToBuiltin->getKind() == BuiltinType::Float ||
2929 ToBuiltin->getKind() == BuiltinType::Double))
2930 return true;
2931
2932 // Half can be promoted to float.
2933 if (!getLangOpts().NativeHalfType &&
2934 FromBuiltin->getKind() == BuiltinType::Half &&
2935 ToBuiltin->getKind() == BuiltinType::Float)
2936 return true;
2937 }
2938
2939 return false;
2940}
2941
2942bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2943 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2944 if (!FromComplex)
2945 return false;
2946
2947 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2948 if (!ToComplex)
2949 return false;
2950
2951 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2952 ToType: ToComplex->getElementType()) ||
2953 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2954 ToType: ToComplex->getElementType());
2955}
2956
2957bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
2958 if (!getLangOpts().OverflowBehaviorTypes)
2959 return false;
2960
2961 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2962 return false;
2963
2964 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2965}
2966
2967bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
2968 QualType ToType) {
2969 if (!getLangOpts().OverflowBehaviorTypes)
2970 return false;
2971
2972 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2973 if (ToType->isBooleanType())
2974 return false;
2975 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2976 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2977 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2978 if (ToED->isScoped())
2979 return false;
2980 }
2981 return true;
2982 }
2983
2984 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2985 return true;
2986
2987 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2988 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
2989
2990 return false;
2991}
2992
2993/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2994/// the pointer type FromPtr to a pointer to type ToPointee, with the
2995/// same type qualifiers as FromPtr has on its pointee type. ToType,
2996/// if non-empty, will be a pointer to ToType that may or may not have
2997/// the right set of qualifiers on its pointee.
2998///
2999static QualType
3000BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
3001 QualType ToPointee, QualType ToType,
3002 ASTContext &Context,
3003 bool StripObjCLifetime = false) {
3004 assert((FromPtr->getTypeClass() == Type::Pointer ||
3005 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3006 "Invalid similarly-qualified pointer type");
3007
3008 /// Conversions to 'id' subsume cv-qualifier conversions.
3009 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3010 return ToType.getUnqualifiedType();
3011
3012 QualType CanonFromPointee
3013 = Context.getCanonicalType(T: FromPtr->getPointeeType());
3014 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
3015 Qualifiers Quals = CanonFromPointee.getQualifiers();
3016
3017 if (StripObjCLifetime)
3018 Quals.removeObjCLifetime();
3019
3020 // Exact qualifier match -> return the pointer type we're converting to.
3021 if (CanonToPointee.getLocalQualifiers() == Quals) {
3022 // ToType is exactly what we need. Return it.
3023 if (!ToType.isNull())
3024 return ToType.getUnqualifiedType();
3025
3026 // Build a pointer to ToPointee. It has the right qualifiers
3027 // already.
3028 if (isa<ObjCObjectPointerType>(Val: ToType))
3029 return Context.getObjCObjectPointerType(OIT: ToPointee);
3030 return Context.getPointerType(T: ToPointee);
3031 }
3032
3033 // Just build a canonical type that has the right qualifiers.
3034 QualType QualifiedCanonToPointee
3035 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3036
3037 if (isa<ObjCObjectPointerType>(Val: ToType))
3038 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3039 return Context.getPointerType(T: QualifiedCanonToPointee);
3040}
3041
3042static bool isNullPointerConstantForConversion(Expr *Expr,
3043 bool InOverloadResolution,
3044 ASTContext &Context) {
3045 // Handle value-dependent integral null pointer constants correctly.
3046 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3047 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3048 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3049 return !InOverloadResolution;
3050
3051 return Expr->isNullPointerConstant(Ctx&: Context,
3052 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3053 : Expr::NPC_ValueDependentIsNull);
3054}
3055
3056bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3057 bool InOverloadResolution,
3058 QualType& ConvertedType,
3059 bool &IncompatibleObjC) {
3060 IncompatibleObjC = false;
3061 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3062 IncompatibleObjC))
3063 return true;
3064
3065 // Conversion from a null pointer constant to any Objective-C pointer type.
3066 if (ToType->isObjCObjectPointerType() &&
3067 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3068 ConvertedType = ToType;
3069 return true;
3070 }
3071
3072 // Blocks: Block pointers can be converted to void*.
3073 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3074 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3075 ConvertedType = ToType;
3076 return true;
3077 }
3078 // Blocks: A null pointer constant can be converted to a block
3079 // pointer type.
3080 if (ToType->isBlockPointerType() &&
3081 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3082 ConvertedType = ToType;
3083 return true;
3084 }
3085
3086 // If the left-hand-side is nullptr_t, the right side can be a null
3087 // pointer constant.
3088 if (ToType->isNullPtrType() &&
3089 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3090 ConvertedType = ToType;
3091 return true;
3092 }
3093
3094 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3095 if (!ToTypePtr)
3096 return false;
3097
3098 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3099 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3100 ConvertedType = ToType;
3101 return true;
3102 }
3103
3104 // Beyond this point, both types need to be pointers
3105 // , including objective-c pointers.
3106 QualType ToPointeeType = ToTypePtr->getPointeeType();
3107 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3108 !getLangOpts().ObjCAutoRefCount) {
3109 ConvertedType = BuildSimilarlyQualifiedPointerType(
3110 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3111 Context);
3112 return true;
3113 }
3114 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3115 if (!FromTypePtr)
3116 return false;
3117
3118 QualType FromPointeeType = FromTypePtr->getPointeeType();
3119
3120 // If the unqualified pointee types are the same, this can't be a
3121 // pointer conversion, so don't do all of the work below.
3122 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3123 return false;
3124
3125 // An rvalue of type "pointer to cv T," where T is an object type,
3126 // can be converted to an rvalue of type "pointer to cv void" (C++
3127 // 4.10p2).
3128 if (FromPointeeType->isIncompleteOrObjectType() &&
3129 ToPointeeType->isVoidType()) {
3130 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3131 ToPointee: ToPointeeType,
3132 ToType, Context,
3133 /*StripObjCLifetime=*/true);
3134 return true;
3135 }
3136
3137 // MSVC allows implicit function to void* type conversion.
3138 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3139 ToPointeeType->isVoidType()) {
3140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3141 ToPointee: ToPointeeType,
3142 ToType, Context);
3143 return true;
3144 }
3145
3146 // When we're overloading in C, we allow a special kind of pointer
3147 // conversion for compatible-but-not-identical pointee types.
3148 if (!getLangOpts().CPlusPlus &&
3149 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3150 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3151 ToPointee: ToPointeeType,
3152 ToType, Context);
3153 return true;
3154 }
3155
3156 // C++ [conv.ptr]p3:
3157 //
3158 // An rvalue of type "pointer to cv D," where D is a class type,
3159 // can be converted to an rvalue of type "pointer to cv B," where
3160 // B is a base class (clause 10) of D. If B is an inaccessible
3161 // (clause 11) or ambiguous (10.2) base class of D, a program that
3162 // necessitates this conversion is ill-formed. The result of the
3163 // conversion is a pointer to the base class sub-object of the
3164 // derived class object. The null pointer value is converted to
3165 // the null pointer value of the destination type.
3166 //
3167 // Note that we do not check for ambiguity or inaccessibility
3168 // here. That is handled by CheckPointerConversion.
3169 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3170 ToPointeeType->isRecordType() &&
3171 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3172 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3173 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3174 ToPointee: ToPointeeType,
3175 ToType, Context);
3176 return true;
3177 }
3178
3179 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3180 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3181 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3182 ToPointee: ToPointeeType,
3183 ToType, Context);
3184 return true;
3185 }
3186
3187 return false;
3188}
3189
3190/// Adopt the given qualifiers for the given type.
3191static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3192 Qualifiers TQs = T.getQualifiers();
3193
3194 // Check whether qualifiers already match.
3195 if (TQs == Qs)
3196 return T;
3197
3198 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3199 return Context.getQualifiedType(T, Qs);
3200
3201 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3202}
3203
3204bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3205 QualType& ConvertedType,
3206 bool &IncompatibleObjC) {
3207 if (!getLangOpts().ObjC)
3208 return false;
3209
3210 // The set of qualifiers on the type we're converting from.
3211 Qualifiers FromQualifiers = FromType.getQualifiers();
3212
3213 // First, we handle all conversions on ObjC object pointer types.
3214 const ObjCObjectPointerType* ToObjCPtr =
3215 ToType->getAs<ObjCObjectPointerType>();
3216 const ObjCObjectPointerType *FromObjCPtr =
3217 FromType->getAs<ObjCObjectPointerType>();
3218
3219 if (ToObjCPtr && FromObjCPtr) {
3220 // If the pointee types are the same (ignoring qualifications),
3221 // then this is not a pointer conversion.
3222 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3223 T2: FromObjCPtr->getPointeeType()))
3224 return false;
3225
3226 // Conversion between Objective-C pointers.
3227 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3228 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3229 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3230 if (getLangOpts().CPlusPlus && LHS && RHS &&
3231 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3232 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3233 return false;
3234 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3235 ToPointee: ToObjCPtr->getPointeeType(),
3236 ToType, Context);
3237 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3238 return true;
3239 }
3240
3241 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3242 // Okay: this is some kind of implicit downcast of Objective-C
3243 // interfaces, which is permitted. However, we're going to
3244 // complain about it.
3245 IncompatibleObjC = true;
3246 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3247 ToPointee: ToObjCPtr->getPointeeType(),
3248 ToType, Context);
3249 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3250 return true;
3251 }
3252 }
3253 // Beyond this point, both types need to be C pointers or block pointers.
3254 QualType ToPointeeType;
3255 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3256 ToPointeeType = ToCPtr->getPointeeType();
3257 else if (const BlockPointerType *ToBlockPtr =
3258 ToType->getAs<BlockPointerType>()) {
3259 // Objective C++: We're able to convert from a pointer to any object
3260 // to a block pointer type.
3261 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3262 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3263 return true;
3264 }
3265 ToPointeeType = ToBlockPtr->getPointeeType();
3266 }
3267 else if (FromType->getAs<BlockPointerType>() &&
3268 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3269 // Objective C++: We're able to convert from a block pointer type to a
3270 // pointer to any object.
3271 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3272 return true;
3273 }
3274 else
3275 return false;
3276
3277 QualType FromPointeeType;
3278 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3279 FromPointeeType = FromCPtr->getPointeeType();
3280 else if (const BlockPointerType *FromBlockPtr =
3281 FromType->getAs<BlockPointerType>())
3282 FromPointeeType = FromBlockPtr->getPointeeType();
3283 else
3284 return false;
3285
3286 // If we have pointers to pointers, recursively check whether this
3287 // is an Objective-C conversion.
3288 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3289 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3290 IncompatibleObjC)) {
3291 // We always complain about this conversion.
3292 IncompatibleObjC = true;
3293 ConvertedType = Context.getPointerType(T: ConvertedType);
3294 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3295 return true;
3296 }
3297 // Allow conversion of pointee being objective-c pointer to another one;
3298 // as in I* to id.
3299 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3300 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3301 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3302 IncompatibleObjC)) {
3303
3304 ConvertedType = Context.getPointerType(T: ConvertedType);
3305 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3306 return true;
3307 }
3308
3309 // If we have pointers to functions or blocks, check whether the only
3310 // differences in the argument and result types are in Objective-C
3311 // pointer conversions. If so, we permit the conversion (but
3312 // complain about it).
3313 const FunctionProtoType *FromFunctionType
3314 = FromPointeeType->getAs<FunctionProtoType>();
3315 const FunctionProtoType *ToFunctionType
3316 = ToPointeeType->getAs<FunctionProtoType>();
3317 if (FromFunctionType && ToFunctionType) {
3318 // If the function types are exactly the same, this isn't an
3319 // Objective-C pointer conversion.
3320 if (Context.getCanonicalType(T: FromPointeeType)
3321 == Context.getCanonicalType(T: ToPointeeType))
3322 return false;
3323
3324 // Perform the quick checks that will tell us whether these
3325 // function types are obviously different.
3326 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3327 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3328 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3329 return false;
3330
3331 bool HasObjCConversion = false;
3332 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3333 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3334 // Okay, the types match exactly. Nothing to do.
3335 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3336 ToType: ToFunctionType->getReturnType(),
3337 ConvertedType, IncompatibleObjC)) {
3338 // Okay, we have an Objective-C pointer conversion.
3339 HasObjCConversion = true;
3340 } else {
3341 // Function types are too different. Abort.
3342 return false;
3343 }
3344
3345 // Check argument types.
3346 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3347 ArgIdx != NumArgs; ++ArgIdx) {
3348 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3349 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3350 if (Context.getCanonicalType(T: FromArgType)
3351 == Context.getCanonicalType(T: ToArgType)) {
3352 // Okay, the types match exactly. Nothing to do.
3353 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3354 ConvertedType, IncompatibleObjC)) {
3355 // Okay, we have an Objective-C pointer conversion.
3356 HasObjCConversion = true;
3357 } else {
3358 // Argument types are too different. Abort.
3359 return false;
3360 }
3361 }
3362
3363 if (HasObjCConversion) {
3364 // We had an Objective-C conversion. Allow this pointer
3365 // conversion, but complain about it.
3366 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3367 IncompatibleObjC = true;
3368 return true;
3369 }
3370 }
3371
3372 return false;
3373}
3374
3375bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3376 QualType& ConvertedType) {
3377 QualType ToPointeeType;
3378 if (const BlockPointerType *ToBlockPtr =
3379 ToType->getAs<BlockPointerType>())
3380 ToPointeeType = ToBlockPtr->getPointeeType();
3381 else
3382 return false;
3383
3384 QualType FromPointeeType;
3385 if (const BlockPointerType *FromBlockPtr =
3386 FromType->getAs<BlockPointerType>())
3387 FromPointeeType = FromBlockPtr->getPointeeType();
3388 else
3389 return false;
3390 // We have pointer to blocks, check whether the only
3391 // differences in the argument and result types are in Objective-C
3392 // pointer conversions. If so, we permit the conversion.
3393
3394 const FunctionProtoType *FromFunctionType
3395 = FromPointeeType->getAs<FunctionProtoType>();
3396 const FunctionProtoType *ToFunctionType
3397 = ToPointeeType->getAs<FunctionProtoType>();
3398
3399 if (!FromFunctionType || !ToFunctionType)
3400 return false;
3401
3402 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3403 return true;
3404
3405 // Perform the quick checks that will tell us whether these
3406 // function types are obviously different.
3407 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3408 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3409 return false;
3410
3411 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3412 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3413 if (FromEInfo != ToEInfo)
3414 return false;
3415
3416 bool IncompatibleObjC = false;
3417 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3418 T2: ToFunctionType->getReturnType())) {
3419 // Okay, the types match exactly. Nothing to do.
3420 } else {
3421 QualType RHS = FromFunctionType->getReturnType();
3422 QualType LHS = ToFunctionType->getReturnType();
3423 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3424 !RHS.hasQualifiers() && LHS.hasQualifiers())
3425 LHS = LHS.getUnqualifiedType();
3426
3427 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3428 // OK exact match.
3429 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3430 ConvertedType, IncompatibleObjC)) {
3431 if (IncompatibleObjC)
3432 return false;
3433 // Okay, we have an Objective-C pointer conversion.
3434 }
3435 else
3436 return false;
3437 }
3438
3439 // Check argument types.
3440 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3441 ArgIdx != NumArgs; ++ArgIdx) {
3442 IncompatibleObjC = false;
3443 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3444 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3445 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3446 // Okay, the types match exactly. Nothing to do.
3447 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3448 ConvertedType, IncompatibleObjC)) {
3449 if (IncompatibleObjC)
3450 return false;
3451 // Okay, we have an Objective-C pointer conversion.
3452 } else
3453 // Argument types are too different. Abort.
3454 return false;
3455 }
3456
3457 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3458 bool CanUseToFPT, CanUseFromFPT;
3459 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3460 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3461 NewParamInfos))
3462 return false;
3463
3464 ConvertedType = ToType;
3465 return true;
3466}
3467
3468enum {
3469 ft_default,
3470 ft_different_class,
3471 ft_parameter_arity,
3472 ft_parameter_mismatch,
3473 ft_return_type,
3474 ft_qualifer_mismatch,
3475 ft_noexcept
3476};
3477
3478/// Attempts to get the FunctionProtoType from a Type. Handles
3479/// MemberFunctionPointers properly.
3480static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3481 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3482 return FPT;
3483
3484 if (auto *MPT = FromType->getAs<MemberPointerType>())
3485 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3486
3487 return nullptr;
3488}
3489
3490void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3491 QualType FromType, QualType ToType) {
3492 // If either type is not valid, include no extra info.
3493 if (FromType.isNull() || ToType.isNull()) {
3494 PDiag << ft_default;
3495 return;
3496 }
3497
3498 // Get the function type from the pointers.
3499 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3500 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3501 *ToMember = ToType->castAs<MemberPointerType>();
3502 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3503 D2: ToMember->getMostRecentCXXRecordDecl())) {
3504 PDiag << ft_different_class;
3505 if (ToMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 TD: ToMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << ToMember->getQualifier();
3510 if (FromMember->isSugared())
3511 PDiag << Context.getCanonicalTagType(
3512 TD: FromMember->getMostRecentCXXRecordDecl());
3513 else
3514 PDiag << FromMember->getQualifier();
3515 return;
3516 }
3517 FromType = FromMember->getPointeeType();
3518 ToType = ToMember->getPointeeType();
3519 }
3520
3521 if (FromType->isPointerType())
3522 FromType = FromType->getPointeeType();
3523 if (ToType->isPointerType())
3524 ToType = ToType->getPointeeType();
3525
3526 // Remove references.
3527 FromType = FromType.getNonReferenceType();
3528 ToType = ToType.getNonReferenceType();
3529
3530 // Don't print extra info for non-specialized template functions.
3531 if (FromType->isInstantiationDependentType() &&
3532 !FromType->getAs<TemplateSpecializationType>()) {
3533 PDiag << ft_default;
3534 return;
3535 }
3536
3537 // No extra info for same types.
3538 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3539 PDiag << ft_default;
3540 return;
3541 }
3542
3543 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3544 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3545
3546 // Both types need to be function types.
3547 if (!FromFunction || !ToFunction) {
3548 PDiag << ft_default;
3549 return;
3550 }
3551
3552 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3553 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3554 << FromFunction->getNumParams();
3555 return;
3556 }
3557
3558 // Handle different parameter types.
3559 unsigned ArgPos;
3560 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3561 PDiag << ft_parameter_mismatch << ArgPos + 1
3562 << ToFunction->getParamType(i: ArgPos)
3563 << FromFunction->getParamType(i: ArgPos);
3564 return;
3565 }
3566
3567 // Handle different return type.
3568 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3569 T2: ToFunction->getReturnType())) {
3570 PDiag << ft_return_type << ToFunction->getReturnType()
3571 << FromFunction->getReturnType();
3572 return;
3573 }
3574
3575 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3576 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3577 << FromFunction->getMethodQuals();
3578 return;
3579 }
3580
3581 // Handle exception specification differences on canonical type (in C++17
3582 // onwards).
3583 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3584 ->isNothrow() !=
3585 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3586 ->isNothrow()) {
3587 PDiag << ft_noexcept;
3588 return;
3589 }
3590
3591 // Unable to find a difference, so add no extra info.
3592 PDiag << ft_default;
3593}
3594
3595bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3596 ArrayRef<QualType> New, unsigned *ArgPos,
3597 bool Reversed) {
3598 assert(llvm::size(Old) == llvm::size(New) &&
3599 "Can't compare parameters of functions with different number of "
3600 "parameters!");
3601
3602 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3603 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3604 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3605
3606 // Ignore address spaces in pointee type. This is to disallow overloading
3607 // on __ptr32/__ptr64 address spaces.
3608 QualType OldType =
3609 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3610 QualType NewType =
3611 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3612
3613 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3614 if (ArgPos)
3615 *ArgPos = Idx;
3616 return false;
3617 }
3618 }
3619 return true;
3620}
3621
3622bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3623 const FunctionProtoType *NewType,
3624 unsigned *ArgPos, bool Reversed) {
3625 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3626 New: NewType->param_types(), ArgPos, Reversed);
3627}
3628
3629bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3630 const FunctionDecl *NewFunction,
3631 unsigned *ArgPos,
3632 bool Reversed) {
3633
3634 if (OldFunction->getNumNonObjectParams() !=
3635 NewFunction->getNumNonObjectParams())
3636 return false;
3637
3638 unsigned OldIgnore =
3639 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3640 unsigned NewIgnore =
3641 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3642
3643 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3644 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3645
3646 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3647 New: NewPT->param_types().slice(N: NewIgnore),
3648 ArgPos, Reversed);
3649}
3650
3651bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3652 CastKind &Kind,
3653 CXXCastPath& BasePath,
3654 bool IgnoreBaseAccess,
3655 bool Diagnose) {
3656 QualType FromType = From->getType();
3657 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3658
3659 Kind = CK_BitCast;
3660
3661 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3662 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3663 Expr::NPCK_ZeroExpression) {
3664 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3665 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3666 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3667 << ToType << From->getSourceRange());
3668 else if (!isUnevaluatedContext())
3669 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3670 << ToType << From->getSourceRange();
3671 }
3672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3673 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3674 QualType FromPointeeType = FromPtrType->getPointeeType(),
3675 ToPointeeType = ToPtrType->getPointeeType();
3676
3677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3678 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3679 // We must have a derived-to-base conversion. Check an
3680 // ambiguous or inaccessible conversion.
3681 unsigned InaccessibleID = 0;
3682 unsigned AmbiguousID = 0;
3683 if (Diagnose) {
3684 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3685 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3686 }
3687 if (CheckDerivedToBaseConversion(
3688 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3689 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3690 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3691 return true;
3692
3693 // The conversion was successful.
3694 Kind = CK_DerivedToBase;
3695 }
3696
3697 if (Diagnose && !IsCStyleOrFunctionalCast &&
3698 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3699 assert(getLangOpts().MSVCCompat &&
3700 "this should only be possible with MSVCCompat!");
3701 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3702 << From->getSourceRange();
3703 }
3704 }
3705 } else if (const ObjCObjectPointerType *ToPtrType =
3706 ToType->getAs<ObjCObjectPointerType>()) {
3707 if (const ObjCObjectPointerType *FromPtrType =
3708 FromType->getAs<ObjCObjectPointerType>()) {
3709 // Objective-C++ conversions are always okay.
3710 // FIXME: We should have a different class of conversions for the
3711 // Objective-C++ implicit conversions.
3712 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3713 return false;
3714 } else if (FromType->isBlockPointerType()) {
3715 Kind = CK_BlockPointerToObjCPointerCast;
3716 } else {
3717 Kind = CK_CPointerToObjCPointerCast;
3718 }
3719 } else if (ToType->isBlockPointerType()) {
3720 if (!FromType->isBlockPointerType())
3721 Kind = CK_AnyPointerToBlockPointerCast;
3722 }
3723
3724 // We shouldn't fall into this case unless it's valid for other
3725 // reasons.
3726 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3727 Kind = CK_NullToPointer;
3728
3729 return false;
3730}
3731
3732bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3733 QualType ToType,
3734 bool InOverloadResolution,
3735 QualType &ConvertedType) {
3736 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3737 if (!ToTypePtr)
3738 return false;
3739
3740 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3741 if (From->isNullPointerConstant(Ctx&: Context,
3742 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3743 : Expr::NPC_ValueDependentIsNull)) {
3744 ConvertedType = ToType;
3745 return true;
3746 }
3747
3748 // Otherwise, both types have to be member pointers.
3749 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3750 if (!FromTypePtr)
3751 return false;
3752
3753 // A pointer to member of B can be converted to a pointer to member of D,
3754 // where D is derived from B (C++ 4.11p2).
3755 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3756 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3757
3758 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3759 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3760 ConvertedType = Context.getMemberPointerType(
3761 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3762 return true;
3763 }
3764
3765 return false;
3766}
3767
3768Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3769 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3770 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3771 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3772 // Lock down the inheritance model right now in MS ABI, whether or not the
3773 // pointee types are the same.
3774 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3775 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3776 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3777 }
3778
3779 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3780 if (!FromPtrType) {
3781 // This must be a null pointer to member pointer conversion
3782 Kind = CK_NullToMemberPointer;
3783 return MemberPointerConversionResult::Success;
3784 }
3785
3786 // T == T, modulo cv
3787 if (Direction == MemberPointerConversionDirection::Upcast &&
3788 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3789 T2: ToPtrType->getPointeeType()))
3790 return MemberPointerConversionResult::DifferentPointee;
3791
3792 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3793 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3794
3795 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3796 const CXXRecordDecl *Cls) {
3797 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3798 PD << Qual;
3799 else
3800 PD << Context.getCanonicalTagType(TD: Cls);
3801 };
3802 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3803 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3804 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3805 return PD;
3806 };
3807
3808 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3809 if (Direction == MemberPointerConversionDirection::Upcast)
3810 std::swap(a&: Base, b&: Derived);
3811
3812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3813 /*DetectVirtual=*/true);
3814 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3815 return MemberPointerConversionResult::NotDerived;
3816
3817 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3818 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3819 PD << int(Direction);
3820 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3821 Diag(Loc: CheckLoc, PD);
3822 return MemberPointerConversionResult::Ambiguous;
3823 }
3824
3825 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3826 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3827 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3828 Diag(Loc: CheckLoc, PD);
3829 return MemberPointerConversionResult::Virtual;
3830 }
3831
3832 // Must be a base to derived member conversion.
3833 BuildBasePathArray(Paths, BasePath);
3834 Kind = Direction == MemberPointerConversionDirection::Upcast
3835 ? CK_DerivedToBaseMemberPointer
3836 : CK_BaseToDerivedMemberPointer;
3837
3838 if (!IgnoreBaseAccess)
3839 switch (CheckBaseClassAccess(
3840 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3841 DiagID: Direction == MemberPointerConversionDirection::Upcast
3842 ? diag::err_upcast_to_inaccessible_base
3843 : diag::err_downcast_from_inaccessible_base,
3844 SetupPDiag: [&](PartialDiagnostic &PD) {
3845 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3846 DerivedQual = ToPtrType->getQualifier();
3847 if (Direction == MemberPointerConversionDirection::Upcast)
3848 std::swap(a&: BaseQual, b&: DerivedQual);
3849 DiagCls(PD, DerivedQual, Derived);
3850 DiagCls(PD, BaseQual, Base);
3851 })) {
3852 case Sema::AR_accessible:
3853 case Sema::AR_delayed:
3854 case Sema::AR_dependent:
3855 // Optimistically assume that the delayed and dependent cases
3856 // will work out.
3857 break;
3858
3859 case Sema::AR_inaccessible:
3860 return MemberPointerConversionResult::Inaccessible;
3861 }
3862
3863 return MemberPointerConversionResult::Success;
3864}
3865
3866/// Determine whether the lifetime conversion between the two given
3867/// qualifiers sets is nontrivial.
3868static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3869 Qualifiers ToQuals) {
3870 // Converting anything to const __unsafe_unretained is trivial.
3871 if (ToQuals.hasConst() &&
3872 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3873 return false;
3874
3875 return true;
3876}
3877
3878/// Perform a single iteration of the loop for checking if a qualification
3879/// conversion is valid.
3880///
3881/// Specifically, check whether any change between the qualifiers of \p
3882/// FromType and \p ToType is permissible, given knowledge about whether every
3883/// outer layer is const-qualified.
3884static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3885 bool CStyle, bool IsTopLevel,
3886 bool &PreviousToQualsIncludeConst,
3887 bool &ObjCLifetimeConversion,
3888 const ASTContext &Ctx) {
3889 Qualifiers FromQuals = FromType.getQualifiers();
3890 Qualifiers ToQuals = ToType.getQualifiers();
3891
3892 // Ignore __unaligned qualifier.
3893 FromQuals.removeUnaligned();
3894
3895 // Objective-C ARC:
3896 // Check Objective-C lifetime conversions.
3897 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3898 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3899 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3900 ObjCLifetimeConversion = true;
3901 FromQuals.removeObjCLifetime();
3902 ToQuals.removeObjCLifetime();
3903 } else {
3904 // Qualification conversions cannot cast between different
3905 // Objective-C lifetime qualifiers.
3906 return false;
3907 }
3908 }
3909
3910 // Allow addition/removal of GC attributes but not changing GC attributes.
3911 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3912 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3913 FromQuals.removeObjCGCAttr();
3914 ToQuals.removeObjCGCAttr();
3915 }
3916
3917 // __ptrauth qualifiers must match exactly.
3918 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3919 return false;
3920
3921 // -- for every j > 0, if const is in cv 1,j then const is in cv
3922 // 2,j, and similarly for volatile.
3923 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3924 return false;
3925
3926 // If address spaces mismatch:
3927 // - in top level it is only valid to convert to addr space that is a
3928 // superset in all cases apart from C-style casts where we allow
3929 // conversions between overlapping address spaces.
3930 // - in non-top levels it is not a valid conversion.
3931 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3932 (!IsTopLevel ||
3933 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3934 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3935 return false;
3936
3937 // -- if the cv 1,j and cv 2,j are different, then const is in
3938 // every cv for 0 < k < j.
3939 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3940 !PreviousToQualsIncludeConst)
3941 return false;
3942
3943 // The following wording is from C++20, where the result of the conversion
3944 // is T3, not T2.
3945 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3946 // "array of unknown bound of"
3947 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3948 return false;
3949
3950 // -- if the resulting P3,i is different from P1,i [...], then const is
3951 // added to every cv 3_k for 0 < k < i.
3952 if (!CStyle && FromType->isConstantArrayType() &&
3953 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3954 return false;
3955
3956 // Keep track of whether all prior cv-qualifiers in the "to" type
3957 // include const.
3958 PreviousToQualsIncludeConst =
3959 PreviousToQualsIncludeConst && ToQuals.hasConst();
3960 return true;
3961}
3962
3963bool
3964Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3965 bool CStyle, bool &ObjCLifetimeConversion) {
3966 FromType = Context.getCanonicalType(T: FromType);
3967 ToType = Context.getCanonicalType(T: ToType);
3968 ObjCLifetimeConversion = false;
3969
3970 // If FromType and ToType are the same type, this is not a
3971 // qualification conversion.
3972 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3973 return false;
3974
3975 // (C++ 4.4p4):
3976 // A conversion can add cv-qualifiers at levels other than the first
3977 // in multi-level pointers, subject to the following rules: [...]
3978 bool PreviousToQualsIncludeConst = true;
3979 bool UnwrappedAnyPointer = false;
3980 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3981 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3982 IsTopLevel: !UnwrappedAnyPointer,
3983 PreviousToQualsIncludeConst,
3984 ObjCLifetimeConversion, Ctx: getASTContext()))
3985 return false;
3986 UnwrappedAnyPointer = true;
3987 }
3988
3989 // We are left with FromType and ToType being the pointee types
3990 // after unwrapping the original FromType and ToType the same number
3991 // of times. If we unwrapped any pointers, and if FromType and
3992 // ToType have the same unqualified type (since we checked
3993 // qualifiers above), then this is a qualification conversion.
3994 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3995}
3996
3997/// - Determine whether this is a conversion from a scalar type to an
3998/// atomic type.
3999///
4000/// If successful, updates \c SCS's second and third steps in the conversion
4001/// sequence to finish the conversion.
4002static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4003 bool InOverloadResolution,
4004 StandardConversionSequence &SCS,
4005 bool CStyle) {
4006 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4007 if (!ToAtomic)
4008 return false;
4009
4010 StandardConversionSequence InnerSCS;
4011 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
4012 InOverloadResolution, SCS&: InnerSCS,
4013 CStyle, /*AllowObjCWritebackConversion=*/false))
4014 return false;
4015
4016 SCS.Second = InnerSCS.Second;
4017 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4018 SCS.Third = InnerSCS.Third;
4019 SCS.QualificationIncludesObjCLifetime
4020 = InnerSCS.QualificationIncludesObjCLifetime;
4021 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4022 return true;
4023}
4024
4025static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
4026 QualType ToType,
4027 bool InOverloadResolution,
4028 StandardConversionSequence &SCS,
4029 bool CStyle) {
4030 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4031 if (!ToOBT)
4032 return false;
4033
4034 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4035 QualType FromType = From->getType();
4036 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4037 return false;
4038
4039 StandardConversionSequence InnerSCS;
4040 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4041 InOverloadResolution, SCS&: InnerSCS, CStyle,
4042 /*AllowObjCWritebackConversion=*/false))
4043 return false;
4044
4045 SCS.Second = InnerSCS.Second;
4046 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4047 SCS.Third = InnerSCS.Third;
4048 SCS.QualificationIncludesObjCLifetime =
4049 InnerSCS.QualificationIncludesObjCLifetime;
4050 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4051 return true;
4052}
4053
4054static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4055 CXXConstructorDecl *Constructor,
4056 QualType Type) {
4057 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4058 if (CtorType->getNumParams() > 0) {
4059 QualType FirstArg = CtorType->getParamType(i: 0);
4060 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4061 return true;
4062 }
4063 return false;
4064}
4065
4066static OverloadingResult
4067IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4068 CXXRecordDecl *To,
4069 UserDefinedConversionSequence &User,
4070 OverloadCandidateSet &CandidateSet,
4071 bool AllowExplicit) {
4072 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4073 for (auto *D : S.LookupConstructors(Class: To)) {
4074 auto Info = getConstructorInfo(ND: D);
4075 if (!Info)
4076 continue;
4077
4078 bool Usable = !Info.Constructor->isInvalidDecl() &&
4079 S.isInitListConstructor(Ctor: Info.Constructor);
4080 if (Usable) {
4081 bool SuppressUserConversions = false;
4082 if (Info.ConstructorTmpl)
4083 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4084 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false,
4087 AllowExplicit);
4088 else
4089 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4090 CandidateSet, SuppressUserConversions,
4091 /*PartialOverloading*/ false, AllowExplicit);
4092 }
4093 }
4094
4095 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4096
4097 OverloadCandidateSet::iterator Best;
4098 switch (auto Result =
4099 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4100 case OR_Deleted:
4101 case OR_Success: {
4102 // Record the standard conversion we used and the conversion function.
4103 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4104 QualType ThisType = Constructor->getFunctionObjectParameterType();
4105 // Initializer lists don't have conversions as such.
4106 User.Before.setAsIdentityConversion();
4107 User.HadMultipleCandidates = HadMultipleCandidates;
4108 User.ConversionFunction = Constructor;
4109 User.FoundConversionFunction = Best->FoundDecl;
4110 User.After.setAsIdentityConversion();
4111 User.After.setFromType(ThisType);
4112 User.After.setAllToTypes(ToType);
4113 return Result;
4114 }
4115
4116 case OR_No_Viable_Function:
4117 return OR_No_Viable_Function;
4118 case OR_Ambiguous:
4119 return OR_Ambiguous;
4120 }
4121
4122 llvm_unreachable("Invalid OverloadResult!");
4123}
4124
4125/// Determines whether there is a user-defined conversion sequence
4126/// (C++ [over.ics.user]) that converts expression From to the type
4127/// ToType. If such a conversion exists, User will contain the
4128/// user-defined conversion sequence that performs such a conversion
4129/// and this routine will return true. Otherwise, this routine returns
4130/// false and User is unspecified.
4131///
4132/// \param AllowExplicit true if the conversion should consider C++0x
4133/// "explicit" conversion functions as well as non-explicit conversion
4134/// functions (C++0x [class.conv.fct]p2).
4135///
4136/// \param AllowObjCConversionOnExplicit true if the conversion should
4137/// allow an extra Objective-C pointer conversion on uses of explicit
4138/// constructors. Requires \c AllowExplicit to also be set.
4139static OverloadingResult
4140IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4141 UserDefinedConversionSequence &User,
4142 OverloadCandidateSet &CandidateSet,
4143 AllowedExplicit AllowExplicit,
4144 bool AllowObjCConversionOnExplicit) {
4145 assert(AllowExplicit != AllowedExplicit::None ||
4146 !AllowObjCConversionOnExplicit);
4147 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4148
4149 // Whether we will only visit constructors.
4150 bool ConstructorsOnly = false;
4151
4152 // If the type we are conversion to is a class type, enumerate its
4153 // constructors.
4154 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4155 // C++ [over.match.ctor]p1:
4156 // When objects of class type are direct-initialized (8.5), or
4157 // copy-initialized from an expression of the same or a
4158 // derived class type (8.5), overload resolution selects the
4159 // constructor. [...] For copy-initialization, the candidate
4160 // functions are all the converting constructors (12.3.1) of
4161 // that class. The argument list is the expression-list within
4162 // the parentheses of the initializer.
4163 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4164 (From->getType()->isRecordType() &&
4165 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4166 ConstructorsOnly = true;
4167
4168 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4169 // We're not going to find any constructors.
4170 } else if (auto *ToRecordDecl =
4171 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4172 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4173
4174 Expr **Args = &From;
4175 unsigned NumArgs = 1;
4176 bool ListInitializing = false;
4177 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4178 // But first, see if there is an init-list-constructor that will work.
4179 OverloadingResult Result = IsInitializerListConstructorConversion(
4180 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4181 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4182 if (Result != OR_No_Viable_Function)
4183 return Result;
4184 // Never mind.
4185 CandidateSet.clear(
4186 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4187
4188 // If we're list-initializing, we pass the individual elements as
4189 // arguments, not the entire list.
4190 Args = InitList->getInits();
4191 NumArgs = InitList->getNumInits();
4192 ListInitializing = true;
4193 }
4194
4195 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4196 auto Info = getConstructorInfo(ND: D);
4197 if (!Info)
4198 continue;
4199
4200 bool Usable = !Info.Constructor->isInvalidDecl();
4201 if (!ListInitializing)
4202 Usable = Usable && Info.Constructor->isConvertingConstructor(
4203 /*AllowExplicit*/ true);
4204 if (Usable) {
4205 bool SuppressUserConversions = !ConstructorsOnly;
4206 // C++20 [over.best.ics.general]/4.5:
4207 // if the target is the first parameter of a constructor [of class
4208 // X] and the constructor [...] is a candidate by [...] the second
4209 // phase of [over.match.list] when the initializer list has exactly
4210 // one element that is itself an initializer list, [...] and the
4211 // conversion is to X or reference to cv X, user-defined conversion
4212 // sequences are not considered.
4213 if (SuppressUserConversions && ListInitializing) {
4214 SuppressUserConversions =
4215 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4216 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4217 Type: ToType);
4218 }
4219 if (Info.ConstructorTmpl)
4220 S.AddTemplateOverloadCandidate(
4221 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4222 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4223 CandidateSet, SuppressUserConversions,
4224 /*PartialOverloading*/ false,
4225 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4226 else
4227 // Allow one user-defined conversion when user specifies a
4228 // From->ToType conversion via an static cast (c-style, etc).
4229 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4230 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4231 SuppressUserConversions,
4232 /*PartialOverloading*/ false,
4233 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4234 }
4235 }
4236 }
4237 }
4238
4239 // Enumerate conversion functions, if we're allowed to.
4240 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4241 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4242 // No conversion functions from incomplete types.
4243 } else if (const RecordType *FromRecordType =
4244 From->getType()->getAsCanonical<RecordType>()) {
4245 if (auto *FromRecordDecl =
4246 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4247 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4248 // Add all of the conversion functions as candidates.
4249 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4250 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4251 DeclAccessPair FoundDecl = I.getPair();
4252 NamedDecl *D = FoundDecl.getDecl();
4253 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4254 if (isa<UsingShadowDecl>(Val: D))
4255 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4256
4257 CXXConversionDecl *Conv;
4258 FunctionTemplateDecl *ConvTemplate;
4259 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4260 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4261 else
4262 Conv = cast<CXXConversionDecl>(Val: D);
4263
4264 if (ConvTemplate)
4265 S.AddTemplateConversionCandidate(
4266 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4267 CandidateSet, AllowObjCConversionOnExplicit,
4268 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4269 else
4270 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4271 CandidateSet, AllowObjCConversionOnExplicit,
4272 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4273 }
4274 }
4275 }
4276
4277 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4278
4279 OverloadCandidateSet::iterator Best;
4280 switch (auto Result =
4281 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4282 case OR_Success:
4283 case OR_Deleted:
4284 // Record the standard conversion we used and the conversion function.
4285 if (CXXConstructorDecl *Constructor
4286 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4287 // C++ [over.ics.user]p1:
4288 // If the user-defined conversion is specified by a
4289 // constructor (12.3.1), the initial standard conversion
4290 // sequence converts the source type to the type required by
4291 // the argument of the constructor.
4292 //
4293 if (isa<InitListExpr>(Val: From)) {
4294 // Initializer lists don't have conversions as such.
4295 User.Before.setAsIdentityConversion();
4296 User.Before.FromBracedInitList = true;
4297 } else {
4298 if (Best->Conversions[0].isEllipsis())
4299 User.EllipsisConversion = true;
4300 else {
4301 User.Before = Best->Conversions[0].Standard;
4302 User.EllipsisConversion = false;
4303 }
4304 }
4305 User.HadMultipleCandidates = HadMultipleCandidates;
4306 User.ConversionFunction = Constructor;
4307 User.FoundConversionFunction = Best->FoundDecl;
4308 User.After.setAsIdentityConversion();
4309 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4310 User.After.setAllToTypes(ToType);
4311 return Result;
4312 }
4313 if (CXXConversionDecl *Conversion
4314 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4315
4316 assert(Best->HasFinalConversion);
4317
4318 // C++ [over.ics.user]p1:
4319 //
4320 // [...] If the user-defined conversion is specified by a
4321 // conversion function (12.3.2), the initial standard
4322 // conversion sequence converts the source type to the
4323 // implicit object parameter of the conversion function.
4324 User.Before = Best->Conversions[0].Standard;
4325 User.HadMultipleCandidates = HadMultipleCandidates;
4326 User.ConversionFunction = Conversion;
4327 User.FoundConversionFunction = Best->FoundDecl;
4328 User.EllipsisConversion = false;
4329
4330 // C++ [over.ics.user]p2:
4331 // The second standard conversion sequence converts the
4332 // result of the user-defined conversion to the target type
4333 // for the sequence. Since an implicit conversion sequence
4334 // is an initialization, the special rules for
4335 // initialization by user-defined conversion apply when
4336 // selecting the best user-defined conversion for a
4337 // user-defined conversion sequence (see 13.3.3 and
4338 // 13.3.3.1).
4339 User.After = Best->FinalConversion;
4340 return Result;
4341 }
4342 llvm_unreachable("Not a constructor or conversion function?");
4343
4344 case OR_No_Viable_Function:
4345 return OR_No_Viable_Function;
4346
4347 case OR_Ambiguous:
4348 return OR_Ambiguous;
4349 }
4350
4351 llvm_unreachable("Invalid OverloadResult!");
4352}
4353
4354bool
4355Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4356 ImplicitConversionSequence ICS;
4357 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4358 OverloadCandidateSet::CSK_Normal);
4359 OverloadingResult OvResult =
4360 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4361 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4362
4363 if (!(OvResult == OR_Ambiguous ||
4364 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4365 return false;
4366
4367 auto Cands = CandidateSet.CompleteCandidates(
4368 S&: *this,
4369 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4370 Args: From);
4371 if (OvResult == OR_Ambiguous)
4372 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4373 << From->getType() << ToType << From->getSourceRange();
4374 else { // OR_No_Viable_Function && !CandidateSet.empty()
4375 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4376 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4377 Args: From->getType(), Args: From->getSourceRange()))
4378 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4379 << false << From->getType() << From->getSourceRange() << ToType;
4380 }
4381
4382 CandidateSet.NoteCandidates(
4383 S&: *this, Args: From, Cands);
4384 return true;
4385}
4386
4387// Helper for compareConversionFunctions that gets the FunctionType that the
4388// conversion-operator return value 'points' to, or nullptr.
4389static const FunctionType *
4390getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4391 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4392 const PointerType *RetPtrTy =
4393 ConvFuncTy->getReturnType()->getAs<PointerType>();
4394
4395 if (!RetPtrTy)
4396 return nullptr;
4397
4398 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4399}
4400
4401/// Compare the user-defined conversion functions or constructors
4402/// of two user-defined conversion sequences to determine whether any ordering
4403/// is possible.
4404static ImplicitConversionSequence::CompareKind
4405compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4406 FunctionDecl *Function2) {
4407 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4408 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4409 if (!Conv1 || !Conv2)
4410 return ImplicitConversionSequence::Indistinguishable;
4411
4412 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4413 return ImplicitConversionSequence::Indistinguishable;
4414
4415 // Objective-C++:
4416 // If both conversion functions are implicitly-declared conversions from
4417 // a lambda closure type to a function pointer and a block pointer,
4418 // respectively, always prefer the conversion to a function pointer,
4419 // because the function pointer is more lightweight and is more likely
4420 // to keep code working.
4421 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4422 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4423 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4424 if (Block1 != Block2)
4425 return Block1 ? ImplicitConversionSequence::Worse
4426 : ImplicitConversionSequence::Better;
4427 }
4428
4429 // In order to support multiple calling conventions for the lambda conversion
4430 // operator (such as when the free and member function calling convention is
4431 // different), prefer the 'free' mechanism, followed by the calling-convention
4432 // of operator(). The latter is in place to support the MSVC-like solution of
4433 // defining ALL of the possible conversions in regards to calling-convention.
4434 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4435 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4436
4437 if (Conv1FuncRet && Conv2FuncRet &&
4438 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4439 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4440 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4441
4442 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4443 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4444
4445 CallingConv CallOpCC =
4446 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4447 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4448 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4449 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4450 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4451
4452 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4453 for (CallingConv CC : PrefOrder) {
4454 if (Conv1CC == CC)
4455 return ImplicitConversionSequence::Better;
4456 if (Conv2CC == CC)
4457 return ImplicitConversionSequence::Worse;
4458 }
4459 }
4460
4461 return ImplicitConversionSequence::Indistinguishable;
4462}
4463
4464static bool hasDeprecatedStringLiteralToCharPtrConversion(
4465 const ImplicitConversionSequence &ICS) {
4466 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4467 (ICS.isUserDefined() &&
4468 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4469}
4470
4471/// CompareImplicitConversionSequences - Compare two implicit
4472/// conversion sequences to determine whether one is better than the
4473/// other or if they are indistinguishable (C++ 13.3.3.2).
4474static ImplicitConversionSequence::CompareKind
4475CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4476 const ImplicitConversionSequence& ICS1,
4477 const ImplicitConversionSequence& ICS2)
4478{
4479 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4480 // conversion sequences (as defined in 13.3.3.1)
4481 // -- a standard conversion sequence (13.3.3.1.1) is a better
4482 // conversion sequence than a user-defined conversion sequence or
4483 // an ellipsis conversion sequence, and
4484 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4485 // conversion sequence than an ellipsis conversion sequence
4486 // (13.3.3.1.3).
4487 //
4488 // C++0x [over.best.ics]p10:
4489 // For the purpose of ranking implicit conversion sequences as
4490 // described in 13.3.3.2, the ambiguous conversion sequence is
4491 // treated as a user-defined sequence that is indistinguishable
4492 // from any other user-defined conversion sequence.
4493
4494 // String literal to 'char *' conversion has been deprecated in C++03. It has
4495 // been removed from C++11. We still accept this conversion, if it happens at
4496 // the best viable function. Otherwise, this conversion is considered worse
4497 // than ellipsis conversion. Consider this as an extension; this is not in the
4498 // standard. For example:
4499 //
4500 // int &f(...); // #1
4501 // void f(char*); // #2
4502 // void g() { int &r = f("foo"); }
4503 //
4504 // In C++03, we pick #2 as the best viable function.
4505 // In C++11, we pick #1 as the best viable function, because ellipsis
4506 // conversion is better than string-literal to char* conversion (since there
4507 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4508 // convert arguments, #2 would be the best viable function in C++11.
4509 // If the best viable function has this conversion, a warning will be issued
4510 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4511
4512 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4513 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4514 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4515 // Ill-formedness must not differ
4516 ICS1.isBad() == ICS2.isBad())
4517 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4518 ? ImplicitConversionSequence::Worse
4519 : ImplicitConversionSequence::Better;
4520
4521 if (ICS1.getKindRank() < ICS2.getKindRank())
4522 return ImplicitConversionSequence::Better;
4523 if (ICS2.getKindRank() < ICS1.getKindRank())
4524 return ImplicitConversionSequence::Worse;
4525
4526 // The following checks require both conversion sequences to be of
4527 // the same kind.
4528 if (ICS1.getKind() != ICS2.getKind())
4529 return ImplicitConversionSequence::Indistinguishable;
4530
4531 ImplicitConversionSequence::CompareKind Result =
4532 ImplicitConversionSequence::Indistinguishable;
4533
4534 // Two implicit conversion sequences of the same form are
4535 // indistinguishable conversion sequences unless one of the
4536 // following rules apply: (C++ 13.3.3.2p3):
4537
4538 // List-initialization sequence L1 is a better conversion sequence than
4539 // list-initialization sequence L2 if:
4540 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4541 // if not that,
4542 // — L1 and L2 convert to arrays of the same element type, and either the
4543 // number of elements n_1 initialized by L1 is less than the number of
4544 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4545 // an array of unknown bound and L1 does not,
4546 // even if one of the other rules in this paragraph would otherwise apply.
4547 if (!ICS1.isBad()) {
4548 bool StdInit1 = false, StdInit2 = false;
4549 if (ICS1.hasInitializerListContainerType())
4550 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4551 Element: nullptr);
4552 if (ICS2.hasInitializerListContainerType())
4553 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4554 Element: nullptr);
4555 if (StdInit1 != StdInit2)
4556 return StdInit1 ? ImplicitConversionSequence::Better
4557 : ImplicitConversionSequence::Worse;
4558
4559 if (ICS1.hasInitializerListContainerType() &&
4560 ICS2.hasInitializerListContainerType())
4561 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4562 T: ICS1.getInitializerListContainerType()))
4563 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4564 T: ICS2.getInitializerListContainerType())) {
4565 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4566 T2: CAT2->getElementType())) {
4567 // Both to arrays of the same element type
4568 if (CAT1->getSize() != CAT2->getSize())
4569 // Different sized, the smaller wins
4570 return CAT1->getSize().ult(RHS: CAT2->getSize())
4571 ? ImplicitConversionSequence::Better
4572 : ImplicitConversionSequence::Worse;
4573 if (ICS1.isInitializerListOfIncompleteArray() !=
4574 ICS2.isInitializerListOfIncompleteArray())
4575 // One is incomplete, it loses
4576 return ICS2.isInitializerListOfIncompleteArray()
4577 ? ImplicitConversionSequence::Better
4578 : ImplicitConversionSequence::Worse;
4579 }
4580 }
4581 }
4582
4583 if (ICS1.isStandard())
4584 // Standard conversion sequence S1 is a better conversion sequence than
4585 // standard conversion sequence S2 if [...]
4586 Result = CompareStandardConversionSequences(S, Loc,
4587 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4588 else if (ICS1.isUserDefined()) {
4589 // With lazy template loading, it is possible to find non-canonical
4590 // FunctionDecls, depending on when redecl chains are completed. Make sure
4591 // to compare the canonical decls of conversion functions. This avoids
4592 // ambiguity problems for templated conversion operators.
4593 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4594 if (ConvFunc1)
4595 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4596 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4597 if (ConvFunc2)
4598 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4599 // User-defined conversion sequence U1 is a better conversion
4600 // sequence than another user-defined conversion sequence U2 if
4601 // they contain the same user-defined conversion function or
4602 // constructor and if the second standard conversion sequence of
4603 // U1 is better than the second standard conversion sequence of
4604 // U2 (C++ 13.3.3.2p3).
4605 if (ConvFunc1 == ConvFunc2)
4606 Result = CompareStandardConversionSequences(S, Loc,
4607 SCS1: ICS1.UserDefined.After,
4608 SCS2: ICS2.UserDefined.After);
4609 else
4610 Result = compareConversionFunctions(S,
4611 Function1: ICS1.UserDefined.ConversionFunction,
4612 Function2: ICS2.UserDefined.ConversionFunction);
4613 }
4614
4615 return Result;
4616}
4617
4618// Per 13.3.3.2p3, compare the given standard conversion sequences to
4619// determine if one is a proper subset of the other.
4620static ImplicitConversionSequence::CompareKind
4621compareStandardConversionSubsets(ASTContext &Context,
4622 const StandardConversionSequence& SCS1,
4623 const StandardConversionSequence& SCS2) {
4624 ImplicitConversionSequence::CompareKind Result
4625 = ImplicitConversionSequence::Indistinguishable;
4626
4627 // the identity conversion sequence is considered to be a subsequence of
4628 // any non-identity conversion sequence
4629 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4630 return ImplicitConversionSequence::Better;
4631 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4632 return ImplicitConversionSequence::Worse;
4633
4634 if (SCS1.Second != SCS2.Second) {
4635 if (SCS1.Second == ICK_Identity)
4636 Result = ImplicitConversionSequence::Better;
4637 else if (SCS2.Second == ICK_Identity)
4638 Result = ImplicitConversionSequence::Worse;
4639 else
4640 return ImplicitConversionSequence::Indistinguishable;
4641 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4642 return ImplicitConversionSequence::Indistinguishable;
4643
4644 if (SCS1.Third == SCS2.Third) {
4645 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4646 : ImplicitConversionSequence::Indistinguishable;
4647 }
4648
4649 if (SCS1.Third == ICK_Identity)
4650 return Result == ImplicitConversionSequence::Worse
4651 ? ImplicitConversionSequence::Indistinguishable
4652 : ImplicitConversionSequence::Better;
4653
4654 if (SCS2.Third == ICK_Identity)
4655 return Result == ImplicitConversionSequence::Better
4656 ? ImplicitConversionSequence::Indistinguishable
4657 : ImplicitConversionSequence::Worse;
4658
4659 return ImplicitConversionSequence::Indistinguishable;
4660}
4661
4662/// Determine whether one of the given reference bindings is better
4663/// than the other based on what kind of bindings they are.
4664static bool
4665isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4666 const StandardConversionSequence &SCS2) {
4667 // C++0x [over.ics.rank]p3b4:
4668 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4669 // implicit object parameter of a non-static member function declared
4670 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4671 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4672 // lvalue reference to a function lvalue and S2 binds an rvalue
4673 // reference*.
4674 //
4675 // FIXME: Rvalue references. We're going rogue with the above edits,
4676 // because the semantics in the current C++0x working paper (N3225 at the
4677 // time of this writing) break the standard definition of std::forward
4678 // and std::reference_wrapper when dealing with references to functions.
4679 // Proposed wording changes submitted to CWG for consideration.
4680 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4681 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4682 return false;
4683
4684 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4685 SCS2.IsLvalueReference) ||
4686 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4687 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4688}
4689
4690enum class FixedEnumPromotion {
4691 None,
4692 ToUnderlyingType,
4693 ToPromotedUnderlyingType
4694};
4695
4696/// Returns kind of fixed enum promotion the \a SCS uses.
4697static FixedEnumPromotion
4698getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4699
4700 if (SCS.Second != ICK_Integral_Promotion)
4701 return FixedEnumPromotion::None;
4702
4703 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4704 if (!Enum)
4705 return FixedEnumPromotion::None;
4706
4707 if (!Enum->isFixed())
4708 return FixedEnumPromotion::None;
4709
4710 QualType UnderlyingType = Enum->getIntegerType();
4711 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4712 return FixedEnumPromotion::ToUnderlyingType;
4713
4714 return FixedEnumPromotion::ToPromotedUnderlyingType;
4715}
4716
4717/// CompareStandardConversionSequences - Compare two standard
4718/// conversion sequences to determine whether one is better than the
4719/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4720static ImplicitConversionSequence::CompareKind
4721CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4722 const StandardConversionSequence& SCS1,
4723 const StandardConversionSequence& SCS2)
4724{
4725 // Standard conversion sequence S1 is a better conversion sequence
4726 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4727
4728 // -- S1 is a proper subsequence of S2 (comparing the conversion
4729 // sequences in the canonical form defined by 13.3.3.1.1,
4730 // excluding any Lvalue Transformation; the identity conversion
4731 // sequence is considered to be a subsequence of any
4732 // non-identity conversion sequence) or, if not that,
4733 if (ImplicitConversionSequence::CompareKind CK
4734 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4735 return CK;
4736
4737 // -- the rank of S1 is better than the rank of S2 (by the rules
4738 // defined below), or, if not that,
4739 ImplicitConversionRank Rank1 = SCS1.getRank();
4740 ImplicitConversionRank Rank2 = SCS2.getRank();
4741 if (Rank1 < Rank2)
4742 return ImplicitConversionSequence::Better;
4743 else if (Rank2 < Rank1)
4744 return ImplicitConversionSequence::Worse;
4745
4746 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4747 // are indistinguishable unless one of the following rules
4748 // applies:
4749
4750 // A conversion that is not a conversion of a pointer, or
4751 // pointer to member, to bool is better than another conversion
4752 // that is such a conversion.
4753 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4754 return SCS2.isPointerConversionToBool()
4755 ? ImplicitConversionSequence::Better
4756 : ImplicitConversionSequence::Worse;
4757
4758 // C++14 [over.ics.rank]p4b2:
4759 // This is retroactively applied to C++11 by CWG 1601.
4760 //
4761 // A conversion that promotes an enumeration whose underlying type is fixed
4762 // to its underlying type is better than one that promotes to the promoted
4763 // underlying type, if the two are different.
4764 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4765 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4766 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4767 FEP1 != FEP2)
4768 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4769 ? ImplicitConversionSequence::Better
4770 : ImplicitConversionSequence::Worse;
4771
4772 // C++ [over.ics.rank]p4b2:
4773 //
4774 // If class B is derived directly or indirectly from class A,
4775 // conversion of B* to A* is better than conversion of B* to
4776 // void*, and conversion of A* to void* is better than conversion
4777 // of B* to void*.
4778 bool SCS1ConvertsToVoid
4779 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4780 bool SCS2ConvertsToVoid
4781 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4782 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4783 // Exactly one of the conversion sequences is a conversion to
4784 // a void pointer; it's the worse conversion.
4785 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4786 : ImplicitConversionSequence::Worse;
4787 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4788 // Neither conversion sequence converts to a void pointer; compare
4789 // their derived-to-base conversions.
4790 if (ImplicitConversionSequence::CompareKind DerivedCK
4791 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4792 return DerivedCK;
4793 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4794 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4795 // Both conversion sequences are conversions to void
4796 // pointers. Compare the source types to determine if there's an
4797 // inheritance relationship in their sources.
4798 QualType FromType1 = SCS1.getFromType();
4799 QualType FromType2 = SCS2.getFromType();
4800
4801 // Adjust the types we're converting from via the array-to-pointer
4802 // conversion, if we need to.
4803 if (SCS1.First == ICK_Array_To_Pointer)
4804 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4805 if (SCS2.First == ICK_Array_To_Pointer)
4806 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4807
4808 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4809 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4810
4811 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4812 return ImplicitConversionSequence::Better;
4813 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4814 return ImplicitConversionSequence::Worse;
4815
4816 // Objective-C++: If one interface is more specific than the
4817 // other, it is the better one.
4818 const ObjCObjectPointerType* FromObjCPtr1
4819 = FromType1->getAs<ObjCObjectPointerType>();
4820 const ObjCObjectPointerType* FromObjCPtr2
4821 = FromType2->getAs<ObjCObjectPointerType>();
4822 if (FromObjCPtr1 && FromObjCPtr2) {
4823 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4824 RHSOPT: FromObjCPtr2);
4825 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4826 RHSOPT: FromObjCPtr1);
4827 if (AssignLeft != AssignRight) {
4828 return AssignLeft? ImplicitConversionSequence::Better
4829 : ImplicitConversionSequence::Worse;
4830 }
4831 }
4832 }
4833
4834 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4835 // Check for a better reference binding based on the kind of bindings.
4836 if (isBetterReferenceBindingKind(SCS1, SCS2))
4837 return ImplicitConversionSequence::Better;
4838 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4839 return ImplicitConversionSequence::Worse;
4840 }
4841
4842 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4843 // bullet 3).
4844 if (ImplicitConversionSequence::CompareKind QualCK
4845 = CompareQualificationConversions(S, SCS1, SCS2))
4846 return QualCK;
4847
4848 if (ImplicitConversionSequence::CompareKind ObtCK =
4849 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4850 return ObtCK;
4851
4852 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4853 // C++ [over.ics.rank]p3b4:
4854 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4855 // which the references refer are the same type except for
4856 // top-level cv-qualifiers, and the type to which the reference
4857 // initialized by S2 refers is more cv-qualified than the type
4858 // to which the reference initialized by S1 refers.
4859 QualType T1 = SCS1.getToType(Idx: 2);
4860 QualType T2 = SCS2.getToType(Idx: 2);
4861 T1 = S.Context.getCanonicalType(T: T1);
4862 T2 = S.Context.getCanonicalType(T: T2);
4863 Qualifiers T1Quals, T2Quals;
4864 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4865 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4866 if (UnqualT1 == UnqualT2) {
4867 // Objective-C++ ARC: If the references refer to objects with different
4868 // lifetimes, prefer bindings that don't change lifetime.
4869 if (SCS1.ObjCLifetimeConversionBinding !=
4870 SCS2.ObjCLifetimeConversionBinding) {
4871 return SCS1.ObjCLifetimeConversionBinding
4872 ? ImplicitConversionSequence::Worse
4873 : ImplicitConversionSequence::Better;
4874 }
4875
4876 // If the type is an array type, promote the element qualifiers to the
4877 // type for comparison.
4878 if (isa<ArrayType>(Val: T1) && T1Quals)
4879 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4880 if (isa<ArrayType>(Val: T2) && T2Quals)
4881 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4882 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4883 return ImplicitConversionSequence::Better;
4884 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4885 return ImplicitConversionSequence::Worse;
4886 }
4887 }
4888
4889 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4890 // floating-to-integral conversion if the integral conversion
4891 // is between types of the same size.
4892 // For example:
4893 // void f(float);
4894 // void f(int);
4895 // int main {
4896 // long a;
4897 // f(a);
4898 // }
4899 // Here, MSVC will call f(int) instead of generating a compile error
4900 // as clang will do in standard mode.
4901 if (S.getLangOpts().MSVCCompat &&
4902 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4903 SCS1.Second == ICK_Integral_Conversion &&
4904 SCS2.Second == ICK_Floating_Integral &&
4905 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4906 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4907 return ImplicitConversionSequence::Better;
4908
4909 // Prefer a compatible vector conversion over a lax vector conversion
4910 // For example:
4911 //
4912 // typedef float __v4sf __attribute__((__vector_size__(16)));
4913 // void f(vector float);
4914 // void f(vector signed int);
4915 // int main() {
4916 // __v4sf a;
4917 // f(a);
4918 // }
4919 // Here, we'd like to choose f(vector float) and not
4920 // report an ambiguous call error
4921 if (SCS1.Second == ICK_Vector_Conversion &&
4922 SCS2.Second == ICK_Vector_Conversion) {
4923 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4924 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4925 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4926 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4927
4928 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4929 return SCS1IsCompatibleVectorConversion
4930 ? ImplicitConversionSequence::Better
4931 : ImplicitConversionSequence::Worse;
4932 }
4933
4934 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4935 SCS2.Second == ICK_SVE_Vector_Conversion) {
4936 bool SCS1IsCompatibleSVEVectorConversion =
4937 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4938 bool SCS2IsCompatibleSVEVectorConversion =
4939 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4940
4941 if (SCS1IsCompatibleSVEVectorConversion !=
4942 SCS2IsCompatibleSVEVectorConversion)
4943 return SCS1IsCompatibleSVEVectorConversion
4944 ? ImplicitConversionSequence::Better
4945 : ImplicitConversionSequence::Worse;
4946 }
4947
4948 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4949 SCS2.Second == ICK_RVV_Vector_Conversion) {
4950 bool SCS1IsCompatibleRVVVectorConversion =
4951 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4952 bool SCS2IsCompatibleRVVVectorConversion =
4953 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4954
4955 if (SCS1IsCompatibleRVVVectorConversion !=
4956 SCS2IsCompatibleRVVVectorConversion)
4957 return SCS1IsCompatibleRVVVectorConversion
4958 ? ImplicitConversionSequence::Better
4959 : ImplicitConversionSequence::Worse;
4960 }
4961 return ImplicitConversionSequence::Indistinguishable;
4962}
4963
4964/// CompareOverflowBehaviorConversions - Compares two standard conversion
4965/// sequences to determine whether they can be ranked based on their
4966/// OverflowBehaviorType's underlying type.
4967static ImplicitConversionSequence::CompareKind
4968CompareOverflowBehaviorConversions(Sema &S,
4969 const StandardConversionSequence &SCS1,
4970 const StandardConversionSequence &SCS2) {
4971
4972 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4973 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4974 return ImplicitConversionSequence::Better;
4975
4976 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4977 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
4978 return ImplicitConversionSequence::Worse;
4979
4980 return ImplicitConversionSequence::Indistinguishable;
4981}
4982
4983/// CompareQualificationConversions - Compares two standard conversion
4984/// sequences to determine whether they can be ranked based on their
4985/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4986static ImplicitConversionSequence::CompareKind
4987CompareQualificationConversions(Sema &S,
4988 const StandardConversionSequence& SCS1,
4989 const StandardConversionSequence& SCS2) {
4990 // C++ [over.ics.rank]p3:
4991 // -- S1 and S2 differ only in their qualification conversion and
4992 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4993 // [C++98]
4994 // [...] and the cv-qualification signature of type T1 is a proper subset
4995 // of the cv-qualification signature of type T2, and S1 is not the
4996 // deprecated string literal array-to-pointer conversion (4.2).
4997 // [C++2a]
4998 // [...] where T1 can be converted to T2 by a qualification conversion.
4999 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5000 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5001 return ImplicitConversionSequence::Indistinguishable;
5002
5003 // FIXME: the example in the standard doesn't use a qualification
5004 // conversion (!)
5005 QualType T1 = SCS1.getToType(Idx: 2);
5006 QualType T2 = SCS2.getToType(Idx: 2);
5007 T1 = S.Context.getCanonicalType(T: T1);
5008 T2 = S.Context.getCanonicalType(T: T2);
5009 assert(!T1->isReferenceType() && !T2->isReferenceType());
5010 Qualifiers T1Quals, T2Quals;
5011 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5012 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5013
5014 // If the types are the same, we won't learn anything by unwrapping
5015 // them.
5016 if (UnqualT1 == UnqualT2)
5017 return ImplicitConversionSequence::Indistinguishable;
5018
5019 // Don't ever prefer a standard conversion sequence that uses the deprecated
5020 // string literal array to pointer conversion.
5021 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5022 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5023
5024 // Objective-C++ ARC:
5025 // Prefer qualification conversions not involving a change in lifetime
5026 // to qualification conversions that do change lifetime.
5027 if (SCS1.QualificationIncludesObjCLifetime &&
5028 !SCS2.QualificationIncludesObjCLifetime)
5029 CanPick1 = false;
5030 if (SCS2.QualificationIncludesObjCLifetime &&
5031 !SCS1.QualificationIncludesObjCLifetime)
5032 CanPick2 = false;
5033
5034 bool ObjCLifetimeConversion;
5035 if (CanPick1 &&
5036 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5037 CanPick1 = false;
5038 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5039 // directions, so we can't short-cut this second check in general.
5040 if (CanPick2 &&
5041 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5042 CanPick2 = false;
5043
5044 if (CanPick1 != CanPick2)
5045 return CanPick1 ? ImplicitConversionSequence::Better
5046 : ImplicitConversionSequence::Worse;
5047 return ImplicitConversionSequence::Indistinguishable;
5048}
5049
5050/// CompareDerivedToBaseConversions - Compares two standard conversion
5051/// sequences to determine whether they can be ranked based on their
5052/// various kinds of derived-to-base conversions (C++
5053/// [over.ics.rank]p4b3). As part of these checks, we also look at
5054/// conversions between Objective-C interface types.
5055static ImplicitConversionSequence::CompareKind
5056CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5057 const StandardConversionSequence& SCS1,
5058 const StandardConversionSequence& SCS2) {
5059 QualType FromType1 = SCS1.getFromType();
5060 QualType ToType1 = SCS1.getToType(Idx: 1);
5061 QualType FromType2 = SCS2.getFromType();
5062 QualType ToType2 = SCS2.getToType(Idx: 1);
5063
5064 // Adjust the types we're converting from via the array-to-pointer
5065 // conversion, if we need to.
5066 if (SCS1.First == ICK_Array_To_Pointer)
5067 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5068 if (SCS2.First == ICK_Array_To_Pointer)
5069 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5070
5071 // Canonicalize all of the types.
5072 FromType1 = S.Context.getCanonicalType(T: FromType1);
5073 ToType1 = S.Context.getCanonicalType(T: ToType1);
5074 FromType2 = S.Context.getCanonicalType(T: FromType2);
5075 ToType2 = S.Context.getCanonicalType(T: ToType2);
5076
5077 // C++ [over.ics.rank]p4b3:
5078 //
5079 // If class B is derived directly or indirectly from class A and
5080 // class C is derived directly or indirectly from B,
5081 //
5082 // Compare based on pointer conversions.
5083 if (SCS1.Second == ICK_Pointer_Conversion &&
5084 SCS2.Second == ICK_Pointer_Conversion &&
5085 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5086 FromType1->isPointerType() && FromType2->isPointerType() &&
5087 ToType1->isPointerType() && ToType2->isPointerType()) {
5088 QualType FromPointee1 =
5089 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5090 QualType ToPointee1 =
5091 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5092 QualType FromPointee2 =
5093 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5094 QualType ToPointee2 =
5095 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5096
5097 // -- conversion of C* to B* is better than conversion of C* to A*,
5098 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5099 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5100 return ImplicitConversionSequence::Better;
5101 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5102 return ImplicitConversionSequence::Worse;
5103 }
5104
5105 // -- conversion of B* to A* is better than conversion of C* to A*,
5106 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5107 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5108 return ImplicitConversionSequence::Better;
5109 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5110 return ImplicitConversionSequence::Worse;
5111 }
5112 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5113 SCS2.Second == ICK_Pointer_Conversion) {
5114 const ObjCObjectPointerType *FromPtr1
5115 = FromType1->getAs<ObjCObjectPointerType>();
5116 const ObjCObjectPointerType *FromPtr2
5117 = FromType2->getAs<ObjCObjectPointerType>();
5118 const ObjCObjectPointerType *ToPtr1
5119 = ToType1->getAs<ObjCObjectPointerType>();
5120 const ObjCObjectPointerType *ToPtr2
5121 = ToType2->getAs<ObjCObjectPointerType>();
5122
5123 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5124 // Apply the same conversion ranking rules for Objective-C pointer types
5125 // that we do for C++ pointers to class types. However, we employ the
5126 // Objective-C pseudo-subtyping relationship used for assignment of
5127 // Objective-C pointer types.
5128 bool FromAssignLeft
5129 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5130 bool FromAssignRight
5131 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5132 bool ToAssignLeft
5133 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5134 bool ToAssignRight
5135 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5136
5137 // A conversion to an a non-id object pointer type or qualified 'id'
5138 // type is better than a conversion to 'id'.
5139 if (ToPtr1->isObjCIdType() &&
5140 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5141 return ImplicitConversionSequence::Worse;
5142 if (ToPtr2->isObjCIdType() &&
5143 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5144 return ImplicitConversionSequence::Better;
5145
5146 // A conversion to a non-id object pointer type is better than a
5147 // conversion to a qualified 'id' type
5148 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5149 return ImplicitConversionSequence::Worse;
5150 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5151 return ImplicitConversionSequence::Better;
5152
5153 // A conversion to an a non-Class object pointer type or qualified 'Class'
5154 // type is better than a conversion to 'Class'.
5155 if (ToPtr1->isObjCClassType() &&
5156 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5157 return ImplicitConversionSequence::Worse;
5158 if (ToPtr2->isObjCClassType() &&
5159 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5160 return ImplicitConversionSequence::Better;
5161
5162 // A conversion to a non-Class object pointer type is better than a
5163 // conversion to a qualified 'Class' type.
5164 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5165 return ImplicitConversionSequence::Worse;
5166 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5167 return ImplicitConversionSequence::Better;
5168
5169 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5170 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5171 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5172 (ToAssignLeft != ToAssignRight)) {
5173 if (FromPtr1->isSpecialized()) {
5174 // "conversion of B<A> * to B * is better than conversion of B * to
5175 // C *.
5176 bool IsFirstSame =
5177 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5178 bool IsSecondSame =
5179 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5180 if (IsFirstSame) {
5181 if (!IsSecondSame)
5182 return ImplicitConversionSequence::Better;
5183 } else if (IsSecondSame)
5184 return ImplicitConversionSequence::Worse;
5185 }
5186 return ToAssignLeft? ImplicitConversionSequence::Worse
5187 : ImplicitConversionSequence::Better;
5188 }
5189
5190 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5191 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5192 (FromAssignLeft != FromAssignRight))
5193 return FromAssignLeft? ImplicitConversionSequence::Better
5194 : ImplicitConversionSequence::Worse;
5195 }
5196 }
5197
5198 // Ranking of member-pointer types.
5199 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5200 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5201 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5202 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5203 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5204 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5205 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5206 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5207 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5208 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5209 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5210 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5211 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5212 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5213 return ImplicitConversionSequence::Worse;
5214 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5215 return ImplicitConversionSequence::Better;
5216 }
5217 // conversion of B::* to C::* is better than conversion of A::* to C::*
5218 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5219 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5220 return ImplicitConversionSequence::Better;
5221 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5222 return ImplicitConversionSequence::Worse;
5223 }
5224 }
5225
5226 if (SCS1.Second == ICK_Derived_To_Base) {
5227 // -- conversion of C to B is better than conversion of C to A,
5228 // -- binding of an expression of type C to a reference of type
5229 // B& is better than binding an expression of type C to a
5230 // reference of type A&,
5231 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5232 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5233 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5234 return ImplicitConversionSequence::Better;
5235 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5236 return ImplicitConversionSequence::Worse;
5237 }
5238
5239 // -- conversion of B to A is better than conversion of C to A.
5240 // -- binding of an expression of type B to a reference of type
5241 // A& is better than binding an expression of type C to a
5242 // reference of type A&,
5243 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5244 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5245 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5246 return ImplicitConversionSequence::Better;
5247 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5248 return ImplicitConversionSequence::Worse;
5249 }
5250 }
5251
5252 return ImplicitConversionSequence::Indistinguishable;
5253}
5254
5255static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5256 if (!T.getQualifiers().hasUnaligned())
5257 return T;
5258
5259 Qualifiers Q;
5260 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5261 Q.removeUnaligned();
5262 return Ctx.getQualifiedType(T, Qs: Q);
5263}
5264
5265Sema::ReferenceCompareResult
5266Sema::CompareReferenceRelationship(SourceLocation Loc,
5267 QualType OrigT1, QualType OrigT2,
5268 ReferenceConversions *ConvOut) {
5269 assert(!OrigT1->isReferenceType() &&
5270 "T1 must be the pointee type of the reference type");
5271 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5272
5273 QualType T1 = Context.getCanonicalType(T: OrigT1);
5274 QualType T2 = Context.getCanonicalType(T: OrigT2);
5275 Qualifiers T1Quals, T2Quals;
5276 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5277 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5278
5279 ReferenceConversions ConvTmp;
5280 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5281 Conv = ReferenceConversions();
5282
5283 // C++2a [dcl.init.ref]p4:
5284 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5285 // reference-related to "cv2 T2" if T1 is similar to T2, or
5286 // T1 is a base class of T2.
5287 // "cv1 T1" is reference-compatible with "cv2 T2" if
5288 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5289 // "pointer to cv1 T1" via a standard conversion sequence.
5290
5291 // Check for standard conversions we can apply to pointers: derived-to-base
5292 // conversions, ObjC pointer conversions, and function pointer conversions.
5293 // (Qualification conversions are checked last.)
5294 if (UnqualT1 == UnqualT2) {
5295 // Nothing to do.
5296 } else if (isCompleteType(Loc, T: OrigT2) &&
5297 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5298 Conv |= ReferenceConversions::DerivedToBase;
5299 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5300 UnqualT2->isObjCObjectOrInterfaceType() &&
5301 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5302 Conv |= ReferenceConversions::ObjC;
5303 else if (UnqualT2->isFunctionType() &&
5304 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5305 Conv |= ReferenceConversions::Function;
5306 // No need to check qualifiers; function types don't have them.
5307 return Ref_Compatible;
5308 }
5309 bool ConvertedReferent = Conv != 0;
5310
5311 // We can have a qualification conversion. Compute whether the types are
5312 // similar at the same time.
5313 bool PreviousToQualsIncludeConst = true;
5314 bool TopLevel = true;
5315 do {
5316 if (T1 == T2)
5317 break;
5318
5319 // We will need a qualification conversion.
5320 Conv |= ReferenceConversions::Qualification;
5321
5322 // Track whether we performed a qualification conversion anywhere other
5323 // than the top level. This matters for ranking reference bindings in
5324 // overload resolution.
5325 if (!TopLevel)
5326 Conv |= ReferenceConversions::NestedQualification;
5327
5328 // MS compiler ignores __unaligned qualifier for references; do the same.
5329 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5330 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5331
5332 // If we find a qualifier mismatch, the types are not reference-compatible,
5333 // but are still be reference-related if they're similar.
5334 bool ObjCLifetimeConversion = false;
5335 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5336 PreviousToQualsIncludeConst,
5337 ObjCLifetimeConversion, Ctx: getASTContext()))
5338 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5339 ? Ref_Related
5340 : Ref_Incompatible;
5341
5342 // FIXME: Should we track this for any level other than the first?
5343 if (ObjCLifetimeConversion)
5344 Conv |= ReferenceConversions::ObjCLifetime;
5345
5346 TopLevel = false;
5347 } while (Context.UnwrapSimilarTypes(T1, T2));
5348
5349 // At this point, if the types are reference-related, we must either have the
5350 // same inner type (ignoring qualifiers), or must have already worked out how
5351 // to convert the referent.
5352 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5353 ? Ref_Compatible
5354 : Ref_Incompatible;
5355}
5356
5357/// Look for a user-defined conversion to a value reference-compatible
5358/// with DeclType. Return true if something definite is found.
5359static bool
5360FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5361 QualType DeclType, SourceLocation DeclLoc,
5362 Expr *Init, QualType T2, bool AllowRvalues,
5363 bool AllowExplicit) {
5364 assert(T2->isRecordType() && "Can only find conversions of record types.");
5365 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5366 OverloadCandidateSet CandidateSet(
5367 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5368 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5369 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5370 NamedDecl *D = *I;
5371 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5372 if (isa<UsingShadowDecl>(Val: D))
5373 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5374
5375 FunctionTemplateDecl *ConvTemplate
5376 = dyn_cast<FunctionTemplateDecl>(Val: D);
5377 CXXConversionDecl *Conv;
5378 if (ConvTemplate)
5379 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5380 else
5381 Conv = cast<CXXConversionDecl>(Val: D);
5382
5383 if (AllowRvalues) {
5384 // If we are initializing an rvalue reference, don't permit conversion
5385 // functions that return lvalues.
5386 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5387 const ReferenceType *RefType
5388 = Conv->getConversionType()->getAs<LValueReferenceType>();
5389 if (RefType && !RefType->getPointeeType()->isFunctionType())
5390 continue;
5391 }
5392
5393 if (!ConvTemplate &&
5394 S.CompareReferenceRelationship(
5395 Loc: DeclLoc,
5396 OrigT1: Conv->getConversionType()
5397 .getNonReferenceType()
5398 .getUnqualifiedType(),
5399 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5400 Sema::Ref_Incompatible)
5401 continue;
5402 } else {
5403 // If the conversion function doesn't return a reference type,
5404 // it can't be considered for this conversion. An rvalue reference
5405 // is only acceptable if its referencee is a function type.
5406
5407 const ReferenceType *RefType =
5408 Conv->getConversionType()->getAs<ReferenceType>();
5409 if (!RefType ||
5410 (!RefType->isLValueReferenceType() &&
5411 !RefType->getPointeeType()->isFunctionType()))
5412 continue;
5413 }
5414
5415 if (ConvTemplate)
5416 S.AddTemplateConversionCandidate(
5417 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5418 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5419 else
5420 S.AddConversionCandidate(
5421 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5422 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5423 }
5424
5425 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5426
5427 OverloadCandidateSet::iterator Best;
5428 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5429 case OR_Success:
5430
5431 assert(Best->HasFinalConversion);
5432
5433 // C++ [over.ics.ref]p1:
5434 //
5435 // [...] If the parameter binds directly to the result of
5436 // applying a conversion function to the argument
5437 // expression, the implicit conversion sequence is a
5438 // user-defined conversion sequence (13.3.3.1.2), with the
5439 // second standard conversion sequence either an identity
5440 // conversion or, if the conversion function returns an
5441 // entity of a type that is a derived class of the parameter
5442 // type, a derived-to-base Conversion.
5443 if (!Best->FinalConversion.DirectBinding)
5444 return false;
5445
5446 ICS.setUserDefined();
5447 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5448 ICS.UserDefined.After = Best->FinalConversion;
5449 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5450 ICS.UserDefined.ConversionFunction = Best->Function;
5451 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5452 ICS.UserDefined.EllipsisConversion = false;
5453 assert(ICS.UserDefined.After.ReferenceBinding &&
5454 ICS.UserDefined.After.DirectBinding &&
5455 "Expected a direct reference binding!");
5456 return true;
5457
5458 case OR_Ambiguous:
5459 ICS.setAmbiguous();
5460 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5461 Cand != CandidateSet.end(); ++Cand)
5462 if (Cand->Best)
5463 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5464 return true;
5465
5466 case OR_No_Viable_Function:
5467 case OR_Deleted:
5468 // There was no suitable conversion, or we found a deleted
5469 // conversion; continue with other checks.
5470 return false;
5471 }
5472
5473 llvm_unreachable("Invalid OverloadResult!");
5474}
5475
5476/// Compute an implicit conversion sequence for reference
5477/// initialization.
5478static ImplicitConversionSequence
5479TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5480 SourceLocation DeclLoc,
5481 bool SuppressUserConversions,
5482 bool AllowExplicit) {
5483 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5484
5485 // Most paths end in a failed conversion.
5486 ImplicitConversionSequence ICS;
5487 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5488
5489 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5490 QualType T2 = Init->getType();
5491
5492 // If the initializer is the address of an overloaded function, try
5493 // to resolve the overloaded function. If all goes well, T2 is the
5494 // type of the resulting function.
5495 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5496 DeclAccessPair Found;
5497 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5498 Complain: false, Found))
5499 T2 = Fn->getType();
5500 }
5501
5502 // Compute some basic properties of the types and the initializer.
5503 bool isRValRef = DeclType->isRValueReferenceType();
5504 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5505
5506 Sema::ReferenceConversions RefConv;
5507 Sema::ReferenceCompareResult RefRelationship =
5508 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5509
5510 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5511 ICS.setStandard();
5512 ICS.Standard.First = ICK_Identity;
5513 // FIXME: A reference binding can be a function conversion too. We should
5514 // consider that when ordering reference-to-function bindings.
5515 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5516 ? ICK_Derived_To_Base
5517 : (RefConv & Sema::ReferenceConversions::ObjC)
5518 ? ICK_Compatible_Conversion
5519 : ICK_Identity;
5520 ICS.Standard.Dimension = ICK_Identity;
5521 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5522 // a reference binding that performs a non-top-level qualification
5523 // conversion as a qualification conversion, not as an identity conversion.
5524 ICS.Standard.Third = (RefConv &
5525 Sema::ReferenceConversions::NestedQualification)
5526 ? ICK_Qualification
5527 : ICK_Identity;
5528 ICS.Standard.setFromType(T2);
5529 ICS.Standard.setToType(Idx: 0, T: T2);
5530 ICS.Standard.setToType(Idx: 1, T: T1);
5531 ICS.Standard.setToType(Idx: 2, T: T1);
5532 ICS.Standard.ReferenceBinding = true;
5533 ICS.Standard.DirectBinding = BindsDirectly;
5534 ICS.Standard.IsLvalueReference = !isRValRef;
5535 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5536 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5537 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5538 ICS.Standard.ObjCLifetimeConversionBinding =
5539 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5540 ICS.Standard.FromBracedInitList = false;
5541 ICS.Standard.CopyConstructor = nullptr;
5542 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5543 };
5544
5545 // C++0x [dcl.init.ref]p5:
5546 // A reference to type "cv1 T1" is initialized by an expression
5547 // of type "cv2 T2" as follows:
5548
5549 // -- If reference is an lvalue reference and the initializer expression
5550 if (!isRValRef) {
5551 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5552 // reference-compatible with "cv2 T2," or
5553 //
5554 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5555 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5556 // C++ [over.ics.ref]p1:
5557 // When a parameter of reference type binds directly (8.5.3)
5558 // to an argument expression, the implicit conversion sequence
5559 // is the identity conversion, unless the argument expression
5560 // has a type that is a derived class of the parameter type,
5561 // in which case the implicit conversion sequence is a
5562 // derived-to-base Conversion (13.3.3.1).
5563 SetAsReferenceBinding(/*BindsDirectly=*/true);
5564
5565 // Nothing more to do: the inaccessibility/ambiguity check for
5566 // derived-to-base conversions is suppressed when we're
5567 // computing the implicit conversion sequence (C++
5568 // [over.best.ics]p2).
5569 return ICS;
5570 }
5571
5572 // -- has a class type (i.e., T2 is a class type), where T1 is
5573 // not reference-related to T2, and can be implicitly
5574 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5575 // is reference-compatible with "cv3 T3" 92) (this
5576 // conversion is selected by enumerating the applicable
5577 // conversion functions (13.3.1.6) and choosing the best
5578 // one through overload resolution (13.3)),
5579 if (!SuppressUserConversions && T2->isRecordType() &&
5580 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5581 RefRelationship == Sema::Ref_Incompatible) {
5582 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5583 Init, T2, /*AllowRvalues=*/false,
5584 AllowExplicit))
5585 return ICS;
5586 }
5587 }
5588
5589 // -- Otherwise, the reference shall be an lvalue reference to a
5590 // non-volatile const type (i.e., cv1 shall be const), or the reference
5591 // shall be an rvalue reference.
5592 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5593 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5594 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5595 return ICS;
5596 }
5597
5598 // -- If the initializer expression
5599 //
5600 // -- is an xvalue, class prvalue, array prvalue or function
5601 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5602 if (RefRelationship == Sema::Ref_Compatible &&
5603 (InitCategory.isXValue() ||
5604 (InitCategory.isPRValue() &&
5605 (T2->isRecordType() || T2->isArrayType())) ||
5606 (InitCategory.isLValue() && T2->isFunctionType()))) {
5607 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5608 // binding unless we're binding to a class prvalue.
5609 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5610 // allow the use of rvalue references in C++98/03 for the benefit of
5611 // standard library implementors; therefore, we need the xvalue check here.
5612 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5613 !(InitCategory.isPRValue() || T2->isRecordType()));
5614 return ICS;
5615 }
5616
5617 // -- has a class type (i.e., T2 is a class type), where T1 is not
5618 // reference-related to T2, and can be implicitly converted to
5619 // an xvalue, class prvalue, or function lvalue of type
5620 // "cv3 T3", where "cv1 T1" is reference-compatible with
5621 // "cv3 T3",
5622 //
5623 // then the reference is bound to the value of the initializer
5624 // expression in the first case and to the result of the conversion
5625 // in the second case (or, in either case, to an appropriate base
5626 // class subobject).
5627 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5628 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5629 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5630 Init, T2, /*AllowRvalues=*/true,
5631 AllowExplicit)) {
5632 // In the second case, if the reference is an rvalue reference
5633 // and the second standard conversion sequence of the
5634 // user-defined conversion sequence includes an lvalue-to-rvalue
5635 // conversion, the program is ill-formed.
5636 if (ICS.isUserDefined() && isRValRef &&
5637 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5638 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5639
5640 return ICS;
5641 }
5642
5643 // A temporary of function type cannot be created; don't even try.
5644 if (T1->isFunctionType())
5645 return ICS;
5646
5647 // -- Otherwise, a temporary of type "cv1 T1" is created and
5648 // initialized from the initializer expression using the
5649 // rules for a non-reference copy initialization (8.5). The
5650 // reference is then bound to the temporary. If T1 is
5651 // reference-related to T2, cv1 must be the same
5652 // cv-qualification as, or greater cv-qualification than,
5653 // cv2; otherwise, the program is ill-formed.
5654 if (RefRelationship == Sema::Ref_Related) {
5655 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5656 // we would be reference-compatible or reference-compatible with
5657 // added qualification. But that wasn't the case, so the reference
5658 // initialization fails.
5659 //
5660 // Note that we only want to check address spaces and cvr-qualifiers here.
5661 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5662 Qualifiers T1Quals = T1.getQualifiers();
5663 Qualifiers T2Quals = T2.getQualifiers();
5664 T1Quals.removeObjCGCAttr();
5665 T1Quals.removeObjCLifetime();
5666 T2Quals.removeObjCGCAttr();
5667 T2Quals.removeObjCLifetime();
5668 // MS compiler ignores __unaligned qualifier for references; do the same.
5669 T1Quals.removeUnaligned();
5670 T2Quals.removeUnaligned();
5671 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5672 return ICS;
5673 }
5674
5675 // If at least one of the types is a class type, the types are not
5676 // related, and we aren't allowed any user conversions, the
5677 // reference binding fails. This case is important for breaking
5678 // recursion, since TryImplicitConversion below will attempt to
5679 // create a temporary through the use of a copy constructor.
5680 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5681 (T1->isRecordType() || T2->isRecordType()))
5682 return ICS;
5683
5684 // If T1 is reference-related to T2 and the reference is an rvalue
5685 // reference, the initializer expression shall not be an lvalue.
5686 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5687 Init->Classify(Ctx&: S.Context).isLValue()) {
5688 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5689 return ICS;
5690 }
5691
5692 // C++ [over.ics.ref]p2:
5693 // When a parameter of reference type is not bound directly to
5694 // an argument expression, the conversion sequence is the one
5695 // required to convert the argument expression to the
5696 // underlying type of the reference according to
5697 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5698 // to copy-initializing a temporary of the underlying type with
5699 // the argument expression. Any difference in top-level
5700 // cv-qualification is subsumed by the initialization itself
5701 // and does not constitute a conversion.
5702 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5703 AllowExplicit: AllowedExplicit::None,
5704 /*InOverloadResolution=*/false,
5705 /*CStyle=*/false,
5706 /*AllowObjCWritebackConversion=*/false,
5707 /*AllowObjCConversionOnExplicit=*/false);
5708
5709 // Of course, that's still a reference binding.
5710 if (ICS.isStandard()) {
5711 ICS.Standard.ReferenceBinding = true;
5712 ICS.Standard.IsLvalueReference = !isRValRef;
5713 ICS.Standard.BindsToFunctionLvalue = false;
5714 ICS.Standard.BindsToRvalue = true;
5715 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5716 ICS.Standard.ObjCLifetimeConversionBinding = false;
5717 } else if (ICS.isUserDefined()) {
5718 const ReferenceType *LValRefType =
5719 ICS.UserDefined.ConversionFunction->getReturnType()
5720 ->getAs<LValueReferenceType>();
5721
5722 // C++ [over.ics.ref]p3:
5723 // Except for an implicit object parameter, for which see 13.3.1, a
5724 // standard conversion sequence cannot be formed if it requires [...]
5725 // binding an rvalue reference to an lvalue other than a function
5726 // lvalue.
5727 // Note that the function case is not possible here.
5728 if (isRValRef && LValRefType) {
5729 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5730 return ICS;
5731 }
5732
5733 ICS.UserDefined.After.ReferenceBinding = true;
5734 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5735 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5736 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5737 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5738 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5739 ICS.UserDefined.After.FromBracedInitList = false;
5740 }
5741
5742 return ICS;
5743}
5744
5745static ImplicitConversionSequence
5746TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5747 bool SuppressUserConversions,
5748 bool InOverloadResolution,
5749 bool AllowObjCWritebackConversion,
5750 bool AllowExplicit = false);
5751
5752/// TryListConversion - Try to copy-initialize a value of type ToType from the
5753/// initializer list From.
5754static ImplicitConversionSequence
5755TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5756 bool SuppressUserConversions,
5757 bool InOverloadResolution,
5758 bool AllowObjCWritebackConversion) {
5759 // C++11 [over.ics.list]p1:
5760 // When an argument is an initializer list, it is not an expression and
5761 // special rules apply for converting it to a parameter type.
5762
5763 ImplicitConversionSequence Result;
5764 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5765
5766 // We need a complete type for what follows. With one C++20 exception,
5767 // incomplete types can never be initialized from init lists.
5768 QualType InitTy = ToType;
5769 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5770 if (AT && S.getLangOpts().CPlusPlus20)
5771 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5772 // C++20 allows list initialization of an incomplete array type.
5773 InitTy = IAT->getElementType();
5774 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5775 return Result;
5776
5777 // C++20 [over.ics.list]/2:
5778 // If the initializer list is a designated-initializer-list, a conversion
5779 // is only possible if the parameter has an aggregate type
5780 //
5781 // FIXME: The exception for reference initialization here is not part of the
5782 // language rules, but follow other compilers in adding it as a tentative DR
5783 // resolution.
5784 bool IsDesignatedInit = From->hasDesignatedInit();
5785 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5786 IsDesignatedInit)
5787 return Result;
5788
5789 // Per DR1467 and DR2137:
5790 // If the parameter type is an aggregate class X and the initializer list
5791 // has a single element of type cv U, where U is X or a class derived from
5792 // X, the implicit conversion sequence is the one required to convert the
5793 // element to the parameter type.
5794 //
5795 // Otherwise, if the parameter type is a character array [... ]
5796 // and the initializer list has a single element that is an
5797 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5798 // implicit conversion sequence is the identity conversion.
5799 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5800 if (ToType->isRecordType() && ToType->isAggregateType()) {
5801 QualType InitType = From->getInit(Init: 0)->getType();
5802 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5803 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5804 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5805 SuppressUserConversions,
5806 InOverloadResolution,
5807 AllowObjCWritebackConversion);
5808 }
5809
5810 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5811 InitializedEntity Entity =
5812 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5813 /*Consumed=*/false);
5814 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5815 Result.setStandard();
5816 Result.Standard.setAsIdentityConversion();
5817 Result.Standard.setFromType(ToType);
5818 Result.Standard.setAllToTypes(ToType);
5819 return Result;
5820 }
5821 }
5822 }
5823
5824 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5825 // C++11 [over.ics.list]p2:
5826 // If the parameter type is std::initializer_list<X> or "array of X" and
5827 // all the elements can be implicitly converted to X, the implicit
5828 // conversion sequence is the worst conversion necessary to convert an
5829 // element of the list to X.
5830 //
5831 // C++14 [over.ics.list]p3:
5832 // Otherwise, if the parameter type is "array of N X", if the initializer
5833 // list has exactly N elements or if it has fewer than N elements and X is
5834 // default-constructible, and if all the elements of the initializer list
5835 // can be implicitly converted to X, the implicit conversion sequence is
5836 // the worst conversion necessary to convert an element of the list to X.
5837 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5838 unsigned e = From->getNumInits();
5839 ImplicitConversionSequence DfltElt;
5840 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5841 ToType: QualType());
5842 QualType ContTy = ToType;
5843 bool IsUnbounded = false;
5844 if (AT) {
5845 InitTy = AT->getElementType();
5846 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5847 if (CT->getSize().ult(RHS: e)) {
5848 // Too many inits, fatally bad
5849 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5850 ToType);
5851 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5852 return Result;
5853 }
5854 if (CT->getSize().ugt(RHS: e)) {
5855 // Need an init from empty {}, is there one?
5856 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5857 From->getEndLoc(), /*isExplicit=*/false);
5858 EmptyList.setType(S.Context.VoidTy);
5859 DfltElt = TryListConversion(
5860 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5861 InOverloadResolution, AllowObjCWritebackConversion);
5862 if (DfltElt.isBad()) {
5863 // No {} init, fatally bad
5864 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5865 ToType);
5866 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5867 return Result;
5868 }
5869 }
5870 } else {
5871 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5872 IsUnbounded = true;
5873 if (!e) {
5874 // Cannot convert to zero-sized.
5875 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5876 ToType);
5877 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5878 return Result;
5879 }
5880 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5881 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5882 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5883 }
5884 }
5885
5886 Result.setStandard();
5887 Result.Standard.setAsIdentityConversion();
5888 Result.Standard.setFromType(InitTy);
5889 Result.Standard.setAllToTypes(InitTy);
5890 for (unsigned i = 0; i < e; ++i) {
5891 Expr *Init = From->getInit(Init: i);
5892 ImplicitConversionSequence ICS = TryCopyInitialization(
5893 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5894 AllowObjCWritebackConversion);
5895
5896 // Keep the worse conversion seen so far.
5897 // FIXME: Sequences are not totally ordered, so 'worse' can be
5898 // ambiguous. CWG has been informed.
5899 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5900 ICS2: Result) ==
5901 ImplicitConversionSequence::Worse) {
5902 Result = ICS;
5903 // Bail as soon as we find something unconvertible.
5904 if (Result.isBad()) {
5905 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5906 return Result;
5907 }
5908 }
5909 }
5910
5911 // If we needed any implicit {} initialization, compare that now.
5912 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5913 // has been informed that this might not be the best thing.
5914 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5915 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5916 ImplicitConversionSequence::Worse)
5917 Result = DfltElt;
5918 // Record the type being initialized so that we may compare sequences
5919 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5920 return Result;
5921 }
5922
5923 // C++14 [over.ics.list]p4:
5924 // C++11 [over.ics.list]p3:
5925 // Otherwise, if the parameter is a non-aggregate class X and overload
5926 // resolution chooses a single best constructor [...] the implicit
5927 // conversion sequence is a user-defined conversion sequence. If multiple
5928 // constructors are viable but none is better than the others, the
5929 // implicit conversion sequence is a user-defined conversion sequence.
5930 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5931 // This function can deal with initializer lists.
5932 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5933 AllowExplicit: AllowedExplicit::None,
5934 InOverloadResolution, /*CStyle=*/false,
5935 AllowObjCWritebackConversion,
5936 /*AllowObjCConversionOnExplicit=*/false);
5937 }
5938
5939 // C++14 [over.ics.list]p5:
5940 // C++11 [over.ics.list]p4:
5941 // Otherwise, if the parameter has an aggregate type which can be
5942 // initialized from the initializer list [...] the implicit conversion
5943 // sequence is a user-defined conversion sequence.
5944 if (ToType->isAggregateType()) {
5945 // Type is an aggregate, argument is an init list. At this point it comes
5946 // down to checking whether the initialization works.
5947 // FIXME: Find out whether this parameter is consumed or not.
5948 InitializedEntity Entity =
5949 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5950 /*Consumed=*/false);
5951 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5952 From)) {
5953 Result.setUserDefined();
5954 Result.UserDefined.Before.setAsIdentityConversion();
5955 // Initializer lists don't have a type.
5956 Result.UserDefined.Before.setFromType(QualType());
5957 Result.UserDefined.Before.setAllToTypes(QualType());
5958
5959 Result.UserDefined.After.setAsIdentityConversion();
5960 Result.UserDefined.After.setFromType(ToType);
5961 Result.UserDefined.After.setAllToTypes(ToType);
5962 Result.UserDefined.ConversionFunction = nullptr;
5963 }
5964 return Result;
5965 }
5966
5967 // C++14 [over.ics.list]p6:
5968 // C++11 [over.ics.list]p5:
5969 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5970 if (ToType->isReferenceType()) {
5971 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5972 // mention initializer lists in any way. So we go by what list-
5973 // initialization would do and try to extrapolate from that.
5974
5975 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5976
5977 // If the initializer list has a single element that is reference-related
5978 // to the parameter type, we initialize the reference from that.
5979 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5980 Expr *Init = From->getInit(Init: 0);
5981
5982 QualType T2 = Init->getType();
5983
5984 // If the initializer is the address of an overloaded function, try
5985 // to resolve the overloaded function. If all goes well, T2 is the
5986 // type of the resulting function.
5987 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5988 DeclAccessPair Found;
5989 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5990 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5991 T2 = Fn->getType();
5992 }
5993
5994 // Compute some basic properties of the types and the initializer.
5995 Sema::ReferenceCompareResult RefRelationship =
5996 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5997
5998 if (RefRelationship >= Sema::Ref_Related) {
5999 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
6000 SuppressUserConversions,
6001 /*AllowExplicit=*/false);
6002 }
6003 }
6004
6005 // Otherwise, we bind the reference to a temporary created from the
6006 // initializer list.
6007 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
6008 InOverloadResolution,
6009 AllowObjCWritebackConversion);
6010 if (Result.isFailure())
6011 return Result;
6012 assert(!Result.isEllipsis() &&
6013 "Sub-initialization cannot result in ellipsis conversion.");
6014
6015 // Can we even bind to a temporary?
6016 if (ToType->isRValueReferenceType() ||
6017 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6018 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6019 Result.UserDefined.After;
6020 SCS.ReferenceBinding = true;
6021 SCS.IsLvalueReference = ToType->isLValueReferenceType();
6022 SCS.BindsToRvalue = true;
6023 SCS.BindsToFunctionLvalue = false;
6024 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
6025 SCS.ObjCLifetimeConversionBinding = false;
6026 SCS.FromBracedInitList = false;
6027
6028 } else
6029 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6030 FromExpr: From, ToType);
6031 return Result;
6032 }
6033
6034 // C++14 [over.ics.list]p7:
6035 // C++11 [over.ics.list]p6:
6036 // Otherwise, if the parameter type is not a class:
6037 if (!ToType->isRecordType()) {
6038 // - if the initializer list has one element that is not itself an
6039 // initializer list, the implicit conversion sequence is the one
6040 // required to convert the element to the parameter type.
6041 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6042 // single integer.
6043 unsigned NumInits = From->getNumInits();
6044 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6045 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6046 Result = TryCopyInitialization(
6047 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6048 InOverloadResolution, AllowObjCWritebackConversion);
6049 if (Result.isStandard())
6050 Result.Standard.FromBracedInitList = true;
6051 }
6052 // - if the initializer list has no elements, the implicit conversion
6053 // sequence is the identity conversion.
6054 else if (NumInits == 0) {
6055 Result.setStandard();
6056 Result.Standard.setAsIdentityConversion();
6057 Result.Standard.setFromType(ToType);
6058 Result.Standard.setAllToTypes(ToType);
6059 }
6060 return Result;
6061 }
6062
6063 // C++14 [over.ics.list]p8:
6064 // C++11 [over.ics.list]p7:
6065 // In all cases other than those enumerated above, no conversion is possible
6066 return Result;
6067}
6068
6069/// TryCopyInitialization - Try to copy-initialize a value of type
6070/// ToType from the expression From. Return the implicit conversion
6071/// sequence required to pass this argument, which may be a bad
6072/// conversion sequence (meaning that the argument cannot be passed to
6073/// a parameter of this type). If @p SuppressUserConversions, then we
6074/// do not permit any user-defined conversion sequences.
6075static ImplicitConversionSequence
6076TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6077 bool SuppressUserConversions,
6078 bool InOverloadResolution,
6079 bool AllowObjCWritebackConversion,
6080 bool AllowExplicit) {
6081 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6082 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6083 InOverloadResolution,AllowObjCWritebackConversion);
6084
6085 if (ToType->isReferenceType())
6086 return TryReferenceInit(S, Init: From, DeclType: ToType,
6087 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6088 SuppressUserConversions, AllowExplicit);
6089
6090 return TryImplicitConversion(S, From, ToType,
6091 SuppressUserConversions,
6092 AllowExplicit: AllowedExplicit::None,
6093 InOverloadResolution,
6094 /*CStyle=*/false,
6095 AllowObjCWritebackConversion,
6096 /*AllowObjCConversionOnExplicit=*/false);
6097}
6098
6099static bool TryCopyInitialization(const CanQualType FromQTy,
6100 const CanQualType ToQTy,
6101 Sema &S,
6102 SourceLocation Loc,
6103 ExprValueKind FromVK) {
6104 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6105 ImplicitConversionSequence ICS =
6106 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6107
6108 return !ICS.isBad();
6109}
6110
6111/// TryObjectArgumentInitialization - Try to initialize the object
6112/// parameter of the given member function (@c Method) from the
6113/// expression @p From.
6114static ImplicitConversionSequence TryObjectArgumentInitialization(
6115 Sema &S, SourceLocation Loc, QualType FromType,
6116 Expr::Classification FromClassification, CXXMethodDecl *Method,
6117 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6118 QualType ExplicitParameterType = QualType(),
6119 bool SuppressUserConversion = false) {
6120
6121 // We need to have an object of class type.
6122 if (const auto *PT = FromType->getAs<PointerType>()) {
6123 FromType = PT->getPointeeType();
6124
6125 // When we had a pointer, it's implicitly dereferenced, so we
6126 // better have an lvalue.
6127 assert(FromClassification.isLValue());
6128 }
6129
6130 auto ValueKindFromClassification = [](Expr::Classification C) {
6131 if (C.isPRValue())
6132 return clang::VK_PRValue;
6133 if (C.isXValue())
6134 return VK_XValue;
6135 return clang::VK_LValue;
6136 };
6137
6138 if (Method->isExplicitObjectMemberFunction()) {
6139 if (ExplicitParameterType.isNull())
6140 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6141 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6142 ValueKindFromClassification(FromClassification));
6143 ImplicitConversionSequence ICS = TryCopyInitialization(
6144 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6145 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6146 if (ICS.isBad())
6147 ICS.Bad.FromExpr = nullptr;
6148 return ICS;
6149 }
6150
6151 assert(FromType->isRecordType());
6152
6153 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6154 // C++98 [class.dtor]p2:
6155 // A destructor can be invoked for a const, volatile or const volatile
6156 // object.
6157 // C++98 [over.match.funcs]p4:
6158 // For static member functions, the implicit object parameter is considered
6159 // to match any object (since if the function is selected, the object is
6160 // discarded).
6161 Qualifiers Quals = Method->getMethodQualifiers();
6162 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6163 Quals.addConst();
6164 Quals.addVolatile();
6165 }
6166
6167 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6168
6169 // Set up the conversion sequence as a "bad" conversion, to allow us
6170 // to exit early.
6171 ImplicitConversionSequence ICS;
6172
6173 // C++0x [over.match.funcs]p4:
6174 // For non-static member functions, the type of the implicit object
6175 // parameter is
6176 //
6177 // - "lvalue reference to cv X" for functions declared without a
6178 // ref-qualifier or with the & ref-qualifier
6179 // - "rvalue reference to cv X" for functions declared with the &&
6180 // ref-qualifier
6181 //
6182 // where X is the class of which the function is a member and cv is the
6183 // cv-qualification on the member function declaration.
6184 //
6185 // However, when finding an implicit conversion sequence for the argument, we
6186 // are not allowed to perform user-defined conversions
6187 // (C++ [over.match.funcs]p5). We perform a simplified version of
6188 // reference binding here, that allows class rvalues to bind to
6189 // non-constant references.
6190
6191 // First check the qualifiers.
6192 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6193 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6194 if (ImplicitParamType.getCVRQualifiers() !=
6195 FromTypeCanon.getLocalCVRQualifiers() &&
6196 !ImplicitParamType.isAtLeastAsQualifiedAs(
6197 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6198 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6199 FromType, ToType: ImplicitParamType);
6200 return ICS;
6201 }
6202
6203 if (FromTypeCanon.hasAddressSpace()) {
6204 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6205 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6206 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6207 Ctx: S.getASTContext())) {
6208 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6209 FromType, ToType: ImplicitParamType);
6210 return ICS;
6211 }
6212 }
6213
6214 // Check that we have either the same type or a derived type. It
6215 // affects the conversion rank.
6216 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6217 ImplicitConversionKind SecondKind;
6218 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6219 SecondKind = ICK_Identity;
6220 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6221 SecondKind = ICK_Derived_To_Base;
6222 } else if (!Method->isExplicitObjectMemberFunction()) {
6223 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6224 FromType, ToType: ImplicitParamType);
6225 return ICS;
6226 }
6227
6228 // Check the ref-qualifier.
6229 switch (Method->getRefQualifier()) {
6230 case RQ_None:
6231 // Do nothing; we don't care about lvalueness or rvalueness.
6232 break;
6233
6234 case RQ_LValue:
6235 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6236 // non-const lvalue reference cannot bind to an rvalue
6237 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6238 ToType: ImplicitParamType);
6239 return ICS;
6240 }
6241 break;
6242
6243 case RQ_RValue:
6244 if (!FromClassification.isRValue()) {
6245 // rvalue reference cannot bind to an lvalue
6246 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6247 ToType: ImplicitParamType);
6248 return ICS;
6249 }
6250 break;
6251 }
6252
6253 // Success. Mark this as a reference binding.
6254 ICS.setStandard();
6255 ICS.Standard.setAsIdentityConversion();
6256 ICS.Standard.Second = SecondKind;
6257 ICS.Standard.setFromType(FromType);
6258 ICS.Standard.setAllToTypes(ImplicitParamType);
6259 ICS.Standard.ReferenceBinding = true;
6260 ICS.Standard.DirectBinding = true;
6261 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6262 ICS.Standard.BindsToFunctionLvalue = false;
6263 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6264 ICS.Standard.FromBracedInitList = false;
6265 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6266 = (Method->getRefQualifier() == RQ_None);
6267 return ICS;
6268}
6269
6270/// PerformObjectArgumentInitialization - Perform initialization of
6271/// the implicit object parameter for the given Method with the given
6272/// expression.
6273ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6274 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6275 CXXMethodDecl *Method) {
6276 QualType FromRecordType, DestType;
6277 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6278
6279 if (getLangOpts().HLSL &&
6280 From->getType().getAddressSpace() == LangAS::hlsl_constant) {
6281 QualType CastType = From->getType().getLocalUnqualifiedType().withConst();
6282 From = ImplicitCastExpr::Create(Context, T: CastType, Kind: CK_LValueToRValue, Operand: From,
6283 /*BasePath=*/nullptr, Cat: VK_PRValue,
6284 FPO: FPOptionsOverride());
6285 }
6286
6287 Expr::Classification FromClassification;
6288 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6289 FromRecordType = PT->getPointeeType();
6290 DestType = Method->getThisType();
6291 FromClassification = Expr::Classification::makeSimpleLValue();
6292 } else {
6293 FromRecordType = From->getType();
6294 DestType = ImplicitParamRecordType;
6295 FromClassification = From->Classify(Ctx&: Context);
6296
6297 // CWG2813 [expr.call]p6:
6298 // If the function is an implicit object member function, the object
6299 // expression of the class member access shall be a glvalue [...]
6300 if (From->isPRValue()) {
6301 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6302 BoundToLvalueReference: Method->getRefQualifier() !=
6303 RefQualifierKind::RQ_RValue);
6304 }
6305 }
6306
6307 // Note that we always use the true parent context when performing
6308 // the actual argument initialization.
6309 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6310 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6311 ActingContext: Method->getParent());
6312 if (ICS.isBad()) {
6313 switch (ICS.Bad.Kind) {
6314 case BadConversionSequence::bad_qualifiers: {
6315 Qualifiers FromQs = FromRecordType.getQualifiers();
6316 Qualifiers ToQs = DestType.getQualifiers();
6317 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6318 if (CVR) {
6319 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6320 << Method->getDeclName() << FromRecordType << (CVR - 1)
6321 << From->getSourceRange();
6322 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6323 << Method->getDeclName();
6324 return ExprError();
6325 }
6326 break;
6327 }
6328
6329 case BadConversionSequence::lvalue_ref_to_rvalue:
6330 case BadConversionSequence::rvalue_ref_to_lvalue: {
6331 bool IsRValueQualified =
6332 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6333 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6334 << Method->getDeclName() << FromClassification.isRValue()
6335 << IsRValueQualified;
6336 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6337 << Method->getDeclName();
6338 return ExprError();
6339 }
6340
6341 case BadConversionSequence::no_conversion:
6342 case BadConversionSequence::unrelated_class:
6343 break;
6344
6345 case BadConversionSequence::too_few_initializers:
6346 case BadConversionSequence::too_many_initializers:
6347 llvm_unreachable("Lists are not objects");
6348 }
6349
6350 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6351 << ImplicitParamRecordType << FromRecordType
6352 << From->getSourceRange();
6353 }
6354
6355 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6356 ExprResult FromRes =
6357 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6358 if (FromRes.isInvalid())
6359 return ExprError();
6360 From = FromRes.get();
6361 }
6362
6363 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6364 CastKind CK;
6365 QualType PteeTy = DestType->getPointeeType();
6366 LangAS DestAS =
6367 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6368 if (FromRecordType.getAddressSpace() != DestAS)
6369 CK = CK_AddressSpaceConversion;
6370 else
6371 CK = CK_NoOp;
6372 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6373 }
6374 return From;
6375}
6376
6377/// TryContextuallyConvertToBool - Attempt to contextually convert the
6378/// expression From to bool (C++0x [conv]p3).
6379static ImplicitConversionSequence
6380TryContextuallyConvertToBool(Sema &S, Expr *From) {
6381 // C++ [dcl.init]/17.8:
6382 // - Otherwise, if the initialization is direct-initialization, the source
6383 // type is std::nullptr_t, and the destination type is bool, the initial
6384 // value of the object being initialized is false.
6385 if (From->getType()->isNullPtrType())
6386 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6387 DestType: S.Context.BoolTy,
6388 NeedLValToRVal: From->isGLValue());
6389
6390 // All other direct-initialization of bool is equivalent to an implicit
6391 // conversion to bool in which explicit conversions are permitted.
6392 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6393 /*SuppressUserConversions=*/false,
6394 AllowExplicit: AllowedExplicit::Conversions,
6395 /*InOverloadResolution=*/false,
6396 /*CStyle=*/false,
6397 /*AllowObjCWritebackConversion=*/false,
6398 /*AllowObjCConversionOnExplicit=*/false);
6399}
6400
6401ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6402 if (checkPlaceholderForOverload(S&: *this, E&: From))
6403 return ExprError();
6404 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6405 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6406
6407 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6408 if (!ICS.isBad())
6409 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6410 Action: AssignmentAction::Converting);
6411 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6412 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6413 << From->getType() << From->getSourceRange();
6414 return ExprError();
6415}
6416
6417/// Check that the specified conversion is permitted in a converted constant
6418/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6419/// is acceptable.
6420static bool CheckConvertedConstantConversions(Sema &S,
6421 StandardConversionSequence &SCS) {
6422 // Since we know that the target type is an integral or unscoped enumeration
6423 // type, most conversion kinds are impossible. All possible First and Third
6424 // conversions are fine.
6425 switch (SCS.Second) {
6426 case ICK_Identity:
6427 case ICK_Integral_Promotion:
6428 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6429 case ICK_Zero_Queue_Conversion:
6430 return true;
6431
6432 case ICK_Boolean_Conversion:
6433 // Conversion from an integral or unscoped enumeration type to bool is
6434 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6435 // conversion, so we allow it in a converted constant expression.
6436 //
6437 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6438 // a lot of popular code. We should at least add a warning for this
6439 // (non-conforming) extension.
6440 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6441 SCS.getToType(Idx: 2)->isBooleanType();
6442
6443 case ICK_Pointer_Conversion:
6444 case ICK_Pointer_Member:
6445 // C++1z: null pointer conversions and null member pointer conversions are
6446 // only permitted if the source type is std::nullptr_t.
6447 return SCS.getFromType()->isNullPtrType();
6448
6449 case ICK_Floating_Promotion:
6450 case ICK_Complex_Promotion:
6451 case ICK_Floating_Conversion:
6452 case ICK_Complex_Conversion:
6453 case ICK_Floating_Integral:
6454 case ICK_Compatible_Conversion:
6455 case ICK_Derived_To_Base:
6456 case ICK_Vector_Conversion:
6457 case ICK_SVE_Vector_Conversion:
6458 case ICK_RVV_Vector_Conversion:
6459 case ICK_HLSL_Vector_Splat:
6460 case ICK_HLSL_Matrix_Splat:
6461 case ICK_Vector_Splat:
6462 case ICK_Complex_Real:
6463 case ICK_Block_Pointer_Conversion:
6464 case ICK_TransparentUnionConversion:
6465 case ICK_Writeback_Conversion:
6466 case ICK_Zero_Event_Conversion:
6467 case ICK_C_Only_Conversion:
6468 case ICK_Incompatible_Pointer_Conversion:
6469 case ICK_Fixed_Point_Conversion:
6470 case ICK_HLSL_Vector_Truncation:
6471 case ICK_HLSL_Matrix_Truncation:
6472 return false;
6473
6474 case ICK_Lvalue_To_Rvalue:
6475 case ICK_Array_To_Pointer:
6476 case ICK_Function_To_Pointer:
6477 case ICK_HLSL_Array_RValue:
6478 llvm_unreachable("found a first conversion kind in Second");
6479
6480 case ICK_Function_Conversion:
6481 case ICK_Qualification:
6482 llvm_unreachable("found a third conversion kind in Second");
6483
6484 case ICK_Num_Conversion_Kinds:
6485 break;
6486 }
6487
6488 llvm_unreachable("unknown conversion kind");
6489}
6490
6491/// BuildConvertedConstantExpression - Check that the expression From is a
6492/// converted constant expression of type T, perform the conversion but
6493/// does not evaluate the expression
6494static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6495 QualType T, CCEKind CCE,
6496 NamedDecl *Dest,
6497 APValue &PreNarrowingValue) {
6498 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6499 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool ||
6500 CCE == CCEKind::PackIndex);
6501 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6502 "converted constant expression outside C++11 or TTP matching");
6503
6504 if (checkPlaceholderForOverload(S, E&: From))
6505 return ExprError();
6506
6507 if (From->containsErrors()) {
6508 if (S.Context.hasSameType(T1: From->getType(), T2: T))
6509 return From;
6510
6511 // The expression already has errors, so the correct cast kind can't be
6512 // determined. Use RecoveryExpr to keep the expected type T and mark the
6513 // result as invalid, preventing further cascading errors.
6514 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6515 T);
6516 }
6517
6518 // C++1z [expr.const]p3:
6519 // A converted constant expression of type T is an expression,
6520 // implicitly converted to type T, where the converted
6521 // expression is a constant expression and the implicit conversion
6522 // sequence contains only [... list of conversions ...].
6523 ImplicitConversionSequence ICS =
6524 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6525 ? TryContextuallyConvertToBool(S, From)
6526 : TryCopyInitialization(S, From, ToType: T,
6527 /*SuppressUserConversions=*/false,
6528 /*InOverloadResolution=*/false,
6529 /*AllowObjCWritebackConversion=*/false,
6530 /*AllowExplicit=*/false);
6531 StandardConversionSequence *SCS = nullptr;
6532 switch (ICS.getKind()) {
6533 case ImplicitConversionSequence::StandardConversion:
6534 SCS = &ICS.Standard;
6535 break;
6536 case ImplicitConversionSequence::UserDefinedConversion:
6537 if (T->isRecordType())
6538 SCS = &ICS.UserDefined.Before;
6539 else
6540 SCS = &ICS.UserDefined.After;
6541 break;
6542 case ImplicitConversionSequence::AmbiguousConversion:
6543 case ImplicitConversionSequence::BadConversion:
6544 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6545 return S.Diag(Loc: From->getBeginLoc(),
6546 DiagID: diag::err_typecheck_converted_constant_expression)
6547 << From->getType() << From->getSourceRange() << T;
6548 return ExprError();
6549
6550 case ImplicitConversionSequence::EllipsisConversion:
6551 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6552 llvm_unreachable("bad conversion in converted constant expression");
6553 }
6554
6555 // Check that we would only use permitted conversions.
6556 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6557 return S.Diag(Loc: From->getBeginLoc(),
6558 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6559 << From->getType() << From->getSourceRange() << T;
6560 }
6561 // [...] and where the reference binding (if any) binds directly.
6562 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6563 return S.Diag(Loc: From->getBeginLoc(),
6564 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6565 << From->getType() << From->getSourceRange() << T;
6566 }
6567 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6568 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6569 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6570 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6571 // case explicitly.
6572 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6573 return S.Diag(Loc: From->getBeginLoc(),
6574 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6575 << From->getSourceRange();
6576 }
6577
6578 // Usually we can simply apply the ImplicitConversionSequence we formed
6579 // earlier, but that's not guaranteed to work when initializing an object of
6580 // class type.
6581 ExprResult Result;
6582 bool IsTemplateArgument =
6583 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6584 if (T->isRecordType()) {
6585 assert(IsTemplateArgument &&
6586 "unexpected class type converted constant expr");
6587 Result = S.PerformCopyInitialization(
6588 Entity: InitializedEntity::InitializeTemplateParameter(
6589 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6590 EqualLoc: SourceLocation(), Init: From);
6591 } else {
6592 Result =
6593 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6594 }
6595 if (Result.isInvalid())
6596 return Result;
6597
6598 // C++2a [intro.execution]p5:
6599 // A full-expression is [...] a constant-expression [...]
6600 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6601 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6602 IsTemplateArgument);
6603 if (Result.isInvalid())
6604 return Result;
6605
6606 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6607
6608 // Check for a narrowing implicit conversion.
6609 bool ReturnPreNarrowingValue = false;
6610 QualType PreNarrowingType;
6611 switch (SCS->getNarrowingKind(
6612 Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue, ConstantType&: PreNarrowingType,
6613 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6614 case NK_Variable_Narrowing:
6615 // Implicit conversion to a narrower type, and the value is not a constant
6616 // expression. We'll diagnose this in a moment.
6617 case NK_Not_Narrowing:
6618 break;
6619
6620 case NK_Constant_Narrowing:
6621 if (CCE == CCEKind::ArrayBound &&
6622 PreNarrowingType->isIntegralOrEnumerationType() &&
6623 PreNarrowingValue.isInt()) {
6624 // Don't diagnose array bound narrowing here; we produce more precise
6625 // errors by allowing the un-narrowed value through.
6626 ReturnPreNarrowingValue = true;
6627 break;
6628 }
6629 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6630 << CCE << /*Constant*/ 1
6631 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6632 // If this is an SFINAE Context, treat the result as invalid so it stops
6633 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6634 // FIXME: Should do this whenever the above diagnostic is an error, but
6635 // without further changes this would degrade some other diagnostics.
6636 if (S.isSFINAEContext())
6637 return ExprError();
6638 break;
6639
6640 case NK_Dependent_Narrowing:
6641 // Implicit conversion to a narrower type, but the expression is
6642 // value-dependent so we can't tell whether it's actually narrowing.
6643 // For matching the parameters of a TTP, the conversion is ill-formed
6644 // if it may narrow.
6645 if (CCE != CCEKind::TempArgStrict)
6646 break;
6647 [[fallthrough]];
6648 case NK_Type_Narrowing:
6649 // FIXME: It would be better to diagnose that the expression is not a
6650 // constant expression.
6651 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6652 << CCE << /*Constant*/ 0 << From->getType() << T;
6653 if (S.isSFINAEContext())
6654 return ExprError();
6655 break;
6656 }
6657 if (!ReturnPreNarrowingValue)
6658 PreNarrowingValue = {};
6659
6660 return Result;
6661}
6662
6663/// CheckConvertedConstantExpression - Check that the expression From is a
6664/// converted constant expression of type T, perform the conversion and produce
6665/// the converted expression, per C++11 [expr.const]p3.
6666static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6667 QualType T, APValue &Value,
6668 CCEKind CCE, bool RequireInt,
6669 NamedDecl *Dest) {
6670
6671 APValue PreNarrowingValue;
6672 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6673 PreNarrowingValue);
6674 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6675 Value = APValue();
6676 return Result;
6677 }
6678 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6679 RequireInt, PreNarrowingValue);
6680}
6681
6682ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6683 CCEKind CCE,
6684 NamedDecl *Dest) {
6685 APValue PreNarrowingValue;
6686 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6687 PreNarrowingValue);
6688}
6689
6690ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6691 APValue &Value, CCEKind CCE,
6692 NamedDecl *Dest) {
6693 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6694 Dest);
6695}
6696
6697ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6698 llvm::APSInt &Value,
6699 CCEKind CCE) {
6700 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6701
6702 APValue V;
6703 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6704 /*Dest=*/nullptr);
6705 if (!R.isInvalid() && !R.get()->isValueDependent())
6706 Value = V.getInt();
6707 return R;
6708}
6709
6710ExprResult
6711Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6712 CCEKind CCE, bool RequireInt,
6713 const APValue &PreNarrowingValue) {
6714
6715 ExprResult Result = E;
6716 // Check the expression is a constant expression.
6717 SmallVector<PartialDiagnosticAt, 8> Notes;
6718 SmallVector<PartialDiagnosticAt> MSWarning;
6719 Expr::EvalResult Eval;
6720 Eval.Diag = &Notes;
6721 Eval.ExtendedDiag = &MSWarning;
6722
6723 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6724
6725 ConstantExprKind Kind;
6726 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6727 Kind = ConstantExprKind::ClassTemplateArgument;
6728 else if (CCE == CCEKind::TemplateArg)
6729 Kind = ConstantExprKind::NonClassTemplateArgument;
6730 else
6731 Kind = ConstantExprKind::Normal;
6732
6733 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6734 (RequireInt && !Eval.Val.isInt())) {
6735 // The expression can't be folded, so we can't keep it at this position in
6736 // the AST.
6737 Result = ExprError();
6738 } else {
6739 Value = Eval.Val;
6740 // For -fms-compatibility mode we relax some requirements
6741 // for constant folding in non-SFINAE contexts
6742 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6743 if (Notes.empty() && !CantFold) {
6744 for (auto &Info : MSWarning)
6745 Diag(Loc: Info.first, PD: Info.second);
6746 // It's a constant expression.
6747 Expr *E = Result.get();
6748 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6749 // We expect a ConstantExpr to have a value associated with it
6750 // by this point.
6751 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6752 "ConstantExpr has no value associated with it");
6753 (void)CE;
6754 } else {
6755 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6756 }
6757 if (!PreNarrowingValue.isAbsent())
6758 Value = std::move(PreNarrowingValue);
6759 return E;
6760 }
6761 }
6762
6763 // It's not a constant expression. Produce an appropriate diagnostic.
6764 if (Notes.size() == 1 &&
6765 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6766 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6767 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6768 diag::note_constexpr_invalid_template_arg) {
6769 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6770 for (unsigned I = 0; I < Notes.size(); ++I)
6771 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6772 } else {
6773 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6774 << CCE << E->getSourceRange();
6775 for (unsigned I = 0; I < Notes.size(); ++I)
6776 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6777 }
6778 return ExprError();
6779}
6780
6781/// dropPointerConversions - If the given standard conversion sequence
6782/// involves any pointer conversions, remove them. This may change
6783/// the result type of the conversion sequence.
6784static void dropPointerConversion(StandardConversionSequence &SCS) {
6785 if (SCS.Second == ICK_Pointer_Conversion) {
6786 SCS.Second = ICK_Identity;
6787 SCS.Dimension = ICK_Identity;
6788 SCS.Third = ICK_Identity;
6789 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6790 }
6791}
6792
6793/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6794/// convert the expression From to an Objective-C pointer type.
6795static ImplicitConversionSequence
6796TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6797 // Do an implicit conversion to 'id'.
6798 QualType Ty = S.Context.getObjCIdType();
6799 ImplicitConversionSequence ICS
6800 = TryImplicitConversion(S, From, ToType: Ty,
6801 // FIXME: Are these flags correct?
6802 /*SuppressUserConversions=*/false,
6803 AllowExplicit: AllowedExplicit::Conversions,
6804 /*InOverloadResolution=*/false,
6805 /*CStyle=*/false,
6806 /*AllowObjCWritebackConversion=*/false,
6807 /*AllowObjCConversionOnExplicit=*/true);
6808
6809 // Strip off any final conversions to 'id'.
6810 switch (ICS.getKind()) {
6811 case ImplicitConversionSequence::BadConversion:
6812 case ImplicitConversionSequence::AmbiguousConversion:
6813 case ImplicitConversionSequence::EllipsisConversion:
6814 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6815 break;
6816
6817 case ImplicitConversionSequence::UserDefinedConversion:
6818 dropPointerConversion(SCS&: ICS.UserDefined.After);
6819 break;
6820
6821 case ImplicitConversionSequence::StandardConversion:
6822 dropPointerConversion(SCS&: ICS.Standard);
6823 break;
6824 }
6825
6826 return ICS;
6827}
6828
6829ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6830 if (checkPlaceholderForOverload(S&: *this, E&: From))
6831 return ExprError();
6832
6833 QualType Ty = Context.getObjCIdType();
6834 ImplicitConversionSequence ICS =
6835 TryContextuallyConvertToObjCPointer(S&: *this, From);
6836 if (!ICS.isBad())
6837 return PerformImplicitConversion(From, ToType: Ty, ICS,
6838 Action: AssignmentAction::Converting);
6839 return ExprResult();
6840}
6841
6842static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6843 const Expr *Base = nullptr;
6844 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6845 "expected a member expression");
6846
6847 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6848 M && !M->isImplicitAccess())
6849 Base = M->getBase();
6850 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6851 M && !M->isImplicitAccess())
6852 Base = M->getBase();
6853
6854 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6855
6856 if (T->isPointerType())
6857 T = T->getPointeeType();
6858
6859 return T;
6860}
6861
6862static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6863 const FunctionDecl *Fun) {
6864 QualType ObjType = Obj->getType();
6865 if (ObjType->isPointerType()) {
6866 ObjType = ObjType->getPointeeType();
6867 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6868 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6869 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6870 }
6871 return Obj;
6872}
6873
6874ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6875 FunctionDecl *Fun) {
6876 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6877 return S.PerformCopyInitialization(
6878 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6879 EqualLoc: Obj->getExprLoc(), Init: Obj);
6880}
6881
6882static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6883 Expr *Object, MultiExprArg &Args,
6884 SmallVectorImpl<Expr *> &NewArgs) {
6885 assert(Method->isExplicitObjectMemberFunction() &&
6886 "Method is not an explicit member function");
6887 assert(NewArgs.empty() && "NewArgs should be empty");
6888
6889 NewArgs.reserve(N: Args.size() + 1);
6890 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6891 NewArgs.push_back(Elt: This);
6892 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6893 Args = NewArgs;
6894 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6895 Method, CallLoc: Object->getBeginLoc());
6896}
6897
6898/// Determine whether the provided type is an integral type, or an enumeration
6899/// type of a permitted flavor.
6900bool Sema::ICEConvertDiagnoser::match(QualType T) {
6901 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6902 : T->isIntegralOrUnscopedEnumerationType();
6903}
6904
6905static ExprResult
6906diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6907 Sema::ContextualImplicitConverter &Converter,
6908 QualType T, UnresolvedSetImpl &ViableConversions) {
6909
6910 if (Converter.Suppress)
6911 return ExprError();
6912
6913 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6914 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6915 CXXConversionDecl *Conv =
6916 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6917 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6918 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6919 }
6920 return From;
6921}
6922
6923static bool
6924diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6925 Sema::ContextualImplicitConverter &Converter,
6926 QualType T, bool HadMultipleCandidates,
6927 UnresolvedSetImpl &ExplicitConversions) {
6928 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6929 DeclAccessPair Found = ExplicitConversions[0];
6930 CXXConversionDecl *Conversion =
6931 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6932
6933 // The user probably meant to invoke the given explicit
6934 // conversion; use it.
6935 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6936 std::string TypeStr;
6937 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6938
6939 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6940 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6941 Code: "static_cast<" + TypeStr + ">(")
6942 << FixItHint::CreateInsertion(
6943 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6944 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6945
6946 // If we aren't in a SFINAE context, build a call to the
6947 // explicit conversion function.
6948 if (SemaRef.isSFINAEContext())
6949 return true;
6950
6951 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6952 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6953 HadMultipleCandidates);
6954 if (Result.isInvalid())
6955 return true;
6956
6957 // Replace the conversion with a RecoveryExpr, so we don't try to
6958 // instantiate it later, but can further diagnose here.
6959 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6960 SubExprs: From, T: Result.get()->getType());
6961 if (Result.isInvalid())
6962 return true;
6963 From = Result.get();
6964 }
6965 return false;
6966}
6967
6968static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6969 Sema::ContextualImplicitConverter &Converter,
6970 QualType T, bool HadMultipleCandidates,
6971 DeclAccessPair &Found) {
6972 CXXConversionDecl *Conversion =
6973 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6974 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6975
6976 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6977 if (!Converter.SuppressConversion) {
6978 if (SemaRef.isSFINAEContext())
6979 return true;
6980
6981 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6982 << From->getSourceRange();
6983 }
6984
6985 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6986 HadMultipleCandidates);
6987 if (Result.isInvalid())
6988 return true;
6989 // Record usage of conversion in an implicit cast.
6990 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6991 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6992 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6993 FPO: SemaRef.CurFPFeatureOverrides());
6994 return false;
6995}
6996
6997static ExprResult finishContextualImplicitConversion(
6998 Sema &SemaRef, SourceLocation Loc, Expr *From,
6999 Sema::ContextualImplicitConverter &Converter) {
7000 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
7001 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
7002 << From->getSourceRange();
7003
7004 return SemaRef.DefaultLvalueConversion(E: From);
7005}
7006
7007static void
7008collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
7009 UnresolvedSetImpl &ViableConversions,
7010 OverloadCandidateSet &CandidateSet) {
7011 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7012 NamedDecl *D = FoundDecl.getDecl();
7013 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
7014 if (isa<UsingShadowDecl>(Val: D))
7015 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
7016
7017 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
7018 SemaRef.AddTemplateConversionCandidate(
7019 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7020 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7021 continue;
7022 }
7023 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
7024 SemaRef.AddConversionCandidate(
7025 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7026 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7027 }
7028}
7029
7030/// Attempt to convert the given expression to a type which is accepted
7031/// by the given converter.
7032///
7033/// This routine will attempt to convert an expression of class type to a
7034/// type accepted by the specified converter. In C++11 and before, the class
7035/// must have a single non-explicit conversion function converting to a matching
7036/// type. In C++1y, there can be multiple such conversion functions, but only
7037/// one target type.
7038///
7039/// \param Loc The source location of the construct that requires the
7040/// conversion.
7041///
7042/// \param From The expression we're converting from.
7043///
7044/// \param Converter Used to control and diagnose the conversion process.
7045///
7046/// \returns The expression, converted to an integral or enumeration type if
7047/// successful.
7048ExprResult Sema::PerformContextualImplicitConversion(
7049 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7050 // We can't perform any more checking for type-dependent expressions.
7051 if (From->isTypeDependent())
7052 return From;
7053
7054 // Process placeholders immediately.
7055 if (From->hasPlaceholderType()) {
7056 ExprResult result = CheckPlaceholderExpr(E: From);
7057 if (result.isInvalid())
7058 return result;
7059 From = result.get();
7060 }
7061
7062 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7063 ExprResult Converted = DefaultLvalueConversion(E: From);
7064 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7065 From = Converted.isUsable() ? Converted.get() : nullptr;
7066 // If the expression already has a matching type, we're golden.
7067 if (Converter.match(T))
7068 return Converted;
7069
7070 // FIXME: Check for missing '()' if T is a function type?
7071
7072 // We can only perform contextual implicit conversions on objects of class
7073 // type.
7074 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7075 if (!RecordTy || !getLangOpts().CPlusPlus) {
7076 if (!Converter.Suppress)
7077 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7078 return From;
7079 }
7080
7081 // We must have a complete class type.
7082 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7083 ContextualImplicitConverter &Converter;
7084 Expr *From;
7085
7086 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7087 : Converter(Converter), From(From) {}
7088
7089 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7090 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7091 }
7092 } IncompleteDiagnoser(Converter, From);
7093
7094 if (Converter.Suppress ? !isCompleteType(Loc, T)
7095 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7096 return From;
7097
7098 // Look for a conversion to an integral or enumeration type.
7099 UnresolvedSet<4>
7100 ViableConversions; // These are *potentially* viable in C++1y.
7101 UnresolvedSet<4> ExplicitConversions;
7102 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7103 ->getDefinitionOrSelf()
7104 ->getVisibleConversionFunctions();
7105
7106 bool HadMultipleCandidates =
7107 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7108
7109 // To check that there is only one target type, in C++1y:
7110 QualType ToType;
7111 bool HasUniqueTargetType = true;
7112
7113 // Collect explicit or viable (potentially in C++1y) conversions.
7114 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7115 NamedDecl *D = (*I)->getUnderlyingDecl();
7116 CXXConversionDecl *Conversion;
7117 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7118 if (ConvTemplate) {
7119 if (getLangOpts().CPlusPlus14)
7120 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7121 else
7122 continue; // C++11 does not consider conversion operator templates(?).
7123 } else
7124 Conversion = cast<CXXConversionDecl>(Val: D);
7125
7126 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7127 "Conversion operator templates are considered potentially "
7128 "viable in C++1y");
7129
7130 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7131 if (Converter.match(T: CurToType) || ConvTemplate) {
7132
7133 if (Conversion->isExplicit()) {
7134 // FIXME: For C++1y, do we need this restriction?
7135 // cf. diagnoseNoViableConversion()
7136 if (!ConvTemplate)
7137 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7138 } else {
7139 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7140 if (ToType.isNull())
7141 ToType = CurToType.getUnqualifiedType();
7142 else if (HasUniqueTargetType &&
7143 (CurToType.getUnqualifiedType() != ToType))
7144 HasUniqueTargetType = false;
7145 }
7146 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7147 }
7148 }
7149 }
7150
7151 if (getLangOpts().CPlusPlus14) {
7152 // C++1y [conv]p6:
7153 // ... An expression e of class type E appearing in such a context
7154 // is said to be contextually implicitly converted to a specified
7155 // type T and is well-formed if and only if e can be implicitly
7156 // converted to a type T that is determined as follows: E is searched
7157 // for conversion functions whose return type is cv T or reference to
7158 // cv T such that T is allowed by the context. There shall be
7159 // exactly one such T.
7160
7161 // If no unique T is found:
7162 if (ToType.isNull()) {
7163 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7164 HadMultipleCandidates,
7165 ExplicitConversions))
7166 return ExprError();
7167 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7168 }
7169
7170 // If more than one unique Ts are found:
7171 if (!HasUniqueTargetType)
7172 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7173 ViableConversions);
7174
7175 // If one unique T is found:
7176 // First, build a candidate set from the previously recorded
7177 // potentially viable conversions.
7178 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7179 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7180 CandidateSet);
7181
7182 // Then, perform overload resolution over the candidate set.
7183 OverloadCandidateSet::iterator Best;
7184 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7185 case OR_Success: {
7186 // Apply this conversion.
7187 DeclAccessPair Found =
7188 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7189 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7190 HadMultipleCandidates, Found))
7191 return ExprError();
7192 break;
7193 }
7194 case OR_Ambiguous:
7195 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7196 ViableConversions);
7197 case OR_No_Viable_Function:
7198 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7199 HadMultipleCandidates,
7200 ExplicitConversions))
7201 return ExprError();
7202 [[fallthrough]];
7203 case OR_Deleted:
7204 // We'll complain below about a non-integral condition type.
7205 break;
7206 }
7207 } else {
7208 switch (ViableConversions.size()) {
7209 case 0: {
7210 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7211 HadMultipleCandidates,
7212 ExplicitConversions))
7213 return ExprError();
7214
7215 // We'll complain below about a non-integral condition type.
7216 break;
7217 }
7218 case 1: {
7219 // Apply this conversion.
7220 DeclAccessPair Found = ViableConversions[0];
7221 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7222 HadMultipleCandidates, Found))
7223 return ExprError();
7224 break;
7225 }
7226 default:
7227 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7228 ViableConversions);
7229 }
7230 }
7231
7232 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7233}
7234
7235/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7236/// an acceptable non-member overloaded operator for a call whose
7237/// arguments have types T1 (and, if non-empty, T2). This routine
7238/// implements the check in C++ [over.match.oper]p3b2 concerning
7239/// enumeration types.
7240static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7241 FunctionDecl *Fn,
7242 ArrayRef<Expr *> Args) {
7243 QualType T1 = Args[0]->getType();
7244 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7245
7246 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7247 return true;
7248
7249 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7250 return true;
7251
7252 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7253 if (Proto->getNumParams() < 1)
7254 return false;
7255
7256 if (T1->isEnumeralType()) {
7257 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7258 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7259 return true;
7260 }
7261
7262 if (Proto->getNumParams() < 2)
7263 return false;
7264
7265 if (!T2.isNull() && T2->isEnumeralType()) {
7266 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7267 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7268 return true;
7269 }
7270
7271 return false;
7272}
7273
7274static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7275 if (FD->isTargetMultiVersionDefault())
7276 return false;
7277
7278 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7279 return FD->isTargetMultiVersion();
7280
7281 if (!FD->isMultiVersion())
7282 return false;
7283
7284 // Among multiple target versions consider either the default,
7285 // or the first non-default in the absence of default version.
7286 unsigned SeenAt = 0;
7287 unsigned I = 0;
7288 bool HasDefault = false;
7289 FD->getASTContext().forEachMultiversionedFunctionVersion(
7290 FD, Pred: [&](const FunctionDecl *CurFD) {
7291 if (FD == CurFD)
7292 SeenAt = I;
7293 else if (CurFD->isTargetMultiVersionDefault())
7294 HasDefault = true;
7295 ++I;
7296 });
7297 return HasDefault || SeenAt != 0;
7298}
7299
7300void Sema::AddOverloadCandidate(
7301 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7302 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7303 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7304 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7305 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7306 bool StrictPackMatch) {
7307 const FunctionProtoType *Proto
7308 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7309 assert(Proto && "Functions without a prototype cannot be overloaded");
7310 assert(!Function->getDescribedFunctionTemplate() &&
7311 "Use AddTemplateOverloadCandidate for function templates");
7312
7313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7314 if (!isa<CXXConstructorDecl>(Val: Method)) {
7315 // If we get here, it's because we're calling a member function
7316 // that is named without a member access expression (e.g.,
7317 // "this->f") that was either written explicitly or created
7318 // implicitly. This can happen with a qualified call to a member
7319 // function, e.g., X::f(). We use an empty type for the implied
7320 // object argument (C++ [over.call.func]p3), and the acting context
7321 // is irrelevant.
7322 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7323 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7324 CandidateSet, SuppressUserConversions,
7325 PartialOverloading, EarlyConversions, PO,
7326 StrictPackMatch);
7327 return;
7328 }
7329 // We treat a constructor like a non-member function, since its object
7330 // argument doesn't participate in overload resolution.
7331 }
7332
7333 if (!CandidateSet.isNewCandidate(F: Function, PO))
7334 return;
7335
7336 // C++11 [class.copy]p11: [DR1402]
7337 // A defaulted move constructor that is defined as deleted is ignored by
7338 // overload resolution.
7339 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7340 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7341 Constructor->isMoveConstructor())
7342 return;
7343
7344 // Overload resolution is always an unevaluated context.
7345 EnterExpressionEvaluationContext Unevaluated(
7346 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7347
7348 // C++ [over.match.oper]p3:
7349 // if no operand has a class type, only those non-member functions in the
7350 // lookup set that have a first parameter of type T1 or "reference to
7351 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7352 // is a right operand) a second parameter of type T2 or "reference to
7353 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7354 // candidate functions.
7355 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7356 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7357 return;
7358
7359 // Add this candidate
7360 OverloadCandidate &Candidate =
7361 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7362 Candidate.FoundDecl = FoundDecl;
7363 Candidate.Function = Function;
7364 Candidate.Viable = true;
7365 Candidate.RewriteKind =
7366 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7367 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7368 Candidate.ExplicitCallArguments = Args.size();
7369 Candidate.StrictPackMatch = StrictPackMatch;
7370
7371 // Explicit functions are not actually candidates at all if we're not
7372 // allowing them in this context, but keep them around so we can point
7373 // to them in diagnostics.
7374 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7375 Candidate.Viable = false;
7376 Candidate.FailureKind = ovl_fail_explicit;
7377 return;
7378 }
7379
7380 // Functions with internal linkage are only viable in the same module unit.
7381 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7382 /// FIXME: Currently, the semantics of linkage in clang is slightly
7383 /// different from the semantics in C++ spec. In C++ spec, only names
7384 /// have linkage. So that all entities of the same should share one
7385 /// linkage. But in clang, different entities of the same could have
7386 /// different linkage.
7387 const NamedDecl *ND = Function;
7388 bool IsImplicitlyInstantiated = false;
7389 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7390 ND = SpecInfo->getTemplate();
7391 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7392 TSK_ImplicitInstantiation;
7393 }
7394
7395 /// Don't remove inline functions with internal linkage from the overload
7396 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7397 /// However:
7398 /// - Inline functions with internal linkage are a common pattern in
7399 /// headers to avoid ODR issues.
7400 /// - The global module is meant to be a transition mechanism for C and C++
7401 /// headers, and the current rules as written work against that goal.
7402 const bool IsInlineFunctionInGMF =
7403 Function->isFromGlobalModule() &&
7404 (IsImplicitlyInstantiated || Function->isInlined());
7405
7406 // Don't exclude internal-linkage entities from the current TU's global
7407 // module fragment.
7408 const Module *CurrentModule = getCurrentModule();
7409 const bool IsCurrentUnitGMFDecl =
7410 Function->isFromGlobalModule() && CurrentModule &&
7411 Function->getOwningModule()->getTopLevelModule() ==
7412 CurrentModule->getTopLevelModule();
7413
7414 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7415 !IsCurrentUnitGMFDecl) {
7416 Candidate.Viable = false;
7417 Candidate.FailureKind = ovl_fail_module_mismatched;
7418 return;
7419 }
7420 }
7421
7422 if (isNonViableMultiVersionOverload(FD: Function)) {
7423 Candidate.Viable = false;
7424 Candidate.FailureKind = ovl_non_default_multiversion_function;
7425 return;
7426 }
7427
7428 if (Constructor) {
7429 // C++ [class.copy]p3:
7430 // A member function template is never instantiated to perform the copy
7431 // of a class object to an object of its class type.
7432 CanQualType ClassType =
7433 Context.getCanonicalTagType(TD: Constructor->getParent());
7434 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7435 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7436 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7437 Base: ClassType))) {
7438 Candidate.Viable = false;
7439 Candidate.FailureKind = ovl_fail_illegal_constructor;
7440 return;
7441 }
7442
7443 // C++ [over.match.funcs]p8: (proposed DR resolution)
7444 // A constructor inherited from class type C that has a first parameter
7445 // of type "reference to P" (including such a constructor instantiated
7446 // from a template) is excluded from the set of candidate functions when
7447 // constructing an object of type cv D if the argument list has exactly
7448 // one argument and D is reference-related to P and P is reference-related
7449 // to C.
7450 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7451 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7452 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7453 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7454 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7455 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7456 SourceLocation Loc = Args.front()->getExprLoc();
7457 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7458 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7459 Candidate.Viable = false;
7460 Candidate.FailureKind = ovl_fail_inhctor_slice;
7461 return;
7462 }
7463 }
7464
7465 // Check that the constructor is capable of constructing an object in the
7466 // destination address space.
7467 if (!Qualifiers::isAddressSpaceSupersetOf(
7468 A: Constructor->getMethodQualifiers().getAddressSpace(),
7469 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7470 Candidate.Viable = false;
7471 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7472 }
7473 }
7474
7475 unsigned NumParams = Proto->getNumParams();
7476
7477 // (C++ 13.3.2p2): A candidate function having fewer than m
7478 // parameters is viable only if it has an ellipsis in its parameter
7479 // list (8.3.5).
7480 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7481 !Proto->isVariadic() &&
7482 shouldEnforceArgLimit(PartialOverloading, Function)) {
7483 Candidate.Viable = false;
7484 Candidate.FailureKind = ovl_fail_too_many_arguments;
7485 return;
7486 }
7487
7488 // (C++ 13.3.2p2): A candidate function having more than m parameters
7489 // is viable only if the (m+1)st parameter has a default argument
7490 // (8.3.6). For the purposes of overload resolution, the
7491 // parameter list is truncated on the right, so that there are
7492 // exactly m parameters.
7493 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7494 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7495 !PartialOverloading) {
7496 // Not enough arguments.
7497 Candidate.Viable = false;
7498 Candidate.FailureKind = ovl_fail_too_few_arguments;
7499 return;
7500 }
7501
7502 // (CUDA B.1): Check for invalid calls between targets.
7503 if (getLangOpts().CUDA) {
7504 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7505 // Skip the check for callers that are implicit members, because in this
7506 // case we may not yet know what the member's target is; the target is
7507 // inferred for the member automatically, based on the bases and fields of
7508 // the class.
7509 if (!(Caller && Caller->isImplicit()) &&
7510 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7511 Candidate.Viable = false;
7512 Candidate.FailureKind = ovl_fail_bad_target;
7513 return;
7514 }
7515 }
7516
7517 if (Function->getTrailingRequiresClause()) {
7518 ConstraintSatisfaction Satisfaction;
7519 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7520 /*ForOverloadResolution*/ true) ||
7521 !Satisfaction.IsSatisfied) {
7522 Candidate.Viable = false;
7523 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7524 return;
7525 }
7526 }
7527
7528 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7529 // Determine the implicit conversion sequences for each of the
7530 // arguments.
7531 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7532 unsigned ConvIdx =
7533 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7534 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7535 // We already formed a conversion sequence for this parameter during
7536 // template argument deduction.
7537 } else if (ArgIdx < NumParams) {
7538 // (C++ 13.3.2p3): for F to be a viable function, there shall
7539 // exist for each argument an implicit conversion sequence
7540 // (13.3.3.1) that converts that argument to the corresponding
7541 // parameter of F.
7542 QualType ParamType = Proto->getParamType(i: ArgIdx);
7543 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7544 if (ParamABI == ParameterABI::HLSLOut ||
7545 ParamABI == ParameterABI::HLSLInOut) {
7546 ParamType = ParamType.getNonReferenceType();
7547 if (ParamABI == ParameterABI::HLSLInOut &&
7548 Args[ArgIdx]->getType().getAddressSpace() ==
7549 LangAS::hlsl_groupshared)
7550 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7551 }
7552 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7553 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7554 /*InOverloadResolution=*/true,
7555 /*AllowObjCWritebackConversion=*/
7556 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7557 if (Candidate.Conversions[ConvIdx].isBad()) {
7558 Candidate.Viable = false;
7559 Candidate.FailureKind = ovl_fail_bad_conversion;
7560 return;
7561 }
7562 } else {
7563 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7564 // argument for which there is no corresponding parameter is
7565 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7566 Candidate.Conversions[ConvIdx].setEllipsis();
7567 }
7568 }
7569
7570 if (EnableIfAttr *FailedAttr =
7571 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7572 Candidate.Viable = false;
7573 Candidate.FailureKind = ovl_fail_enable_if;
7574 Candidate.DeductionFailure.Data = FailedAttr;
7575 return;
7576 }
7577}
7578
7579ObjCMethodDecl *
7580Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7581 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7582 if (Methods.size() <= 1)
7583 return nullptr;
7584
7585 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7586 bool Match = true;
7587 ObjCMethodDecl *Method = Methods[b];
7588 unsigned NumNamedArgs = Sel.getNumArgs();
7589 // Method might have more arguments than selector indicates. This is due
7590 // to addition of c-style arguments in method.
7591 if (Method->param_size() > NumNamedArgs)
7592 NumNamedArgs = Method->param_size();
7593 if (Args.size() < NumNamedArgs)
7594 continue;
7595
7596 for (unsigned i = 0; i < NumNamedArgs; i++) {
7597 // We can't do any type-checking on a type-dependent argument.
7598 if (Args[i]->isTypeDependent()) {
7599 Match = false;
7600 break;
7601 }
7602
7603 ParmVarDecl *param = Method->parameters()[i];
7604 Expr *argExpr = Args[i];
7605 assert(argExpr && "SelectBestMethod(): missing expression");
7606
7607 // Strip the unbridged-cast placeholder expression off unless it's
7608 // a consumed argument.
7609 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7610 !param->hasAttr<CFConsumedAttr>())
7611 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7612
7613 // If the parameter is __unknown_anytype, move on to the next method.
7614 if (param->getType() == Context.UnknownAnyTy) {
7615 Match = false;
7616 break;
7617 }
7618
7619 ImplicitConversionSequence ConversionState
7620 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7621 /*SuppressUserConversions*/false,
7622 /*InOverloadResolution=*/true,
7623 /*AllowObjCWritebackConversion=*/
7624 getLangOpts().ObjCAutoRefCount,
7625 /*AllowExplicit*/false);
7626 // This function looks for a reasonably-exact match, so we consider
7627 // incompatible pointer conversions to be a failure here.
7628 if (ConversionState.isBad() ||
7629 (ConversionState.isStandard() &&
7630 ConversionState.Standard.Second ==
7631 ICK_Incompatible_Pointer_Conversion)) {
7632 Match = false;
7633 break;
7634 }
7635 }
7636 // Promote additional arguments to variadic methods.
7637 if (Match && Method->isVariadic()) {
7638 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7639 if (Args[i]->isTypeDependent()) {
7640 Match = false;
7641 break;
7642 }
7643 ExprResult Arg = DefaultVariadicArgumentPromotion(
7644 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7645 if (Arg.isInvalid()) {
7646 Match = false;
7647 break;
7648 }
7649 }
7650 } else {
7651 // Check for extra arguments to non-variadic methods.
7652 if (Args.size() != NumNamedArgs)
7653 Match = false;
7654 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7655 // Special case when selectors have no argument. In this case, select
7656 // one with the most general result type of 'id'.
7657 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7658 QualType ReturnT = Methods[b]->getReturnType();
7659 if (ReturnT->isObjCIdType())
7660 return Methods[b];
7661 }
7662 }
7663 }
7664
7665 if (Match)
7666 return Method;
7667 }
7668 return nullptr;
7669}
7670
7671static bool convertArgsForAvailabilityChecks(
7672 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7673 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7674 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7675 if (ThisArg) {
7676 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7677 assert(!isa<CXXConstructorDecl>(Method) &&
7678 "Shouldn't have `this` for ctors!");
7679 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7680 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7681 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7682 if (R.isInvalid())
7683 return false;
7684 ConvertedThis = R.get();
7685 } else {
7686 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7687 (void)MD;
7688 assert((MissingImplicitThis || MD->isStatic() ||
7689 isa<CXXConstructorDecl>(MD)) &&
7690 "Expected `this` for non-ctor instance methods");
7691 }
7692 ConvertedThis = nullptr;
7693 }
7694
7695 // Ignore any variadic arguments. Converting them is pointless, since the
7696 // user can't refer to them in the function condition.
7697 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7698
7699 // Convert the arguments.
7700 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7701 ExprResult R;
7702 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7703 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7704 EqualLoc: SourceLocation(), Init: Args[I]);
7705
7706 if (R.isInvalid())
7707 return false;
7708
7709 ConvertedArgs.push_back(Elt: R.get());
7710 }
7711
7712 if (Trap.hasErrorOccurred())
7713 return false;
7714
7715 // Push default arguments if needed.
7716 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7717 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7718 ParmVarDecl *P = Function->getParamDecl(i);
7719 if (!P->hasDefaultArg())
7720 return false;
7721 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7722 if (R.isInvalid())
7723 return false;
7724 ConvertedArgs.push_back(Elt: R.get());
7725 }
7726
7727 if (Trap.hasErrorOccurred())
7728 return false;
7729 }
7730 return true;
7731}
7732
7733EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7734 SourceLocation CallLoc,
7735 ArrayRef<Expr *> Args,
7736 bool MissingImplicitThis) {
7737 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7738 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7739 return nullptr;
7740
7741 SFINAETrap Trap(*this);
7742 // Perform the access checking immediately so any access diagnostics are
7743 // caught by the SFINAE trap.
7744 llvm::scope_exit UndelayDiags(
7745 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7746 DelayedDiagnostics.popUndelayed(state: CurrentState);
7747 });
7748 SmallVector<Expr *, 16> ConvertedArgs;
7749 // FIXME: We should look into making enable_if late-parsed.
7750 Expr *DiscardedThis;
7751 if (!convertArgsForAvailabilityChecks(
7752 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7753 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7754 return *EnableIfAttrs.begin();
7755
7756 for (auto *EIA : EnableIfAttrs) {
7757 APValue Result;
7758 // FIXME: This doesn't consider value-dependent cases, because doing so is
7759 // very difficult. Ideally, we should handle them more gracefully.
7760 if (EIA->getCond()->isValueDependent() ||
7761 !EIA->getCond()->EvaluateWithSubstitution(
7762 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7763 return EIA;
7764
7765 if (!Result.isInt() || !Result.getInt().getBoolValue())
7766 return EIA;
7767 }
7768 return nullptr;
7769}
7770
7771template <typename CheckFn>
7772static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7773 bool ArgDependent, SourceLocation Loc,
7774 CheckFn &&IsSuccessful) {
7775 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7776 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7777 if (ArgDependent == DIA->getArgDependent())
7778 Attrs.push_back(Elt: DIA);
7779 }
7780
7781 // Common case: No diagnose_if attributes, so we can quit early.
7782 if (Attrs.empty())
7783 return false;
7784
7785 auto WarningBegin = std::stable_partition(
7786 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7787 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7788 DIA->getWarningGroup().empty();
7789 });
7790
7791 // Note that diagnose_if attributes are late-parsed, so they appear in the
7792 // correct order (unlike enable_if attributes).
7793 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7794 IsSuccessful);
7795 if (ErrAttr != WarningBegin) {
7796 const DiagnoseIfAttr *DIA = *ErrAttr;
7797 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7798 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7799 << DIA->getParent() << DIA->getCond()->getSourceRange();
7800 return true;
7801 }
7802
7803 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7804 switch (Sev) {
7805 case DiagnoseIfAttr::DS_warning:
7806 return diag::Severity::Warning;
7807 case DiagnoseIfAttr::DS_error:
7808 return diag::Severity::Error;
7809 }
7810 llvm_unreachable("Fully covered switch above!");
7811 };
7812
7813 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7814 if (IsSuccessful(DIA)) {
7815 if (DIA->getWarningGroup().empty() &&
7816 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7817 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7818 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7819 << DIA->getParent() << DIA->getCond()->getSourceRange();
7820 } else {
7821 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7822 DIA->getWarningGroup());
7823 assert(DiagGroup);
7824 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7825 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7826 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7827 S.Diag(Loc, DiagID) << DIA->getMessage();
7828 }
7829 }
7830
7831 return false;
7832}
7833
7834bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7835 const Expr *ThisArg,
7836 ArrayRef<const Expr *> Args,
7837 SourceLocation Loc) {
7838 return diagnoseDiagnoseIfAttrsWith(
7839 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7840 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7841 APValue Result;
7842 // It's sane to use the same Args for any redecl of this function, since
7843 // EvaluateWithSubstitution only cares about the position of each
7844 // argument in the arg list, not the ParmVarDecl* it maps to.
7845 if (!DIA->getCond()->EvaluateWithSubstitution(
7846 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7847 return false;
7848 return Result.isInt() && Result.getInt().getBoolValue();
7849 });
7850}
7851
7852bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7853 SourceLocation Loc) {
7854 return diagnoseDiagnoseIfAttrsWith(
7855 S&: *this, ND, /*ArgDependent=*/false, Loc,
7856 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7857 bool Result;
7858 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7859 Result;
7860 });
7861}
7862
7863void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7864 ArrayRef<Expr *> Args,
7865 OverloadCandidateSet &CandidateSet,
7866 TemplateArgumentListInfo *ExplicitTemplateArgs,
7867 bool SuppressUserConversions,
7868 bool PartialOverloading,
7869 bool FirstArgumentIsBase) {
7870 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7871 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7872 ArrayRef<Expr *> FunctionArgs = Args;
7873
7874 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7875 FunctionDecl *FD =
7876 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7877
7878 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7879 QualType ObjectType;
7880 Expr::Classification ObjectClassification;
7881 if (Args.size() > 0) {
7882 if (Expr *E = Args[0]) {
7883 // Use the explicit base to restrict the lookup:
7884 ObjectType = E->getType();
7885 // Pointers in the object arguments are implicitly dereferenced, so we
7886 // always classify them as l-values.
7887 if (!ObjectType.isNull() && ObjectType->isPointerType())
7888 ObjectClassification = Expr::Classification::makeSimpleLValue();
7889 else
7890 ObjectClassification = E->Classify(Ctx&: Context);
7891 } // .. else there is an implicit base.
7892 FunctionArgs = Args.slice(N: 1);
7893 }
7894 if (FunTmpl) {
7895 AddMethodTemplateCandidate(
7896 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7897 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7898 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7899 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7900 PartialOverloading);
7901 } else {
7902 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7903 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7904 ObjectClassification, Args: FunctionArgs, CandidateSet,
7905 SuppressUserConversions, PartialOverloading);
7906 }
7907 } else {
7908 // This branch handles both standalone functions and static methods.
7909
7910 // Slice the first argument (which is the base) when we access
7911 // static method as non-static.
7912 if (Args.size() > 0 &&
7913 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7914 !isa<CXXConstructorDecl>(Val: FD)))) {
7915 assert(cast<CXXMethodDecl>(FD)->isStatic());
7916 FunctionArgs = Args.slice(N: 1);
7917 }
7918 if (FunTmpl) {
7919 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7920 ExplicitTemplateArgs, Args: FunctionArgs,
7921 CandidateSet, SuppressUserConversions,
7922 PartialOverloading);
7923 } else {
7924 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7925 SuppressUserConversions, PartialOverloading);
7926 }
7927 }
7928 }
7929}
7930
7931void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7932 Expr::Classification ObjectClassification,
7933 ArrayRef<Expr *> Args,
7934 OverloadCandidateSet &CandidateSet,
7935 bool SuppressUserConversions,
7936 OverloadCandidateParamOrder PO) {
7937 NamedDecl *Decl = FoundDecl.getDecl();
7938 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7939
7940 if (isa<UsingShadowDecl>(Val: Decl))
7941 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7942
7943 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7944 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7945 "Expected a member function template");
7946 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7947 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7948 ObjectClassification, Args, CandidateSet,
7949 SuppressUserConversions, PartialOverloading: false, PO);
7950 } else {
7951 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7952 ObjectType, ObjectClassification, Args, CandidateSet,
7953 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7954 }
7955}
7956
7957void Sema::AddMethodCandidate(
7958 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7959 CXXRecordDecl *ActingContext, QualType ObjectType,
7960 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7961 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7962 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7963 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7964 const FunctionProtoType *Proto
7965 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7966 assert(Proto && "Methods without a prototype cannot be overloaded");
7967 assert(!isa<CXXConstructorDecl>(Method) &&
7968 "Use AddOverloadCandidate for constructors");
7969
7970 if (!CandidateSet.isNewCandidate(F: Method, PO))
7971 return;
7972
7973 // C++11 [class.copy]p23: [DR1402]
7974 // A defaulted move assignment operator that is defined as deleted is
7975 // ignored by overload resolution.
7976 if (Method->isDefaulted() && Method->isDeleted() &&
7977 Method->isMoveAssignmentOperator())
7978 return;
7979
7980 // Overload resolution is always an unevaluated context.
7981 EnterExpressionEvaluationContext Unevaluated(
7982 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7983
7984 bool IgnoreExplicitObject =
7985 (Method->isExplicitObjectMemberFunction() &&
7986 CandidateSet.getKind() ==
7987 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7988 bool ImplicitObjectMethodTreatedAsStatic =
7989 CandidateSet.getKind() ==
7990 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7991 Method->isImplicitObjectMemberFunction();
7992
7993 unsigned ExplicitOffset =
7994 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7995
7996 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7997 int(ImplicitObjectMethodTreatedAsStatic);
7998
7999 unsigned ExtraArgs =
8000 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
8001 ? 0
8002 : 1;
8003
8004 // Add this candidate
8005 OverloadCandidate &Candidate =
8006 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
8007 Candidate.FoundDecl = FoundDecl;
8008 Candidate.Function = Method;
8009 Candidate.RewriteKind =
8010 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
8011 Candidate.TookAddressOfOverload =
8012 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8013 Candidate.ExplicitCallArguments = Args.size();
8014 Candidate.StrictPackMatch = StrictPackMatch;
8015
8016 // (C++ 13.3.2p2): A candidate function having fewer than m
8017 // parameters is viable only if it has an ellipsis in its parameter
8018 // list (8.3.5).
8019 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
8020 !Proto->isVariadic() &&
8021 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
8022 Candidate.Viable = false;
8023 Candidate.FailureKind = ovl_fail_too_many_arguments;
8024 return;
8025 }
8026
8027 // (C++ 13.3.2p2): A candidate function having more than m parameters
8028 // is viable only if the (m+1)st parameter has a default argument
8029 // (8.3.6). For the purposes of overload resolution, the
8030 // parameter list is truncated on the right, so that there are
8031 // exactly m parameters.
8032 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8033 ExplicitOffset +
8034 int(ImplicitObjectMethodTreatedAsStatic);
8035
8036 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8037 // Not enough arguments.
8038 Candidate.Viable = false;
8039 Candidate.FailureKind = ovl_fail_too_few_arguments;
8040 return;
8041 }
8042
8043 Candidate.Viable = true;
8044
8045 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8046 if (!IgnoreExplicitObject) {
8047 if (ObjectType.isNull())
8048 Candidate.IgnoreObjectArgument = true;
8049 else if (Method->isStatic()) {
8050 // [over.best.ics.general]p8
8051 // When the parameter is the implicit object parameter of a static member
8052 // function, the implicit conversion sequence is a standard conversion
8053 // sequence that is neither better nor worse than any other standard
8054 // conversion sequence.
8055 //
8056 // This is a rule that was introduced in C++23 to support static lambdas.
8057 // We apply it retroactively because we want to support static lambdas as
8058 // an extension and it doesn't hurt previous code.
8059 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8060 } else {
8061 // Determine the implicit conversion sequence for the object
8062 // parameter.
8063 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8064 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8065 Method, ActingContext, /*InOverloadResolution=*/true);
8066 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8067 Candidate.Viable = false;
8068 Candidate.FailureKind = ovl_fail_bad_conversion;
8069 return;
8070 }
8071 }
8072 }
8073
8074 // (CUDA B.1): Check for invalid calls between targets.
8075 if (getLangOpts().CUDA)
8076 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8077 Callee: Method)) {
8078 Candidate.Viable = false;
8079 Candidate.FailureKind = ovl_fail_bad_target;
8080 return;
8081 }
8082
8083 if (Method->getTrailingRequiresClause()) {
8084 ConstraintSatisfaction Satisfaction;
8085 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8086 /*ForOverloadResolution*/ true) ||
8087 !Satisfaction.IsSatisfied) {
8088 Candidate.Viable = false;
8089 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8090 return;
8091 }
8092 }
8093
8094 // Determine the implicit conversion sequences for each of the
8095 // arguments.
8096 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8097 unsigned ConvIdx =
8098 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8099 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8100 // We already formed a conversion sequence for this parameter during
8101 // template argument deduction.
8102 } else if (ArgIdx < NumParams) {
8103 // (C++ 13.3.2p3): for F to be a viable function, there shall
8104 // exist for each argument an implicit conversion sequence
8105 // (13.3.3.1) that converts that argument to the corresponding
8106 // parameter of F.
8107 QualType ParamType;
8108 if (ImplicitObjectMethodTreatedAsStatic) {
8109 ParamType = ArgIdx == 0
8110 ? Method->getFunctionObjectParameterReferenceType()
8111 : Proto->getParamType(i: ArgIdx - 1);
8112 } else {
8113 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8114 }
8115 Candidate.Conversions[ConvIdx]
8116 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8117 SuppressUserConversions,
8118 /*InOverloadResolution=*/true,
8119 /*AllowObjCWritebackConversion=*/
8120 getLangOpts().ObjCAutoRefCount);
8121 if (Candidate.Conversions[ConvIdx].isBad()) {
8122 Candidate.Viable = false;
8123 Candidate.FailureKind = ovl_fail_bad_conversion;
8124 return;
8125 }
8126 } else {
8127 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8128 // argument for which there is no corresponding parameter is
8129 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8130 Candidate.Conversions[ConvIdx].setEllipsis();
8131 }
8132 }
8133
8134 if (EnableIfAttr *FailedAttr =
8135 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8136 Candidate.Viable = false;
8137 Candidate.FailureKind = ovl_fail_enable_if;
8138 Candidate.DeductionFailure.Data = FailedAttr;
8139 return;
8140 }
8141
8142 if (isNonViableMultiVersionOverload(FD: Method)) {
8143 Candidate.Viable = false;
8144 Candidate.FailureKind = ovl_non_default_multiversion_function;
8145 }
8146}
8147
8148static void AddMethodTemplateCandidateImmediately(
8149 Sema &S, OverloadCandidateSet &CandidateSet,
8150 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8151 CXXRecordDecl *ActingContext,
8152 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8153 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8154 bool SuppressUserConversions, bool PartialOverloading,
8155 OverloadCandidateParamOrder PO) {
8156
8157 // C++ [over.match.funcs]p7:
8158 // In each case where a candidate is a function template, candidate
8159 // function template specializations are generated using template argument
8160 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8161 // candidate functions in the usual way.113) A given name can refer to one
8162 // or more function templates and also to a set of overloaded non-template
8163 // functions. In such a case, the candidate functions generated from each
8164 // function template are combined with the set of non-template candidate
8165 // functions.
8166 TemplateDeductionInfo Info(CandidateSet.getLocation());
8167 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8168 FunctionDecl *Specialization = nullptr;
8169 ConversionSequenceList Conversions;
8170 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8171 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8172 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8173 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8174 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8175 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8176 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8177 bool OnlyInitializeNonUserDefinedConversions) {
8178 return S.CheckNonDependentConversions(
8179 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8180 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8181 SuppressUserConversions,
8182 OnlyInitializeNonUserDefinedConversions),
8183 ActingContext, ObjectType, ObjectClassification, PO);
8184 });
8185 Result != TemplateDeductionResult::Success) {
8186 OverloadCandidate &Candidate =
8187 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8188 Candidate.FoundDecl = FoundDecl;
8189 Candidate.Function = Method;
8190 Candidate.Viable = false;
8191 Candidate.RewriteKind =
8192 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8193 Candidate.IsSurrogate = false;
8194 Candidate.TookAddressOfOverload =
8195 CandidateSet.getKind() ==
8196 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8197
8198 Candidate.IgnoreObjectArgument =
8199 Method->isStatic() ||
8200 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8201 Candidate.ExplicitCallArguments = Args.size();
8202 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8203 Candidate.FailureKind = ovl_fail_bad_conversion;
8204 else {
8205 Candidate.FailureKind = ovl_fail_bad_deduction;
8206 Candidate.DeductionFailure =
8207 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8208 }
8209 return;
8210 }
8211
8212 // Add the function template specialization produced by template argument
8213 // deduction as a candidate.
8214 assert(Specialization && "Missing member function template specialization?");
8215 assert(isa<CXXMethodDecl>(Specialization) &&
8216 "Specialization is not a member function?");
8217 S.AddMethodCandidate(
8218 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8219 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8220 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8221}
8222
8223void Sema::AddMethodTemplateCandidate(
8224 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8225 CXXRecordDecl *ActingContext,
8226 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8227 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8228 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8229 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8230 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8231 return;
8232
8233 if (ExplicitTemplateArgs ||
8234 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this)) {
8235 AddMethodTemplateCandidateImmediately(
8236 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8237 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8238 SuppressUserConversions, PartialOverloading, PO);
8239 return;
8240 }
8241
8242 CandidateSet.AddDeferredMethodTemplateCandidate(
8243 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8244 Args, SuppressUserConversions, PartialOverloading, PO);
8245}
8246
8247/// Determine whether a given function template has a simple explicit specifier
8248/// or a non-value-dependent explicit-specification that evaluates to true.
8249static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8250 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8251}
8252
8253static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8254 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8255 ExplicitSpecKind::Unresolved;
8256}
8257
8258static void AddTemplateOverloadCandidateImmediately(
8259 Sema &S, OverloadCandidateSet &CandidateSet,
8260 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8261 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8262 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8263 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8264 bool AggregateCandidateDeduction) {
8265
8266 // If the function template has a non-dependent explicit specification,
8267 // exclude it now if appropriate; we are not permitted to perform deduction
8268 // and substitution in this case.
8269 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8270 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8271 Candidate.FoundDecl = FoundDecl;
8272 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8273 Candidate.Viable = false;
8274 Candidate.FailureKind = ovl_fail_explicit;
8275 return;
8276 }
8277
8278 // C++ [over.match.funcs]p7:
8279 // In each case where a candidate is a function template, candidate
8280 // function template specializations are generated using template argument
8281 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8282 // candidate functions in the usual way.113) A given name can refer to one
8283 // or more function templates and also to a set of overloaded non-template
8284 // functions. In such a case, the candidate functions generated from each
8285 // function template are combined with the set of non-template candidate
8286 // functions.
8287 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8288 FunctionTemplate->getTemplateDepth());
8289 FunctionDecl *Specialization = nullptr;
8290 ConversionSequenceList Conversions;
8291 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8292 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8293 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8294 /*PartialOrdering=*/false,
8295 /*ObjectType=*/QualType(),
8296 /*ObjectClassification=*/Expr::Classification(),
8297 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8298 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8299 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8300 bool OnlyInitializeNonUserDefinedConversions) {
8301 return S.CheckNonDependentConversions(
8302 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8303 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8304 SuppressUserConversions,
8305 OnlyInitializeNonUserDefinedConversions),
8306 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8307 });
8308 Result != TemplateDeductionResult::Success) {
8309 OverloadCandidate &Candidate =
8310 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8311 Candidate.FoundDecl = FoundDecl;
8312 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8313 Candidate.Viable = false;
8314 Candidate.RewriteKind =
8315 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8316 Candidate.IsSurrogate = false;
8317 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8318 // Ignore the object argument if there is one, since we don't have an object
8319 // type.
8320 Candidate.TookAddressOfOverload =
8321 CandidateSet.getKind() ==
8322 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8323
8324 Candidate.IgnoreObjectArgument =
8325 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8326 !cast<CXXMethodDecl>(Val: Candidate.Function)
8327 ->isExplicitObjectMemberFunction() &&
8328 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8329
8330 Candidate.ExplicitCallArguments = Args.size();
8331 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8332 Candidate.FailureKind = ovl_fail_bad_conversion;
8333 else {
8334 Candidate.FailureKind = ovl_fail_bad_deduction;
8335 Candidate.DeductionFailure =
8336 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8337 }
8338 return;
8339 }
8340
8341 // Add the function template specialization produced by template argument
8342 // deduction as a candidate.
8343 assert(Specialization && "Missing function template specialization?");
8344 S.AddOverloadCandidate(
8345 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8346 PartialOverloading, AllowExplicit,
8347 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8348 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8349 StrictPackMatch: Info.hasStrictPackMatch());
8350}
8351
8352void Sema::AddTemplateOverloadCandidate(
8353 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8354 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8355 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8356 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8357 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8358 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8359 return;
8360
8361 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8362
8363 if (ExplicitTemplateArgs ||
8364 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8365 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8366 DependentExplicitSpecifier)) {
8367
8368 AddTemplateOverloadCandidateImmediately(
8369 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8370 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8371 IsADLCandidate, PO, AggregateCandidateDeduction);
8372
8373 if (DependentExplicitSpecifier)
8374 CandidateSet.DisableResolutionByPerfectCandidate();
8375 return;
8376 }
8377
8378 CandidateSet.AddDeferredTemplateCandidate(
8379 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8380 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8381 AggregateCandidateDeduction);
8382}
8383
8384bool Sema::CheckNonDependentConversions(
8385 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8386 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8387 ConversionSequenceList &Conversions,
8388 CheckNonDependentConversionsFlag UserConversionFlag,
8389 CXXRecordDecl *ActingContext, QualType ObjectType,
8390 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8391 // FIXME: The cases in which we allow explicit conversions for constructor
8392 // arguments never consider calling a constructor template. It's not clear
8393 // that is correct.
8394 const bool AllowExplicit = false;
8395
8396 bool ForOverloadSetAddressResolution =
8397 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8398 auto *FD = FunctionTemplate->getTemplatedDecl();
8399 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8400 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8401 !isa<CXXConstructorDecl>(Val: Method);
8402 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8403
8404 if (Conversions.empty())
8405 Conversions =
8406 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8407
8408 // Overload resolution is always an unevaluated context.
8409 EnterExpressionEvaluationContext Unevaluated(
8410 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8411
8412 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8413 // require that, but this check should never result in a hard error, and
8414 // overload resolution is permitted to sidestep instantiations.
8415 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8416 !ObjectType.isNull()) {
8417 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8418 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8419 !ParamTypes[0]->isDependentType()) {
8420 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8421 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8422 Method, ActingContext, /*InOverloadResolution=*/true,
8423 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8424 : QualType());
8425 if (Conversions[ConvIdx].isBad())
8426 return true;
8427 }
8428 }
8429
8430 // A speculative workaround for self-dependent constraint bugs that manifest
8431 // after CWG2369.
8432 // FIXME: Add references to the standard once P3606 is adopted.
8433 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8434 QualType ArgType) {
8435 ParamType = ParamType.getNonReferenceType();
8436 ArgType = ArgType.getNonReferenceType();
8437 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8438 if (PointerConv) {
8439 ParamType = ParamType->getPointeeType();
8440 ArgType = ArgType->getPointeeType();
8441 }
8442
8443 if (auto *RD = ParamType->getAsCXXRecordDecl();
8444 RD && RD->hasDefinition() &&
8445 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8446 auto Info = getConstructorInfo(ND);
8447 if (!Info)
8448 return false;
8449 CXXConstructorDecl *Ctor = Info.Constructor;
8450 /// isConvertingConstructor takes copy/move constructors into
8451 /// account!
8452 return !Ctor->isCopyOrMoveConstructor() &&
8453 Ctor->isConvertingConstructor(
8454 /*AllowExplicit=*/true);
8455 }))
8456 return true;
8457 if (auto *RD = ArgType->getAsCXXRecordDecl();
8458 RD && RD->hasDefinition() &&
8459 !RD->getVisibleConversionFunctions().empty())
8460 return true;
8461
8462 return false;
8463 };
8464
8465 unsigned Offset =
8466 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8467 : 0;
8468
8469 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8470 I != N; ++I) {
8471 QualType ParamType = ParamTypes[I + Offset];
8472 if (!ParamType->isDependentType()) {
8473 unsigned ConvIdx;
8474 if (PO == OverloadCandidateParamOrder::Reversed) {
8475 ConvIdx = Args.size() - 1 - I;
8476 assert(Args.size() + ThisConversions == 2 &&
8477 "number of args (including 'this') must be exactly 2 for "
8478 "reversed order");
8479 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8480 // would also be 0. 'this' got ConvIdx = 1 previously.
8481 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8482 } else {
8483 // For members, 'this' got ConvIdx = 0 previously.
8484 ConvIdx = ThisConversions + I;
8485 }
8486 if (Conversions[ConvIdx].isInitialized())
8487 continue;
8488 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8489 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8490 continue;
8491 Conversions[ConvIdx] = TryCopyInitialization(
8492 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8493 /*InOverloadResolution=*/true,
8494 /*AllowObjCWritebackConversion=*/
8495 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8496 if (Conversions[ConvIdx].isBad())
8497 return true;
8498 }
8499 }
8500
8501 return false;
8502}
8503
8504/// Determine whether this is an allowable conversion from the result
8505/// of an explicit conversion operator to the expected type, per C++
8506/// [over.match.conv]p1 and [over.match.ref]p1.
8507///
8508/// \param ConvType The return type of the conversion function.
8509///
8510/// \param ToType The type we are converting to.
8511///
8512/// \param AllowObjCPointerConversion Allow a conversion from one
8513/// Objective-C pointer to another.
8514///
8515/// \returns true if the conversion is allowable, false otherwise.
8516static bool isAllowableExplicitConversion(Sema &S,
8517 QualType ConvType, QualType ToType,
8518 bool AllowObjCPointerConversion) {
8519 QualType ToNonRefType = ToType.getNonReferenceType();
8520
8521 // Easy case: the types are the same.
8522 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8523 return true;
8524
8525 // Allow qualification conversions.
8526 bool ObjCLifetimeConversion;
8527 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8528 ObjCLifetimeConversion))
8529 return true;
8530
8531 // If we're not allowed to consider Objective-C pointer conversions,
8532 // we're done.
8533 if (!AllowObjCPointerConversion)
8534 return false;
8535
8536 // Is this an Objective-C pointer conversion?
8537 bool IncompatibleObjC = false;
8538 QualType ConvertedType;
8539 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8540 IncompatibleObjC);
8541}
8542
8543void Sema::AddConversionCandidate(
8544 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8545 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8546 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8547 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8548 assert(!Conversion->getDescribedFunctionTemplate() &&
8549 "Conversion function templates use AddTemplateConversionCandidate");
8550 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8551 if (!CandidateSet.isNewCandidate(F: Conversion))
8552 return;
8553
8554 // If the conversion function has an undeduced return type, trigger its
8555 // deduction now.
8556 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8557 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8558 return;
8559 ConvType = Conversion->getConversionType().getNonReferenceType();
8560 }
8561
8562 // If we don't allow any conversion of the result type, ignore conversion
8563 // functions that don't convert to exactly (possibly cv-qualified) T.
8564 if (!AllowResultConversion &&
8565 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8566 return;
8567
8568 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8569 // operator is only a candidate if its return type is the target type or
8570 // can be converted to the target type with a qualification conversion.
8571 //
8572 // FIXME: Include such functions in the candidate list and explain why we
8573 // can't select them.
8574 if (Conversion->isExplicit() &&
8575 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8576 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8577 return;
8578
8579 // Overload resolution is always an unevaluated context.
8580 EnterExpressionEvaluationContext Unevaluated(
8581 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8582
8583 // Add this candidate
8584 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8585 Candidate.FoundDecl = FoundDecl;
8586 Candidate.Function = Conversion;
8587 Candidate.FinalConversion.setAsIdentityConversion();
8588 Candidate.FinalConversion.setFromType(ConvType);
8589 Candidate.FinalConversion.setAllToTypes(ToType);
8590 Candidate.HasFinalConversion = true;
8591 Candidate.Viable = true;
8592 Candidate.ExplicitCallArguments = 1;
8593 Candidate.StrictPackMatch = StrictPackMatch;
8594
8595 // Explicit functions are not actually candidates at all if we're not
8596 // allowing them in this context, but keep them around so we can point
8597 // to them in diagnostics.
8598 if (!AllowExplicit && Conversion->isExplicit()) {
8599 Candidate.Viable = false;
8600 Candidate.FailureKind = ovl_fail_explicit;
8601 return;
8602 }
8603
8604 // C++ [over.match.funcs]p4:
8605 // For conversion functions, the function is considered to be a member of
8606 // the class of the implicit implied object argument for the purpose of
8607 // defining the type of the implicit object parameter.
8608 //
8609 // Determine the implicit conversion sequence for the implicit
8610 // object parameter.
8611 QualType ObjectType = From->getType();
8612 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8613 ObjectType = FromPtrType->getPointeeType();
8614 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8615 // C++23 [over.best.ics.general]
8616 // However, if the target is [...]
8617 // - the object parameter of a user-defined conversion function
8618 // [...] user-defined conversion sequences are not considered.
8619 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8620 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8621 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8622 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8623 /*SuppressUserConversion*/ true);
8624
8625 if (Candidate.Conversions[0].isBad()) {
8626 Candidate.Viable = false;
8627 Candidate.FailureKind = ovl_fail_bad_conversion;
8628 return;
8629 }
8630
8631 if (Conversion->getTrailingRequiresClause()) {
8632 ConstraintSatisfaction Satisfaction;
8633 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8634 !Satisfaction.IsSatisfied) {
8635 Candidate.Viable = false;
8636 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8637 return;
8638 }
8639 }
8640
8641 // We won't go through a user-defined type conversion function to convert a
8642 // derived to base as such conversions are given Conversion Rank. They only
8643 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8644 QualType FromCanon
8645 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8646 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8647 if (FromCanon == ToCanon ||
8648 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8649 Candidate.Viable = false;
8650 Candidate.FailureKind = ovl_fail_trivial_conversion;
8651 return;
8652 }
8653
8654 // To determine what the conversion from the result of calling the
8655 // conversion function to the type we're eventually trying to
8656 // convert to (ToType), we need to synthesize a call to the
8657 // conversion function and attempt copy initialization from it. This
8658 // makes sure that we get the right semantics with respect to
8659 // lvalues/rvalues and the type. Fortunately, we can allocate this
8660 // call on the stack and we don't need its arguments to be
8661 // well-formed.
8662 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8663 VK_LValue, From->getBeginLoc());
8664 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8665 Context.getPointerType(T: Conversion->getType()),
8666 CK_FunctionToPointerDecay, &ConversionRef,
8667 VK_PRValue, FPOptionsOverride());
8668
8669 QualType ConversionType = Conversion->getConversionType();
8670 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8671 Candidate.Viable = false;
8672 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8673 return;
8674 }
8675
8676 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8677
8678 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8679
8680 // Introduce a temporary expression with the right type and value category
8681 // that we can use for deduction purposes.
8682 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8683
8684 ImplicitConversionSequence ICS =
8685 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8686 /*SuppressUserConversions=*/true,
8687 /*InOverloadResolution=*/false,
8688 /*AllowObjCWritebackConversion=*/false);
8689
8690 switch (ICS.getKind()) {
8691 case ImplicitConversionSequence::StandardConversion:
8692 Candidate.FinalConversion = ICS.Standard;
8693 Candidate.HasFinalConversion = true;
8694
8695 // C++ [over.ics.user]p3:
8696 // If the user-defined conversion is specified by a specialization of a
8697 // conversion function template, the second standard conversion sequence
8698 // shall have exact match rank.
8699 if (Conversion->getPrimaryTemplate() &&
8700 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8701 Candidate.Viable = false;
8702 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8703 return;
8704 }
8705
8706 // C++0x [dcl.init.ref]p5:
8707 // In the second case, if the reference is an rvalue reference and
8708 // the second standard conversion sequence of the user-defined
8709 // conversion sequence includes an lvalue-to-rvalue conversion, the
8710 // program is ill-formed.
8711 if (ToType->isRValueReferenceType() &&
8712 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8713 Candidate.Viable = false;
8714 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8715 return;
8716 }
8717 break;
8718
8719 case ImplicitConversionSequence::BadConversion:
8720 Candidate.Viable = false;
8721 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8722 return;
8723
8724 default:
8725 llvm_unreachable(
8726 "Can only end up with a standard conversion sequence or failure");
8727 }
8728
8729 if (EnableIfAttr *FailedAttr =
8730 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8731 Candidate.Viable = false;
8732 Candidate.FailureKind = ovl_fail_enable_if;
8733 Candidate.DeductionFailure.Data = FailedAttr;
8734 return;
8735 }
8736
8737 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8738 Candidate.Viable = false;
8739 Candidate.FailureKind = ovl_non_default_multiversion_function;
8740 }
8741}
8742
8743static void AddTemplateConversionCandidateImmediately(
8744 Sema &S, OverloadCandidateSet &CandidateSet,
8745 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8746 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8747 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8748 bool AllowResultConversion) {
8749
8750 // If the function template has a non-dependent explicit specification,
8751 // exclude it now if appropriate; we are not permitted to perform deduction
8752 // and substitution in this case.
8753 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8754 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8755 Candidate.FoundDecl = FoundDecl;
8756 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8757 Candidate.Viable = false;
8758 Candidate.FailureKind = ovl_fail_explicit;
8759 return;
8760 }
8761
8762 QualType ObjectType = From->getType();
8763 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8764
8765 TemplateDeductionInfo Info(CandidateSet.getLocation());
8766 CXXConversionDecl *Specialization = nullptr;
8767 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8768 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8769 Specialization, Info);
8770 Result != TemplateDeductionResult::Success) {
8771 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8772 Candidate.FoundDecl = FoundDecl;
8773 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8774 Candidate.Viable = false;
8775 Candidate.FailureKind = ovl_fail_bad_deduction;
8776 Candidate.ExplicitCallArguments = 1;
8777 Candidate.DeductionFailure =
8778 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8779 return;
8780 }
8781
8782 // Add the conversion function template specialization produced by
8783 // template argument deduction as a candidate.
8784 assert(Specialization && "Missing function template specialization?");
8785 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8786 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8787 AllowExplicit, AllowResultConversion,
8788 StrictPackMatch: Info.hasStrictPackMatch());
8789}
8790
8791void Sema::AddTemplateConversionCandidate(
8792 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8793 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8794 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8795 bool AllowExplicit, bool AllowResultConversion) {
8796 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8797 "Only conversion function templates permitted here");
8798
8799 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8800 return;
8801
8802 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8803 CandidateSet.getKind() ==
8804 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8805 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8806 AddTemplateConversionCandidateImmediately(
8807 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8808 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8809 AllowResultConversion);
8810
8811 CandidateSet.DisableResolutionByPerfectCandidate();
8812 return;
8813 }
8814
8815 CandidateSet.AddDeferredConversionTemplateCandidate(
8816 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8817 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8818}
8819
8820void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8821 DeclAccessPair FoundDecl,
8822 CXXRecordDecl *ActingContext,
8823 const FunctionProtoType *Proto,
8824 Expr *Object,
8825 ArrayRef<Expr *> Args,
8826 OverloadCandidateSet& CandidateSet) {
8827 if (!CandidateSet.isNewCandidate(F: Conversion))
8828 return;
8829
8830 // Overload resolution is always an unevaluated context.
8831 EnterExpressionEvaluationContext Unevaluated(
8832 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8833
8834 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8835 Candidate.FoundDecl = FoundDecl;
8836 Candidate.Function = nullptr;
8837 Candidate.Surrogate = Conversion;
8838 Candidate.IsSurrogate = true;
8839 Candidate.Viable = true;
8840 Candidate.ExplicitCallArguments = Args.size();
8841
8842 // Determine the implicit conversion sequence for the implicit
8843 // object parameter.
8844 ImplicitConversionSequence ObjectInit;
8845 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8846 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8847 ToType: Conversion->getParamDecl(i: 0)->getType(),
8848 /*SuppressUserConversions=*/false,
8849 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8850 } else {
8851 ObjectInit = TryObjectArgumentInitialization(
8852 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8853 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8854 }
8855
8856 if (ObjectInit.isBad()) {
8857 Candidate.Viable = false;
8858 Candidate.FailureKind = ovl_fail_bad_conversion;
8859 Candidate.Conversions[0] = ObjectInit;
8860 return;
8861 }
8862
8863 // The first conversion is actually a user-defined conversion whose
8864 // first conversion is ObjectInit's standard conversion (which is
8865 // effectively a reference binding). Record it as such.
8866 Candidate.Conversions[0].setUserDefined();
8867 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8868 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8869 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8870 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8871 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8872 Candidate.Conversions[0].UserDefined.After
8873 = Candidate.Conversions[0].UserDefined.Before;
8874 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8875
8876 // Find the
8877 unsigned NumParams = Proto->getNumParams();
8878
8879 // (C++ 13.3.2p2): A candidate function having fewer than m
8880 // parameters is viable only if it has an ellipsis in its parameter
8881 // list (8.3.5).
8882 if (Args.size() > NumParams && !Proto->isVariadic()) {
8883 Candidate.Viable = false;
8884 Candidate.FailureKind = ovl_fail_too_many_arguments;
8885 return;
8886 }
8887
8888 // Function types don't have any default arguments, so just check if
8889 // we have enough arguments.
8890 if (Args.size() < NumParams) {
8891 // Not enough arguments.
8892 Candidate.Viable = false;
8893 Candidate.FailureKind = ovl_fail_too_few_arguments;
8894 return;
8895 }
8896
8897 // Determine the implicit conversion sequences for each of the
8898 // arguments.
8899 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8900 if (ArgIdx < NumParams) {
8901 // (C++ 13.3.2p3): for F to be a viable function, there shall
8902 // exist for each argument an implicit conversion sequence
8903 // (13.3.3.1) that converts that argument to the corresponding
8904 // parameter of F.
8905 QualType ParamType = Proto->getParamType(i: ArgIdx);
8906 Candidate.Conversions[ArgIdx + 1]
8907 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8908 /*SuppressUserConversions=*/false,
8909 /*InOverloadResolution=*/false,
8910 /*AllowObjCWritebackConversion=*/
8911 getLangOpts().ObjCAutoRefCount);
8912 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8913 Candidate.Viable = false;
8914 Candidate.FailureKind = ovl_fail_bad_conversion;
8915 return;
8916 }
8917 } else {
8918 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8919 // argument for which there is no corresponding parameter is
8920 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8921 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8922 }
8923 }
8924
8925 if (Conversion->getTrailingRequiresClause()) {
8926 ConstraintSatisfaction Satisfaction;
8927 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8928 /*ForOverloadResolution*/ true) ||
8929 !Satisfaction.IsSatisfied) {
8930 Candidate.Viable = false;
8931 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8932 return;
8933 }
8934 }
8935
8936 if (EnableIfAttr *FailedAttr =
8937 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8938 Candidate.Viable = false;
8939 Candidate.FailureKind = ovl_fail_enable_if;
8940 Candidate.DeductionFailure.Data = FailedAttr;
8941 return;
8942 }
8943}
8944
8945void Sema::AddNonMemberOperatorCandidates(
8946 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8947 OverloadCandidateSet &CandidateSet,
8948 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8949 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8950 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8951 ArrayRef<Expr *> FunctionArgs = Args;
8952
8953 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8954 FunctionDecl *FD =
8955 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8956
8957 // Don't consider rewritten functions if we're not rewriting.
8958 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8959 continue;
8960
8961 assert(!isa<CXXMethodDecl>(FD) &&
8962 "unqualified operator lookup found a member function");
8963
8964 if (FunTmpl) {
8965 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8966 Args: FunctionArgs, CandidateSet);
8967 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8968
8969 // As template candidates are not deduced immediately,
8970 // persist the array in the overload set.
8971 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8972 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8973 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8974 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8975 IsADLCandidate: ADLCallKind::NotADL,
8976 PO: OverloadCandidateParamOrder::Reversed);
8977 }
8978 } else {
8979 if (ExplicitTemplateArgs)
8980 continue;
8981 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8982 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8983 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8984 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8985 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8986 PO: OverloadCandidateParamOrder::Reversed);
8987 }
8988 }
8989}
8990
8991void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8992 SourceLocation OpLoc,
8993 ArrayRef<Expr *> Args,
8994 OverloadCandidateSet &CandidateSet,
8995 OverloadCandidateParamOrder PO) {
8996 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8997
8998 // C++ [over.match.oper]p3:
8999 // For a unary operator @ with an operand of a type whose
9000 // cv-unqualified version is T1, and for a binary operator @ with
9001 // a left operand of a type whose cv-unqualified version is T1 and
9002 // a right operand of a type whose cv-unqualified version is T2,
9003 // three sets of candidate functions, designated member
9004 // candidates, non-member candidates and built-in candidates, are
9005 // constructed as follows:
9006 QualType T1 = Args[0]->getType();
9007
9008 // -- If T1 is a complete class type or a class currently being
9009 // defined, the set of member candidates is the result of the
9010 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9011 // the set of member candidates is empty.
9012 if (T1->isRecordType()) {
9013 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
9014 auto *T1RD = T1->getAsCXXRecordDecl();
9015 // Complete the type if it can be completed.
9016 // If the type is neither complete nor being defined, bail out now.
9017 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9018 return;
9019
9020 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9021 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
9022 Operators.suppressAccessDiagnostics();
9023
9024 for (LookupResult::iterator Oper = Operators.begin(),
9025 OperEnd = Operators.end();
9026 Oper != OperEnd; ++Oper) {
9027 if (Oper->getAsFunction() &&
9028 PO == OverloadCandidateParamOrder::Reversed &&
9029 !CandidateSet.getRewriteInfo().shouldAddReversed(
9030 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
9031 continue;
9032 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
9033 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
9034 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
9035 }
9036 }
9037}
9038
9039void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
9040 OverloadCandidateSet& CandidateSet,
9041 bool IsAssignmentOperator,
9042 unsigned NumContextualBoolArguments) {
9043 // Overload resolution is always an unevaluated context.
9044 EnterExpressionEvaluationContext Unevaluated(
9045 *this, Sema::ExpressionEvaluationContext::Unevaluated);
9046
9047 // Add this candidate
9048 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
9049 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
9050 Candidate.Function = nullptr;
9051 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
9052
9053 // Determine the implicit conversion sequences for each of the
9054 // arguments.
9055 Candidate.Viable = true;
9056 Candidate.ExplicitCallArguments = Args.size();
9057 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9058 // C++ [over.match.oper]p4:
9059 // For the built-in assignment operators, conversions of the
9060 // left operand are restricted as follows:
9061 // -- no temporaries are introduced to hold the left operand, and
9062 // -- no user-defined conversions are applied to the left
9063 // operand to achieve a type match with the left-most
9064 // parameter of a built-in candidate.
9065 //
9066 // We block these conversions by turning off user-defined
9067 // conversions, since that is the only way that initialization of
9068 // a reference to a non-class type can occur from something that
9069 // is not of the same type.
9070 if (ArgIdx < NumContextualBoolArguments) {
9071 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9072 "Contextual conversion to bool requires bool type");
9073 Candidate.Conversions[ArgIdx]
9074 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9075 } else {
9076 Candidate.Conversions[ArgIdx]
9077 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9078 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9079 /*InOverloadResolution=*/false,
9080 /*AllowObjCWritebackConversion=*/
9081 getLangOpts().ObjCAutoRefCount);
9082 }
9083 if (Candidate.Conversions[ArgIdx].isBad()) {
9084 Candidate.Viable = false;
9085 Candidate.FailureKind = ovl_fail_bad_conversion;
9086 break;
9087 }
9088 }
9089}
9090
9091namespace {
9092
9093/// BuiltinCandidateTypeSet - A set of types that will be used for the
9094/// candidate operator functions for built-in operators (C++
9095/// [over.built]). The types are separated into pointer types and
9096/// enumeration types.
9097class BuiltinCandidateTypeSet {
9098 /// TypeSet - A set of types.
9099 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9100
9101 /// PointerTypes - The set of pointer types that will be used in the
9102 /// built-in candidates.
9103 TypeSet PointerTypes;
9104
9105 /// MemberPointerTypes - The set of member pointer types that will be
9106 /// used in the built-in candidates.
9107 TypeSet MemberPointerTypes;
9108
9109 /// EnumerationTypes - The set of enumeration types that will be
9110 /// used in the built-in candidates.
9111 TypeSet EnumerationTypes;
9112
9113 /// The set of vector types that will be used in the built-in
9114 /// candidates.
9115 TypeSet VectorTypes;
9116
9117 /// The set of matrix types that will be used in the built-in
9118 /// candidates.
9119 TypeSet MatrixTypes;
9120
9121 /// The set of _BitInt types that will be used in the built-in candidates.
9122 TypeSet BitIntTypes;
9123
9124 /// A flag indicating non-record types are viable candidates
9125 bool HasNonRecordTypes;
9126
9127 /// A flag indicating whether either arithmetic or enumeration types
9128 /// were present in the candidate set.
9129 bool HasArithmeticOrEnumeralTypes;
9130
9131 /// A flag indicating whether the nullptr type was present in the
9132 /// candidate set.
9133 bool HasNullPtrType;
9134
9135 /// Sema - The semantic analysis instance where we are building the
9136 /// candidate type set.
9137 Sema &SemaRef;
9138
9139 /// Context - The AST context in which we will build the type sets.
9140 ASTContext &Context;
9141
9142 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9143 const Qualifiers &VisibleQuals);
9144 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9145
9146public:
9147 /// iterator - Iterates through the types that are part of the set.
9148 typedef TypeSet::iterator iterator;
9149
9150 BuiltinCandidateTypeSet(Sema &SemaRef)
9151 : HasNonRecordTypes(false),
9152 HasArithmeticOrEnumeralTypes(false),
9153 HasNullPtrType(false),
9154 SemaRef(SemaRef),
9155 Context(SemaRef.Context) { }
9156
9157 void AddTypesConvertedFrom(QualType Ty,
9158 SourceLocation Loc,
9159 bool AllowUserConversions,
9160 bool AllowExplicitConversions,
9161 const Qualifiers &VisibleTypeConversionsQuals);
9162
9163 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9164 llvm::iterator_range<iterator> member_pointer_types() {
9165 return MemberPointerTypes;
9166 }
9167 llvm::iterator_range<iterator> enumeration_types() {
9168 return EnumerationTypes;
9169 }
9170 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9171 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9172 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9173
9174 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9175 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9176 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9177 bool hasNullPtrType() const { return HasNullPtrType; }
9178};
9179
9180} // end anonymous namespace
9181
9182/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9183/// the set of pointer types along with any more-qualified variants of
9184/// that type. For example, if @p Ty is "int const *", this routine
9185/// will add "int const *", "int const volatile *", "int const
9186/// restrict *", and "int const volatile restrict *" to the set of
9187/// pointer types. Returns true if the add of @p Ty itself succeeded,
9188/// false otherwise.
9189///
9190/// FIXME: what to do about extended qualifiers?
9191bool
9192BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9193 const Qualifiers &VisibleQuals) {
9194
9195 // Insert this type.
9196 if (!PointerTypes.insert(X: Ty))
9197 return false;
9198
9199 QualType PointeeTy;
9200 const PointerType *PointerTy = Ty->getAs<PointerType>();
9201 bool buildObjCPtr = false;
9202 if (!PointerTy) {
9203 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9204 PointeeTy = PTy->getPointeeType();
9205 buildObjCPtr = true;
9206 } else {
9207 PointeeTy = PointerTy->getPointeeType();
9208 }
9209
9210 // Don't add qualified variants of arrays. For one, they're not allowed
9211 // (the qualifier would sink to the element type), and for another, the
9212 // only overload situation where it matters is subscript or pointer +- int,
9213 // and those shouldn't have qualifier variants anyway.
9214 if (PointeeTy->isArrayType())
9215 return true;
9216
9217 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9218 bool hasVolatile = VisibleQuals.hasVolatile();
9219 bool hasRestrict = VisibleQuals.hasRestrict();
9220
9221 // Iterate through all strict supersets of BaseCVR.
9222 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9223 if ((CVR | BaseCVR) != CVR) continue;
9224 // Skip over volatile if no volatile found anywhere in the types.
9225 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9226
9227 // Skip over restrict if no restrict found anywhere in the types, or if
9228 // the type cannot be restrict-qualified.
9229 if ((CVR & Qualifiers::Restrict) &&
9230 (!hasRestrict ||
9231 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9232 continue;
9233
9234 // Build qualified pointee type.
9235 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9236
9237 // Build qualified pointer type.
9238 QualType QPointerTy;
9239 if (!buildObjCPtr)
9240 QPointerTy = Context.getPointerType(T: QPointeeTy);
9241 else
9242 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9243
9244 // Insert qualified pointer type.
9245 PointerTypes.insert(X: QPointerTy);
9246 }
9247
9248 return true;
9249}
9250
9251/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9252/// to the set of pointer types along with any more-qualified variants of
9253/// that type. For example, if @p Ty is "int const *", this routine
9254/// will add "int const *", "int const volatile *", "int const
9255/// restrict *", and "int const volatile restrict *" to the set of
9256/// pointer types. Returns true if the add of @p Ty itself succeeded,
9257/// false otherwise.
9258///
9259/// FIXME: what to do about extended qualifiers?
9260bool
9261BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9262 QualType Ty) {
9263 // Insert this type.
9264 if (!MemberPointerTypes.insert(X: Ty))
9265 return false;
9266
9267 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9268 assert(PointerTy && "type was not a member pointer type!");
9269
9270 QualType PointeeTy = PointerTy->getPointeeType();
9271 // Don't add qualified variants of arrays. For one, they're not allowed
9272 // (the qualifier would sink to the element type), and for another, the
9273 // only overload situation where it matters is subscript or pointer +- int,
9274 // and those shouldn't have qualifier variants anyway.
9275 if (PointeeTy->isArrayType())
9276 return true;
9277 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9278
9279 // Iterate through all strict supersets of the pointee type's CVR
9280 // qualifiers.
9281 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9282 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9283 if ((CVR | BaseCVR) != CVR) continue;
9284
9285 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9286 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9287 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9288 }
9289
9290 return true;
9291}
9292
9293/// AddTypesConvertedFrom - Add each of the types to which the type @p
9294/// Ty can be implicit converted to the given set of @p Types. We're
9295/// primarily interested in pointer types and enumeration types. We also
9296/// take member pointer types, for the conditional operator.
9297/// AllowUserConversions is true if we should look at the conversion
9298/// functions of a class type, and AllowExplicitConversions if we
9299/// should also include the explicit conversion functions of a class
9300/// type.
9301void
9302BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9303 SourceLocation Loc,
9304 bool AllowUserConversions,
9305 bool AllowExplicitConversions,
9306 const Qualifiers &VisibleQuals) {
9307 // Only deal with canonical types.
9308 Ty = Context.getCanonicalType(T: Ty);
9309
9310 // Look through reference types; they aren't part of the type of an
9311 // expression for the purposes of conversions.
9312 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9313 Ty = RefTy->getPointeeType();
9314
9315 // If we're dealing with an array type, decay to the pointer.
9316 if (Ty->isArrayType())
9317 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9318
9319 // Otherwise, we don't care about qualifiers on the type.
9320 Ty = Ty.getLocalUnqualifiedType();
9321
9322 // Flag if we ever add a non-record type.
9323 bool TyIsRec = Ty->isRecordType();
9324 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9325
9326 // Flag if we encounter an arithmetic type.
9327 HasArithmeticOrEnumeralTypes =
9328 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9329
9330 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9331 PointerTypes.insert(X: Ty);
9332 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9333 // Insert our type, and its more-qualified variants, into the set
9334 // of types.
9335 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9336 return;
9337 } else if (Ty->isMemberPointerType()) {
9338 // Member pointers are far easier, since the pointee can't be converted.
9339 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9340 return;
9341 } else if (Ty->isEnumeralType()) {
9342 HasArithmeticOrEnumeralTypes = true;
9343 EnumerationTypes.insert(X: Ty);
9344 } else if (Ty->isBitIntType()) {
9345 HasArithmeticOrEnumeralTypes = true;
9346 BitIntTypes.insert(X: Ty);
9347 } else if (Ty->isVectorType()) {
9348 // We treat vector types as arithmetic types in many contexts as an
9349 // extension.
9350 HasArithmeticOrEnumeralTypes = true;
9351 VectorTypes.insert(X: Ty);
9352 } else if (Ty->isMatrixType()) {
9353 // Similar to vector types, we treat vector types as arithmetic types in
9354 // many contexts as an extension.
9355 HasArithmeticOrEnumeralTypes = true;
9356 MatrixTypes.insert(X: Ty);
9357 } else if (Ty->isNullPtrType()) {
9358 HasNullPtrType = true;
9359 } else if (AllowUserConversions && TyIsRec) {
9360 // No conversion functions in incomplete types.
9361 if (!SemaRef.isCompleteType(Loc, T: Ty))
9362 return;
9363
9364 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9365 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9366 if (isa<UsingShadowDecl>(Val: D))
9367 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9368
9369 // Skip conversion function templates; they don't tell us anything
9370 // about which builtin types we can convert to.
9371 if (isa<FunctionTemplateDecl>(Val: D))
9372 continue;
9373
9374 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9375 if (AllowExplicitConversions || !Conv->isExplicit()) {
9376 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9377 VisibleQuals);
9378 }
9379 }
9380 }
9381}
9382/// Helper function for adjusting address spaces for the pointer or reference
9383/// operands of builtin operators depending on the argument.
9384static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9385 Expr *Arg) {
9386 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9387}
9388
9389/// Helper function for AddBuiltinOperatorCandidates() that adds
9390/// the volatile- and non-volatile-qualified assignment operators for the
9391/// given type to the candidate set.
9392static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9393 QualType T,
9394 ArrayRef<Expr *> Args,
9395 OverloadCandidateSet &CandidateSet) {
9396 QualType ParamTypes[2];
9397
9398 // T& operator=(T&, T)
9399 ParamTypes[0] = S.Context.getLValueReferenceType(
9400 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9401 ParamTypes[1] = T;
9402 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9403 /*IsAssignmentOperator=*/true);
9404
9405 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9406 // volatile T& operator=(volatile T&, T)
9407 ParamTypes[0] = S.Context.getLValueReferenceType(
9408 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9409 Arg: Args[0]));
9410 ParamTypes[1] = T;
9411 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9412 /*IsAssignmentOperator=*/true);
9413 }
9414}
9415
9416/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9417/// if any, found in visible type conversion functions found in ArgExpr's type.
9418static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9419 Qualifiers VRQuals;
9420 CXXRecordDecl *ClassDecl;
9421 if (const MemberPointerType *RHSMPType =
9422 ArgExpr->getType()->getAs<MemberPointerType>())
9423 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9424 else
9425 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9426 if (!ClassDecl) {
9427 // Just to be safe, assume the worst case.
9428 VRQuals.addVolatile();
9429 VRQuals.addRestrict();
9430 return VRQuals;
9431 }
9432 if (!ClassDecl->hasDefinition())
9433 return VRQuals;
9434
9435 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9436 if (isa<UsingShadowDecl>(Val: D))
9437 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9438 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9439 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9440 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9441 CanTy = ResTypeRef->getPointeeType();
9442 // Need to go down the pointer/mempointer chain and add qualifiers
9443 // as see them.
9444 bool done = false;
9445 while (!done) {
9446 if (CanTy.isRestrictQualified())
9447 VRQuals.addRestrict();
9448 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9449 CanTy = ResTypePtr->getPointeeType();
9450 else if (const MemberPointerType *ResTypeMPtr =
9451 CanTy->getAs<MemberPointerType>())
9452 CanTy = ResTypeMPtr->getPointeeType();
9453 else
9454 done = true;
9455 if (CanTy.isVolatileQualified())
9456 VRQuals.addVolatile();
9457 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9458 return VRQuals;
9459 }
9460 }
9461 }
9462 return VRQuals;
9463}
9464
9465// Note: We're currently only handling qualifiers that are meaningful for the
9466// LHS of compound assignment overloading.
9467static void forAllQualifierCombinationsImpl(
9468 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9469 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9470 // _Atomic
9471 if (Available.hasAtomic()) {
9472 Available.removeAtomic();
9473 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9474 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9475 return;
9476 }
9477
9478 // volatile
9479 if (Available.hasVolatile()) {
9480 Available.removeVolatile();
9481 assert(!Applied.hasVolatile());
9482 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9483 Callback);
9484 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9485 return;
9486 }
9487
9488 Callback(Applied);
9489}
9490
9491static void forAllQualifierCombinations(
9492 QualifiersAndAtomic Quals,
9493 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9494 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9495 Callback);
9496}
9497
9498static QualType makeQualifiedLValueReferenceType(QualType Base,
9499 QualifiersAndAtomic Quals,
9500 Sema &S) {
9501 if (Quals.hasAtomic())
9502 Base = S.Context.getAtomicType(T: Base);
9503 if (Quals.hasVolatile())
9504 Base = S.Context.getVolatileType(T: Base);
9505 return S.Context.getLValueReferenceType(T: Base);
9506}
9507
9508namespace {
9509
9510/// Helper class to manage the addition of builtin operator overload
9511/// candidates. It provides shared state and utility methods used throughout
9512/// the process, as well as a helper method to add each group of builtin
9513/// operator overloads from the standard to a candidate set.
9514class BuiltinOperatorOverloadBuilder {
9515 // Common instance state available to all overload candidate addition methods.
9516 Sema &S;
9517 ArrayRef<Expr *> Args;
9518 QualifiersAndAtomic VisibleTypeConversionsQuals;
9519 bool HasArithmeticOrEnumeralCandidateType;
9520 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9521 OverloadCandidateSet &CandidateSet;
9522
9523 static constexpr int ArithmeticTypesCap = 26;
9524 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9525
9526 // Define some indices used to iterate over the arithmetic types in
9527 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9528 // types are that preserved by promotion (C++ [over.built]p2).
9529 unsigned FirstIntegralType,
9530 LastIntegralType;
9531 unsigned FirstPromotedIntegralType,
9532 LastPromotedIntegralType;
9533 unsigned FirstPromotedArithmeticType,
9534 LastPromotedArithmeticType;
9535 unsigned NumArithmeticTypes;
9536
9537 void InitArithmeticTypes() {
9538 // Start of promoted types.
9539 FirstPromotedArithmeticType = 0;
9540 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9541 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9542 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9543 if (S.Context.getTargetInfo().hasFloat128Type())
9544 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9545 if (S.Context.getTargetInfo().hasIbm128Type())
9546 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9547
9548 // Start of integral types.
9549 FirstIntegralType = ArithmeticTypes.size();
9550 FirstPromotedIntegralType = ArithmeticTypes.size();
9551 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9552 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9553 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9554 if (S.Context.getTargetInfo().hasInt128Type() ||
9555 (S.Context.getAuxTargetInfo() &&
9556 S.Context.getAuxTargetInfo()->hasInt128Type()))
9557 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9558 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9559 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9560 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9561 if (S.Context.getTargetInfo().hasInt128Type() ||
9562 (S.Context.getAuxTargetInfo() &&
9563 S.Context.getAuxTargetInfo()->hasInt128Type()))
9564 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9565
9566 /// We add candidates for the unique, unqualified _BitInt types present in
9567 /// the candidate type set. The candidate set already handled ensuring the
9568 /// type is unqualified and canonical, but because we're adding from N
9569 /// different sets, we need to do some extra work to unique things. Insert
9570 /// the candidates into a unique set, then move from that set into the list
9571 /// of arithmetic types.
9572 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9573 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9574 for (QualType BitTy : Candidate.bitint_types())
9575 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9576 }
9577 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9578 LastPromotedIntegralType = ArithmeticTypes.size();
9579 LastPromotedArithmeticType = ArithmeticTypes.size();
9580 // End of promoted types.
9581
9582 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9583 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9584 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9585 if (S.Context.getLangOpts().Char8)
9586 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9587 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9588 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9589 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9590 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9591 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9592 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9593 LastIntegralType = ArithmeticTypes.size();
9594 NumArithmeticTypes = ArithmeticTypes.size();
9595 // End of integral types.
9596 // FIXME: What about complex? What about half?
9597
9598 // We don't know for sure how many bit-precise candidates were involved, so
9599 // we subtract those from the total when testing whether we're under the
9600 // cap or not.
9601 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9602 ArithmeticTypesCap &&
9603 "Enough inline storage for all arithmetic types.");
9604 }
9605
9606 /// Helper method to factor out the common pattern of adding overloads
9607 /// for '++' and '--' builtin operators.
9608 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9609 bool HasVolatile,
9610 bool HasRestrict) {
9611 QualType ParamTypes[2] = {
9612 S.Context.getLValueReferenceType(T: CandidateTy),
9613 S.Context.IntTy
9614 };
9615
9616 // Non-volatile version.
9617 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9618
9619 // Use a heuristic to reduce number of builtin candidates in the set:
9620 // add volatile version only if there are conversions to a volatile type.
9621 if (HasVolatile) {
9622 ParamTypes[0] =
9623 S.Context.getLValueReferenceType(
9624 T: S.Context.getVolatileType(T: CandidateTy));
9625 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9626 }
9627
9628 // Add restrict version only if there are conversions to a restrict type
9629 // and our candidate type is a non-restrict-qualified pointer.
9630 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9631 !CandidateTy.isRestrictQualified()) {
9632 ParamTypes[0]
9633 = S.Context.getLValueReferenceType(
9634 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9635 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9636
9637 if (HasVolatile) {
9638 ParamTypes[0]
9639 = S.Context.getLValueReferenceType(
9640 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9641 CVR: (Qualifiers::Volatile |
9642 Qualifiers::Restrict)));
9643 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9644 }
9645 }
9646
9647 }
9648
9649 /// Helper to add an overload candidate for a binary builtin with types \p L
9650 /// and \p R.
9651 void AddCandidate(QualType L, QualType R) {
9652 QualType LandR[2] = {L, R};
9653 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9654 }
9655
9656public:
9657 BuiltinOperatorOverloadBuilder(
9658 Sema &S, ArrayRef<Expr *> Args,
9659 QualifiersAndAtomic VisibleTypeConversionsQuals,
9660 bool HasArithmeticOrEnumeralCandidateType,
9661 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9662 OverloadCandidateSet &CandidateSet)
9663 : S(S), Args(Args),
9664 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9665 HasArithmeticOrEnumeralCandidateType(
9666 HasArithmeticOrEnumeralCandidateType),
9667 CandidateTypes(CandidateTypes),
9668 CandidateSet(CandidateSet) {
9669
9670 InitArithmeticTypes();
9671 }
9672
9673 // Increment is deprecated for bool since C++17.
9674 //
9675 // C++ [over.built]p3:
9676 //
9677 // For every pair (T, VQ), where T is an arithmetic type other
9678 // than bool, and VQ is either volatile or empty, there exist
9679 // candidate operator functions of the form
9680 //
9681 // VQ T& operator++(VQ T&);
9682 // T operator++(VQ T&, int);
9683 //
9684 // C++ [over.built]p4:
9685 //
9686 // For every pair (T, VQ), where T is an arithmetic type other
9687 // than bool, and VQ is either volatile or empty, there exist
9688 // candidate operator functions of the form
9689 //
9690 // VQ T& operator--(VQ T&);
9691 // T operator--(VQ T&, int);
9692 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9693 if (!HasArithmeticOrEnumeralCandidateType)
9694 return;
9695
9696 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9697 const auto TypeOfT = ArithmeticTypes[Arith];
9698 if (TypeOfT == S.Context.BoolTy) {
9699 if (Op == OO_MinusMinus)
9700 continue;
9701 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9702 continue;
9703 }
9704 addPlusPlusMinusMinusStyleOverloads(
9705 CandidateTy: TypeOfT,
9706 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9707 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9708 }
9709 }
9710
9711 // C++ [over.built]p5:
9712 //
9713 // For every pair (T, VQ), where T is a cv-qualified or
9714 // cv-unqualified object type, and VQ is either volatile or
9715 // empty, there exist candidate operator functions of the form
9716 //
9717 // T*VQ& operator++(T*VQ&);
9718 // T*VQ& operator--(T*VQ&);
9719 // T* operator++(T*VQ&, int);
9720 // T* operator--(T*VQ&, int);
9721 void addPlusPlusMinusMinusPointerOverloads() {
9722 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9723 // Skip pointer types that aren't pointers to object types.
9724 if (!PtrTy->getPointeeType()->isObjectType())
9725 continue;
9726
9727 addPlusPlusMinusMinusStyleOverloads(
9728 CandidateTy: PtrTy,
9729 HasVolatile: (!PtrTy.isVolatileQualified() &&
9730 VisibleTypeConversionsQuals.hasVolatile()),
9731 HasRestrict: (!PtrTy.isRestrictQualified() &&
9732 VisibleTypeConversionsQuals.hasRestrict()));
9733 }
9734 }
9735
9736 // C++ [over.built]p6:
9737 // For every cv-qualified or cv-unqualified object type T, there
9738 // exist candidate operator functions of the form
9739 //
9740 // T& operator*(T*);
9741 //
9742 // C++ [over.built]p7:
9743 // For every function type T that does not have cv-qualifiers or a
9744 // ref-qualifier, there exist candidate operator functions of the form
9745 // T& operator*(T*);
9746 void addUnaryStarPointerOverloads() {
9747 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9748 QualType PointeeTy = ParamTy->getPointeeType();
9749 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9750 continue;
9751
9752 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9753 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9754 continue;
9755
9756 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9757 }
9758 }
9759
9760 // C++ [over.built]p9:
9761 // For every promoted arithmetic type T, there exist candidate
9762 // operator functions of the form
9763 //
9764 // T operator+(T);
9765 // T operator-(T);
9766 void addUnaryPlusOrMinusArithmeticOverloads() {
9767 if (!HasArithmeticOrEnumeralCandidateType)
9768 return;
9769
9770 for (unsigned Arith = FirstPromotedArithmeticType;
9771 Arith < LastPromotedArithmeticType; ++Arith) {
9772 QualType ArithTy = ArithmeticTypes[Arith];
9773 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9774 }
9775
9776 // Extension: We also add these operators for vector types.
9777 for (QualType VecTy : CandidateTypes[0].vector_types())
9778 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9779 }
9780
9781 // C++ [over.built]p8:
9782 // For every type T, there exist candidate operator functions of
9783 // the form
9784 //
9785 // T* operator+(T*);
9786 void addUnaryPlusPointerOverloads() {
9787 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9788 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9789 }
9790
9791 // C++ [over.built]p10:
9792 // For every promoted integral type T, there exist candidate
9793 // operator functions of the form
9794 //
9795 // T operator~(T);
9796 void addUnaryTildePromotedIntegralOverloads() {
9797 if (!HasArithmeticOrEnumeralCandidateType)
9798 return;
9799
9800 for (unsigned Int = FirstPromotedIntegralType;
9801 Int < LastPromotedIntegralType; ++Int) {
9802 QualType IntTy = ArithmeticTypes[Int];
9803 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9804 }
9805
9806 // Extension: We also add this operator for vector types.
9807 for (QualType VecTy : CandidateTypes[0].vector_types())
9808 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9809 }
9810
9811 // C++ [over.match.oper]p16:
9812 // For every pointer to member type T or type std::nullptr_t, there
9813 // exist candidate operator functions of the form
9814 //
9815 // bool operator==(T,T);
9816 // bool operator!=(T,T);
9817 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9818 /// Set of (canonical) types that we've already handled.
9819 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9820
9821 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9822 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9823 // Don't add the same builtin candidate twice.
9824 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9825 continue;
9826
9827 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9828 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9829 }
9830
9831 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9832 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9833 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9834 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9835 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9836 }
9837 }
9838 }
9839 }
9840
9841 // C++ [over.built]p15:
9842 //
9843 // For every T, where T is an enumeration type or a pointer type,
9844 // there exist candidate operator functions of the form
9845 //
9846 // bool operator<(T, T);
9847 // bool operator>(T, T);
9848 // bool operator<=(T, T);
9849 // bool operator>=(T, T);
9850 // bool operator==(T, T);
9851 // bool operator!=(T, T);
9852 // R operator<=>(T, T)
9853 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9854 // C++ [over.match.oper]p3:
9855 // [...]the built-in candidates include all of the candidate operator
9856 // functions defined in 13.6 that, compared to the given operator, [...]
9857 // do not have the same parameter-type-list as any non-template non-member
9858 // candidate.
9859 //
9860 // Note that in practice, this only affects enumeration types because there
9861 // aren't any built-in candidates of record type, and a user-defined operator
9862 // must have an operand of record or enumeration type. Also, the only other
9863 // overloaded operator with enumeration arguments, operator=,
9864 // cannot be overloaded for enumeration types, so this is the only place
9865 // where we must suppress candidates like this.
9866 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9867 UserDefinedBinaryOperators;
9868
9869 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9870 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9871 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9872 CEnd = CandidateSet.end();
9873 C != CEnd; ++C) {
9874 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9875 continue;
9876
9877 if (C->Function->isFunctionTemplateSpecialization())
9878 continue;
9879
9880 // We interpret "same parameter-type-list" as applying to the
9881 // "synthesized candidate, with the order of the two parameters
9882 // reversed", not to the original function.
9883 bool Reversed = C->isReversed();
9884 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9885 ->getType()
9886 .getUnqualifiedType();
9887 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9888 ->getType()
9889 .getUnqualifiedType();
9890
9891 // Skip if either parameter isn't of enumeral type.
9892 if (!FirstParamType->isEnumeralType() ||
9893 !SecondParamType->isEnumeralType())
9894 continue;
9895
9896 // Add this operator to the set of known user-defined operators.
9897 UserDefinedBinaryOperators.insert(
9898 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9899 y: S.Context.getCanonicalType(T: SecondParamType)));
9900 }
9901 }
9902 }
9903
9904 /// Set of (canonical) types that we've already handled.
9905 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9906
9907 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9908 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9909 // Don't add the same builtin candidate twice.
9910 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9911 continue;
9912 if (IsSpaceship && PtrTy->isFunctionPointerType())
9913 continue;
9914
9915 QualType ParamTypes[2] = {PtrTy, PtrTy};
9916 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9917 }
9918 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9919 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9920
9921 // Don't add the same builtin candidate twice, or if a user defined
9922 // candidate exists.
9923 if (!AddedTypes.insert(Ptr: CanonType).second ||
9924 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9925 y&: CanonType)))
9926 continue;
9927 QualType ParamTypes[2] = {EnumTy, EnumTy};
9928 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9929 }
9930 }
9931 }
9932
9933 // C++ [over.built]p13:
9934 //
9935 // For every cv-qualified or cv-unqualified object type T
9936 // there exist candidate operator functions of the form
9937 //
9938 // T* operator+(T*, ptrdiff_t);
9939 // T& operator[](T*, ptrdiff_t); [BELOW]
9940 // T* operator-(T*, ptrdiff_t);
9941 // T* operator+(ptrdiff_t, T*);
9942 // T& operator[](ptrdiff_t, T*); [BELOW]
9943 //
9944 // C++ [over.built]p14:
9945 //
9946 // For every T, where T is a pointer to object type, there
9947 // exist candidate operator functions of the form
9948 //
9949 // ptrdiff_t operator-(T, T);
9950 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9951 /// Set of (canonical) types that we've already handled.
9952 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9953
9954 for (int Arg = 0; Arg < 2; ++Arg) {
9955 QualType AsymmetricParamTypes[2] = {
9956 S.Context.getPointerDiffType(),
9957 S.Context.getPointerDiffType(),
9958 };
9959 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9960 QualType PointeeTy = PtrTy->getPointeeType();
9961 if (!PointeeTy->isObjectType())
9962 continue;
9963
9964 AsymmetricParamTypes[Arg] = PtrTy;
9965 if (Arg == 0 || Op == OO_Plus) {
9966 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9967 // T* operator+(ptrdiff_t, T*);
9968 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9969 }
9970 if (Op == OO_Minus) {
9971 // ptrdiff_t operator-(T, T);
9972 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9973 continue;
9974
9975 QualType ParamTypes[2] = {PtrTy, PtrTy};
9976 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9977 }
9978 }
9979 }
9980 }
9981
9982 // C++ [over.built]p12:
9983 //
9984 // For every pair of promoted arithmetic types L and R, there
9985 // exist candidate operator functions of the form
9986 //
9987 // LR operator*(L, R);
9988 // LR operator/(L, R);
9989 // LR operator+(L, R);
9990 // LR operator-(L, R);
9991 // bool operator<(L, R);
9992 // bool operator>(L, R);
9993 // bool operator<=(L, R);
9994 // bool operator>=(L, R);
9995 // bool operator==(L, R);
9996 // bool operator!=(L, R);
9997 //
9998 // where LR is the result of the usual arithmetic conversions
9999 // between types L and R.
10000 //
10001 // C++ [over.built]p24:
10002 //
10003 // For every pair of promoted arithmetic types L and R, there exist
10004 // candidate operator functions of the form
10005 //
10006 // LR operator?(bool, L, R);
10007 //
10008 // where LR is the result of the usual arithmetic conversions
10009 // between types L and R.
10010 // Our candidates ignore the first parameter.
10011 void addGenericBinaryArithmeticOverloads() {
10012 if (!HasArithmeticOrEnumeralCandidateType)
10013 return;
10014
10015 for (unsigned Left = FirstPromotedArithmeticType;
10016 Left < LastPromotedArithmeticType; ++Left) {
10017 for (unsigned Right = FirstPromotedArithmeticType;
10018 Right < LastPromotedArithmeticType; ++Right) {
10019 QualType LandR[2] = { ArithmeticTypes[Left],
10020 ArithmeticTypes[Right] };
10021 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10022 }
10023 }
10024
10025 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10026 // conditional operator for vector types.
10027 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10028 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10029 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10030 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10031 }
10032 }
10033
10034 /// Add binary operator overloads for each candidate matrix type M1, M2:
10035 /// * (M1, M1) -> M1
10036 /// * (M1, M1.getElementType()) -> M1
10037 /// * (M2.getElementType(), M2) -> M2
10038 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10039 void addMatrixBinaryArithmeticOverloads() {
10040 if (!HasArithmeticOrEnumeralCandidateType)
10041 return;
10042
10043 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10044 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
10045 AddCandidate(L: M1, R: M1);
10046 }
10047
10048 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10049 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
10050 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
10051 AddCandidate(L: M2, R: M2);
10052 }
10053 }
10054
10055 // C++2a [over.built]p14:
10056 //
10057 // For every integral type T there exists a candidate operator function
10058 // of the form
10059 //
10060 // std::strong_ordering operator<=>(T, T)
10061 //
10062 // C++2a [over.built]p15:
10063 //
10064 // For every pair of floating-point types L and R, there exists a candidate
10065 // operator function of the form
10066 //
10067 // std::partial_ordering operator<=>(L, R);
10068 //
10069 // FIXME: The current specification for integral types doesn't play nice with
10070 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10071 // comparisons. Under the current spec this can lead to ambiguity during
10072 // overload resolution. For example:
10073 //
10074 // enum A : int {a};
10075 // auto x = (a <=> (long)42);
10076 //
10077 // error: call is ambiguous for arguments 'A' and 'long'.
10078 // note: candidate operator<=>(int, int)
10079 // note: candidate operator<=>(long, long)
10080 //
10081 // To avoid this error, this function deviates from the specification and adds
10082 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10083 // arithmetic types (the same as the generic relational overloads).
10084 //
10085 // For now this function acts as a placeholder.
10086 void addThreeWayArithmeticOverloads() {
10087 addGenericBinaryArithmeticOverloads();
10088 }
10089
10090 // C++ [over.built]p17:
10091 //
10092 // For every pair of promoted integral types L and R, there
10093 // exist candidate operator functions of the form
10094 //
10095 // LR operator%(L, R);
10096 // LR operator&(L, R);
10097 // LR operator^(L, R);
10098 // LR operator|(L, R);
10099 // L operator<<(L, R);
10100 // L operator>>(L, R);
10101 //
10102 // where LR is the result of the usual arithmetic conversions
10103 // between types L and R.
10104 void addBinaryBitwiseArithmeticOverloads() {
10105 if (!HasArithmeticOrEnumeralCandidateType)
10106 return;
10107
10108 for (unsigned Left = FirstPromotedIntegralType;
10109 Left < LastPromotedIntegralType; ++Left) {
10110 for (unsigned Right = FirstPromotedIntegralType;
10111 Right < LastPromotedIntegralType; ++Right) {
10112 QualType LandR[2] = { ArithmeticTypes[Left],
10113 ArithmeticTypes[Right] };
10114 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10115 }
10116 }
10117 }
10118
10119 // C++ [over.built]p20:
10120 //
10121 // For every pair (T, VQ), where T is an enumeration or
10122 // pointer to member type and VQ is either volatile or
10123 // empty, there exist candidate operator functions of the form
10124 //
10125 // VQ T& operator=(VQ T&, T);
10126 void addAssignmentMemberPointerOrEnumeralOverloads() {
10127 /// Set of (canonical) types that we've already handled.
10128 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10129
10130 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10131 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10132 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10133 continue;
10134
10135 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10136 }
10137
10138 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10139 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10140 continue;
10141
10142 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10143 }
10144 }
10145 }
10146
10147 // C++ [over.built]p19:
10148 //
10149 // For every pair (T, VQ), where T is any type and VQ is either
10150 // volatile or empty, there exist candidate operator functions
10151 // of the form
10152 //
10153 // T*VQ& operator=(T*VQ&, T*);
10154 //
10155 // C++ [over.built]p21:
10156 //
10157 // For every pair (T, VQ), where T is a cv-qualified or
10158 // cv-unqualified object type and VQ is either volatile or
10159 // empty, there exist candidate operator functions of the form
10160 //
10161 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10162 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10163 void addAssignmentPointerOverloads(bool isEqualOp) {
10164 /// Set of (canonical) types that we've already handled.
10165 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10166
10167 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10168 // If this is operator=, keep track of the builtin candidates we added.
10169 if (isEqualOp)
10170 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10171 else if (!PtrTy->getPointeeType()->isObjectType())
10172 continue;
10173
10174 // non-volatile version
10175 QualType ParamTypes[2] = {
10176 S.Context.getLValueReferenceType(T: PtrTy),
10177 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10178 };
10179 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10180 /*IsAssignmentOperator=*/ isEqualOp);
10181
10182 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10183 VisibleTypeConversionsQuals.hasVolatile();
10184 if (NeedVolatile) {
10185 // volatile version
10186 ParamTypes[0] =
10187 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10188 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10189 /*IsAssignmentOperator=*/isEqualOp);
10190 }
10191
10192 if (!PtrTy.isRestrictQualified() &&
10193 VisibleTypeConversionsQuals.hasRestrict()) {
10194 // restrict version
10195 ParamTypes[0] =
10196 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10197 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10198 /*IsAssignmentOperator=*/isEqualOp);
10199
10200 if (NeedVolatile) {
10201 // volatile restrict version
10202 ParamTypes[0] =
10203 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10204 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10205 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10206 /*IsAssignmentOperator=*/isEqualOp);
10207 }
10208 }
10209 }
10210
10211 if (isEqualOp) {
10212 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10213 // Make sure we don't add the same candidate twice.
10214 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10215 continue;
10216
10217 QualType ParamTypes[2] = {
10218 S.Context.getLValueReferenceType(T: PtrTy),
10219 PtrTy,
10220 };
10221
10222 // non-volatile version
10223 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10224 /*IsAssignmentOperator=*/true);
10225
10226 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10227 VisibleTypeConversionsQuals.hasVolatile();
10228 if (NeedVolatile) {
10229 // volatile version
10230 ParamTypes[0] = S.Context.getLValueReferenceType(
10231 T: S.Context.getVolatileType(T: PtrTy));
10232 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10233 /*IsAssignmentOperator=*/true);
10234 }
10235
10236 if (!PtrTy.isRestrictQualified() &&
10237 VisibleTypeConversionsQuals.hasRestrict()) {
10238 // restrict version
10239 ParamTypes[0] = S.Context.getLValueReferenceType(
10240 T: S.Context.getRestrictType(T: PtrTy));
10241 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10242 /*IsAssignmentOperator=*/true);
10243
10244 if (NeedVolatile) {
10245 // volatile restrict version
10246 ParamTypes[0] =
10247 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10248 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10249 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10250 /*IsAssignmentOperator=*/true);
10251 }
10252 }
10253 }
10254 }
10255 }
10256
10257 // C++ [over.built]p18:
10258 //
10259 // For every triple (L, VQ, R), where L is an arithmetic type,
10260 // VQ is either volatile or empty, and R is a promoted
10261 // arithmetic type, there exist candidate operator functions of
10262 // the form
10263 //
10264 // VQ L& operator=(VQ L&, R);
10265 // VQ L& operator*=(VQ L&, R);
10266 // VQ L& operator/=(VQ L&, R);
10267 // VQ L& operator+=(VQ L&, R);
10268 // VQ L& operator-=(VQ L&, R);
10269 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10270 if (!HasArithmeticOrEnumeralCandidateType)
10271 return;
10272
10273 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10274 for (unsigned Right = FirstPromotedArithmeticType;
10275 Right < LastPromotedArithmeticType; ++Right) {
10276 QualType ParamTypes[2];
10277 ParamTypes[1] = ArithmeticTypes[Right];
10278 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10279 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10280
10281 forAllQualifierCombinations(
10282 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10283 ParamTypes[0] =
10284 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10285 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10286 /*IsAssignmentOperator=*/isEqualOp);
10287 });
10288 }
10289 }
10290
10291 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10292 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10293 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10294 QualType ParamTypes[2];
10295 ParamTypes[1] = Vec2Ty;
10296 // Add this built-in operator as a candidate (VQ is empty).
10297 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10298 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10299 /*IsAssignmentOperator=*/isEqualOp);
10300
10301 // Add this built-in operator as a candidate (VQ is 'volatile').
10302 if (VisibleTypeConversionsQuals.hasVolatile()) {
10303 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10304 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10305 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10306 /*IsAssignmentOperator=*/isEqualOp);
10307 }
10308 }
10309 }
10310
10311 // C++ [over.built]p22:
10312 //
10313 // For every triple (L, VQ, R), where L is an integral type, VQ
10314 // is either volatile or empty, and R is a promoted integral
10315 // type, there exist candidate operator functions of the form
10316 //
10317 // VQ L& operator%=(VQ L&, R);
10318 // VQ L& operator<<=(VQ L&, R);
10319 // VQ L& operator>>=(VQ L&, R);
10320 // VQ L& operator&=(VQ L&, R);
10321 // VQ L& operator^=(VQ L&, R);
10322 // VQ L& operator|=(VQ L&, R);
10323 void addAssignmentIntegralOverloads() {
10324 if (!HasArithmeticOrEnumeralCandidateType)
10325 return;
10326
10327 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10328 for (unsigned Right = FirstPromotedIntegralType;
10329 Right < LastPromotedIntegralType; ++Right) {
10330 QualType ParamTypes[2];
10331 ParamTypes[1] = ArithmeticTypes[Right];
10332 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10333 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10334
10335 forAllQualifierCombinations(
10336 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10337 ParamTypes[0] =
10338 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10339 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10340 });
10341 }
10342 }
10343 }
10344
10345 // C++ [over.operator]p23:
10346 //
10347 // There also exist candidate operator functions of the form
10348 //
10349 // bool operator!(bool);
10350 // bool operator&&(bool, bool);
10351 // bool operator||(bool, bool);
10352 void addExclaimOverload() {
10353 QualType ParamTy = S.Context.BoolTy;
10354 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10355 /*IsAssignmentOperator=*/false,
10356 /*NumContextualBoolArguments=*/1);
10357 }
10358 void addAmpAmpOrPipePipeOverload() {
10359 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10360 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10361 /*IsAssignmentOperator=*/false,
10362 /*NumContextualBoolArguments=*/2);
10363 }
10364
10365 // C++ [over.built]p13:
10366 //
10367 // For every cv-qualified or cv-unqualified object type T there
10368 // exist candidate operator functions of the form
10369 //
10370 // T* operator+(T*, ptrdiff_t); [ABOVE]
10371 // T& operator[](T*, ptrdiff_t);
10372 // T* operator-(T*, ptrdiff_t); [ABOVE]
10373 // T* operator+(ptrdiff_t, T*); [ABOVE]
10374 // T& operator[](ptrdiff_t, T*);
10375 void addSubscriptOverloads() {
10376 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10377 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10378 QualType PointeeType = PtrTy->getPointeeType();
10379 if (!PointeeType->isObjectType())
10380 continue;
10381
10382 // T& operator[](T*, ptrdiff_t)
10383 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10384 }
10385
10386 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10387 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10388 QualType PointeeType = PtrTy->getPointeeType();
10389 if (!PointeeType->isObjectType())
10390 continue;
10391
10392 // T& operator[](ptrdiff_t, T*)
10393 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10394 }
10395 }
10396
10397 // C++ [over.built]p11:
10398 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10399 // C1 is the same type as C2 or is a derived class of C2, T is an object
10400 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10401 // there exist candidate operator functions of the form
10402 //
10403 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10404 //
10405 // where CV12 is the union of CV1 and CV2.
10406 void addArrowStarOverloads() {
10407 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10408 QualType C1Ty = PtrTy;
10409 QualType C1;
10410 QualifierCollector Q1;
10411 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10412 if (!isa<RecordType>(Val: C1))
10413 continue;
10414 // heuristic to reduce number of builtin candidates in the set.
10415 // Add volatile/restrict version only if there are conversions to a
10416 // volatile/restrict type.
10417 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10418 continue;
10419 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10420 continue;
10421 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10422 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10423 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10424 *D2 = mptr->getMostRecentCXXRecordDecl();
10425 if (!declaresSameEntity(D1, D2) &&
10426 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10427 break;
10428 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10429 // build CV12 T&
10430 QualType T = mptr->getPointeeType();
10431 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10432 T.isVolatileQualified())
10433 continue;
10434 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10435 T.isRestrictQualified())
10436 continue;
10437 T = Q1.apply(Context: S.Context, QT: T);
10438 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10439 }
10440 }
10441 }
10442
10443 // Note that we don't consider the first argument, since it has been
10444 // contextually converted to bool long ago. The candidates below are
10445 // therefore added as binary.
10446 //
10447 // C++ [over.built]p25:
10448 // For every type T, where T is a pointer, pointer-to-member, or scoped
10449 // enumeration type, there exist candidate operator functions of the form
10450 //
10451 // T operator?(bool, T, T);
10452 //
10453 void addConditionalOperatorOverloads() {
10454 /// Set of (canonical) types that we've already handled.
10455 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10456
10457 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10458 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10459 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10460 continue;
10461
10462 QualType ParamTypes[2] = {PtrTy, PtrTy};
10463 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10464 }
10465
10466 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10467 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10468 continue;
10469
10470 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10471 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10472 }
10473
10474 if (S.getLangOpts().CPlusPlus11) {
10475 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10476 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10477 continue;
10478
10479 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10480 continue;
10481
10482 QualType ParamTypes[2] = {EnumTy, EnumTy};
10483 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10484 }
10485 }
10486 }
10487 }
10488};
10489
10490} // end anonymous namespace
10491
10492void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10493 SourceLocation OpLoc,
10494 ArrayRef<Expr *> Args,
10495 OverloadCandidateSet &CandidateSet) {
10496 // Find all of the types that the arguments can convert to, but only
10497 // if the operator we're looking at has built-in operator candidates
10498 // that make use of these types. Also record whether we encounter non-record
10499 // candidate types or either arithmetic or enumeral candidate types.
10500 QualifiersAndAtomic VisibleTypeConversionsQuals;
10501 VisibleTypeConversionsQuals.addConst();
10502 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10503 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10504 if (Args[ArgIdx]->getType()->isAtomicType())
10505 VisibleTypeConversionsQuals.addAtomic();
10506 }
10507
10508 bool HasNonRecordCandidateType = false;
10509 bool HasArithmeticOrEnumeralCandidateType = false;
10510 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10511 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10512 CandidateTypes.emplace_back(Args&: *this);
10513 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10514 Loc: OpLoc,
10515 AllowUserConversions: true,
10516 AllowExplicitConversions: (Op == OO_Exclaim ||
10517 Op == OO_AmpAmp ||
10518 Op == OO_PipePipe),
10519 VisibleQuals: VisibleTypeConversionsQuals);
10520 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10521 CandidateTypes[ArgIdx].hasNonRecordTypes();
10522 HasArithmeticOrEnumeralCandidateType =
10523 HasArithmeticOrEnumeralCandidateType ||
10524 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10525 }
10526
10527 // Exit early when no non-record types have been added to the candidate set
10528 // for any of the arguments to the operator.
10529 //
10530 // We can't exit early for !, ||, or &&, since there we have always have
10531 // 'bool' overloads.
10532 if (!HasNonRecordCandidateType &&
10533 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10534 return;
10535
10536 // Setup an object to manage the common state for building overloads.
10537 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10538 VisibleTypeConversionsQuals,
10539 HasArithmeticOrEnumeralCandidateType,
10540 CandidateTypes, CandidateSet);
10541
10542 // Dispatch over the operation to add in only those overloads which apply.
10543 switch (Op) {
10544 case OO_None:
10545 case NUM_OVERLOADED_OPERATORS:
10546 llvm_unreachable("Expected an overloaded operator");
10547
10548 case OO_New:
10549 case OO_Delete:
10550 case OO_Array_New:
10551 case OO_Array_Delete:
10552 case OO_Call:
10553 llvm_unreachable(
10554 "Special operators don't use AddBuiltinOperatorCandidates");
10555
10556 case OO_Comma:
10557 case OO_Arrow:
10558 case OO_Coawait:
10559 // C++ [over.match.oper]p3:
10560 // -- For the operator ',', the unary operator '&', the
10561 // operator '->', or the operator 'co_await', the
10562 // built-in candidates set is empty.
10563 break;
10564
10565 case OO_Plus: // '+' is either unary or binary
10566 if (Args.size() == 1)
10567 OpBuilder.addUnaryPlusPointerOverloads();
10568 [[fallthrough]];
10569
10570 case OO_Minus: // '-' is either unary or binary
10571 if (Args.size() == 1) {
10572 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10573 } else {
10574 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10575 OpBuilder.addGenericBinaryArithmeticOverloads();
10576 OpBuilder.addMatrixBinaryArithmeticOverloads();
10577 }
10578 break;
10579
10580 case OO_Star: // '*' is either unary or binary
10581 if (Args.size() == 1)
10582 OpBuilder.addUnaryStarPointerOverloads();
10583 else {
10584 OpBuilder.addGenericBinaryArithmeticOverloads();
10585 OpBuilder.addMatrixBinaryArithmeticOverloads();
10586 }
10587 break;
10588
10589 case OO_Slash:
10590 OpBuilder.addGenericBinaryArithmeticOverloads();
10591 break;
10592
10593 case OO_PlusPlus:
10594 case OO_MinusMinus:
10595 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10596 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10597 break;
10598
10599 case OO_EqualEqual:
10600 case OO_ExclaimEqual:
10601 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10602 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10603 OpBuilder.addGenericBinaryArithmeticOverloads();
10604 break;
10605
10606 case OO_Less:
10607 case OO_Greater:
10608 case OO_LessEqual:
10609 case OO_GreaterEqual:
10610 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10611 OpBuilder.addGenericBinaryArithmeticOverloads();
10612 break;
10613
10614 case OO_Spaceship:
10615 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10616 OpBuilder.addThreeWayArithmeticOverloads();
10617 break;
10618
10619 case OO_Percent:
10620 case OO_Caret:
10621 case OO_Pipe:
10622 case OO_LessLess:
10623 case OO_GreaterGreater:
10624 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10625 break;
10626
10627 case OO_Amp: // '&' is either unary or binary
10628 if (Args.size() == 1)
10629 // C++ [over.match.oper]p3:
10630 // -- For the operator ',', the unary operator '&', or the
10631 // operator '->', the built-in candidates set is empty.
10632 break;
10633
10634 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10635 break;
10636
10637 case OO_Tilde:
10638 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10639 break;
10640
10641 case OO_Equal:
10642 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10643 [[fallthrough]];
10644
10645 case OO_PlusEqual:
10646 case OO_MinusEqual:
10647 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10648 [[fallthrough]];
10649
10650 case OO_StarEqual:
10651 case OO_SlashEqual:
10652 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10653 break;
10654
10655 case OO_PercentEqual:
10656 case OO_LessLessEqual:
10657 case OO_GreaterGreaterEqual:
10658 case OO_AmpEqual:
10659 case OO_CaretEqual:
10660 case OO_PipeEqual:
10661 OpBuilder.addAssignmentIntegralOverloads();
10662 break;
10663
10664 case OO_Exclaim:
10665 OpBuilder.addExclaimOverload();
10666 break;
10667
10668 case OO_AmpAmp:
10669 case OO_PipePipe:
10670 OpBuilder.addAmpAmpOrPipePipeOverload();
10671 break;
10672
10673 case OO_Subscript:
10674 if (Args.size() == 2)
10675 OpBuilder.addSubscriptOverloads();
10676 break;
10677
10678 case OO_ArrowStar:
10679 OpBuilder.addArrowStarOverloads();
10680 break;
10681
10682 case OO_Conditional:
10683 OpBuilder.addConditionalOperatorOverloads();
10684 OpBuilder.addGenericBinaryArithmeticOverloads();
10685 break;
10686 }
10687}
10688
10689void
10690Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10691 SourceLocation Loc,
10692 ArrayRef<Expr *> Args,
10693 TemplateArgumentListInfo *ExplicitTemplateArgs,
10694 OverloadCandidateSet& CandidateSet,
10695 bool PartialOverloading) {
10696 ADLResult Fns;
10697
10698 // FIXME: This approach for uniquing ADL results (and removing
10699 // redundant candidates from the set) relies on pointer-equality,
10700 // which means we need to key off the canonical decl. However,
10701 // always going back to the canonical decl might not get us the
10702 // right set of default arguments. What default arguments are
10703 // we supposed to consider on ADL candidates, anyway?
10704
10705 // FIXME: Pass in the explicit template arguments?
10706 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10707
10708 ArrayRef<Expr *> ReversedArgs;
10709
10710 // Erase all of the candidates we already knew about.
10711 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10712 CandEnd = CandidateSet.end();
10713 Cand != CandEnd; ++Cand)
10714 if (Cand->Function) {
10715 FunctionDecl *Fn = Cand->Function;
10716 Fns.erase(D: Fn);
10717 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10718 Fns.erase(D: FunTmpl);
10719 }
10720
10721 // For each of the ADL candidates we found, add it to the overload
10722 // set.
10723 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10724 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10725
10726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10727 if (ExplicitTemplateArgs)
10728 continue;
10729
10730 AddOverloadCandidate(
10731 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10732 PartialOverloading, /*AllowExplicit=*/true,
10733 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10734 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10735 AddOverloadCandidate(
10736 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10737 /*SuppressUserConversions=*/false, PartialOverloading,
10738 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10739 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10740 }
10741 } else {
10742 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10743 AddTemplateOverloadCandidate(
10744 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10745 /*SuppressUserConversions=*/false, PartialOverloading,
10746 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10747 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10748 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10749
10750 // As template candidates are not deduced immediately,
10751 // persist the array in the overload set.
10752 if (ReversedArgs.empty())
10753 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10754
10755 AddTemplateOverloadCandidate(
10756 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10757 /*SuppressUserConversions=*/false, PartialOverloading,
10758 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10759 PO: OverloadCandidateParamOrder::Reversed);
10760 }
10761 }
10762 }
10763}
10764
10765namespace {
10766enum class Comparison { Equal, Better, Worse };
10767}
10768
10769/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10770/// overload resolution.
10771///
10772/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10773/// Cand1's first N enable_if attributes have precisely the same conditions as
10774/// Cand2's first N enable_if attributes (where N = the number of enable_if
10775/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10776///
10777/// Note that you can have a pair of candidates such that Cand1's enable_if
10778/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10779/// worse than Cand1's.
10780static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10781 const FunctionDecl *Cand2) {
10782 // Common case: One (or both) decls don't have enable_if attrs.
10783 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10784 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10785 if (!Cand1Attr || !Cand2Attr) {
10786 if (Cand1Attr == Cand2Attr)
10787 return Comparison::Equal;
10788 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10789 }
10790
10791 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10792 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10793
10794 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10795 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10796 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10797 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10798
10799 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10800 // has fewer enable_if attributes than Cand2, and vice versa.
10801 if (!Cand1A)
10802 return Comparison::Worse;
10803 if (!Cand2A)
10804 return Comparison::Better;
10805
10806 Cand1ID.clear();
10807 Cand2ID.clear();
10808
10809 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10810 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10811 if (Cand1ID != Cand2ID)
10812 return Comparison::Worse;
10813 }
10814
10815 return Comparison::Equal;
10816}
10817
10818static Comparison
10819isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10820 const OverloadCandidate &Cand2) {
10821 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10822 !Cand2.Function->isMultiVersion())
10823 return Comparison::Equal;
10824
10825 // If both are invalid, they are equal. If one of them is invalid, the other
10826 // is better.
10827 if (Cand1.Function->isInvalidDecl()) {
10828 if (Cand2.Function->isInvalidDecl())
10829 return Comparison::Equal;
10830 return Comparison::Worse;
10831 }
10832 if (Cand2.Function->isInvalidDecl())
10833 return Comparison::Better;
10834
10835 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10836 // cpu_dispatch, else arbitrarily based on the identifiers.
10837 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10838 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10839 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10840 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10841
10842 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10843 return Comparison::Equal;
10844
10845 if (Cand1CPUDisp && !Cand2CPUDisp)
10846 return Comparison::Better;
10847 if (Cand2CPUDisp && !Cand1CPUDisp)
10848 return Comparison::Worse;
10849
10850 if (Cand1CPUSpec && Cand2CPUSpec) {
10851 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10852 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10853 ? Comparison::Better
10854 : Comparison::Worse;
10855
10856 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10857 FirstDiff = std::mismatch(
10858 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10859 first2: Cand2CPUSpec->cpus_begin(),
10860 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10861 return LHS->getName() == RHS->getName();
10862 });
10863
10864 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10865 "Two different cpu-specific versions should not have the same "
10866 "identifier list, otherwise they'd be the same decl!");
10867 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10868 ? Comparison::Better
10869 : Comparison::Worse;
10870 }
10871 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10872}
10873
10874/// Compute the type of the implicit object parameter for the given function,
10875/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10876/// null QualType if there is a 'matches anything' implicit object parameter.
10877static std::optional<QualType>
10878getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10879 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10880 return std::nullopt;
10881
10882 auto *M = cast<CXXMethodDecl>(Val: F);
10883 // Static member functions' object parameters match all types.
10884 if (M->isStatic())
10885 return QualType();
10886 return M->getFunctionObjectParameterReferenceType();
10887}
10888
10889// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10890// represent the same entity.
10891static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10892 const FunctionDecl *F2) {
10893 if (declaresSameEntity(D1: F1, D2: F2))
10894 return true;
10895 auto PT1 = F1->getPrimaryTemplate();
10896 auto PT2 = F2->getPrimaryTemplate();
10897 if (PT1 && PT2) {
10898 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10899 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10900 D2: PT2->getInstantiatedFromMemberTemplate()))
10901 return true;
10902 }
10903 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10904 // different functions with same params). Consider removing this (as no test
10905 // fail w/o it).
10906 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10907 if (First) {
10908 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10909 return *T;
10910 }
10911 assert(I < F->getNumParams());
10912 return F->getParamDecl(i: I++)->getType();
10913 };
10914
10915 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10916 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10917
10918 if (F1NumParams != F2NumParams)
10919 return false;
10920
10921 unsigned I1 = 0, I2 = 0;
10922 for (unsigned I = 0; I != F1NumParams; ++I) {
10923 QualType T1 = NextParam(F1, I1, I == 0);
10924 QualType T2 = NextParam(F2, I2, I == 0);
10925 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10926 if (!Context.hasSameUnqualifiedType(T1, T2))
10927 return false;
10928 }
10929 return true;
10930}
10931
10932/// We're allowed to use constraints partial ordering only if the candidates
10933/// have the same parameter types:
10934/// [over.match.best.general]p2.6
10935/// F1 and F2 are non-template functions with the same
10936/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10937static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10938 FunctionDecl *Fn2,
10939 bool IsFn1Reversed,
10940 bool IsFn2Reversed) {
10941 assert(Fn1 && Fn2);
10942 if (Fn1->isVariadic() != Fn2->isVariadic())
10943 return false;
10944
10945 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10946 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10947 return false;
10948
10949 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10950 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10951 if (Mem1 && Mem2) {
10952 // if they are member functions, both are direct members of the same class,
10953 // and
10954 if (Mem1->getParent() != Mem2->getParent())
10955 return false;
10956 // if both are non-static member functions, they have the same types for
10957 // their object parameters
10958 if (Mem1->isInstance() && Mem2->isInstance() &&
10959 !S.getASTContext().hasSameType(
10960 T1: Mem1->getFunctionObjectParameterReferenceType(),
10961 T2: Mem1->getFunctionObjectParameterReferenceType()))
10962 return false;
10963 }
10964 return true;
10965}
10966
10967static FunctionDecl *
10968getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10969 bool IsFn1Reversed, bool IsFn2Reversed) {
10970 if (!Fn1 || !Fn2)
10971 return nullptr;
10972
10973 // C++ [temp.constr.order]:
10974 // A non-template function F1 is more partial-ordering-constrained than a
10975 // non-template function F2 if:
10976 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10977 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10978
10979 if (Cand1IsSpecialization || Cand2IsSpecialization)
10980 return nullptr;
10981
10982 // - they have the same non-object-parameter-type-lists, and [...]
10983 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10984 IsFn2Reversed))
10985 return nullptr;
10986
10987 // - the declaration of F1 is more constrained than the declaration of F2.
10988 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10989}
10990
10991/// isBetterOverloadCandidate - Determines whether the first overload
10992/// candidate is a better candidate than the second (C++ 13.3.3p1).
10993bool clang::isBetterOverloadCandidate(
10994 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10995 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10996 bool PartialOverloading) {
10997 // Define viable functions to be better candidates than non-viable
10998 // functions.
10999 if (!Cand2.Viable)
11000 return Cand1.Viable;
11001 else if (!Cand1.Viable)
11002 return false;
11003
11004 // [CUDA] A function with 'never' preference is marked not viable, therefore
11005 // is never shown up here. The worst preference shown up here is 'wrong side',
11006 // e.g. an H function called by a HD function in device compilation. This is
11007 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11008 // function which is called only by an H function. A deferred diagnostic will
11009 // be triggered if it is emitted. However a wrong-sided function is still
11010 // a viable candidate here.
11011 //
11012 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11013 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11014 // can be emitted, Cand1 is not better than Cand2. This rule should have
11015 // precedence over other rules.
11016 //
11017 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11018 // other rules should be used to determine which is better. This is because
11019 // host/device based overloading resolution is mostly for determining
11020 // viability of a function. If two functions are both viable, other factors
11021 // should take precedence in preference, e.g. the standard-defined preferences
11022 // like argument conversion ranks or enable_if partial-ordering. The
11023 // preference for pass-object-size parameters is probably most similar to a
11024 // type-based-overloading decision and so should take priority.
11025 //
11026 // If other rules cannot determine which is better, CUDA preference will be
11027 // used again to determine which is better.
11028 //
11029 // TODO: Currently IdentifyPreference does not return correct values
11030 // for functions called in global variable initializers due to missing
11031 // correct context about device/host. Therefore we can only enforce this
11032 // rule when there is a caller. We should enforce this rule for functions
11033 // in global variable initializers once proper context is added.
11034 //
11035 // TODO: We can only enable the hostness based overloading resolution when
11036 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11037 // overloading resolution diagnostics.
11038 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11039 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11040 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11041 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
11042 bool IsCand1ImplicitHD =
11043 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
11044 bool IsCand2ImplicitHD =
11045 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
11046 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
11047 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11048 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11049 // The implicit HD function may be a function in a system header which
11050 // is forced by pragma. In device compilation, if we prefer HD candidates
11051 // over wrong-sided candidates, overloading resolution may change, which
11052 // may result in non-deferrable diagnostics. As a workaround, we let
11053 // implicit HD candidates take equal preference as wrong-sided candidates.
11054 // This will preserve the overloading resolution.
11055 // TODO: We still need special handling of implicit HD functions since
11056 // they may incur other diagnostics to be deferred. We should make all
11057 // host/device related diagnostics deferrable and remove special handling
11058 // of implicit HD functions.
11059 auto EmitThreshold =
11060 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11061 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11062 ? SemaCUDA::CFP_Never
11063 : SemaCUDA::CFP_WrongSide;
11064 auto Cand1Emittable = P1 > EmitThreshold;
11065 auto Cand2Emittable = P2 > EmitThreshold;
11066 if (Cand1Emittable && !Cand2Emittable)
11067 return true;
11068 if (!Cand1Emittable && Cand2Emittable)
11069 return false;
11070 }
11071 }
11072
11073 // C++ [over.match.best]p1: (Changed in C++23)
11074 //
11075 // -- if F is a static member function, ICS1(F) is defined such
11076 // that ICS1(F) is neither better nor worse than ICS1(G) for
11077 // any function G, and, symmetrically, ICS1(G) is neither
11078 // better nor worse than ICS1(F).
11079 unsigned StartArg = 0;
11080 if (!Cand1.TookAddressOfOverload &&
11081 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11082 StartArg = 1;
11083
11084 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11085 // We don't allow incompatible pointer conversions in C++.
11086 if (!S.getLangOpts().CPlusPlus)
11087 return ICS.isStandard() &&
11088 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11089
11090 // The only ill-formed conversion we allow in C++ is the string literal to
11091 // char* conversion, which is only considered ill-formed after C++11.
11092 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11093 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11094 };
11095
11096 // Define functions that don't require ill-formed conversions for a given
11097 // argument to be better candidates than functions that do.
11098 unsigned NumArgs = Cand1.Conversions.size();
11099 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11100 bool HasBetterConversion = false;
11101 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11102 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11103 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11104 if (Cand1Bad != Cand2Bad) {
11105 if (Cand1Bad)
11106 return false;
11107 HasBetterConversion = true;
11108 }
11109 }
11110
11111 if (HasBetterConversion)
11112 return true;
11113
11114 // C++ [over.match.best]p1:
11115 // A viable function F1 is defined to be a better function than another
11116 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11117 // conversion sequence than ICSi(F2), and then...
11118 bool HasWorseConversion = false;
11119 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11120 switch (CompareImplicitConversionSequences(S, Loc,
11121 ICS1: Cand1.Conversions[ArgIdx],
11122 ICS2: Cand2.Conversions[ArgIdx])) {
11123 case ImplicitConversionSequence::Better:
11124 // Cand1 has a better conversion sequence.
11125 HasBetterConversion = true;
11126 break;
11127
11128 case ImplicitConversionSequence::Worse:
11129 if (Cand1.Function && Cand2.Function &&
11130 Cand1.isReversed() != Cand2.isReversed() &&
11131 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11132 // Work around large-scale breakage caused by considering reversed
11133 // forms of operator== in C++20:
11134 //
11135 // When comparing a function against a reversed function, if we have a
11136 // better conversion for one argument and a worse conversion for the
11137 // other, the implicit conversion sequences are treated as being equally
11138 // good.
11139 //
11140 // This prevents a comparison function from being considered ambiguous
11141 // with a reversed form that is written in the same way.
11142 //
11143 // We diagnose this as an extension from CreateOverloadedBinOp.
11144 HasWorseConversion = true;
11145 break;
11146 }
11147
11148 // Cand1 can't be better than Cand2.
11149 return false;
11150
11151 case ImplicitConversionSequence::Indistinguishable:
11152 // Do nothing.
11153 break;
11154 }
11155 }
11156
11157 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11158 // ICSj(F2), or, if not that,
11159 if (HasBetterConversion && !HasWorseConversion)
11160 return true;
11161
11162 // -- the context is an initialization by user-defined conversion
11163 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11164 // from the return type of F1 to the destination type (i.e.,
11165 // the type of the entity being initialized) is a better
11166 // conversion sequence than the standard conversion sequence
11167 // from the return type of F2 to the destination type.
11168 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11169 Cand1.Function && Cand2.Function &&
11170 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11171 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11172
11173 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11174 // First check whether we prefer one of the conversion functions over the
11175 // other. This only distinguishes the results in non-standard, extension
11176 // cases such as the conversion from a lambda closure type to a function
11177 // pointer or block.
11178 ImplicitConversionSequence::CompareKind Result =
11179 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11180 if (Result == ImplicitConversionSequence::Indistinguishable)
11181 Result = CompareStandardConversionSequences(S, Loc,
11182 SCS1: Cand1.FinalConversion,
11183 SCS2: Cand2.FinalConversion);
11184
11185 if (Result != ImplicitConversionSequence::Indistinguishable)
11186 return Result == ImplicitConversionSequence::Better;
11187
11188 // FIXME: Compare kind of reference binding if conversion functions
11189 // convert to a reference type used in direct reference binding, per
11190 // C++14 [over.match.best]p1 section 2 bullet 3.
11191 }
11192
11193 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11194 // as combined with the resolution to CWG issue 243.
11195 //
11196 // When the context is initialization by constructor ([over.match.ctor] or
11197 // either phase of [over.match.list]), a constructor is preferred over
11198 // a conversion function.
11199 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11200 Cand1.Function && Cand2.Function &&
11201 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11202 isa<CXXConstructorDecl>(Val: Cand2.Function))
11203 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11204
11205 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11206 return Cand2.StrictPackMatch;
11207
11208 // -- F1 is a non-template function and F2 is a function template
11209 // specialization, or, if not that,
11210 bool Cand1IsSpecialization = Cand1.Function &&
11211 Cand1.Function->getPrimaryTemplate();
11212 bool Cand2IsSpecialization = Cand2.Function &&
11213 Cand2.Function->getPrimaryTemplate();
11214 if (Cand1IsSpecialization != Cand2IsSpecialization)
11215 return Cand2IsSpecialization;
11216
11217 // -- F1 and F2 are function template specializations, and the function
11218 // template for F1 is more specialized than the template for F2
11219 // according to the partial ordering rules described in 14.5.5.2, or,
11220 // if not that,
11221 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11222 const auto *Obj1Context =
11223 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11224 const auto *Obj2Context =
11225 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11226 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11227 FT1: Cand1.Function->getPrimaryTemplate(),
11228 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11229 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11230 : TPOC_Call,
11231 NumCallArguments1: Cand1.ExplicitCallArguments,
11232 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11233 : QualType{},
11234 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11235 : QualType{},
11236 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11237 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11238 }
11239 }
11240
11241 // -— F1 and F2 are non-template functions and F1 is more
11242 // partial-ordering-constrained than F2 [...],
11243 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11244 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11245 IsFn2Reversed: Cand2.isReversed());
11246 F && F == Cand1.Function)
11247 return true;
11248
11249 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11250 // class B of D, and for all arguments the corresponding parameters of
11251 // F1 and F2 have the same type.
11252 // FIXME: Implement the "all parameters have the same type" check.
11253 bool Cand1IsInherited =
11254 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11255 bool Cand2IsInherited =
11256 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11257 if (Cand1IsInherited != Cand2IsInherited)
11258 return Cand2IsInherited;
11259 else if (Cand1IsInherited) {
11260 assert(Cand2IsInherited);
11261 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11262 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11263 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11264 return true;
11265 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11266 return false;
11267 // Inherited from sibling base classes: still ambiguous.
11268 }
11269
11270 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11271 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11272 // with reversed order of parameters and F1 is not
11273 //
11274 // We rank reversed + different operator as worse than just reversed, but
11275 // that comparison can never happen, because we only consider reversing for
11276 // the maximally-rewritten operator (== or <=>).
11277 if (Cand1.RewriteKind != Cand2.RewriteKind)
11278 return Cand1.RewriteKind < Cand2.RewriteKind;
11279
11280 // Check C++17 tie-breakers for deduction guides.
11281 {
11282 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11283 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11284 if (Guide1 && Guide2) {
11285 // -- F1 is generated from a deduction-guide and F2 is not
11286 if (Guide1->isImplicit() != Guide2->isImplicit())
11287 return Guide2->isImplicit();
11288
11289 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11290 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11291 return true;
11292 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11293 return false;
11294
11295 // --F1 is generated from a non-template constructor and F2 is generated
11296 // from a constructor template
11297 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11298 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11299 if (Constructor1 && Constructor2) {
11300 bool isC1Templated = Constructor1->getTemplatedKind() !=
11301 FunctionDecl::TemplatedKind::TK_NonTemplate;
11302 bool isC2Templated = Constructor2->getTemplatedKind() !=
11303 FunctionDecl::TemplatedKind::TK_NonTemplate;
11304 if (isC1Templated != isC2Templated)
11305 return isC2Templated;
11306 }
11307 }
11308 }
11309
11310 // Check for enable_if value-based overload resolution.
11311 if (Cand1.Function && Cand2.Function) {
11312 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11313 if (Cmp != Comparison::Equal)
11314 return Cmp == Comparison::Better;
11315 }
11316
11317 bool HasPS1 = Cand1.Function != nullptr &&
11318 functionHasPassObjectSizeParams(FD: Cand1.Function);
11319 bool HasPS2 = Cand2.Function != nullptr &&
11320 functionHasPassObjectSizeParams(FD: Cand2.Function);
11321 if (HasPS1 != HasPS2 && HasPS1)
11322 return true;
11323
11324 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11325 if (MV == Comparison::Better)
11326 return true;
11327 if (MV == Comparison::Worse)
11328 return false;
11329
11330 // If other rules cannot determine which is better, CUDA preference is used
11331 // to determine which is better.
11332 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11333 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11334 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11335 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11336 }
11337
11338 // General member function overloading is handled above, so this only handles
11339 // constructors with address spaces.
11340 // This only handles address spaces since C++ has no other
11341 // qualifier that can be used with constructors.
11342 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11343 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11344 if (CD1 && CD2) {
11345 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11346 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11347 if (AS1 != AS2) {
11348 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11349 return true;
11350 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11351 return false;
11352 }
11353 }
11354
11355 return false;
11356}
11357
11358/// Determine whether two declarations are "equivalent" for the purposes of
11359/// name lookup and overload resolution. This applies when the same internal/no
11360/// linkage entity is defined by two modules (probably by textually including
11361/// the same header). In such a case, we don't consider the declarations to
11362/// declare the same entity, but we also don't want lookups with both
11363/// declarations visible to be ambiguous in some cases (this happens when using
11364/// a modularized libstdc++).
11365bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11366 const NamedDecl *B) {
11367 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11368 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11369 if (!VA || !VB)
11370 return false;
11371
11372 // The declarations must be declaring the same name as an internal linkage
11373 // entity in different modules.
11374 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11375 DC: VB->getDeclContext()->getRedeclContext()) ||
11376 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11377 VA->isExternallyVisible() || VB->isExternallyVisible())
11378 return false;
11379
11380 // Check that the declarations appear to be equivalent.
11381 //
11382 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11383 // For constants and functions, we should check the initializer or body is
11384 // the same. For non-constant variables, we shouldn't allow it at all.
11385 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11386 return true;
11387
11388 // Enum constants within unnamed enumerations will have different types, but
11389 // may still be similar enough to be interchangeable for our purposes.
11390 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11391 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11392 // Only handle anonymous enums. If the enumerations were named and
11393 // equivalent, they would have been merged to the same type.
11394 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11395 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11396 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11397 !Context.hasSameType(T1: EnumA->getIntegerType(),
11398 T2: EnumB->getIntegerType()))
11399 return false;
11400 // Allow this only if the value is the same for both enumerators.
11401 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11402 }
11403 }
11404
11405 // Nothing else is sufficiently similar.
11406 return false;
11407}
11408
11409void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11410 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11411 assert(D && "Unknown declaration");
11412 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11413
11414 Module *M = getOwningModule(Entity: D);
11415 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11416 << !M << (M ? M->getFullModuleName() : "");
11417
11418 for (auto *E : Equiv) {
11419 Module *M = getOwningModule(Entity: E);
11420 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11421 << !M << (M ? M->getFullModuleName() : "");
11422 }
11423}
11424
11425bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11426 return FailureKind == ovl_fail_bad_deduction &&
11427 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11428 TemplateDeductionResult::ConstraintsNotSatisfied &&
11429 static_cast<CNSInfo *>(DeductionFailure.Data)
11430 ->Satisfaction.ContainsErrors;
11431}
11432
11433void OverloadCandidateSet::AddDeferredTemplateCandidate(
11434 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11435 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11436 bool PartialOverloading, bool AllowExplicit,
11437 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11438 bool AggregateCandidateDeduction) {
11439
11440 auto *C =
11441 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11442
11443 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11444 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11445 /*AllowObjCConversionOnExplicit=*/false,
11446 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11447 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11448 .FunctionTemplate: FunctionTemplate,
11449 .FoundDecl: FoundDecl,
11450 .Args: Args,
11451 .IsADLCandidate: IsADLCandidate,
11452 .PO: PO};
11453
11454 HasDeferredTemplateConstructors |=
11455 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11456}
11457
11458void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11459 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11460 CXXRecordDecl *ActingContext, QualType ObjectType,
11461 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11462 bool SuppressUserConversions, bool PartialOverloading,
11463 OverloadCandidateParamOrder PO) {
11464
11465 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11466
11467 auto *C =
11468 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11469
11470 C = new (C) DeferredMethodTemplateOverloadCandidate{
11471 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11472 /*AllowObjCConversionOnExplicit=*/false,
11473 /*AllowResultConversion=*/false,
11474 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11475 /*AggregateCandidateDeduction=*/false},
11476 .FunctionTemplate: MethodTmpl,
11477 .FoundDecl: FoundDecl,
11478 .Args: Args,
11479 .ActingContext: ActingContext,
11480 .ObjectClassification: ObjectClassification,
11481 .ObjectType: ObjectType,
11482 .PO: PO};
11483}
11484
11485void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11486 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11487 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11488 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11489 bool AllowResultConversion) {
11490
11491 auto *C =
11492 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11493
11494 C = new (C) DeferredConversionTemplateOverloadCandidate{
11495 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11496 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11497 /*AllowExplicit=*/false,
11498 /*SuppressUserConversions=*/false,
11499 /*PartialOverloading*/ false,
11500 /*AggregateCandidateDeduction=*/false},
11501 .FunctionTemplate: FunctionTemplate,
11502 .FoundDecl: FoundDecl,
11503 .ActingContext: ActingContext,
11504 .From: From,
11505 .ToType: ToType};
11506}
11507
11508static void
11509AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11510 DeferredMethodTemplateOverloadCandidate &C) {
11511
11512 AddMethodTemplateCandidateImmediately(
11513 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11514 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11515 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11516}
11517
11518static void
11519AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11520 DeferredFunctionTemplateOverloadCandidate &C) {
11521 AddTemplateOverloadCandidateImmediately(
11522 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11523 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11524 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11525 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11526}
11527
11528static void
11529AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11530 DeferredConversionTemplateOverloadCandidate &C) {
11531 return AddTemplateConversionCandidateImmediately(
11532 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11533 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11534 AllowResultConversion: C.AllowResultConversion);
11535}
11536
11537void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11538 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11539 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11540 while (Cand) {
11541 switch (Cand->Kind) {
11542 case DeferredTemplateOverloadCandidate::Function:
11543 AddTemplateOverloadCandidate(
11544 S, CandidateSet&: *this,
11545 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11546 break;
11547 case DeferredTemplateOverloadCandidate::Method:
11548 AddTemplateOverloadCandidate(
11549 S, CandidateSet&: *this,
11550 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11551 break;
11552 case DeferredTemplateOverloadCandidate::Conversion:
11553 AddTemplateOverloadCandidate(
11554 S, CandidateSet&: *this,
11555 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11556 break;
11557 }
11558 Cand = Cand->Next;
11559 }
11560 FirstDeferredCandidate = nullptr;
11561 DeferredCandidatesCount = 0;
11562}
11563
11564OverloadingResult
11565OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11566 Best->Best = true;
11567 if (Best->Function && Best->Function->isDeleted())
11568 return OR_Deleted;
11569 return OR_Success;
11570}
11571
11572void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11573 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11574 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11575 // are accepted by both clang and NVCC. However, during a particular
11576 // compilation mode only one call variant is viable. We need to
11577 // exclude non-viable overload candidates from consideration based
11578 // only on their host/device attributes. Specifically, if one
11579 // candidate call is WrongSide and the other is SameSide, we ignore
11580 // the WrongSide candidate.
11581 // We only need to remove wrong-sided candidates here if
11582 // -fgpu-exclude-wrong-side-overloads is off. When
11583 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11584 // uniformly in isBetterOverloadCandidate.
11585 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11586 return;
11587 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11588
11589 bool ContainsSameSideCandidate =
11590 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11591 // Check viable function only.
11592 return Cand->Viable && Cand->Function &&
11593 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11594 SemaCUDA::CFP_SameSide;
11595 });
11596
11597 if (!ContainsSameSideCandidate)
11598 return;
11599
11600 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11601 // Check viable function only to avoid unnecessary data copying/moving.
11602 return Cand->Viable && Cand->Function &&
11603 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11604 SemaCUDA::CFP_WrongSide;
11605 };
11606 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11607}
11608
11609/// Computes the best viable function (C++ 13.3.3)
11610/// within an overload candidate set.
11611///
11612/// \param Loc The location of the function name (or operator symbol) for
11613/// which overload resolution occurs.
11614///
11615/// \param Best If overload resolution was successful or found a deleted
11616/// function, \p Best points to the candidate function found.
11617///
11618/// \returns The result of overload resolution.
11619OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11620 SourceLocation Loc,
11621 iterator &Best) {
11622
11623 assert((shouldDeferTemplateArgumentDeduction(S) ||
11624 DeferredCandidatesCount == 0) &&
11625 "Unexpected deferred template candidates");
11626
11627 bool TwoPhaseResolution =
11628 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11629
11630 if (TwoPhaseResolution) {
11631 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11632 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11633 if (!(HasDeferredTemplateConstructors &&
11634 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11635 return Res;
11636 }
11637 }
11638
11639 InjectNonDeducedTemplateCandidates(S);
11640 return BestViableFunctionImpl(S, Loc, Best);
11641}
11642
11643OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11644 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11645
11646 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11647 Candidates.reserve(N: this->Candidates.size());
11648 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11649 result: std::back_inserter(x&: Candidates),
11650 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11651
11652 if (S.getLangOpts().CUDA)
11653 CudaExcludeWrongSideCandidates(S, Candidates);
11654
11655 Best = end();
11656 for (auto *Cand : Candidates) {
11657 Cand->Best = false;
11658 if (Cand->Viable) {
11659 if (Best == end() ||
11660 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11661 Best = Cand;
11662 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11663 // This candidate has constraint that we were unable to evaluate because
11664 // it referenced an expression that contained an error. Rather than fall
11665 // back onto a potentially unintended candidate (made worse by
11666 // subsuming constraints), treat this as 'no viable candidate'.
11667 Best = end();
11668 return OR_No_Viable_Function;
11669 }
11670 }
11671
11672 // If we didn't find any viable functions, abort.
11673 if (Best == end())
11674 return OR_No_Viable_Function;
11675
11676 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11677 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11678 PendingBest.push_back(Elt: &*Best);
11679 Best->Best = true;
11680
11681 // Make sure that this function is better than every other viable
11682 // function. If not, we have an ambiguity.
11683 while (!PendingBest.empty()) {
11684 auto *Curr = PendingBest.pop_back_val();
11685 for (auto *Cand : Candidates) {
11686 if (Cand->Viable && !Cand->Best &&
11687 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11688 PendingBest.push_back(Elt: Cand);
11689 Cand->Best = true;
11690
11691 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11692 B: Curr->Function))
11693 EquivalentCands.push_back(Elt: Cand->Function);
11694 else
11695 Best = end();
11696 }
11697 }
11698 }
11699
11700 if (Best == end())
11701 return OR_Ambiguous;
11702
11703 OverloadingResult R = ResultForBestCandidate(Best);
11704
11705 if (!EquivalentCands.empty())
11706 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11707 Equiv: EquivalentCands);
11708 return R;
11709}
11710
11711namespace {
11712
11713enum OverloadCandidateKind {
11714 oc_function,
11715 oc_method,
11716 oc_reversed_binary_operator,
11717 oc_constructor,
11718 oc_implicit_default_constructor,
11719 oc_implicit_copy_constructor,
11720 oc_implicit_move_constructor,
11721 oc_implicit_copy_assignment,
11722 oc_implicit_move_assignment,
11723 oc_implicit_equality_comparison,
11724 oc_inherited_constructor
11725};
11726
11727enum OverloadCandidateSelect {
11728 ocs_non_template,
11729 ocs_template,
11730 ocs_described_template,
11731};
11732
11733static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11734ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11735 const FunctionDecl *Fn,
11736 OverloadCandidateRewriteKind CRK,
11737 std::string &Description) {
11738
11739 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11740 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11741 isTemplate = true;
11742 Description = S.getTemplateArgumentBindingsText(
11743 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11744 }
11745
11746 OverloadCandidateSelect Select = [&]() {
11747 if (!Description.empty())
11748 return ocs_described_template;
11749 return isTemplate ? ocs_template : ocs_non_template;
11750 }();
11751
11752 OverloadCandidateKind Kind = [&]() {
11753 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11754 return oc_implicit_equality_comparison;
11755
11756 if (CRK & CRK_Reversed)
11757 return oc_reversed_binary_operator;
11758
11759 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11760 if (!Ctor->isImplicit()) {
11761 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11762 return oc_inherited_constructor;
11763 else
11764 return oc_constructor;
11765 }
11766
11767 if (Ctor->isDefaultConstructor())
11768 return oc_implicit_default_constructor;
11769
11770 if (Ctor->isMoveConstructor())
11771 return oc_implicit_move_constructor;
11772
11773 assert(Ctor->isCopyConstructor() &&
11774 "unexpected sort of implicit constructor");
11775 return oc_implicit_copy_constructor;
11776 }
11777
11778 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11779 // This actually gets spelled 'candidate function' for now, but
11780 // it doesn't hurt to split it out.
11781 if (!Meth->isImplicit())
11782 return oc_method;
11783
11784 if (Meth->isMoveAssignmentOperator())
11785 return oc_implicit_move_assignment;
11786
11787 if (Meth->isCopyAssignmentOperator())
11788 return oc_implicit_copy_assignment;
11789
11790 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11791 return oc_method;
11792 }
11793
11794 return oc_function;
11795 }();
11796
11797 return std::make_pair(x&: Kind, y&: Select);
11798}
11799
11800void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11801 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11802 // set.
11803 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11804 S.Diag(Loc: FoundDecl->getLocation(),
11805 DiagID: diag::note_ovl_candidate_inherited_constructor)
11806 << Shadow->getNominatedBaseClass();
11807}
11808
11809} // end anonymous namespace
11810
11811static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11812 const FunctionDecl *FD) {
11813 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11814 bool AlwaysTrue;
11815 if (EnableIf->getCond()->isValueDependent() ||
11816 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11817 return false;
11818 if (!AlwaysTrue)
11819 return false;
11820 }
11821 return true;
11822}
11823
11824/// Returns true if we can take the address of the function.
11825///
11826/// \param Complain - If true, we'll emit a diagnostic
11827/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11828/// we in overload resolution?
11829/// \param Loc - The location of the statement we're complaining about. Ignored
11830/// if we're not complaining, or if we're in overload resolution.
11831static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11832 bool Complain,
11833 bool InOverloadResolution,
11834 SourceLocation Loc) {
11835 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11836 if (Complain) {
11837 if (InOverloadResolution)
11838 S.Diag(Loc: FD->getBeginLoc(),
11839 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11840 else
11841 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11842 }
11843 return false;
11844 }
11845
11846 if (FD->getTrailingRequiresClause()) {
11847 ConstraintSatisfaction Satisfaction;
11848 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11849 return false;
11850 if (!Satisfaction.IsSatisfied) {
11851 if (Complain) {
11852 if (InOverloadResolution) {
11853 SmallString<128> TemplateArgString;
11854 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11855 TemplateArgString += " ";
11856 TemplateArgString += S.getTemplateArgumentBindingsText(
11857 Params: FunTmpl->getTemplateParameters(),
11858 Args: *FD->getTemplateSpecializationArgs());
11859 }
11860
11861 S.Diag(Loc: FD->getBeginLoc(),
11862 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11863 << TemplateArgString;
11864 } else
11865 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11866 << FD;
11867 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11868 }
11869 return false;
11870 }
11871 }
11872
11873 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11874 return P->hasAttr<PassObjectSizeAttr>();
11875 });
11876 if (I == FD->param_end())
11877 return true;
11878
11879 if (Complain) {
11880 // Add one to ParamNo because it's user-facing
11881 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11882 if (InOverloadResolution)
11883 S.Diag(Loc: FD->getLocation(),
11884 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11885 << ParamNo;
11886 else
11887 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11888 << FD << ParamNo;
11889 }
11890 return false;
11891}
11892
11893static bool checkAddressOfCandidateIsAvailable(Sema &S,
11894 const FunctionDecl *FD) {
11895 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11896 /*InOverloadResolution=*/true,
11897 /*Loc=*/SourceLocation());
11898}
11899
11900bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11901 bool Complain,
11902 SourceLocation Loc) {
11903 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11904 /*InOverloadResolution=*/false,
11905 Loc);
11906}
11907
11908// Don't print candidates other than the one that matches the calling
11909// convention of the call operator, since that is guaranteed to exist.
11910static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11911 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11912
11913 if (!ConvD)
11914 return false;
11915 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11916 if (!RD->isLambda())
11917 return false;
11918
11919 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11920 CallingConv CallOpCC =
11921 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11922 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11923 CallingConv ConvToCC =
11924 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11925
11926 return ConvToCC != CallOpCC;
11927}
11928
11929// Notes the location of an overload candidate.
11930void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11931 OverloadCandidateRewriteKind RewriteKind,
11932 QualType DestType, bool TakingAddress) {
11933 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11934 return;
11935 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11936 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11937 return;
11938 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11939 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11940 return;
11941 if (shouldSkipNotingLambdaConversionDecl(Fn))
11942 return;
11943
11944 std::string FnDesc;
11945 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11946 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11947 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11948 << (unsigned)KSPair.first << (unsigned)KSPair.second
11949 << Fn << FnDesc;
11950
11951 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11952 Diag(Loc: Fn->getLocation(), PD);
11953 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11954}
11955
11956static void
11957MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11958 // Perhaps the ambiguity was caused by two atomic constraints that are
11959 // 'identical' but not equivalent:
11960 //
11961 // void foo() requires (sizeof(T) > 4) { } // #1
11962 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11963 //
11964 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11965 // #2 to subsume #1, but these constraint are not considered equivalent
11966 // according to the subsumption rules because they are not the same
11967 // source-level construct. This behavior is quite confusing and we should try
11968 // to help the user figure out what happened.
11969
11970 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11971 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11972 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11973 if (!I->Function)
11974 continue;
11975 SmallVector<AssociatedConstraint, 3> AC;
11976 if (auto *Template = I->Function->getPrimaryTemplate())
11977 Template->getAssociatedConstraints(AC);
11978 else
11979 I->Function->getAssociatedConstraints(ACs&: AC);
11980 if (AC.empty())
11981 continue;
11982 if (FirstCand == nullptr) {
11983 FirstCand = I->Function;
11984 FirstAC = AC;
11985 } else if (SecondCand == nullptr) {
11986 SecondCand = I->Function;
11987 SecondAC = AC;
11988 } else {
11989 // We have more than one pair of constrained functions - this check is
11990 // expensive and we'd rather not try to diagnose it.
11991 return;
11992 }
11993 }
11994 if (!SecondCand)
11995 return;
11996 // The diagnostic can only happen if there are associated constraints on
11997 // both sides (there needs to be some identical atomic constraint).
11998 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11999 D2: SecondCand, AC2: SecondAC))
12000 // Just show the user one diagnostic, they'll probably figure it out
12001 // from here.
12002 return;
12003}
12004
12005// Notes the location of all overload candidates designated through
12006// OverloadedExpr
12007void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12008 bool TakingAddress) {
12009 assert(OverloadedExpr->getType() == Context.OverloadTy);
12010
12011 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
12012 OverloadExpr *OvlExpr = Ovl.Expression;
12013
12014 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12015 IEnd = OvlExpr->decls_end();
12016 I != IEnd; ++I) {
12017 if (FunctionTemplateDecl *FunTmpl =
12018 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12019 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
12020 TakingAddress);
12021 } else if (FunctionDecl *Fun
12022 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12023 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
12024 }
12025 }
12026}
12027
12028/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12029/// "lead" diagnostic; it will be given two arguments, the source and
12030/// target types of the conversion.
12031void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
12032 Sema &S,
12033 SourceLocation CaretLoc,
12034 const PartialDiagnostic &PDiag) const {
12035 S.Diag(Loc: CaretLoc, PD: PDiag)
12036 << Ambiguous.getFromType() << Ambiguous.getToType();
12037 unsigned CandsShown = 0;
12038 AmbiguousConversionSequence::const_iterator I, E;
12039 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12040 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12041 break;
12042 ++CandsShown;
12043 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
12044 }
12045 S.Diags.overloadCandidatesShown(N: CandsShown);
12046 if (I != E)
12047 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12048}
12049
12050static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
12051 unsigned I, bool TakingCandidateAddress) {
12052 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12053 assert(Conv.isBad());
12054 assert(Cand->Function && "for now, candidate must be a function");
12055 FunctionDecl *Fn = Cand->Function;
12056
12057 // There's a conversion slot for the object argument if this is a
12058 // non-constructor method. Note that 'I' corresponds the
12059 // conversion-slot index.
12060 bool isObjectArgument = false;
12061 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12062 !isa<CXXConstructorDecl>(Val: Fn)) {
12063 if (I == 0)
12064 isObjectArgument = true;
12065 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12066 I--;
12067 }
12068
12069 std::string FnDesc;
12070 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12071 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12072 Description&: FnDesc);
12073
12074 Expr *FromExpr = Conv.Bad.FromExpr;
12075 QualType FromTy = Conv.Bad.getFromType();
12076 QualType ToTy = Conv.Bad.getToType();
12077 SourceRange ToParamRange;
12078
12079 // FIXME: In presence of parameter packs we can't determine parameter range
12080 // reliably, as we don't have access to instantiation.
12081 bool HasParamPack =
12082 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12083 return Parm->isParameterPack();
12084 });
12085 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12086 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12087
12088 if (FromTy == S.Context.OverloadTy) {
12089 assert(FromExpr && "overload set argument came from implicit argument?");
12090 Expr *E = FromExpr->IgnoreParens();
12091 if (isa<UnaryOperator>(Val: E))
12092 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12093 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12094
12095 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12096 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12097 << ToParamRange << ToTy << Name << I + 1;
12098 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12099 return;
12100 }
12101
12102 // Do some hand-waving analysis to see if the non-viability is due
12103 // to a qualifier mismatch.
12104 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12105 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12106 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12107 CToTy = RT->getPointeeType();
12108 else {
12109 // TODO: detect and diagnose the full richness of const mismatches.
12110 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12111 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12112 CFromTy = FromPT->getPointeeType();
12113 CToTy = ToPT->getPointeeType();
12114 }
12115 }
12116
12117 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12118 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12119 Qualifiers FromQs = CFromTy.getQualifiers();
12120 Qualifiers ToQs = CToTy.getQualifiers();
12121
12122 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12123 if (isObjectArgument)
12124 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12125 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12126 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12127 else
12128 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12129 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12130 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12131 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12132 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12133 return;
12134 }
12135
12136 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12137 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12138 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12139 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12140 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12141 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12142 return;
12143 }
12144
12145 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12146 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12147 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12148 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12149 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12150 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12151 return;
12152 }
12153
12154 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12155 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12156 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12157 << FromTy << !!FromQs.getPointerAuth()
12158 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12159 << ToQs.getPointerAuth().getAsString() << I + 1
12160 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12161 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12162 return;
12163 }
12164
12165 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12166 assert(CVR && "expected qualifiers mismatch");
12167
12168 if (isObjectArgument) {
12169 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12170 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12171 << FromTy << (CVR - 1);
12172 } else {
12173 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12174 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12175 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12176 }
12177 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12178 return;
12179 }
12180
12181 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12182 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12183 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12184 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12185 << (unsigned)isObjectArgument << I + 1
12186 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12187 << ToParamRange;
12188 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12189 return;
12190 }
12191
12192 // Special diagnostic for failure to convert an initializer list, since
12193 // telling the user that it has type void is not useful.
12194 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12195 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12196 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12197 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12198 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12199 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12200 ? 2
12201 : 0);
12202 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12203 return;
12204 }
12205
12206 // Diagnose references or pointers to incomplete types differently,
12207 // since it's far from impossible that the incompleteness triggered
12208 // the failure.
12209 QualType TempFromTy = FromTy.getNonReferenceType();
12210 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12211 TempFromTy = PTy->getPointeeType();
12212 if (TempFromTy->isIncompleteType()) {
12213 // Emit the generic diagnostic and, optionally, add the hints to it.
12214 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12215 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12216 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12217 << (unsigned)(Cand->Fix.Kind);
12218
12219 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12220 return;
12221 }
12222
12223 // Diagnose base -> derived pointer conversions.
12224 unsigned BaseToDerivedConversion = 0;
12225 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12226 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12227 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12228 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12229 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12230 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12231 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12232 Base: FromPtrTy->getPointeeType()))
12233 BaseToDerivedConversion = 1;
12234 }
12235 } else if (const ObjCObjectPointerType *FromPtrTy
12236 = FromTy->getAs<ObjCObjectPointerType>()) {
12237 if (const ObjCObjectPointerType *ToPtrTy
12238 = ToTy->getAs<ObjCObjectPointerType>())
12239 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12240 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12241 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12242 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12243 FromIface->isSuperClassOf(I: ToIface))
12244 BaseToDerivedConversion = 2;
12245 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12246 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12247 Ctx: S.getASTContext()) &&
12248 !FromTy->isIncompleteType() &&
12249 !ToRefTy->getPointeeType()->isIncompleteType() &&
12250 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12251 BaseToDerivedConversion = 3;
12252 }
12253 }
12254
12255 if (BaseToDerivedConversion) {
12256 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12257 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12258 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12259 << I + 1;
12260 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12261 return;
12262 }
12263
12264 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12265 isa<PointerType>(Val: CToTy)) {
12266 Qualifiers FromQs = CFromTy.getQualifiers();
12267 Qualifiers ToQs = CToTy.getQualifiers();
12268 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12269 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12270 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12271 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12272 << I + 1;
12273 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12274 return;
12275 }
12276 }
12277
12278 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12279 return;
12280
12281 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12282 // although this is almost always an error and we advise against it.
12283 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12284 ToTy == S.Context.getLogicalOperationType()) {
12285 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12286 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12287 << Conv.Bad.FromExpr << ToTy;
12288 return;
12289 }
12290
12291 // Emit the generic diagnostic and, optionally, add the hints to it.
12292 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12293 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12294 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12295 << (unsigned)(Cand->Fix.Kind);
12296
12297 // Check that location of Fn is not in system header.
12298 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12299 // If we can fix the conversion, suggest the FixIts.
12300 for (const FixItHint &HI : Cand->Fix.Hints)
12301 FDiag << HI;
12302 }
12303
12304 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12305
12306 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12307}
12308
12309/// Additional arity mismatch diagnosis specific to a function overload
12310/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12311/// over a candidate in any candidate set.
12312static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12313 unsigned NumArgs, bool IsAddressOf = false) {
12314 assert(Cand->Function && "Candidate is required to be a function.");
12315 FunctionDecl *Fn = Cand->Function;
12316 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12317 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12318
12319 // With invalid overloaded operators, it's possible that we think we
12320 // have an arity mismatch when in fact it looks like we have the
12321 // right number of arguments, because only overloaded operators have
12322 // the weird behavior of overloading member and non-member functions.
12323 // Just don't report anything.
12324 if (Fn->isInvalidDecl() &&
12325 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12326 return true;
12327
12328 if (NumArgs < MinParams) {
12329 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12330 (Cand->FailureKind == ovl_fail_bad_deduction &&
12331 Cand->DeductionFailure.getResult() ==
12332 TemplateDeductionResult::TooFewArguments));
12333 } else {
12334 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12335 (Cand->FailureKind == ovl_fail_bad_deduction &&
12336 Cand->DeductionFailure.getResult() ==
12337 TemplateDeductionResult::TooManyArguments));
12338 }
12339
12340 return false;
12341}
12342
12343/// General arity mismatch diagnosis over a candidate in a candidate set.
12344static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12345 unsigned NumFormalArgs,
12346 bool IsAddressOf = false) {
12347 assert(isa<FunctionDecl>(D) &&
12348 "The templated declaration should at least be a function"
12349 " when diagnosing bad template argument deduction due to too many"
12350 " or too few arguments");
12351
12352 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12353
12354 // TODO: treat calls to a missing default constructor as a special case
12355 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12356 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12357 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12358
12359 // at least / at most / exactly
12360 bool HasExplicitObjectParam =
12361 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12362
12363 unsigned ParamCount =
12364 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12365 unsigned mode, modeCount;
12366
12367 if (NumFormalArgs < MinParams) {
12368 if (MinParams != ParamCount || FnTy->isVariadic() ||
12369 FnTy->isTemplateVariadic())
12370 mode = 0; // "at least"
12371 else
12372 mode = 2; // "exactly"
12373 modeCount = MinParams;
12374 } else {
12375 if (MinParams != ParamCount)
12376 mode = 1; // "at most"
12377 else
12378 mode = 2; // "exactly"
12379 modeCount = ParamCount;
12380 }
12381
12382 std::string Description;
12383 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12384 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12385
12386 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12387 if (modeCount == 1 && !IsAddressOf &&
12388 FirstNonObjectParamIdx < Fn->getNumParams() &&
12389 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12390 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12391 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12392 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12393 << NumFormalArgs << HasExplicitObjectParam
12394 << Fn->getParametersSourceRange();
12395 else
12396 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12397 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12398 << Description << mode << modeCount << NumFormalArgs
12399 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12400
12401 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12402}
12403
12404/// Arity mismatch diagnosis specific to a function overload candidate.
12405static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12406 unsigned NumFormalArgs) {
12407 assert(Cand->Function && "Candidate must be a function");
12408 FunctionDecl *Fn = Cand->Function;
12409 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12410 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12411 IsAddressOf: Cand->TookAddressOfOverload);
12412}
12413
12414static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12415 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12416 return TD;
12417 llvm_unreachable("Unsupported: Getting the described template declaration"
12418 " for bad deduction diagnosis");
12419}
12420
12421/// Diagnose a failed template-argument deduction.
12422static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12423 DeductionFailureInfo &DeductionFailure,
12424 unsigned NumArgs, bool TakingCandidateAddress,
12425 TemplateSpecCandidateSetKind CandidateSetKind =
12426 TemplateSpecCandidateSetKind::Normal) {
12427 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12428 NamedDecl *ParamD;
12429 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12430 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12431 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12432 switch (DeductionFailure.getResult()) {
12433 case TemplateDeductionResult::Success:
12434 llvm_unreachable(
12435 "TemplateDeductionResult::Success while diagnosing bad deduction");
12436 case TemplateDeductionResult::NonDependentConversionFailure:
12437 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12438 "while diagnosing bad deduction");
12439 case TemplateDeductionResult::Invalid:
12440 case TemplateDeductionResult::AlreadyDiagnosed:
12441 return;
12442
12443 case TemplateDeductionResult::Incomplete: {
12444 assert(ParamD && "no parameter found for incomplete deduction result");
12445 S.Diag(Loc: Templated->getLocation(),
12446 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12447 << ParamD->getDeclName();
12448 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12449 return;
12450 }
12451
12452 case TemplateDeductionResult::IncompletePack: {
12453 assert(ParamD && "no parameter found for incomplete deduction result");
12454 S.Diag(Loc: Templated->getLocation(),
12455 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12456 << ParamD->getDeclName()
12457 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12458 << *DeductionFailure.getFirstArg();
12459 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12460 return;
12461 }
12462
12463 case TemplateDeductionResult::Underqualified: {
12464 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12465 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12466
12467 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12468
12469 // Param will have been canonicalized, but it should just be a
12470 // qualified version of ParamD, so move the qualifiers to that.
12471 QualifierCollector Qs;
12472 Qs.strip(type: Param);
12473 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12474 assert(S.Context.hasSameType(Param, NonCanonParam));
12475
12476 // Arg has also been canonicalized, but there's nothing we can do
12477 // about that. It also doesn't matter as much, because it won't
12478 // have any template parameters in it (because deduction isn't
12479 // done on dependent types).
12480 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12481
12482 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12483 << ParamD->getDeclName() << Arg << NonCanonParam;
12484 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12485 return;
12486 }
12487
12488 case TemplateDeductionResult::Inconsistent: {
12489 assert(ParamD && "no parameter found for inconsistent deduction result");
12490 int which = 0;
12491 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12492 which = 0;
12493 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12494 // Deduction might have failed because we deduced arguments of two
12495 // different types for a non-type template parameter.
12496 // FIXME: Use a different TDK value for this.
12497 QualType T1 =
12498 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12499 QualType T2 =
12500 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12501 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12502 S.Diag(Loc: Templated->getLocation(),
12503 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12504 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12505 << *DeductionFailure.getSecondArg() << T2;
12506 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12507 return;
12508 }
12509
12510 which = 1;
12511 } else {
12512 which = 2;
12513 }
12514
12515 // Tweak the diagnostic if the problem is that we deduced packs of
12516 // different arities. We'll print the actual packs anyway in case that
12517 // includes additional useful information.
12518 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12519 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12520 DeductionFailure.getFirstArg()->pack_size() !=
12521 DeductionFailure.getSecondArg()->pack_size()) {
12522 which = 3;
12523 }
12524
12525 S.Diag(Loc: Templated->getLocation(),
12526 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12527 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12528 << *DeductionFailure.getSecondArg();
12529 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12530 return;
12531 }
12532
12533 case TemplateDeductionResult::InvalidExplicitArguments: {
12534 assert(ParamD && "no parameter found for invalid explicit arguments");
12535
12536 auto Diag = S.Diag(Loc: Templated->getLocation(),
12537 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch);
12538 if (ParamD->getDeclName())
12539 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12540 else
12541 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12542 << (getDepthAndIndex(ND: ParamD).second + 1);
12543 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12544 SmallString<128> DiagContent;
12545 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: DiagContent);
12546 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12547 } else {
12548 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12549 }
12550
12551 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12552 return;
12553 }
12554 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12555 // Format the template argument list into the argument string.
12556 SmallString<128> TemplateArgString;
12557 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12558 TemplateArgString = " ";
12559 TemplateArgString += S.getTemplateArgumentBindingsText(
12560 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12561 if (TemplateArgString.size() == 1)
12562 TemplateArgString.clear();
12563 S.Diag(Loc: Templated->getLocation(),
12564 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12565 << TemplateArgString;
12566
12567 S.DiagnoseUnsatisfiedConstraint(
12568 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12569 return;
12570 }
12571 case TemplateDeductionResult::TooManyArguments:
12572 case TemplateDeductionResult::TooFewArguments:
12573 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12574 return;
12575
12576 case TemplateDeductionResult::InstantiationDepth:
12577 S.Diag(Loc: Templated->getLocation(),
12578 DiagID: diag::note_ovl_candidate_instantiation_depth);
12579 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12580 return;
12581
12582 case TemplateDeductionResult::SubstitutionFailure: {
12583 // Format the template argument list into the argument string.
12584 SmallString<128> TemplateArgString;
12585 if (TemplateArgumentList *Args =
12586 DeductionFailure.getTemplateArgumentList()) {
12587 TemplateArgString = " ";
12588 TemplateArgString += S.getTemplateArgumentBindingsText(
12589 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12590 if (TemplateArgString.size() == 1)
12591 TemplateArgString.clear();
12592 }
12593
12594 // If this candidate was disabled by enable_if, say so.
12595 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12596 if (PDiag && PDiag->second.getDiagID() ==
12597 diag::err_typename_nested_not_found_enable_if) {
12598 // FIXME: Use the source range of the condition, and the fully-qualified
12599 // name of the enable_if template. These are both present in PDiag.
12600 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12601 << "'enable_if'" << TemplateArgString;
12602 return;
12603 }
12604
12605 // We found a specific requirement that disabled the enable_if.
12606 if (PDiag && PDiag->second.getDiagID() ==
12607 diag::err_typename_nested_not_found_requirement) {
12608 S.Diag(Loc: Templated->getLocation(),
12609 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12610 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12611 return;
12612 }
12613
12614 // Format the SFINAE diagnostic into the argument string.
12615 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12616 // formatted message in another diagnostic.
12617 SmallString<128> SFINAEArgString;
12618 SourceRange R;
12619 if (PDiag) {
12620 SFINAEArgString = ": ";
12621 R = SourceRange(PDiag->first, PDiag->first);
12622 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12623 }
12624
12625 S.Diag(Loc: Templated->getLocation(),
12626 DiagID: diag::note_ovl_candidate_substitution_failure)
12627 << TemplateArgString << SFINAEArgString << R;
12628 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12629 return;
12630 }
12631
12632 case TemplateDeductionResult::DeducedMismatch:
12633 case TemplateDeductionResult::DeducedMismatchNested: {
12634 // Format the template argument list into the argument string.
12635 SmallString<128> TemplateArgString;
12636 if (TemplateArgumentList *Args =
12637 DeductionFailure.getTemplateArgumentList()) {
12638 TemplateArgString = " ";
12639 TemplateArgString += S.getTemplateArgumentBindingsText(
12640 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12641 if (TemplateArgString.size() == 1)
12642 TemplateArgString.clear();
12643 }
12644
12645 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12646 << (*DeductionFailure.getCallArgIndex() + 1)
12647 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12648 << TemplateArgString
12649 << (DeductionFailure.getResult() ==
12650 TemplateDeductionResult::DeducedMismatchNested);
12651 break;
12652 }
12653
12654 case TemplateDeductionResult::NonDeducedMismatch: {
12655 // FIXME: Provide a source location to indicate what we couldn't match.
12656 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12657 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12658 if (FirstTA.getKind() == TemplateArgument::Template &&
12659 SecondTA.getKind() == TemplateArgument::Template) {
12660 TemplateName FirstTN = FirstTA.getAsTemplate();
12661 TemplateName SecondTN = SecondTA.getAsTemplate();
12662 if (FirstTN.getKind() == TemplateName::Template &&
12663 SecondTN.getKind() == TemplateName::Template) {
12664 if (FirstTN.getAsTemplateDecl()->getName() ==
12665 SecondTN.getAsTemplateDecl()->getName()) {
12666 // FIXME: This fixes a bad diagnostic where both templates are named
12667 // the same. This particular case is a bit difficult since:
12668 // 1) It is passed as a string to the diagnostic printer.
12669 // 2) The diagnostic printer only attempts to find a better
12670 // name for types, not decls.
12671 // Ideally, this should folded into the diagnostic printer.
12672 S.Diag(Loc: Templated->getLocation(),
12673 DiagID: CandidateSetKind ==
12674 TemplateSpecCandidateSetKind::FriendTemplate
12675 ? diag::note_friend_template_non_deduced_mismatch_qualified
12676 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12677 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12678 return;
12679 }
12680 }
12681 }
12682
12683 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12684 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12685 return;
12686
12687 // FIXME: For generic lambda parameters, check if the function is a lambda
12688 // call operator, and if so, emit a prettier and more informative
12689 // diagnostic that mentions 'auto' and lambda in addition to
12690 // (or instead of?) the canonical template type parameters.
12691 S.Diag(Loc: Templated->getLocation(),
12692 DiagID: CandidateSetKind == TemplateSpecCandidateSetKind::FriendTemplate
12693 ? diag::note_friend_template_non_deduced_mismatch
12694 : diag::note_ovl_candidate_non_deduced_mismatch)
12695 << FirstTA << SecondTA;
12696 return;
12697 }
12698 // TODO: diagnose these individually, then kill off
12699 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12700 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12701 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12702 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12703 return;
12704 case TemplateDeductionResult::CUDATargetMismatch:
12705 S.Diag(Loc: Templated->getLocation(),
12706 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12707 return;
12708 }
12709}
12710
12711/// Diagnose a failed template-argument deduction, for function calls.
12712static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12713 unsigned NumArgs,
12714 bool TakingCandidateAddress) {
12715 assert(Cand->Function && "Candidate must be a function");
12716 FunctionDecl *Fn = Cand->Function;
12717 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12718 if (TDK == TemplateDeductionResult::TooFewArguments ||
12719 TDK == TemplateDeductionResult::TooManyArguments) {
12720 if (CheckArityMismatch(S, Cand, NumArgs))
12721 return;
12722 }
12723 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12724 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12725}
12726
12727/// CUDA: diagnose an invalid call across targets.
12728static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12729 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12730 assert(Cand->Function && "Candidate must be a Function.");
12731 FunctionDecl *Callee = Cand->Function;
12732
12733 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12734 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12735
12736 std::string FnDesc;
12737 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12738 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12739 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12740
12741 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12742 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12743 << FnDesc /* Ignored */
12744 << CalleeTarget << CallerTarget;
12745
12746 // This could be an implicit constructor for which we could not infer the
12747 // target due to a collsion. Diagnose that case.
12748 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12749 if (Meth != nullptr && Meth->isImplicit()) {
12750 CXXRecordDecl *ParentClass = Meth->getParent();
12751 CXXSpecialMemberKind CSM;
12752
12753 switch (FnKindPair.first) {
12754 default:
12755 return;
12756 case oc_implicit_default_constructor:
12757 CSM = CXXSpecialMemberKind::DefaultConstructor;
12758 break;
12759 case oc_implicit_copy_constructor:
12760 CSM = CXXSpecialMemberKind::CopyConstructor;
12761 break;
12762 case oc_implicit_move_constructor:
12763 CSM = CXXSpecialMemberKind::MoveConstructor;
12764 break;
12765 case oc_implicit_copy_assignment:
12766 CSM = CXXSpecialMemberKind::CopyAssignment;
12767 break;
12768 case oc_implicit_move_assignment:
12769 CSM = CXXSpecialMemberKind::MoveAssignment;
12770 break;
12771 };
12772
12773 bool ConstRHS = false;
12774 if (Meth->getNumParams()) {
12775 if (const ReferenceType *RT =
12776 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12777 ConstRHS = RT->getPointeeType().isConstQualified();
12778 }
12779 }
12780
12781 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12782 /* ConstRHS */ ConstRHS,
12783 /* Diagnose */ true);
12784 }
12785}
12786
12787static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12788 assert(Cand->Function && "Candidate must be a function");
12789 FunctionDecl *Callee = Cand->Function;
12790 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12791
12792 S.Diag(Loc: Callee->getLocation(),
12793 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12794 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12795}
12796
12797static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12798 assert(Cand->Function && "Candidate must be a function");
12799 FunctionDecl *Fn = Cand->Function;
12800 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12801 assert(ES.isExplicit() && "not an explicit candidate");
12802
12803 unsigned Kind;
12804 switch (Fn->getDeclKind()) {
12805 case Decl::Kind::CXXConstructor:
12806 Kind = 0;
12807 break;
12808 case Decl::Kind::CXXConversion:
12809 Kind = 1;
12810 break;
12811 case Decl::Kind::CXXDeductionGuide:
12812 Kind = Fn->isImplicit() ? 0 : 2;
12813 break;
12814 default:
12815 llvm_unreachable("invalid Decl");
12816 }
12817
12818 // Note the location of the first (in-class) declaration; a redeclaration
12819 // (particularly an out-of-class definition) will typically lack the
12820 // 'explicit' specifier.
12821 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12822 FunctionDecl *First = Fn->getFirstDecl();
12823 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12824 First = Pattern->getFirstDecl();
12825
12826 S.Diag(Loc: First->getLocation(),
12827 DiagID: diag::note_ovl_candidate_explicit)
12828 << Kind << (ES.getExpr() ? 1 : 0)
12829 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12830}
12831
12832static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12833 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12834 if (!DG)
12835 return;
12836 TemplateDecl *OriginTemplate =
12837 DG->getDeclName().getCXXDeductionGuideTemplate();
12838 // We want to always print synthesized deduction guides for type aliases.
12839 // They would retain the explicit bit of the corresponding constructor.
12840 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12841 return;
12842 std::string FunctionProto;
12843 llvm::raw_string_ostream OS(FunctionProto);
12844 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12845 if (!Template) {
12846 // This also could be an instantiation. Find out the primary template.
12847 FunctionDecl *Pattern =
12848 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12849 if (!Pattern) {
12850 // The implicit deduction guide is built on an explicit non-template
12851 // deduction guide. Currently, this might be the case only for type
12852 // aliases.
12853 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12854 // gets merged.
12855 assert(OriginTemplate->isTypeAlias() &&
12856 "Non-template implicit deduction guides are only possible for "
12857 "type aliases");
12858 DG->print(Out&: OS);
12859 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12860 << FunctionProto;
12861 return;
12862 }
12863 Template = Pattern->getDescribedFunctionTemplate();
12864 assert(Template && "Cannot find the associated function template of "
12865 "CXXDeductionGuideDecl?");
12866 }
12867 Template->print(Out&: OS);
12868 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12869 << FunctionProto;
12870}
12871
12872/// Generates a 'note' diagnostic for an overload candidate. We've
12873/// already generated a primary error at the call site.
12874///
12875/// It really does need to be a single diagnostic with its caret
12876/// pointed at the candidate declaration. Yes, this creates some
12877/// major challenges of technical writing. Yes, this makes pointing
12878/// out problems with specific arguments quite awkward. It's still
12879/// better than generating twenty screens of text for every failed
12880/// overload.
12881///
12882/// It would be great to be able to express per-candidate problems
12883/// more richly for those diagnostic clients that cared, but we'd
12884/// still have to be just as careful with the default diagnostics.
12885/// \param CtorDestAS Addr space of object being constructed (for ctor
12886/// candidates only).
12887static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12888 unsigned NumArgs,
12889 bool TakingCandidateAddress,
12890 LangAS CtorDestAS = LangAS::Default) {
12891 assert(Cand->Function && "Candidate must be a function");
12892 FunctionDecl *Fn = Cand->Function;
12893 if (shouldSkipNotingLambdaConversionDecl(Fn))
12894 return;
12895
12896 // There is no physical candidate declaration to point to for OpenCL builtins.
12897 // Except for failed conversions, the notes are identical for each candidate,
12898 // so do not generate such notes.
12899 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12900 Cand->FailureKind != ovl_fail_bad_conversion)
12901 return;
12902
12903 // Skip implicit member functions when trying to resolve
12904 // the address of a an overload set for a function pointer.
12905 if (Cand->TookAddressOfOverload &&
12906 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12907 return;
12908
12909 // Note deleted candidates, but only if they're viable.
12910 if (Cand->Viable) {
12911 if (Fn->isDeleted()) {
12912 std::string FnDesc;
12913 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12914 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12915 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12916
12917 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12918 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12919 << (Fn->isDeleted()
12920 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12921 : 0);
12922 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12923 return;
12924 }
12925
12926 // We don't really have anything else to say about viable candidates.
12927 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12928 return;
12929 }
12930
12931 // If this is a synthesized deduction guide we're deducing against, add a note
12932 // for it. These deduction guides are not explicitly spelled in the source
12933 // code, so simply printing a deduction failure note mentioning synthesized
12934 // template parameters or pointing to the header of the surrounding RecordDecl
12935 // would be confusing.
12936 //
12937 // We prefer adding such notes at the end of the deduction failure because
12938 // duplicate code snippets appearing in the diagnostic would likely become
12939 // noisy.
12940 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12941
12942 switch (Cand->FailureKind) {
12943 case ovl_fail_too_many_arguments:
12944 case ovl_fail_too_few_arguments:
12945 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12946
12947 case ovl_fail_bad_deduction:
12948 return DiagnoseBadDeduction(S, Cand, NumArgs,
12949 TakingCandidateAddress);
12950
12951 case ovl_fail_illegal_constructor: {
12952 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12953 << (Fn->getPrimaryTemplate() ? 1 : 0);
12954 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12955 return;
12956 }
12957
12958 case ovl_fail_object_addrspace_mismatch: {
12959 Qualifiers QualsForPrinting;
12960 QualsForPrinting.setAddressSpace(CtorDestAS);
12961 S.Diag(Loc: Fn->getLocation(),
12962 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12963 << QualsForPrinting;
12964 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12965 return;
12966 }
12967
12968 case ovl_fail_trivial_conversion:
12969 case ovl_fail_bad_final_conversion:
12970 case ovl_fail_final_conversion_not_exact:
12971 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12972
12973 case ovl_fail_bad_conversion: {
12974 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12975 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12976 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12977 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12978
12979 // FIXME: this currently happens when we're called from SemaInit
12980 // when user-conversion overload fails. Figure out how to handle
12981 // those conditions and diagnose them well.
12982 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12983 }
12984
12985 case ovl_fail_bad_target:
12986 return DiagnoseBadTarget(S, Cand);
12987
12988 case ovl_fail_enable_if:
12989 return DiagnoseFailedEnableIfAttr(S, Cand);
12990
12991 case ovl_fail_explicit:
12992 return DiagnoseFailedExplicitSpec(S, Cand);
12993
12994 case ovl_fail_inhctor_slice:
12995 // It's generally not interesting to note copy/move constructors here.
12996 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12997 return;
12998 S.Diag(Loc: Fn->getLocation(),
12999 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
13000 << (Fn->getPrimaryTemplate() ? 1 : 0)
13001 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
13002 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13003 return;
13004
13005 case ovl_fail_addr_not_available: {
13006 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
13007 (void)Available;
13008 assert(!Available);
13009 break;
13010 }
13011 case ovl_non_default_multiversion_function:
13012 // Do nothing, these should simply be ignored.
13013 break;
13014
13015 case ovl_fail_constraints_not_satisfied: {
13016 std::string FnDesc;
13017 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13018 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
13019 CRK: Cand->getRewriteKind(), Description&: FnDesc);
13020
13021 S.Diag(Loc: Fn->getLocation(),
13022 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
13023 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13024 << FnDesc /* Ignored */;
13025 ConstraintSatisfaction Satisfaction;
13026 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
13027 /*ForOverloadResolution=*/true))
13028 break;
13029 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13030 }
13031 }
13032}
13033
13034static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
13035 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
13036 return;
13037
13038 // Desugar the type of the surrogate down to a function type,
13039 // retaining as many typedefs as possible while still showing
13040 // the function type (and, therefore, its parameter types).
13041 QualType FnType = Cand->Surrogate->getConversionType();
13042 bool isLValueReference = false;
13043 bool isRValueReference = false;
13044 bool isPointer = false;
13045 if (const LValueReferenceType *FnTypeRef =
13046 FnType->getAs<LValueReferenceType>()) {
13047 FnType = FnTypeRef->getPointeeType();
13048 isLValueReference = true;
13049 } else if (const RValueReferenceType *FnTypeRef =
13050 FnType->getAs<RValueReferenceType>()) {
13051 FnType = FnTypeRef->getPointeeType();
13052 isRValueReference = true;
13053 }
13054 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13055 FnType = FnTypePtr->getPointeeType();
13056 isPointer = true;
13057 }
13058 // Desugar down to a function type.
13059 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13060 // Reconstruct the pointer/reference as appropriate.
13061 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
13062 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13063 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13064
13065 if (!Cand->Viable &&
13066 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13067 S.Diag(Loc: Cand->Surrogate->getLocation(),
13068 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13069 << Cand->Surrogate;
13070 ConstraintSatisfaction Satisfaction;
13071 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13072 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13073 } else {
13074 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13075 << FnType;
13076 }
13077}
13078
13079static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13080 SourceLocation OpLoc,
13081 OverloadCandidate *Cand) {
13082 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13083 std::string TypeStr("operator");
13084 TypeStr += Opc;
13085 TypeStr += "(";
13086 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13087 if (Cand->Conversions.size() == 1) {
13088 TypeStr += ")";
13089 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13090 } else {
13091 TypeStr += ", ";
13092 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13093 TypeStr += ")";
13094 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13095 }
13096}
13097
13098static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13099 OverloadCandidate *Cand) {
13100 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13101 if (ICS.isBad()) break; // all meaningless after first invalid
13102 if (!ICS.isAmbiguous()) continue;
13103
13104 ICS.DiagnoseAmbiguousConversion(
13105 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13106 }
13107}
13108
13109static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13110 if (Cand->Function)
13111 return Cand->Function->getLocation();
13112 if (Cand->IsSurrogate)
13113 return Cand->Surrogate->getLocation();
13114 return SourceLocation();
13115}
13116
13117static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13118 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13119 case TemplateDeductionResult::Success:
13120 case TemplateDeductionResult::NonDependentConversionFailure:
13121 case TemplateDeductionResult::AlreadyDiagnosed:
13122 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13123
13124 case TemplateDeductionResult::Invalid:
13125 case TemplateDeductionResult::Incomplete:
13126 case TemplateDeductionResult::IncompletePack:
13127 return 1;
13128
13129 case TemplateDeductionResult::Underqualified:
13130 case TemplateDeductionResult::Inconsistent:
13131 return 2;
13132
13133 case TemplateDeductionResult::SubstitutionFailure:
13134 case TemplateDeductionResult::DeducedMismatch:
13135 case TemplateDeductionResult::ConstraintsNotSatisfied:
13136 case TemplateDeductionResult::DeducedMismatchNested:
13137 case TemplateDeductionResult::NonDeducedMismatch:
13138 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13139 case TemplateDeductionResult::CUDATargetMismatch:
13140 return 3;
13141
13142 case TemplateDeductionResult::InstantiationDepth:
13143 return 4;
13144
13145 case TemplateDeductionResult::InvalidExplicitArguments:
13146 return 5;
13147
13148 case TemplateDeductionResult::TooManyArguments:
13149 case TemplateDeductionResult::TooFewArguments:
13150 return 6;
13151 }
13152 llvm_unreachable("Unhandled deduction result");
13153}
13154
13155namespace {
13156
13157struct CompareOverloadCandidatesForDisplay {
13158 Sema &S;
13159 SourceLocation Loc;
13160 size_t NumArgs;
13161 OverloadCandidateSet::CandidateSetKind CSK;
13162
13163 CompareOverloadCandidatesForDisplay(
13164 Sema &S, SourceLocation Loc, size_t NArgs,
13165 OverloadCandidateSet::CandidateSetKind CSK)
13166 : S(S), NumArgs(NArgs), CSK(CSK) {}
13167
13168 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13169 // If there are too many or too few arguments, that's the high-order bit we
13170 // want to sort by, even if the immediate failure kind was something else.
13171 if (C->FailureKind == ovl_fail_too_many_arguments ||
13172 C->FailureKind == ovl_fail_too_few_arguments)
13173 return static_cast<OverloadFailureKind>(C->FailureKind);
13174
13175 if (C->Function) {
13176 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13177 return ovl_fail_too_many_arguments;
13178 if (NumArgs < C->Function->getMinRequiredArguments())
13179 return ovl_fail_too_few_arguments;
13180 }
13181
13182 return static_cast<OverloadFailureKind>(C->FailureKind);
13183 }
13184
13185 bool operator()(const OverloadCandidate *L,
13186 const OverloadCandidate *R) {
13187 // Fast-path this check.
13188 if (L == R) return false;
13189
13190 // Order first by viability.
13191 if (L->Viable) {
13192 if (!R->Viable) return true;
13193
13194 if (int Ord = CompareConversions(L: *L, R: *R))
13195 return Ord < 0;
13196 // Use other tie breakers.
13197 } else if (R->Viable)
13198 return false;
13199
13200 assert(L->Viable == R->Viable);
13201
13202 // Criteria by which we can sort non-viable candidates:
13203 if (!L->Viable) {
13204 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13205 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13206
13207 // 1. Arity mismatches come after other candidates.
13208 if (LFailureKind == ovl_fail_too_many_arguments ||
13209 LFailureKind == ovl_fail_too_few_arguments) {
13210 if (RFailureKind == ovl_fail_too_many_arguments ||
13211 RFailureKind == ovl_fail_too_few_arguments) {
13212 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13213 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13214 if (LDist == RDist) {
13215 if (LFailureKind == RFailureKind)
13216 // Sort non-surrogates before surrogates.
13217 return !L->IsSurrogate && R->IsSurrogate;
13218 // Sort candidates requiring fewer parameters than there were
13219 // arguments given after candidates requiring more parameters
13220 // than there were arguments given.
13221 return LFailureKind == ovl_fail_too_many_arguments;
13222 }
13223 return LDist < RDist;
13224 }
13225 return false;
13226 }
13227 if (RFailureKind == ovl_fail_too_many_arguments ||
13228 RFailureKind == ovl_fail_too_few_arguments)
13229 return true;
13230
13231 // 2. Bad conversions come first and are ordered by the number
13232 // of bad conversions and quality of good conversions.
13233 if (LFailureKind == ovl_fail_bad_conversion) {
13234 if (RFailureKind != ovl_fail_bad_conversion)
13235 return true;
13236
13237 // The conversion that can be fixed with a smaller number of changes,
13238 // comes first.
13239 unsigned numLFixes = L->Fix.NumConversionsFixed;
13240 unsigned numRFixes = R->Fix.NumConversionsFixed;
13241 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13242 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13243 if (numLFixes != numRFixes) {
13244 return numLFixes < numRFixes;
13245 }
13246
13247 // If there's any ordering between the defined conversions...
13248 if (int Ord = CompareConversions(L: *L, R: *R))
13249 return Ord < 0;
13250 } else if (RFailureKind == ovl_fail_bad_conversion)
13251 return false;
13252
13253 if (LFailureKind == ovl_fail_bad_deduction) {
13254 if (RFailureKind != ovl_fail_bad_deduction)
13255 return true;
13256
13257 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13258 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13259 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13260 if (LRank != RRank)
13261 return LRank < RRank;
13262 }
13263 } else if (RFailureKind == ovl_fail_bad_deduction)
13264 return false;
13265
13266 // TODO: others?
13267 }
13268
13269 // Sort everything else by location.
13270 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13271 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13272
13273 // Put candidates without locations (e.g. builtins) at the end.
13274 if (LLoc.isValid() && RLoc.isValid())
13275 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13276 if (LLoc.isValid() && !RLoc.isValid())
13277 return true;
13278 if (RLoc.isValid() && !LLoc.isValid())
13279 return false;
13280 assert(!LLoc.isValid() && !RLoc.isValid());
13281 // For builtins and other functions without locations, fallback to the order
13282 // in which they were added into the candidate set.
13283 return L < R;
13284 }
13285
13286private:
13287 struct ConversionSignals {
13288 unsigned KindRank = 0;
13289 ImplicitConversionRank Rank = ICR_Exact_Match;
13290
13291 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13292 ConversionSignals Sig;
13293 Sig.KindRank = Seq.getKindRank();
13294 if (Seq.isStandard())
13295 Sig.Rank = Seq.Standard.getRank();
13296 else if (Seq.isUserDefined())
13297 Sig.Rank = Seq.UserDefined.After.getRank();
13298 // We intend StaticObjectArgumentConversion to compare the same as
13299 // StandardConversion with ICR_ExactMatch rank.
13300 return Sig;
13301 }
13302
13303 static ConversionSignals ForObjectArgument() {
13304 // We intend StaticObjectArgumentConversion to compare the same as
13305 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13306 return {};
13307 }
13308 };
13309
13310 // Returns -1 if conversions in L are considered better.
13311 // 0 if they are considered indistinguishable.
13312 // 1 if conversions in R are better.
13313 int CompareConversions(const OverloadCandidate &L,
13314 const OverloadCandidate &R) {
13315 // We cannot use `isBetterOverloadCandidate` because it is defined
13316 // according to the C++ standard and provides a partial order, but we need
13317 // a total order as this function is used in sort.
13318 assert(L.Conversions.size() == R.Conversions.size());
13319 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13320 auto LS = L.IgnoreObjectArgument && I == 0
13321 ? ConversionSignals::ForObjectArgument()
13322 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13323 auto RS = R.IgnoreObjectArgument
13324 ? ConversionSignals::ForObjectArgument()
13325 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13326 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13327 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13328 ? -1
13329 : 1;
13330 }
13331 // FIXME: find a way to compare templates for being more or less
13332 // specialized that provides a strict weak ordering.
13333 return 0;
13334 }
13335};
13336}
13337
13338/// CompleteNonViableCandidate - Normally, overload resolution only
13339/// computes up to the first bad conversion. Produces the FixIt set if
13340/// possible.
13341static void
13342CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13343 ArrayRef<Expr *> Args,
13344 OverloadCandidateSet::CandidateSetKind CSK) {
13345 assert(!Cand->Viable);
13346
13347 // Don't do anything on failures other than bad conversion.
13348 if (Cand->FailureKind != ovl_fail_bad_conversion)
13349 return;
13350
13351 // We only want the FixIts if all the arguments can be corrected.
13352 bool Unfixable = false;
13353 // Use a implicit copy initialization to check conversion fixes.
13354 Cand->Fix.setConversionChecker(TryCopyInitialization);
13355
13356 // Attempt to fix the bad conversion.
13357 unsigned ConvCount = Cand->Conversions.size();
13358 for (unsigned ConvIdx =
13359 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13360 : 0);
13361 /**/; ++ConvIdx) {
13362 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13363 if (Cand->Conversions[ConvIdx].isInitialized() &&
13364 Cand->Conversions[ConvIdx].isBad()) {
13365 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13366 break;
13367 }
13368 }
13369
13370 // FIXME: this should probably be preserved from the overload
13371 // operation somehow.
13372 bool SuppressUserConversions = false;
13373
13374 unsigned ConvIdx = 0;
13375 unsigned ArgIdx = 0;
13376 ArrayRef<QualType> ParamTypes;
13377 bool Reversed = Cand->isReversed();
13378
13379 if (Cand->IsSurrogate) {
13380 QualType ConvType
13381 = Cand->Surrogate->getConversionType().getNonReferenceType();
13382 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13383 ConvType = ConvPtrType->getPointeeType();
13384 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13385 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13386 ConvIdx = 1;
13387 } else if (Cand->Function) {
13388 ParamTypes =
13389 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13390 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13391 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13392 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13393 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13394 ConvIdx = 1;
13395 if (CSK == OverloadCandidateSet::CSK_Operator &&
13396 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13397 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13398 OO_Subscript)
13399 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13400 ArgIdx = 1;
13401 }
13402 } else {
13403 // Builtin operator.
13404 assert(ConvCount <= 3);
13405 ParamTypes = Cand->BuiltinParamTypes;
13406 }
13407
13408 // Fill in the rest of the conversions.
13409 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13410 ConvIdx != ConvCount && ArgIdx < Args.size();
13411 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13412 if (Cand->Conversions[ConvIdx].isInitialized()) {
13413 // We've already checked this conversion.
13414 } else if (ParamIdx < ParamTypes.size()) {
13415 if (ParamTypes[ParamIdx]->isDependentType())
13416 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13417 Args[ArgIdx]->getType());
13418 else {
13419 Cand->Conversions[ConvIdx] =
13420 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13421 SuppressUserConversions,
13422 /*InOverloadResolution=*/true,
13423 /*AllowObjCWritebackConversion=*/
13424 S.getLangOpts().ObjCAutoRefCount);
13425 // Store the FixIt in the candidate if it exists.
13426 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13427 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13428 }
13429 } else
13430 Cand->Conversions[ConvIdx].setEllipsis();
13431 }
13432}
13433
13434SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13435 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13436 SourceLocation OpLoc,
13437 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13438
13439 InjectNonDeducedTemplateCandidates(S);
13440
13441 // Sort the candidates by viability and position. Sorting directly would
13442 // be prohibitive, so we make a set of pointers and sort those.
13443 SmallVector<OverloadCandidate*, 32> Cands;
13444 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13445 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13446 Cand != LastCand; ++Cand) {
13447 if (!Filter(*Cand))
13448 continue;
13449 switch (OCD) {
13450 case OCD_AllCandidates:
13451 if (!Cand->Viable) {
13452 if (!Cand->Function && !Cand->IsSurrogate) {
13453 // This a non-viable builtin candidate. We do not, in general,
13454 // want to list every possible builtin candidate.
13455 continue;
13456 }
13457 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13458 }
13459 break;
13460
13461 case OCD_ViableCandidates:
13462 if (!Cand->Viable)
13463 continue;
13464 break;
13465
13466 case OCD_AmbiguousCandidates:
13467 if (!Cand->Best)
13468 continue;
13469 break;
13470 }
13471
13472 Cands.push_back(Elt: Cand);
13473 }
13474
13475 llvm::stable_sort(
13476 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13477
13478 return Cands;
13479}
13480
13481bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13482 SourceLocation OpLoc) {
13483 bool DeferHint = false;
13484 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13485 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13486 // host device candidates.
13487 auto WrongSidedCands =
13488 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13489 return (Cand.Viable == false &&
13490 Cand.FailureKind == ovl_fail_bad_target) ||
13491 (Cand.Function &&
13492 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13493 Cand.Function->template hasAttr<CUDADeviceAttr>());
13494 });
13495 DeferHint = !WrongSidedCands.empty();
13496 }
13497 return DeferHint;
13498}
13499
13500/// When overload resolution fails, prints diagnostic messages containing the
13501/// candidates in the candidate set.
13502void OverloadCandidateSet::NoteCandidates(
13503 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13504 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13505 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13506
13507 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13508
13509 {
13510 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13511 S.Diag(Loc: PD.first, PD: PD.second);
13512 }
13513
13514 // In WebAssembly we don't want to emit further diagnostics if a table is
13515 // passed as an argument to a function.
13516 bool NoteCands = true;
13517 for (const Expr *Arg : Args) {
13518 if (Arg->getType()->isWebAssemblyTableType())
13519 NoteCands = false;
13520 }
13521
13522 if (NoteCands)
13523 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13524
13525 if (OCD == OCD_AmbiguousCandidates)
13526 MaybeDiagnoseAmbiguousConstraints(S,
13527 Cands: {Candidates.begin(), Candidates.end()});
13528}
13529
13530void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13531 ArrayRef<OverloadCandidate *> Cands,
13532 StringRef Opc, SourceLocation OpLoc) {
13533 bool ReportedAmbiguousConversions = false;
13534
13535 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13536 unsigned CandsShown = 0;
13537 auto I = Cands.begin(), E = Cands.end();
13538 for (; I != E; ++I) {
13539 OverloadCandidate *Cand = *I;
13540
13541 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13542 ShowOverloads == Ovl_Best) {
13543 break;
13544 }
13545 ++CandsShown;
13546
13547 if (Cand->Function)
13548 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13549 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13550 else if (Cand->IsSurrogate)
13551 NoteSurrogateCandidate(S, Cand);
13552 else {
13553 assert(Cand->Viable &&
13554 "Non-viable built-in candidates are not added to Cands.");
13555 // Generally we only see ambiguities including viable builtin
13556 // operators if overload resolution got screwed up by an
13557 // ambiguous user-defined conversion.
13558 //
13559 // FIXME: It's quite possible for different conversions to see
13560 // different ambiguities, though.
13561 if (!ReportedAmbiguousConversions) {
13562 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13563 ReportedAmbiguousConversions = true;
13564 }
13565
13566 // If this is a viable builtin, print it.
13567 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13568 }
13569 }
13570
13571 // Inform S.Diags that we've shown an overload set with N elements. This may
13572 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13573 S.Diags.overloadCandidatesShown(N: CandsShown);
13574
13575 if (I != E) {
13576 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13577 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13578 }
13579}
13580
13581bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
13582 const Sema &S) const {
13583 if (S.getLangOpts().CUDA) {
13584 auto *Caller = S.getCurFunctionDecl(AllowLambda: true);
13585 // Overloading based on __host__ and __device__ attributes takes
13586 // higher priority, HD functions may favor template candidates even when a
13587 // non-template candidate would be a perfect match.
13588 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13589 Caller->hasAttr<CUDADeviceAttr>())
13590 return false;
13591 }
13592
13593 return
13594 // For user defined conversion we need to check against different
13595 // combination of CV qualifiers and look at any explicit specifier, so
13596 // always deduce template candidates.
13597 Kind != CSK_InitByUserDefinedConversion
13598 // When doing code completion, we want to see all the
13599 // viable candidates.
13600 && Kind != CSK_CodeCompletion;
13601}
13602
13603static SourceLocation
13604GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13605 return Cand->Specialization ? Cand->Specialization->getLocation()
13606 : SourceLocation();
13607}
13608
13609namespace {
13610struct CompareTemplateSpecCandidatesForDisplay {
13611 Sema &S;
13612 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13613
13614 bool operator()(const TemplateSpecCandidate *L,
13615 const TemplateSpecCandidate *R) {
13616 // Fast-path this check.
13617 if (L == R)
13618 return false;
13619
13620 // Assuming that both candidates are not matches...
13621
13622 // Sort by the ranking of deduction failures.
13623 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13624 return RankDeductionFailure(DFI: L->DeductionFailure) <
13625 RankDeductionFailure(DFI: R->DeductionFailure);
13626
13627 // Sort everything else by location.
13628 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13629 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13630
13631 // Put candidates without locations (e.g. builtins) at the end.
13632 if (LLoc.isInvalid())
13633 return false;
13634 if (RLoc.isInvalid())
13635 return true;
13636
13637 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13638 }
13639};
13640}
13641
13642/// Diagnose a template argument deduction failure.
13643/// We are treating these failures as overload failures due to bad
13644/// deductions.
13645void TemplateSpecCandidate::NoteDeductionFailure(
13646 Sema &S, bool ForTakingAddress,
13647 TemplateSpecCandidateSetKind CandidateSetKind) {
13648 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13649 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress,
13650 CandidateSetKind);
13651}
13652
13653void TemplateSpecCandidateSet::destroyCandidates() {
13654 for (iterator i = begin(), e = end(); i != e; ++i) {
13655 i->DeductionFailure.Destroy();
13656 }
13657}
13658
13659void TemplateSpecCandidateSet::clear() {
13660 destroyCandidates();
13661 Candidates.clear();
13662}
13663
13664/// NoteCandidates - When no template specialization match is found, prints
13665/// diagnostic messages containing the non-matching specializations that form
13666/// the candidate set.
13667/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13668/// OCD == OCD_AllCandidates and Cand->Viable == false.
13669void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13670 // Sort the candidates by position (assuming no candidate is a match).
13671 // Sorting directly would be prohibitive, so we make a set of pointers
13672 // and sort those.
13673 SmallVector<TemplateSpecCandidate *, 32> Cands;
13674 Cands.reserve(N: size());
13675 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13676 if (Cand->Specialization)
13677 Cands.push_back(Elt: Cand);
13678 // Otherwise, this is a non-matching builtin candidate. We do not,
13679 // in general, want to list every possible builtin candidate.
13680 }
13681
13682 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13683
13684 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13685 // for generalization purposes (?).
13686 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13687
13688 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13689 unsigned CandsShown = 0;
13690 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13691 TemplateSpecCandidate *Cand = *I;
13692
13693 // Set an arbitrary limit on the number of candidates we'll spam
13694 // the user with. FIXME: This limit should depend on details of the
13695 // candidate list.
13696 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13697 break;
13698 ++CandsShown;
13699
13700 assert(Cand->Specialization &&
13701 "Non-matching built-in candidates are not added to Cands.");
13702 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13703 }
13704
13705 if (I != E)
13706 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13707}
13708
13709// [PossiblyAFunctionType] --> [Return]
13710// NonFunctionType --> NonFunctionType
13711// R (A) --> R(A)
13712// R (*)(A) --> R (A)
13713// R (&)(A) --> R (A)
13714// R (S::*)(A) --> R (A)
13715QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13716 QualType Ret = PossiblyAFunctionType;
13717 if (const PointerType *ToTypePtr =
13718 PossiblyAFunctionType->getAs<PointerType>())
13719 Ret = ToTypePtr->getPointeeType();
13720 else if (const ReferenceType *ToTypeRef =
13721 PossiblyAFunctionType->getAs<ReferenceType>())
13722 Ret = ToTypeRef->getPointeeType();
13723 else if (const MemberPointerType *MemTypePtr =
13724 PossiblyAFunctionType->getAs<MemberPointerType>())
13725 Ret = MemTypePtr->getPointeeType();
13726 Ret =
13727 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13728 return Ret;
13729}
13730
13731static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13732 bool Complain = true) {
13733 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13734 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13735 return true;
13736
13737 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13738 if (S.getLangOpts().CPlusPlus17 &&
13739 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13740 !S.ResolveExceptionSpec(Loc, FPT))
13741 return true;
13742
13743 return false;
13744}
13745
13746namespace {
13747// A helper class to help with address of function resolution
13748// - allows us to avoid passing around all those ugly parameters
13749class AddressOfFunctionResolver {
13750 Sema& S;
13751 Expr* SourceExpr;
13752 const QualType& TargetType;
13753 QualType TargetFunctionType; // Extracted function type from target type
13754
13755 bool Complain;
13756 //DeclAccessPair& ResultFunctionAccessPair;
13757 ASTContext& Context;
13758
13759 bool TargetTypeIsNonStaticMemberFunction;
13760 bool FoundNonTemplateFunction;
13761 bool StaticMemberFunctionFromBoundPointer;
13762 bool HasComplained;
13763
13764 OverloadExpr::FindResult OvlExprInfo;
13765 OverloadExpr *OvlExpr;
13766 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13767 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13768 TemplateSpecCandidateSet FailedCandidates;
13769
13770public:
13771 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13772 const QualType &TargetType, bool Complain)
13773 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13774 Complain(Complain), Context(S.getASTContext()),
13775 TargetTypeIsNonStaticMemberFunction(
13776 !!TargetType->getAs<MemberPointerType>()),
13777 FoundNonTemplateFunction(false),
13778 StaticMemberFunctionFromBoundPointer(false),
13779 HasComplained(false),
13780 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13781 OvlExpr(OvlExprInfo.Expression),
13782 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13783 ExtractUnqualifiedFunctionTypeFromTargetType();
13784
13785 if (TargetFunctionType->isFunctionType()) {
13786 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13787 if (!UME->isImplicitAccess() &&
13788 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13789 StaticMemberFunctionFromBoundPointer = true;
13790 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13791 DeclAccessPair dap;
13792 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13793 ovl: OvlExpr, Complain: false, Found: &dap)) {
13794 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13795 if (!Method->isStatic()) {
13796 // If the target type is a non-function type and the function found
13797 // is a non-static member function, pretend as if that was the
13798 // target, it's the only possible type to end up with.
13799 TargetTypeIsNonStaticMemberFunction = true;
13800
13801 // And skip adding the function if its not in the proper form.
13802 // We'll diagnose this due to an empty set of functions.
13803 if (!OvlExprInfo.HasFormOfMemberPointer)
13804 return;
13805 }
13806
13807 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13808 }
13809 return;
13810 }
13811
13812 if (OvlExpr->hasExplicitTemplateArgs())
13813 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13814
13815 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13816 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13817 EliminateSuboptimalCudaMatches();
13818
13819 // C++ [over.over]p4:
13820 // If more than one function is selected, [...]
13821 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13822 if (FoundNonTemplateFunction) {
13823 EliminateAllTemplateMatches();
13824 EliminateLessPartialOrderingConstrainedMatches();
13825 } else
13826 EliminateAllExceptMostSpecializedTemplate();
13827 }
13828 }
13829 }
13830
13831 bool hasComplained() const { return HasComplained; }
13832
13833private:
13834 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13835 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13836 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13837 }
13838
13839 /// \return true if A is considered a better overload candidate for the
13840 /// desired type than B.
13841 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13842 // If A doesn't have exactly the correct type, we don't want to classify it
13843 // as "better" than anything else. This way, the user is required to
13844 // disambiguate for us if there are multiple candidates and no exact match.
13845 return candidateHasExactlyCorrectType(FD: A) &&
13846 (!candidateHasExactlyCorrectType(FD: B) ||
13847 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13848 }
13849
13850 /// \return true if we were able to eliminate all but one overload candidate,
13851 /// false otherwise.
13852 bool eliminiateSuboptimalOverloadCandidates() {
13853 // Same algorithm as overload resolution -- one pass to pick the "best",
13854 // another pass to be sure that nothing is better than the best.
13855 auto Best = Matches.begin();
13856 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13857 if (isBetterCandidate(A: I->second, B: Best->second))
13858 Best = I;
13859
13860 const FunctionDecl *BestFn = Best->second;
13861 auto IsBestOrInferiorToBest = [this, BestFn](
13862 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13863 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13864 };
13865
13866 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13867 // option, so we can potentially give the user a better error
13868 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13869 return false;
13870 Matches[0] = *Best;
13871 Matches.resize(N: 1);
13872 return true;
13873 }
13874
13875 bool isTargetTypeAFunction() const {
13876 return TargetFunctionType->isFunctionType();
13877 }
13878
13879 // [ToType] [Return]
13880
13881 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13882 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13883 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13884 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13885 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13886 }
13887
13888 // return true if any matching specializations were found
13889 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13890 const DeclAccessPair& CurAccessFunPair) {
13891 if (CXXMethodDecl *Method
13892 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13893 // Skip non-static function templates when converting to pointer, and
13894 // static when converting to member pointer.
13895 bool CanConvertToFunctionPointer =
13896 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13897 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13898 return false;
13899 }
13900 else if (TargetTypeIsNonStaticMemberFunction)
13901 return false;
13902
13903 // C++ [over.over]p2:
13904 // If the name is a function template, template argument deduction is
13905 // done (14.8.2.2), and if the argument deduction succeeds, the
13906 // resulting template argument list is used to generate a single
13907 // function template specialization, which is added to the set of
13908 // overloaded functions considered.
13909 FunctionDecl *Specialization = nullptr;
13910 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13911 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13912 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13913 Specialization, Info, /*IsAddressOfFunction*/ true);
13914 Result != TemplateDeductionResult::Success) {
13915 // Make a note of the failed deduction for diagnostics.
13916 FailedCandidates.addCandidate()
13917 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13918 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13919 return false;
13920 }
13921
13922 // Template argument deduction ensures that we have an exact match or
13923 // compatible pointer-to-function arguments that would be adjusted by ICS.
13924 // This function template specicalization works.
13925 assert(S.isSameOrCompatibleFunctionType(
13926 Context.getCanonicalType(Specialization->getType()),
13927 Context.getCanonicalType(TargetFunctionType)));
13928
13929 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13930 return false;
13931
13932 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13933 return true;
13934 }
13935
13936 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13937 const DeclAccessPair& CurAccessFunPair) {
13938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13939 // Skip non-static functions when converting to pointer, and static
13940 // when converting to member pointer.
13941 bool CanConvertToFunctionPointer =
13942 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13943 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13944 return false;
13945 }
13946 else if (TargetTypeIsNonStaticMemberFunction)
13947 return false;
13948
13949 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13950 if (S.getLangOpts().CUDA) {
13951 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13952 if (!(Caller && Caller->isImplicit()) &&
13953 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13954 return false;
13955 }
13956 if (FunDecl->isMultiVersion()) {
13957 const auto *TA = FunDecl->getAttr<TargetAttr>();
13958 if (TA && !TA->isDefaultVersion())
13959 return false;
13960 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13961 if (TVA && !TVA->isDefaultVersion())
13962 return false;
13963 }
13964
13965 // If any candidate has a placeholder return type, trigger its deduction
13966 // now.
13967 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13968 Complain)) {
13969 HasComplained |= Complain;
13970 return false;
13971 }
13972
13973 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13974 return false;
13975
13976 // If we're in C, we need to support types that aren't exactly identical.
13977 if (!S.getLangOpts().CPlusPlus ||
13978 candidateHasExactlyCorrectType(FD: FunDecl)) {
13979 Matches.push_back(Elt: std::make_pair(
13980 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13981 FoundNonTemplateFunction = true;
13982 return true;
13983 }
13984 }
13985
13986 return false;
13987 }
13988
13989 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13990 bool Ret = false;
13991
13992 // If the overload expression doesn't have the form of a pointer to
13993 // member, don't try to convert it to a pointer-to-member type.
13994 if (IsInvalidFormOfPointerToMemberFunction())
13995 return false;
13996
13997 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13998 E = OvlExpr->decls_end();
13999 I != E; ++I) {
14000 // Look through any using declarations to find the underlying function.
14001 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14002
14003 // C++ [over.over]p3:
14004 // Non-member functions and static member functions match
14005 // targets of type "pointer-to-function" or "reference-to-function."
14006 // Nonstatic member functions match targets of
14007 // type "pointer-to-member-function."
14008 // Note that according to DR 247, the containing class does not matter.
14009 if (FunctionTemplateDecl *FunctionTemplate
14010 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
14011 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
14012 Ret = true;
14013 }
14014 // If we have explicit template arguments supplied, skip non-templates.
14015 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14016 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
14017 Ret = true;
14018 }
14019 assert(Ret || Matches.empty());
14020 return Ret;
14021 }
14022
14023 void EliminateAllExceptMostSpecializedTemplate() {
14024 // [...] and any given function template specialization F1 is
14025 // eliminated if the set contains a second function template
14026 // specialization whose function template is more specialized
14027 // than the function template of F1 according to the partial
14028 // ordering rules of 14.5.5.2.
14029
14030 // The algorithm specified above is quadratic. We instead use a
14031 // two-pass algorithm (similar to the one used to identify the
14032 // best viable function in an overload set) that identifies the
14033 // best function template (if it exists).
14034
14035 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14036 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14037 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
14038
14039 // TODO: It looks like FailedCandidates does not serve much purpose
14040 // here, since the no_viable diagnostic has index 0.
14041 UnresolvedSetIterator Result = S.getMostSpecialized(
14042 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
14043 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
14044 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
14045 << Matches[0].second->getDeclName(),
14046 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
14047 << (unsigned)oc_function << (unsigned)ocs_described_template,
14048 Complain, TargetType: TargetFunctionType);
14049
14050 if (Result != MatchesCopy.end()) {
14051 // Make it the first and only element
14052 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14053 Matches[0].second = cast<FunctionDecl>(Val: *Result);
14054 Matches.resize(N: 1);
14055 } else
14056 HasComplained |= Complain;
14057 }
14058
14059 void EliminateAllTemplateMatches() {
14060 // [...] any function template specializations in the set are
14061 // eliminated if the set also contains a non-template function, [...]
14062 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14063 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14064 ++I;
14065 else {
14066 Matches[I] = Matches[--N];
14067 Matches.resize(N);
14068 }
14069 }
14070 }
14071
14072 void EliminateLessPartialOrderingConstrainedMatches() {
14073 // C++ [over.over]p5:
14074 // [...] Any given non-template function F0 is eliminated if the set
14075 // contains a second non-template function that is more
14076 // partial-ordering-constrained than F0. [...]
14077 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14078 "Call EliminateAllTemplateMatches() first");
14079 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14080 Results.push_back(Elt: Matches[0]);
14081 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14082 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14083 FunctionDecl *F = getMorePartialOrderingConstrained(
14084 S, Fn1: Matches[I].second, Fn2: Results[0].second,
14085 /*IsFn1Reversed=*/false,
14086 /*IsFn2Reversed=*/false);
14087 if (!F) {
14088 Results.push_back(Elt: Matches[I]);
14089 continue;
14090 }
14091 if (F == Matches[I].second) {
14092 Results.clear();
14093 Results.push_back(Elt: Matches[I]);
14094 }
14095 }
14096 std::swap(LHS&: Matches, RHS&: Results);
14097 }
14098
14099 void EliminateSuboptimalCudaMatches() {
14100 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14101 Matches);
14102 }
14103
14104public:
14105 void ComplainNoMatchesFound() const {
14106 assert(Matches.empty());
14107 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14108 << OvlExpr->getName() << TargetFunctionType
14109 << OvlExpr->getSourceRange();
14110 if (FailedCandidates.empty())
14111 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14112 /*TakingAddress=*/true);
14113 else {
14114 // We have some deduction failure messages. Use them to diagnose
14115 // the function templates, and diagnose the non-template candidates
14116 // normally.
14117 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14118 IEnd = OvlExpr->decls_end();
14119 I != IEnd; ++I)
14120 if (FunctionDecl *Fun =
14121 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14122 if (!functionHasPassObjectSizeParams(FD: Fun))
14123 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14124 /*TakingAddress=*/true);
14125 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14126 }
14127 }
14128
14129 bool IsInvalidFormOfPointerToMemberFunction() const {
14130 return TargetTypeIsNonStaticMemberFunction &&
14131 !OvlExprInfo.HasFormOfMemberPointer;
14132 }
14133
14134 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14135 // TODO: Should we condition this on whether any functions might
14136 // have matched, or is it more appropriate to do that in callers?
14137 // TODO: a fixit wouldn't hurt.
14138 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14139 << TargetType << OvlExpr->getSourceRange();
14140 }
14141
14142 bool IsStaticMemberFunctionFromBoundPointer() const {
14143 return StaticMemberFunctionFromBoundPointer;
14144 }
14145
14146 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14147 S.Diag(Loc: OvlExpr->getBeginLoc(),
14148 DiagID: diag::err_invalid_form_pointer_member_function)
14149 << OvlExpr->getSourceRange();
14150 }
14151
14152 void ComplainOfInvalidConversion() const {
14153 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14154 << OvlExpr->getName() << TargetType;
14155 }
14156
14157 void ComplainMultipleMatchesFound() const {
14158 assert(Matches.size() > 1);
14159 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14160 << OvlExpr->getName() << OvlExpr->getSourceRange();
14161 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14162 /*TakingAddress=*/true);
14163 }
14164
14165 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14166
14167 int getNumMatches() const { return Matches.size(); }
14168
14169 FunctionDecl* getMatchingFunctionDecl() const {
14170 if (Matches.size() != 1) return nullptr;
14171 return Matches[0].second;
14172 }
14173
14174 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14175 if (Matches.size() != 1) return nullptr;
14176 return &Matches[0].first;
14177 }
14178};
14179}
14180
14181FunctionDecl *
14182Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14183 QualType TargetType,
14184 bool Complain,
14185 DeclAccessPair &FoundResult,
14186 bool *pHadMultipleCandidates) {
14187 assert(AddressOfExpr->getType() == Context.OverloadTy);
14188
14189 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14190 Complain);
14191 int NumMatches = Resolver.getNumMatches();
14192 FunctionDecl *Fn = nullptr;
14193 bool ShouldComplain = Complain && !Resolver.hasComplained();
14194 if (NumMatches == 0 && ShouldComplain) {
14195 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14196 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14197 else
14198 Resolver.ComplainNoMatchesFound();
14199 }
14200 else if (NumMatches > 1 && ShouldComplain)
14201 Resolver.ComplainMultipleMatchesFound();
14202 else if (NumMatches == 1) {
14203 Fn = Resolver.getMatchingFunctionDecl();
14204 assert(Fn);
14205 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14206 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14207 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14208 if (Complain) {
14209 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14210 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14211 else
14212 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14213 }
14214 }
14215
14216 if (pHadMultipleCandidates)
14217 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14218 return Fn;
14219}
14220
14221FunctionDecl *
14222Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14223 OverloadExpr::FindResult R = OverloadExpr::find(E);
14224 OverloadExpr *Ovl = R.Expression;
14225 bool IsResultAmbiguous = false;
14226 FunctionDecl *Result = nullptr;
14227 DeclAccessPair DAP;
14228 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14229
14230 // Return positive for better, negative for worse, 0 for equal preference.
14231 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14232 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14233 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14234 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14235 };
14236
14237 // Don't use the AddressOfResolver because we're specifically looking for
14238 // cases where we have one overload candidate that lacks
14239 // enable_if/pass_object_size/...
14240 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14241 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14242 if (!FD)
14243 return nullptr;
14244
14245 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14246 continue;
14247
14248 // If we found a better result, update Result.
14249 auto FoundBetter = [&]() {
14250 IsResultAmbiguous = false;
14251 DAP = I.getPair();
14252 Result = FD;
14253 };
14254
14255 // We have more than one result - see if it is more
14256 // partial-ordering-constrained than the previous one.
14257 if (Result) {
14258 // Check CUDA preference first. If the candidates have differennt CUDA
14259 // preference, choose the one with higher CUDA preference. Otherwise,
14260 // choose the one with more constraints.
14261 if (getLangOpts().CUDA) {
14262 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14263 // FD has different preference than Result.
14264 if (PreferenceByCUDA != 0) {
14265 // FD is more preferable than Result.
14266 if (PreferenceByCUDA > 0)
14267 FoundBetter();
14268 continue;
14269 }
14270 }
14271 // FD has the same CUDA preference than Result. Continue to check
14272 // constraints.
14273
14274 // C++ [over.over]p5:
14275 // [...] Any given non-template function F0 is eliminated if the set
14276 // contains a second non-template function that is more
14277 // partial-ordering-constrained than F0 [...]
14278 FunctionDecl *MoreConstrained =
14279 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14280 /*IsFn1Reversed=*/false,
14281 /*IsFn2Reversed=*/false);
14282 if (MoreConstrained != FD) {
14283 if (!MoreConstrained) {
14284 IsResultAmbiguous = true;
14285 AmbiguousDecls.push_back(Elt: FD);
14286 }
14287 continue;
14288 }
14289 // FD is more constrained - replace Result with it.
14290 }
14291 FoundBetter();
14292 }
14293
14294 if (IsResultAmbiguous)
14295 return nullptr;
14296
14297 if (Result) {
14298 // We skipped over some ambiguous declarations which might be ambiguous with
14299 // the selected result.
14300 for (FunctionDecl *Skipped : AmbiguousDecls) {
14301 // If skipped candidate has different CUDA preference than the result,
14302 // there is no ambiguity. Otherwise check whether they have different
14303 // constraints.
14304 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14305 continue;
14306 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14307 return nullptr;
14308 }
14309 Pair = DAP;
14310 }
14311 return Result;
14312}
14313
14314bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14315 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14316 Expr *E = SrcExpr.get();
14317 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14318
14319 DeclAccessPair DAP;
14320 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14321 if (!Found || Found->isCPUDispatchMultiVersion() ||
14322 Found->isCPUSpecificMultiVersion())
14323 return false;
14324
14325 // Emitting multiple diagnostics for a function that is both inaccessible and
14326 // unavailable is consistent with our behavior elsewhere. So, always check
14327 // for both.
14328 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14329 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14330 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14331 if (Res.isInvalid())
14332 return false;
14333 Expr *Fixed = Res.get();
14334 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14335 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14336 else
14337 SrcExpr = Fixed;
14338 return true;
14339}
14340
14341FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14342 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14343 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14344 // C++ [over.over]p1:
14345 // [...] [Note: any redundant set of parentheses surrounding the
14346 // overloaded function name is ignored (5.1). ]
14347 // C++ [over.over]p1:
14348 // [...] The overloaded function name can be preceded by the &
14349 // operator.
14350
14351 // If we didn't actually find any template-ids, we're done.
14352 if (!ovl->hasExplicitTemplateArgs())
14353 return nullptr;
14354
14355 TemplateArgumentListInfo ExplicitTemplateArgs;
14356 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14357
14358 // Look through all of the overloaded functions, searching for one
14359 // whose type matches exactly.
14360 FunctionDecl *Matched = nullptr;
14361 for (UnresolvedSetIterator I = ovl->decls_begin(),
14362 E = ovl->decls_end(); I != E; ++I) {
14363 // C++0x [temp.arg.explicit]p3:
14364 // [...] In contexts where deduction is done and fails, or in contexts
14365 // where deduction is not done, if a template argument list is
14366 // specified and it, along with any default template arguments,
14367 // identifies a single function template specialization, then the
14368 // template-id is an lvalue for the function template specialization.
14369 FunctionTemplateDecl *FunctionTemplate =
14370 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14371 if (!FunctionTemplate)
14372 continue;
14373
14374 // C++ [over.over]p2:
14375 // If the name is a function template, template argument deduction is
14376 // done (14.8.2.2), and if the argument deduction succeeds, the
14377 // resulting template argument list is used to generate a single
14378 // function template specialization, which is added to the set of
14379 // overloaded functions considered.
14380 FunctionDecl *Specialization = nullptr;
14381 TemplateDeductionInfo Info(ovl->getNameLoc());
14382 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14383 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14384 /*IsAddressOfFunction*/ true);
14385 Result != TemplateDeductionResult::Success) {
14386 // Make a note of the failed deduction for diagnostics.
14387 if (FailedTSC)
14388 FailedTSC->addCandidate().set(
14389 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14390 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14391 continue;
14392 }
14393
14394 assert(Specialization && "no specialization and no error?");
14395
14396 // C++ [temp.deduct.call]p6:
14397 // [...] If all successful deductions yield the same deduced A, that
14398 // deduced A is the result of deduction; otherwise, the parameter is
14399 // treated as a non-deduced context.
14400 if (Matched) {
14401 if (ForTypeDeduction &&
14402 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14403 Arg: Specialization->getType()))
14404 continue;
14405 // Multiple matches; we can't resolve to a single declaration.
14406 if (Complain) {
14407 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14408 << ovl->getName();
14409 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14410 }
14411 return nullptr;
14412 }
14413
14414 Matched = Specialization;
14415 if (FoundResult) *FoundResult = I.getPair();
14416 }
14417
14418 if (Matched &&
14419 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14420 return nullptr;
14421
14422 return Matched;
14423}
14424
14425bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14426 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14427 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14428 unsigned DiagIDForComplaining) {
14429 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14430
14431 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14432
14433 DeclAccessPair found;
14434 ExprResult SingleFunctionExpression;
14435 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14436 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14437 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14438 SrcExpr = ExprError();
14439 return true;
14440 }
14441
14442 // It is only correct to resolve to an instance method if we're
14443 // resolving a form that's permitted to be a pointer to member.
14444 // Otherwise we'll end up making a bound member expression, which
14445 // is illegal in all the contexts we resolve like this.
14446 if (!ovl.HasFormOfMemberPointer &&
14447 isa<CXXMethodDecl>(Val: fn) &&
14448 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14449 if (!complain) return false;
14450
14451 Diag(Loc: ovl.Expression->getExprLoc(),
14452 DiagID: diag::err_bound_member_function)
14453 << 0 << ovl.Expression->getSourceRange();
14454
14455 // TODO: I believe we only end up here if there's a mix of
14456 // static and non-static candidates (otherwise the expression
14457 // would have 'bound member' type, not 'overload' type).
14458 // Ideally we would note which candidate was chosen and why
14459 // the static candidates were rejected.
14460 SrcExpr = ExprError();
14461 return true;
14462 }
14463
14464 // Fix the expression to refer to 'fn'.
14465 SingleFunctionExpression =
14466 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14467
14468 // If desired, do function-to-pointer decay.
14469 if (doFunctionPointerConversion) {
14470 SingleFunctionExpression =
14471 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14472 if (SingleFunctionExpression.isInvalid()) {
14473 SrcExpr = ExprError();
14474 return true;
14475 }
14476 }
14477 }
14478
14479 if (!SingleFunctionExpression.isUsable()) {
14480 if (complain) {
14481 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14482 << ovl.Expression->getName()
14483 << DestTypeForComplaining
14484 << OpRangeForComplaining
14485 << ovl.Expression->getQualifierLoc().getSourceRange();
14486 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14487
14488 SrcExpr = ExprError();
14489 return true;
14490 }
14491
14492 return false;
14493 }
14494
14495 SrcExpr = SingleFunctionExpression;
14496 return true;
14497}
14498
14499/// Add a single candidate to the overload set.
14500static void AddOverloadedCallCandidate(Sema &S,
14501 DeclAccessPair FoundDecl,
14502 TemplateArgumentListInfo *ExplicitTemplateArgs,
14503 ArrayRef<Expr *> Args,
14504 OverloadCandidateSet &CandidateSet,
14505 bool PartialOverloading,
14506 bool KnownValid) {
14507 NamedDecl *Callee = FoundDecl.getDecl();
14508 if (isa<UsingShadowDecl>(Val: Callee))
14509 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14510
14511 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14512 if (ExplicitTemplateArgs) {
14513 assert(!KnownValid && "Explicit template arguments?");
14514 return;
14515 }
14516 // Prevent ill-formed function decls to be added as overload candidates.
14517 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14518 return;
14519
14520 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14521 /*SuppressUserConversions=*/false,
14522 PartialOverloading);
14523 return;
14524 }
14525
14526 if (FunctionTemplateDecl *FuncTemplate
14527 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14528 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14529 ExplicitTemplateArgs, Args, CandidateSet,
14530 /*SuppressUserConversions=*/false,
14531 PartialOverloading);
14532 return;
14533 }
14534
14535 assert(!KnownValid && "unhandled case in overloaded call candidate");
14536}
14537
14538void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14539 ArrayRef<Expr *> Args,
14540 OverloadCandidateSet &CandidateSet,
14541 bool PartialOverloading) {
14542
14543#ifndef NDEBUG
14544 // Verify that ArgumentDependentLookup is consistent with the rules
14545 // in C++0x [basic.lookup.argdep]p3:
14546 //
14547 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14548 // and let Y be the lookup set produced by argument dependent
14549 // lookup (defined as follows). If X contains
14550 //
14551 // -- a declaration of a class member, or
14552 //
14553 // -- a block-scope function declaration that is not a
14554 // using-declaration, or
14555 //
14556 // -- a declaration that is neither a function or a function
14557 // template
14558 //
14559 // then Y is empty.
14560
14561 if (ULE->requiresADL()) {
14562 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14563 E = ULE->decls_end(); I != E; ++I) {
14564 assert(!(*I)->getDeclContext()->isRecord());
14565 assert(isa<UsingShadowDecl>(*I) ||
14566 !(*I)->getDeclContext()->isFunctionOrMethod());
14567 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14568 }
14569 }
14570#endif
14571
14572 // It would be nice to avoid this copy.
14573 TemplateArgumentListInfo TABuffer;
14574 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14575 if (ULE->hasExplicitTemplateArgs()) {
14576 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14577 ExplicitTemplateArgs = &TABuffer;
14578 }
14579
14580 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14581 E = ULE->decls_end(); I != E; ++I)
14582 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14583 CandidateSet, PartialOverloading,
14584 /*KnownValid*/ true);
14585
14586 if (ULE->requiresADL())
14587 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14588 Args, ExplicitTemplateArgs,
14589 CandidateSet, PartialOverloading);
14590}
14591
14592void Sema::AddOverloadedCallCandidates(
14593 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14594 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14595 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14596 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14597 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14598}
14599
14600/// Determine whether a declaration with the specified name could be moved into
14601/// a different namespace.
14602static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14603 switch (Name.getCXXOverloadedOperator()) {
14604 case OO_New: case OO_Array_New:
14605 case OO_Delete: case OO_Array_Delete:
14606 return false;
14607
14608 default:
14609 return true;
14610 }
14611}
14612
14613/// Attempt to recover from an ill-formed use of a non-dependent name in a
14614/// template, where the non-dependent name was declared after the template
14615/// was defined. This is common in code written for a compilers which do not
14616/// correctly implement two-stage name lookup.
14617///
14618/// Returns true if a viable candidate was found and a diagnostic was issued.
14619static bool DiagnoseTwoPhaseLookup(
14620 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14621 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14622 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14623 CXXRecordDecl **FoundInClass = nullptr) {
14624 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14625 return false;
14626
14627 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14628 if (DC->isTransparentContext())
14629 continue;
14630
14631 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14632
14633 if (!R.empty()) {
14634 R.suppressDiagnostics();
14635
14636 OverloadCandidateSet Candidates(FnLoc, CSK);
14637 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14638 CandidateSet&: Candidates);
14639
14640 OverloadCandidateSet::iterator Best;
14641 OverloadingResult OR =
14642 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14643
14644 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14645 // We either found non-function declarations or a best viable function
14646 // at class scope. A class-scope lookup result disables ADL. Don't
14647 // look past this, but let the caller know that we found something that
14648 // either is, or might be, usable in this class.
14649 if (FoundInClass) {
14650 *FoundInClass = RD;
14651 if (OR == OR_Success) {
14652 R.clear();
14653 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14654 R.resolveKind();
14655 }
14656 }
14657 return false;
14658 }
14659
14660 if (OR != OR_Success) {
14661 // There wasn't a unique best function or function template.
14662 return false;
14663 }
14664
14665 // Find the namespaces where ADL would have looked, and suggest
14666 // declaring the function there instead.
14667 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14668 Sema::AssociatedClassSet AssociatedClasses;
14669 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14670 AssociatedNamespaces,
14671 AssociatedClasses);
14672 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14673 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14674 DeclContext *Std = SemaRef.getStdNamespace();
14675 for (Sema::AssociatedNamespaceSet::iterator
14676 it = AssociatedNamespaces.begin(),
14677 end = AssociatedNamespaces.end(); it != end; ++it) {
14678 // Never suggest declaring a function within namespace 'std'.
14679 if (Std && Std->Encloses(DC: *it))
14680 continue;
14681
14682 // Never suggest declaring a function within a namespace with a
14683 // reserved name, like __gnu_cxx.
14684 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14685 if (NS &&
14686 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14687 continue;
14688
14689 SuggestedNamespaces.insert(X: *it);
14690 }
14691 }
14692
14693 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14694 << R.getLookupName();
14695 if (SuggestedNamespaces.empty()) {
14696 SemaRef.Diag(Loc: Best->Function->getLocation(),
14697 DiagID: diag::note_not_found_by_two_phase_lookup)
14698 << R.getLookupName() << 0;
14699 } else if (SuggestedNamespaces.size() == 1) {
14700 SemaRef.Diag(Loc: Best->Function->getLocation(),
14701 DiagID: diag::note_not_found_by_two_phase_lookup)
14702 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14703 } else {
14704 // FIXME: It would be useful to list the associated namespaces here,
14705 // but the diagnostics infrastructure doesn't provide a way to produce
14706 // a localized representation of a list of items.
14707 SemaRef.Diag(Loc: Best->Function->getLocation(),
14708 DiagID: diag::note_not_found_by_two_phase_lookup)
14709 << R.getLookupName() << 2;
14710 }
14711
14712 // Try to recover by calling this function.
14713 return true;
14714 }
14715
14716 R.clear();
14717 }
14718
14719 return false;
14720}
14721
14722/// Attempt to recover from ill-formed use of a non-dependent operator in a
14723/// template, where the non-dependent operator was declared after the template
14724/// was defined.
14725///
14726/// Returns true if a viable candidate was found and a diagnostic was issued.
14727static bool
14728DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14729 SourceLocation OpLoc,
14730 ArrayRef<Expr *> Args) {
14731 DeclarationName OpName =
14732 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14733 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14734 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14735 CSK: OverloadCandidateSet::CSK_Operator,
14736 /*ExplicitTemplateArgs=*/nullptr, Args);
14737}
14738
14739namespace {
14740class BuildRecoveryCallExprRAII {
14741 Sema &SemaRef;
14742 Sema::SatisfactionStackResetRAII SatStack;
14743
14744public:
14745 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14746 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14747 SemaRef.IsBuildingRecoveryCallExpr = true;
14748 }
14749
14750 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14751};
14752}
14753
14754/// Attempts to recover from a call where no functions were found.
14755///
14756/// This function will do one of three things:
14757/// * Diagnose, recover, and return a recovery expression.
14758/// * Diagnose, fail to recover, and return ExprError().
14759/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14760/// expected to diagnose as appropriate.
14761static ExprResult
14762BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14763 UnresolvedLookupExpr *ULE,
14764 SourceLocation LParenLoc,
14765 MutableArrayRef<Expr *> Args,
14766 SourceLocation RParenLoc,
14767 bool EmptyLookup, bool AllowTypoCorrection) {
14768 // Do not try to recover if it is already building a recovery call.
14769 // This stops infinite loops for template instantiations like
14770 //
14771 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14772 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14773 if (SemaRef.IsBuildingRecoveryCallExpr)
14774 return ExprResult();
14775 BuildRecoveryCallExprRAII RCE(SemaRef);
14776
14777 CXXScopeSpec SS;
14778 SS.Adopt(Other: ULE->getQualifierLoc());
14779 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14780
14781 TemplateArgumentListInfo TABuffer;
14782 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14783 if (ULE->hasExplicitTemplateArgs()) {
14784 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14785 ExplicitTemplateArgs = &TABuffer;
14786 }
14787
14788 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14789 Sema::LookupOrdinaryName);
14790 CXXRecordDecl *FoundInClass = nullptr;
14791 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14792 CSK: OverloadCandidateSet::CSK_Normal,
14793 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14794 // OK, diagnosed a two-phase lookup issue.
14795 } else if (EmptyLookup) {
14796 // Try to recover from an empty lookup with typo correction.
14797 R.clear();
14798 NoTypoCorrectionCCC NoTypoValidator{};
14799 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14800 ExplicitTemplateArgs != nullptr,
14801 dyn_cast<MemberExpr>(Val: Fn));
14802 CorrectionCandidateCallback &Validator =
14803 AllowTypoCorrection
14804 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14805 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14806 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14807 Args))
14808 return ExprError();
14809 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14810 // We found a usable declaration of the name in a dependent base of some
14811 // enclosing class.
14812 // FIXME: We should also explain why the candidates found by name lookup
14813 // were not viable.
14814 if (SemaRef.DiagnoseDependentMemberLookup(R))
14815 return ExprError();
14816 } else {
14817 // We had viable candidates and couldn't recover; let the caller diagnose
14818 // this.
14819 return ExprResult();
14820 }
14821
14822 // If we get here, we should have issued a diagnostic and formed a recovery
14823 // lookup result.
14824 assert(!R.empty() && "lookup results empty despite recovery");
14825
14826 // If recovery created an ambiguity, just bail out.
14827 if (R.isAmbiguous()) {
14828 R.suppressDiagnostics();
14829 return ExprError();
14830 }
14831
14832 // Build an implicit member call if appropriate. Just drop the
14833 // casts and such from the call, we don't really care.
14834 ExprResult NewFn = ExprError();
14835 if ((*R.begin())->isCXXClassMember())
14836 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14837 TemplateArgs: ExplicitTemplateArgs, S);
14838 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14839 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14840 TemplateArgs: ExplicitTemplateArgs);
14841 else
14842 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14843
14844 if (NewFn.isInvalid())
14845 return ExprError();
14846
14847 // This shouldn't cause an infinite loop because we're giving it
14848 // an expression with viable lookup results, which should never
14849 // end up here.
14850 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14851 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14852 RParenLoc);
14853}
14854
14855bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14856 UnresolvedLookupExpr *ULE,
14857 MultiExprArg Args,
14858 SourceLocation RParenLoc,
14859 OverloadCandidateSet *CandidateSet,
14860 ExprResult *Result) {
14861#ifndef NDEBUG
14862 if (ULE->requiresADL()) {
14863 // To do ADL, we must have found an unqualified name.
14864 assert(!ULE->getQualifier() && "qualified name with ADL");
14865
14866 // We don't perform ADL for implicit declarations of builtins.
14867 // Verify that this was correctly set up.
14868 FunctionDecl *F;
14869 if (ULE->decls_begin() != ULE->decls_end() &&
14870 ULE->decls_begin() + 1 == ULE->decls_end() &&
14871 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14872 F->getBuiltinID() && F->isImplicit())
14873 llvm_unreachable("performing ADL for builtin");
14874
14875 // We don't perform ADL in C.
14876 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14877 }
14878#endif
14879
14880 UnbridgedCastsSet UnbridgedCasts;
14881 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14882 *Result = ExprError();
14883 return true;
14884 }
14885
14886 // Add the functions denoted by the callee to the set of candidate
14887 // functions, including those from argument-dependent lookup.
14888 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14889
14890 if (getLangOpts().MSVCCompat &&
14891 CurContext->isDependentContext() && !isSFINAEContext() &&
14892 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14893
14894 OverloadCandidateSet::iterator Best;
14895 if (CandidateSet->empty() ||
14896 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14897 OR_No_Viable_Function) {
14898 // In Microsoft mode, if we are inside a template class member function
14899 // then create a type dependent CallExpr. The goal is to postpone name
14900 // lookup to instantiation time to be able to search into type dependent
14901 // base classes.
14902 CallExpr *CE =
14903 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14904 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14905 CE->markDependentForPostponedNameLookup();
14906 *Result = CE;
14907 return true;
14908 }
14909 }
14910
14911 if (CandidateSet->empty())
14912 return false;
14913
14914 UnbridgedCasts.restore();
14915 return false;
14916}
14917
14918// Guess at what the return type for an unresolvable overload should be.
14919static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14920 OverloadCandidateSet::iterator *Best) {
14921 std::optional<QualType> Result;
14922 // Adjust Type after seeing a candidate.
14923 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14924 if (!Candidate.Function)
14925 return;
14926 if (Candidate.Function->isInvalidDecl())
14927 return;
14928 QualType T = Candidate.Function->getReturnType();
14929 if (T.isNull())
14930 return;
14931 if (!Result)
14932 Result = T;
14933 else if (Result != T)
14934 Result = QualType();
14935 };
14936
14937 // Look for an unambiguous type from a progressively larger subset.
14938 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14939 //
14940 // First, consider only the best candidate.
14941 if (Best && *Best != CS.end())
14942 ConsiderCandidate(**Best);
14943 // Next, consider only viable candidates.
14944 if (!Result)
14945 for (const auto &C : CS)
14946 if (C.Viable)
14947 ConsiderCandidate(C);
14948 // Finally, consider all candidates.
14949 if (!Result)
14950 for (const auto &C : CS)
14951 ConsiderCandidate(C);
14952
14953 if (!Result)
14954 return QualType();
14955 auto Value = *Result;
14956 if (Value.isNull() || Value->isUndeducedType())
14957 return QualType();
14958 return Value;
14959}
14960
14961/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14962/// the completed call expression. If overload resolution fails, emits
14963/// diagnostics and returns ExprError()
14964static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14965 UnresolvedLookupExpr *ULE,
14966 SourceLocation LParenLoc,
14967 MultiExprArg Args,
14968 SourceLocation RParenLoc,
14969 Expr *ExecConfig,
14970 OverloadCandidateSet *CandidateSet,
14971 OverloadCandidateSet::iterator *Best,
14972 OverloadingResult OverloadResult,
14973 bool AllowTypoCorrection) {
14974 switch (OverloadResult) {
14975 case OR_Success: {
14976 FunctionDecl *FDecl = (*Best)->Function;
14977 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14978 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14979 return ExprError();
14980 ExprResult Res =
14981 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14982 if (Res.isInvalid())
14983 return ExprError();
14984 return SemaRef.BuildResolvedCallExpr(
14985 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14986 /*IsExecConfig=*/false,
14987 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14988 }
14989
14990 case OR_No_Viable_Function: {
14991 if (*Best != CandidateSet->end() &&
14992 CandidateSet->getKind() ==
14993 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14994 if (CXXMethodDecl *M =
14995 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14996 M && M->isImplicitObjectMemberFunction()) {
14997 CandidateSet->NoteCandidates(
14998 PD: PartialDiagnosticAt(
14999 Fn->getBeginLoc(),
15000 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
15001 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15002 return ExprError();
15003 }
15004 }
15005
15006 // Try to recover by looking for viable functions which the user might
15007 // have meant to call.
15008 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
15009 Args, RParenLoc,
15010 EmptyLookup: CandidateSet->empty(),
15011 AllowTypoCorrection);
15012 if (Recovery.isInvalid() || Recovery.isUsable())
15013 return Recovery;
15014
15015 // If the user passes in a function that we can't take the address of, we
15016 // generally end up emitting really bad error messages. Here, we attempt to
15017 // emit better ones.
15018 for (const Expr *Arg : Args) {
15019 if (!Arg->getType()->isFunctionType())
15020 continue;
15021 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
15022 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
15023 if (FD &&
15024 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15025 Loc: Arg->getExprLoc()))
15026 return ExprError();
15027 }
15028 }
15029
15030 CandidateSet->NoteCandidates(
15031 PD: PartialDiagnosticAt(
15032 Fn->getBeginLoc(),
15033 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
15034 << ULE->getName() << Fn->getSourceRange()),
15035 S&: SemaRef, OCD: OCD_AllCandidates, Args);
15036 break;
15037 }
15038
15039 case OR_Ambiguous:
15040 CandidateSet->NoteCandidates(
15041 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
15042 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
15043 << ULE->getName() << Fn->getSourceRange()),
15044 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15045 break;
15046
15047 case OR_Deleted: {
15048 FunctionDecl *FDecl = (*Best)->Function;
15049 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
15050 Range: Fn->getSourceRange(), Name: ULE->getName(),
15051 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
15052
15053 // We emitted an error for the unavailable/deleted function call but keep
15054 // the call in the AST.
15055 ExprResult Res =
15056 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15057 if (Res.isInvalid())
15058 return ExprError();
15059 return SemaRef.BuildResolvedCallExpr(
15060 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15061 /*IsExecConfig=*/false,
15062 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15063 }
15064 }
15065
15066 // Overload resolution failed, try to recover.
15067 SmallVector<Expr *, 8> SubExprs = {Fn};
15068 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
15069 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
15070 T: chooseRecoveryType(CS&: *CandidateSet, Best));
15071}
15072
15073static void markUnaddressableCandidatesUnviable(Sema &S,
15074 OverloadCandidateSet &CS) {
15075 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15076 if (I->Viable &&
15077 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
15078 I->Viable = false;
15079 I->FailureKind = ovl_fail_addr_not_available;
15080 }
15081 }
15082}
15083
15084ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
15085 UnresolvedLookupExpr *ULE,
15086 SourceLocation LParenLoc,
15087 MultiExprArg Args,
15088 SourceLocation RParenLoc,
15089 Expr *ExecConfig,
15090 bool AllowTypoCorrection,
15091 bool CalleesAddressIsTaken) {
15092
15093 OverloadCandidateSet::CandidateSetKind CSK =
15094 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15095 : OverloadCandidateSet::CSK_Normal;
15096
15097 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15098 ExprResult result;
15099
15100 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15101 Result: &result))
15102 return result;
15103
15104 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15105 // functions that aren't addressible are considered unviable.
15106 if (CalleesAddressIsTaken)
15107 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15108
15109 OverloadCandidateSet::iterator Best;
15110 OverloadingResult OverloadResult =
15111 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15112
15113 // [C++23][over.call.func]
15114 // if overload resolution selects a non-static member function,
15115 // the call is ill-formed;
15116 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15117 Best != CandidateSet.end()) {
15118 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15119 M && M->isImplicitObjectMemberFunction()) {
15120 OverloadResult = OR_No_Viable_Function;
15121 }
15122 }
15123
15124 // Model the case with a call to a templated function whose definition
15125 // encloses the call and whose return type contains a placeholder type as if
15126 // the UnresolvedLookupExpr was type-dependent.
15127 if (OverloadResult == OR_Success) {
15128 const FunctionDecl *FDecl = Best->Function;
15129 if (LangOpts.CUDA)
15130 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15131 if (FDecl && FDecl->isTemplateInstantiation() &&
15132 FDecl->getReturnType()->isUndeducedType()) {
15133
15134 // Creating dependent CallExpr is not okay if the enclosing context itself
15135 // is not dependent. This situation notably arises if a non-dependent
15136 // member function calls the later-defined overloaded static function.
15137 //
15138 // For example, in
15139 // class A {
15140 // void c() { callee(1); }
15141 // static auto callee(auto x) { }
15142 // };
15143 //
15144 // Here callee(1) is unresolved at the call site, but is not inside a
15145 // dependent context. There will be no further attempt to resolve this
15146 // call if it is made dependent.
15147
15148 if (const auto *TP =
15149 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15150 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15151 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15152 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15153 }
15154 }
15155 }
15156
15157 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15158 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15159 OverloadResult, AllowTypoCorrection);
15160}
15161
15162ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15163 NestedNameSpecifierLoc NNSLoc,
15164 DeclarationNameInfo DNI,
15165 const UnresolvedSetImpl &Fns,
15166 bool PerformADL) {
15167 return UnresolvedLookupExpr::Create(
15168 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15169 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15170}
15171
15172ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15173 CXXConversionDecl *Method,
15174 bool HadMultipleCandidates) {
15175 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15176 // the FoundDecl as it impedes TransformMemberExpr.
15177 // We go a bit further here: if there's no difference in UnderlyingDecl,
15178 // then using FoundDecl vs Method shouldn't make a difference either.
15179 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15180 FoundDecl = Method;
15181 // Convert the expression to match the conversion function's implicit object
15182 // parameter.
15183 ExprResult Exp;
15184 if (Method->isExplicitObjectMemberFunction())
15185 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15186 else
15187 Exp = PerformImplicitObjectArgumentInitialization(
15188 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15189 if (Exp.isInvalid())
15190 return true;
15191
15192 if (Method->getParent()->isLambda() &&
15193 Method->getConversionType()->isBlockPointerType()) {
15194 // This is a lambda conversion to block pointer; check if the argument
15195 // was a LambdaExpr.
15196 Expr *SubE = E;
15197 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15198 if (CE && CE->getCastKind() == CK_NoOp)
15199 SubE = CE->getSubExpr();
15200 SubE = SubE->IgnoreParens();
15201 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15202 SubE = BE->getSubExpr();
15203 if (isa<LambdaExpr>(Val: SubE)) {
15204 // For the conversion to block pointer on a lambda expression, we
15205 // construct a special BlockLiteral instead; this doesn't really make
15206 // a difference in ARC, but outside of ARC the resulting block literal
15207 // follows the normal lifetime rules for block literals instead of being
15208 // autoreleased.
15209 PushExpressionEvaluationContext(
15210 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15211 ExprResult BlockExp = BuildBlockForLambdaConversion(
15212 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15213 PopExpressionEvaluationContext();
15214
15215 // FIXME: This note should be produced by a CodeSynthesisContext.
15216 if (BlockExp.isInvalid())
15217 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15218 return BlockExp;
15219 }
15220 }
15221 CallExpr *CE;
15222 QualType ResultType = Method->getReturnType();
15223 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15224 ResultType = ResultType.getNonLValueExprType(Context);
15225 if (Method->isExplicitObjectMemberFunction()) {
15226 ExprResult FnExpr =
15227 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15228 HadMultipleCandidates, Loc: E->getBeginLoc());
15229 if (FnExpr.isInvalid())
15230 return ExprError();
15231 Expr *ObjectParam = Exp.get();
15232 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15233 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15234 FPFeatures: CurFPFeatureOverrides());
15235 CE->setUsesMemberSyntax(true);
15236 } else {
15237 MemberExpr *ME =
15238 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15239 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15240 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15241 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15242 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15243
15244 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15245 RP: Exp.get()->getEndLoc(),
15246 FPFeatures: CurFPFeatureOverrides());
15247 }
15248
15249 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15250 Proto: Method->getType()->castAs<FunctionProtoType>()))
15251 return ExprError();
15252
15253 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15254}
15255
15256void Sema::LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
15257 OverloadedOperatorKind Op,
15258 const UnresolvedSetImpl &Fns,
15259 ArrayRef<Expr *> Args, bool PerformADL) {
15260 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15261
15262 SourceLocation OpLoc = CandidateSet.getLocation();
15263 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15264
15265 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15266 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15267 if (PerformADL)
15268 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15269 /*ExplicitTemplateArgs*/ nullptr,
15270 CandidateSet);
15271 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15272}
15273
15274ExprResult
15275Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15276 const UnresolvedSetImpl &Fns,
15277 Expr *Input, bool PerformADL) {
15278 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15279 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15280 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15281 // TODO: provide better source location info.
15282 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15283
15284 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15285 return ExprError();
15286
15287 Expr *Args[2] = { Input, nullptr };
15288 unsigned NumArgs = 1;
15289
15290 // For post-increment and post-decrement, add the implicit '0' as
15291 // the second argument, so that we know this is a post-increment or
15292 // post-decrement.
15293 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15294 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15295 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15296 l: SourceLocation());
15297 NumArgs = 2;
15298 }
15299
15300 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15301
15302 if (Input->isTypeDependent()) {
15303 ExprValueKind VK = ExprValueKind::VK_PRValue;
15304 // [C++26][expr.unary.op][expr.pre.incr]
15305 // The * operator yields an lvalue of type
15306 // The pre/post increment operators yied an lvalue.
15307 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15308 VK = VK_LValue;
15309
15310 if (Fns.empty())
15311 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15312 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15313 FPFeatures: CurFPFeatureOverrides());
15314
15315 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15316 ExprResult Fn = CreateUnresolvedLookupExpr(
15317 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15318 if (Fn.isInvalid())
15319 return ExprError();
15320 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15321 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15322 FPFeatures: CurFPFeatureOverrides());
15323 }
15324
15325 // Build an empty overload set.
15326 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15327 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, Args: ArgsArray, PerformADL);
15328
15329 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15330
15331 // Perform overload resolution.
15332 OverloadCandidateSet::iterator Best;
15333 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15334 case OR_Success: {
15335 // We found a built-in operator or an overloaded operator.
15336 FunctionDecl *FnDecl = Best->Function;
15337
15338 if (FnDecl) {
15339 Expr *Base = nullptr;
15340 // We matched an overloaded operator. Build a call to that
15341 // operator.
15342
15343 // Convert the arguments.
15344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15345 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15346
15347 ExprResult InputInit;
15348 if (Method->isExplicitObjectMemberFunction())
15349 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15350 else
15351 InputInit = PerformImplicitObjectArgumentInitialization(
15352 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15353 if (InputInit.isInvalid())
15354 return ExprError();
15355 Base = Input = InputInit.get();
15356 } else {
15357 // Convert the arguments.
15358 ExprResult InputInit
15359 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15360 Context,
15361 Parm: FnDecl->getParamDecl(i: 0)),
15362 EqualLoc: SourceLocation(),
15363 Init: Input);
15364 if (InputInit.isInvalid())
15365 return ExprError();
15366 Input = InputInit.get();
15367 }
15368
15369 // Build the actual expression node.
15370 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15371 Base, HadMultipleCandidates,
15372 Loc: OpLoc);
15373 if (FnExpr.isInvalid())
15374 return ExprError();
15375
15376 // Determine the result type.
15377 QualType ResultTy = FnDecl->getReturnType();
15378 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15379 ResultTy = ResultTy.getNonLValueExprType(Context);
15380
15381 Args[0] = Input;
15382 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15383 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15384 FPFeatures: CurFPFeatureOverrides(),
15385 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15386
15387 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15388 return ExprError();
15389
15390 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15391 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15392 return ExprError();
15393 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15394 } else {
15395 // We matched a built-in operator. Convert the arguments, then
15396 // break out so that we will build the appropriate built-in
15397 // operator node.
15398 ExprResult InputRes = PerformImplicitConversion(
15399 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15400 Action: AssignmentAction::Passing,
15401 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15402 if (InputRes.isInvalid())
15403 return ExprError();
15404 Input = InputRes.get();
15405 break;
15406 }
15407 }
15408
15409 case OR_No_Viable_Function:
15410 // This is an erroneous use of an operator which can be overloaded by
15411 // a non-member function. Check for non-member operators which were
15412 // defined too late to be candidates.
15413 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15414 // FIXME: Recover by calling the found function.
15415 return ExprError();
15416
15417 // No viable function; fall through to handling this as a
15418 // built-in operator, which will produce an error message for us.
15419 break;
15420
15421 case OR_Ambiguous:
15422 CandidateSet.NoteCandidates(
15423 PD: PartialDiagnosticAt(OpLoc,
15424 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15425 << UnaryOperator::getOpcodeStr(Op: Opc)
15426 << Input->getType() << Input->getSourceRange()),
15427 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15428 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15429 return ExprError();
15430
15431 case OR_Deleted: {
15432 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15433 // object whose method was called. Later in NoteCandidates size of ArgsArray
15434 // is passed further and it eventually ends up compared to number of
15435 // function candidate parameters which never includes the object parameter,
15436 // so slice ArgsArray to make sure apples are compared to apples.
15437 StringLiteral *Msg = Best->Function->getDeletedMessage();
15438 CandidateSet.NoteCandidates(
15439 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15440 << UnaryOperator::getOpcodeStr(Op: Opc)
15441 << (Msg != nullptr)
15442 << (Msg ? Msg->getString() : StringRef())
15443 << Input->getSourceRange()),
15444 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15445 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15446 return ExprError();
15447 }
15448 }
15449
15450 // Either we found no viable overloaded operator or we matched a
15451 // built-in operator. In either case, fall through to trying to
15452 // build a built-in operation.
15453 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15454}
15455
15456void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15457 OverloadedOperatorKind Op,
15458 const UnresolvedSetImpl &Fns,
15459 ArrayRef<Expr *> Args, bool PerformADL) {
15460 SourceLocation OpLoc = CandidateSet.getLocation();
15461
15462 OverloadedOperatorKind ExtraOp =
15463 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15464 ? getRewrittenOverloadedOperator(Kind: Op)
15465 : OO_None;
15466
15467 // Add the candidates from the given function set. This also adds the
15468 // rewritten candidates using these functions if necessary.
15469 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15470
15471 // As template candidates are not deduced immediately,
15472 // persist the array in the overload set.
15473 ArrayRef<Expr *> ReversedArgs;
15474 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15475 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15476 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15477
15478 // Add operator candidates that are member functions.
15479 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15480 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15481 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15482 PO: OverloadCandidateParamOrder::Reversed);
15483
15484 // In C++20, also add any rewritten member candidates.
15485 if (ExtraOp) {
15486 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15487 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15488 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15489 PO: OverloadCandidateParamOrder::Reversed);
15490 }
15491
15492 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15493 // performed for an assignment operator (nor for operator[] nor operator->,
15494 // which don't get here).
15495 if (Op != OO_Equal && PerformADL) {
15496 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15497 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15498 /*ExplicitTemplateArgs*/ nullptr,
15499 CandidateSet);
15500 if (ExtraOp) {
15501 DeclarationName ExtraOpName =
15502 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15503 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15504 /*ExplicitTemplateArgs*/ nullptr,
15505 CandidateSet);
15506 }
15507 }
15508
15509 // Add builtin operator candidates.
15510 //
15511 // FIXME: We don't add any rewritten candidates here. This is strictly
15512 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15513 // resulting in our selecting a rewritten builtin candidate. For example:
15514 //
15515 // enum class E { e };
15516 // bool operator!=(E, E) requires false;
15517 // bool k = E::e != E::e;
15518 //
15519 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15520 // it seems unreasonable to consider rewritten builtin candidates. A core
15521 // issue has been filed proposing to removed this requirement.
15522 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15523}
15524
15525ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15526 BinaryOperatorKind Opc,
15527 const UnresolvedSetImpl &Fns, Expr *LHS,
15528 Expr *RHS, bool PerformADL,
15529 bool AllowRewrittenCandidates,
15530 FunctionDecl *DefaultedFn) {
15531 Expr *Args[2] = { LHS, RHS };
15532 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15533
15534 if (!getLangOpts().CPlusPlus20)
15535 AllowRewrittenCandidates = false;
15536
15537 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15538
15539 // If either side is type-dependent, create an appropriate dependent
15540 // expression.
15541 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15542 if (Fns.empty()) {
15543 // If there are no functions to store, just build a dependent
15544 // BinaryOperator or CompoundAssignment.
15545 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15546 return CompoundAssignOperator::Create(
15547 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15548 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15549 CompResultType: Context.DependentTy);
15550 return BinaryOperator::Create(
15551 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15552 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15553 }
15554
15555 // FIXME: save results of ADL from here?
15556 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15557 // TODO: provide better source location info in DNLoc component.
15558 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15559 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15560 ExprResult Fn = CreateUnresolvedLookupExpr(
15561 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15562 if (Fn.isInvalid())
15563 return ExprError();
15564 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15565 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15566 FPFeatures: CurFPFeatureOverrides());
15567 }
15568
15569 // If this is the .* operator, which is not overloadable, just
15570 // create a built-in binary operator.
15571 if (Opc == BO_PtrMemD) {
15572 auto CheckPlaceholder = [&](Expr *&Arg) {
15573 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15574 if (Res.isUsable())
15575 Arg = Res.get();
15576 return !Res.isUsable();
15577 };
15578
15579 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15580 // expression that contains placeholders (in either the LHS or RHS).
15581 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15582 return ExprError();
15583 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15584 }
15585
15586 // Always do placeholder-like conversions on the RHS.
15587 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15588 return ExprError();
15589
15590 // Do placeholder-like conversion on the LHS; note that we should
15591 // not get here with a PseudoObject LHS.
15592 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15593 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15594 return ExprError();
15595
15596 // If this is the assignment operator, we only perform overload resolution
15597 // if the left-hand side is a class or enumeration type. This is actually
15598 // a hack. The standard requires that we do overload resolution between the
15599 // various built-in candidates, but as DR507 points out, this can lead to
15600 // problems. So we do it this way, which pretty much follows what GCC does.
15601 // Note that we go the traditional code path for compound assignment forms.
15602 // In HLSL, user-defined structs/classes do not have constructors or
15603 // overloadable assignment operators, so we can take this shortcut too.
15604 const Type *LHSTy = Args[0]->getType().getTypePtr();
15605 if (Opc == BO_Assign &&
15606 (!LHSTy->isOverloadableType() ||
15607 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15608 !LHSTy->getAsCXXRecordDecl()->isHLSLBuiltinRecord())))
15609 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15610
15611 // Build the overload set.
15612 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15613 OverloadCandidateSet::OperatorRewriteInfo(
15614 Op, OpLoc, AllowRewrittenCandidates));
15615 if (DefaultedFn)
15616 CandidateSet.exclude(F: DefaultedFn);
15617 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15618
15619 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15620
15621 // Perform overload resolution.
15622 OverloadCandidateSet::iterator Best;
15623 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15624 case OR_Success: {
15625 // We found a built-in operator or an overloaded operator.
15626 FunctionDecl *FnDecl = Best->Function;
15627
15628 bool IsReversed = Best->isReversed();
15629 if (IsReversed)
15630 std::swap(a&: Args[0], b&: Args[1]);
15631
15632 if (FnDecl) {
15633
15634 if (FnDecl->isInvalidDecl())
15635 return ExprError();
15636
15637 Expr *Base = nullptr;
15638 // We matched an overloaded operator. Build a call to that
15639 // operator.
15640
15641 OverloadedOperatorKind ChosenOp =
15642 FnDecl->getDeclName().getCXXOverloadedOperator();
15643
15644 // C++2a [over.match.oper]p9:
15645 // If a rewritten operator== candidate is selected by overload
15646 // resolution for an operator@, its return type shall be cv bool
15647 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15648 !FnDecl->getReturnType()->isBooleanType()) {
15649 bool IsExtension =
15650 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15651 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15652 : diag::err_ovl_rewrite_equalequal_not_bool)
15653 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15654 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15655 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15656 if (!IsExtension)
15657 return ExprError();
15658 }
15659
15660 if (AllowRewrittenCandidates && !IsReversed &&
15661 CandidateSet.getRewriteInfo().isReversible()) {
15662 // We could have reversed this operator, but didn't. Check if some
15663 // reversed form was a viable candidate, and if so, if it had a
15664 // better conversion for either parameter. If so, this call is
15665 // formally ambiguous, and allowing it is an extension.
15666 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15667 for (OverloadCandidate &Cand : CandidateSet) {
15668 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15669 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15670 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15671 if (CompareImplicitConversionSequences(
15672 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15673 ICS2: Best->Conversions[ArgIdx]) ==
15674 ImplicitConversionSequence::Better) {
15675 AmbiguousWith.push_back(Elt: Cand.Function);
15676 break;
15677 }
15678 }
15679 }
15680 }
15681
15682 if (!AmbiguousWith.empty()) {
15683 bool AmbiguousWithSelf =
15684 AmbiguousWith.size() == 1 &&
15685 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15686 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15687 << BinaryOperator::getOpcodeStr(Op: Opc)
15688 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15689 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15690 if (AmbiguousWithSelf) {
15691 Diag(Loc: FnDecl->getLocation(),
15692 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15693 // Mark member== const or provide matching != to disallow reversed
15694 // args. Eg.
15695 // struct S { bool operator==(const S&); };
15696 // S()==S();
15697 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15698 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15699 !MD->isConst() &&
15700 !MD->hasCXXExplicitFunctionObjectParameter() &&
15701 Context.hasSameUnqualifiedType(
15702 T1: MD->getFunctionObjectParameterType(),
15703 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15704 Context.hasSameUnqualifiedType(
15705 T1: MD->getFunctionObjectParameterType(),
15706 T2: Args[0]->getType()) &&
15707 Context.hasSameUnqualifiedType(
15708 T1: MD->getFunctionObjectParameterType(),
15709 T2: Args[1]->getType()))
15710 Diag(Loc: FnDecl->getLocation(),
15711 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15712 } else {
15713 Diag(Loc: FnDecl->getLocation(),
15714 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15715 for (auto *F : AmbiguousWith)
15716 Diag(Loc: F->getLocation(),
15717 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15718 }
15719 }
15720 }
15721
15722 // Check for nonnull = nullable.
15723 // This won't be caught in the arg's initialization: the parameter to
15724 // the assignment operator is not marked nonnull.
15725 if (Op == OO_Equal)
15726 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15727 SrcType: Args[1]->getType(), Loc: OpLoc);
15728
15729 // Convert the arguments.
15730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15731 // Best->Access is only meaningful for class members.
15732 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15733
15734 ExprResult Arg0, Arg1;
15735 unsigned ParamIdx = 0;
15736 if (Method->isExplicitObjectMemberFunction()) {
15737 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15738 ParamIdx = 1;
15739 } else {
15740 Arg0 = PerformImplicitObjectArgumentInitialization(
15741 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15742 }
15743 Arg1 = PerformCopyInitialization(
15744 Entity: InitializedEntity::InitializeParameter(
15745 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15746 EqualLoc: SourceLocation(), Init: Args[1]);
15747 if (Arg0.isInvalid() || Arg1.isInvalid())
15748 return ExprError();
15749
15750 Base = Args[0] = Arg0.getAs<Expr>();
15751 Args[1] = RHS = Arg1.getAs<Expr>();
15752 } else {
15753 // Convert the arguments.
15754 ExprResult Arg0 = PerformCopyInitialization(
15755 Entity: InitializedEntity::InitializeParameter(Context,
15756 Parm: FnDecl->getParamDecl(i: 0)),
15757 EqualLoc: SourceLocation(), Init: Args[0]);
15758 if (Arg0.isInvalid())
15759 return ExprError();
15760
15761 ExprResult Arg1 =
15762 PerformCopyInitialization(
15763 Entity: InitializedEntity::InitializeParameter(Context,
15764 Parm: FnDecl->getParamDecl(i: 1)),
15765 EqualLoc: SourceLocation(), Init: Args[1]);
15766 if (Arg1.isInvalid())
15767 return ExprError();
15768 Args[0] = LHS = Arg0.getAs<Expr>();
15769 Args[1] = RHS = Arg1.getAs<Expr>();
15770 }
15771
15772 // Build the actual expression node.
15773 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15774 FoundDecl: Best->FoundDecl, Base,
15775 HadMultipleCandidates, Loc: OpLoc);
15776 if (FnExpr.isInvalid())
15777 return ExprError();
15778
15779 // Determine the result type.
15780 QualType ResultTy = FnDecl->getReturnType();
15781 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15782 ResultTy = ResultTy.getNonLValueExprType(Context);
15783
15784 CallExpr *TheCall;
15785 ArrayRef<const Expr *> ArgsArray(Args, 2);
15786 const Expr *ImplicitThis = nullptr;
15787
15788 // We always create a CXXOperatorCallExpr, even for explicit object
15789 // members; CodeGen should take care not to emit the this pointer.
15790 TheCall = CXXOperatorCallExpr::Create(
15791 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15792 FPFeatures: CurFPFeatureOverrides(),
15793 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15794 IsReversed);
15795
15796 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15797 Method && Method->isImplicitObjectMemberFunction()) {
15798 // Cut off the implicit 'this'.
15799 ImplicitThis = ArgsArray[0];
15800 ArgsArray = ArgsArray.slice(N: 1);
15801 }
15802
15803 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15804 FD: FnDecl))
15805 return ExprError();
15806
15807 if (Op == OO_Equal) {
15808 // Check for a self move.
15809 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15810 // lifetime check.
15811 checkAssignmentLifetime(
15812 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15813 Init: Args[1]);
15814 }
15815 if (ImplicitThis) {
15816 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15817 QualType ThisTypeFromDecl = Context.getPointerType(
15818 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15819
15820 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15821 ParamTy: ThisTypeFromDecl);
15822 }
15823
15824 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15825 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15826 CallType: VariadicCallType::DoesNotApply);
15827
15828 ExprResult R = MaybeBindToTemporary(E: TheCall);
15829 if (R.isInvalid())
15830 return ExprError();
15831
15832 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15833 if (R.isInvalid())
15834 return ExprError();
15835
15836 // For a rewritten candidate, we've already reversed the arguments
15837 // if needed. Perform the rest of the rewrite now.
15838 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15839 (Op == OO_Spaceship && IsReversed)) {
15840 if (Op == OO_ExclaimEqual) {
15841 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15842 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15843 } else {
15844 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15845 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15846 Expr *ZeroLiteral =
15847 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15848
15849 Sema::CodeSynthesisContext Ctx;
15850 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15851 Ctx.Entity = FnDecl;
15852 pushCodeSynthesisContext(Ctx);
15853
15854 R = CreateOverloadedBinOp(
15855 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15856 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15857 /*AllowRewrittenCandidates=*/false);
15858
15859 popCodeSynthesisContext();
15860 }
15861 if (R.isInvalid())
15862 return ExprError();
15863 } else {
15864 assert(ChosenOp == Op && "unexpected operator name");
15865 }
15866
15867 // Make a note in the AST if we did any rewriting.
15868 if (Best->RewriteKind != CRK_None)
15869 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15870
15871 return R;
15872 } else {
15873 // We matched a built-in operator. Convert the arguments, then
15874 // break out so that we will build the appropriate built-in
15875 // operator node.
15876 ExprResult ArgsRes0 = PerformImplicitConversion(
15877 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15878 Action: AssignmentAction::Passing,
15879 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15880 if (ArgsRes0.isInvalid())
15881 return ExprError();
15882 Args[0] = ArgsRes0.get();
15883
15884 ExprResult ArgsRes1 = PerformImplicitConversion(
15885 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15886 Action: AssignmentAction::Passing,
15887 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15888 if (ArgsRes1.isInvalid())
15889 return ExprError();
15890 Args[1] = ArgsRes1.get();
15891 break;
15892 }
15893 }
15894
15895 case OR_No_Viable_Function: {
15896 // C++ [over.match.oper]p9:
15897 // If the operator is the operator , [...] and there are no
15898 // viable functions, then the operator is assumed to be the
15899 // built-in operator and interpreted according to clause 5.
15900 if (Opc == BO_Comma)
15901 break;
15902
15903 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15904 // compare result using '==' and '<'.
15905 if (DefaultedFn && Opc == BO_Cmp) {
15906 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15907 RHS: Args[1], DefaultedFn);
15908 if (E.isInvalid() || E.isUsable())
15909 return E;
15910 }
15911
15912 // For class as left operand for assignment or compound assignment
15913 // operator do not fall through to handling in built-in, but report that
15914 // no overloaded assignment operator found
15915 ExprResult Result = ExprError();
15916 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15917 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15918 Args, OpLoc);
15919 DeferDiagsRAII DDR(*this,
15920 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15921 if (Args[0]->getType()->isRecordType() &&
15922 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15923 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15924 << BinaryOperator::getOpcodeStr(Op: Opc)
15925 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15926 if (Args[0]->getType()->isIncompleteType()) {
15927 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15928 << Args[0]->getType()
15929 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15930 }
15931 } else {
15932 // This is an erroneous use of an operator which can be overloaded by
15933 // a non-member function. Check for non-member operators which were
15934 // defined too late to be candidates.
15935 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15936 // FIXME: Recover by calling the found function.
15937 return ExprError();
15938
15939 // No viable function; try to create a built-in operation, which will
15940 // produce an error. Then, show the non-viable candidates.
15941 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15942 }
15943 assert(Result.isInvalid() &&
15944 "C++ binary operator overloading is missing candidates!");
15945 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15946 return Result;
15947 }
15948
15949 case OR_Ambiguous:
15950 CandidateSet.NoteCandidates(
15951 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15952 << BinaryOperator::getOpcodeStr(Op: Opc)
15953 << Args[0]->getType()
15954 << Args[1]->getType()
15955 << Args[0]->getSourceRange()
15956 << Args[1]->getSourceRange()),
15957 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15958 OpLoc);
15959 return ExprError();
15960
15961 case OR_Deleted: {
15962 if (isImplicitlyDeleted(FD: Best->Function)) {
15963 FunctionDecl *DeletedFD = Best->Function;
15964 FunctionDecl::DefaultedFunctionKind DFK =
15965 DeletedFD->getDefaultedFunctionKind();
15966 if (DFK.isSpecialMember()) {
15967 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15968 << Args[0]->getType() << DFK.asSpecialMember();
15969 } else {
15970 assert(DFK.isComparison());
15971 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15972 << Args[0]->getType() << DeletedFD;
15973 }
15974
15975 // The user probably meant to call this special member. Just
15976 // explain why it's deleted.
15977 NoteDeletedFunction(FD: DeletedFD);
15978 return ExprError();
15979 }
15980
15981 StringLiteral *Msg = Best->Function->getDeletedMessage();
15982 CandidateSet.NoteCandidates(
15983 PD: PartialDiagnosticAt(
15984 OpLoc,
15985 PDiag(DiagID: diag::err_ovl_deleted_oper)
15986 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15987 .getCXXOverloadedOperator())
15988 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15989 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15990 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15991 OpLoc);
15992 return ExprError();
15993 }
15994 }
15995
15996 // We matched a built-in operator; build it.
15997 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15998}
15999
16000ExprResult Sema::BuildSynthesizedThreeWayComparison(
16001 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16002 FunctionDecl *DefaultedFn) {
16003 const ComparisonCategoryInfo *Info =
16004 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
16005 // If we're not producing a known comparison category type, we can't
16006 // synthesize a three-way comparison. Let the caller diagnose this.
16007 if (!Info)
16008 return ExprResult((Expr*)nullptr);
16009
16010 // If we ever want to perform this synthesis more generally, we will need to
16011 // apply the temporary materialization conversion to the operands.
16012 assert(LHS->isGLValue() && RHS->isGLValue() &&
16013 "cannot use prvalue expressions more than once");
16014 Expr *OrigLHS = LHS;
16015 Expr *OrigRHS = RHS;
16016
16017 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16018 // each of them multiple times below.
16019 LHS = new (Context)
16020 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16021 LHS->getObjectKind(), LHS);
16022 RHS = new (Context)
16023 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16024 RHS->getObjectKind(), RHS);
16025
16026 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
16027 DefaultedFn);
16028 if (Eq.isInvalid())
16029 return ExprError();
16030
16031 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
16032 AllowRewrittenCandidates: true, DefaultedFn);
16033 if (Less.isInvalid())
16034 return ExprError();
16035
16036 ExprResult Greater;
16037 if (Info->isPartial()) {
16038 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
16039 DefaultedFn);
16040 if (Greater.isInvalid())
16041 return ExprError();
16042 }
16043
16044 // Form the list of comparisons we're going to perform.
16045 struct Comparison {
16046 ExprResult Cmp;
16047 ComparisonCategoryResult Result;
16048 } Comparisons[4] =
16049 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
16050 : ComparisonCategoryResult::Equivalent},
16051 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
16052 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
16053 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
16054 };
16055
16056 int I = Info->isPartial() ? 3 : 2;
16057
16058 // Combine the comparisons with suitable conditional expressions.
16059 ExprResult Result;
16060 for (; I >= 0; --I) {
16061 // Build a reference to the comparison category constant.
16062 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
16063 // FIXME: Missing a constant for a comparison category. Diagnose this?
16064 if (!VI)
16065 return ExprResult((Expr*)nullptr);
16066 ExprResult ThisResult =
16067 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
16068 if (ThisResult.isInvalid())
16069 return ExprError();
16070
16071 // Build a conditional unless this is the final case.
16072 if (Result.get()) {
16073 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
16074 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
16075 if (Result.isInvalid())
16076 return ExprError();
16077 } else {
16078 Result = ThisResult;
16079 }
16080 }
16081
16082 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16083 // bind the OpaqueValueExprs before they're (repeatedly) used.
16084 Expr *SyntacticForm = BinaryOperator::Create(
16085 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
16086 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
16087 FPFeatures: CurFPFeatureOverrides());
16088 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16089 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
16090}
16091
16092static bool PrepareArgumentsForCallToObjectOfClassType(
16093 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16094 MultiExprArg Args, SourceLocation LParenLoc) {
16095
16096 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16097 unsigned NumParams = Proto->getNumParams();
16098 unsigned NumArgsSlots =
16099 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16100 // Build the full argument list for the method call (the implicit object
16101 // parameter is placed at the beginning of the list).
16102 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16103 bool IsError = false;
16104 // Initialize the implicit object parameter.
16105 // Check the argument types.
16106 for (unsigned i = 0; i != NumParams; i++) {
16107 Expr *Arg;
16108 if (i < Args.size()) {
16109 Arg = Args[i];
16110 ExprResult InputInit =
16111 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16112 Context&: S.Context, Parm: Method->getParamDecl(i)),
16113 EqualLoc: SourceLocation(), Init: Arg);
16114 IsError |= InputInit.isInvalid();
16115 Arg = InputInit.getAs<Expr>();
16116 } else {
16117 ExprResult DefArg =
16118 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16119 if (DefArg.isInvalid()) {
16120 IsError = true;
16121 break;
16122 }
16123 Arg = DefArg.getAs<Expr>();
16124 }
16125
16126 MethodArgs.push_back(Elt: Arg);
16127 }
16128 return IsError;
16129}
16130
16131ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16132 SourceLocation RLoc,
16133 Expr *Base,
16134 MultiExprArg ArgExpr) {
16135 SmallVector<Expr *, 2> Args;
16136 Args.push_back(Elt: Base);
16137 for (auto *e : ArgExpr) {
16138 Args.push_back(Elt: e);
16139 }
16140 DeclarationName OpName =
16141 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16142
16143 SourceRange Range = ArgExpr.empty()
16144 ? SourceRange{}
16145 : SourceRange(ArgExpr.front()->getBeginLoc(),
16146 ArgExpr.back()->getEndLoc());
16147
16148 // If either side is type-dependent, create an appropriate dependent
16149 // expression.
16150 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16151
16152 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16153 // CHECKME: no 'operator' keyword?
16154 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16155 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16156 ExprResult Fn = CreateUnresolvedLookupExpr(
16157 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16158 if (Fn.isInvalid())
16159 return ExprError();
16160 // Can't add any actual overloads yet
16161
16162 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16163 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16164 FPFeatures: CurFPFeatureOverrides());
16165 }
16166
16167 // Handle placeholders
16168 UnbridgedCastsSet UnbridgedCasts;
16169 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16170 return ExprError();
16171 }
16172 // Build an empty overload set.
16173 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16174
16175 // Subscript can only be overloaded as a member function.
16176
16177 // Add operator candidates that are member functions.
16178 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16179
16180 // Add builtin operator candidates.
16181 if (Args.size() == 2)
16182 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16183
16184 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16185
16186 // Perform overload resolution.
16187 OverloadCandidateSet::iterator Best;
16188 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16189 case OR_Success: {
16190 // We found a built-in operator or an overloaded operator.
16191 FunctionDecl *FnDecl = Best->Function;
16192
16193 if (FnDecl) {
16194 // We matched an overloaded operator. Build a call to that
16195 // operator.
16196
16197 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16198
16199 // Convert the arguments.
16200 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16201 SmallVector<Expr *, 2> MethodArgs;
16202
16203 // Initialize the object parameter.
16204 if (Method->isExplicitObjectMemberFunction()) {
16205 ExprResult Res =
16206 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16207 if (Res.isInvalid())
16208 return ExprError();
16209 Args[0] = Res.get();
16210 ArgExpr = Args;
16211 } else {
16212 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16213 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16214 if (Arg0.isInvalid())
16215 return ExprError();
16216
16217 MethodArgs.push_back(Elt: Arg0.get());
16218 }
16219
16220 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16221 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16222 if (IsError)
16223 return ExprError();
16224
16225 // Build the actual expression node.
16226 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16227 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16228 ExprResult FnExpr = CreateFunctionRefExpr(
16229 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
16230 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
16231 if (FnExpr.isInvalid())
16232 return ExprError();
16233
16234 // Determine the result type
16235 QualType ResultTy = FnDecl->getReturnType();
16236 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16237 ResultTy = ResultTy.getNonLValueExprType(Context);
16238
16239 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16240 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16241 FPFeatures: CurFPFeatureOverrides());
16242
16243 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16244 return ExprError();
16245
16246 if (CheckFunctionCall(FDecl: Method, TheCall,
16247 Proto: Method->getType()->castAs<FunctionProtoType>()))
16248 return ExprError();
16249
16250 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16251 Decl: FnDecl);
16252 } else {
16253 // We matched a built-in operator. Convert the arguments, then
16254 // break out so that we will build the appropriate built-in
16255 // operator node.
16256 ExprResult ArgsRes0 = PerformImplicitConversion(
16257 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16258 Action: AssignmentAction::Passing,
16259 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16260 if (ArgsRes0.isInvalid())
16261 return ExprError();
16262 Args[0] = ArgsRes0.get();
16263
16264 ExprResult ArgsRes1 = PerformImplicitConversion(
16265 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16266 Action: AssignmentAction::Passing,
16267 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16268 if (ArgsRes1.isInvalid())
16269 return ExprError();
16270 Args[1] = ArgsRes1.get();
16271
16272 break;
16273 }
16274 }
16275
16276 case OR_No_Viable_Function: {
16277 PartialDiagnostic PD =
16278 CandidateSet.empty()
16279 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16280 << Args[0]->getType() << /*subscript*/ 0
16281 << Args[0]->getSourceRange() << Range)
16282 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16283 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16284 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16285 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16286 return ExprError();
16287 }
16288
16289 case OR_Ambiguous:
16290 if (Args.size() == 2) {
16291 CandidateSet.NoteCandidates(
16292 PD: PartialDiagnosticAt(
16293 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16294 << "[]" << Args[0]->getType() << Args[1]->getType()
16295 << Args[0]->getSourceRange() << Range),
16296 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16297 } else {
16298 CandidateSet.NoteCandidates(
16299 PD: PartialDiagnosticAt(LLoc,
16300 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16301 << Args[0]->getType()
16302 << Args[0]->getSourceRange() << Range),
16303 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16304 }
16305 return ExprError();
16306
16307 case OR_Deleted: {
16308 StringLiteral *Msg = Best->Function->getDeletedMessage();
16309 CandidateSet.NoteCandidates(
16310 PD: PartialDiagnosticAt(LLoc,
16311 PDiag(DiagID: diag::err_ovl_deleted_oper)
16312 << "[]" << (Msg != nullptr)
16313 << (Msg ? Msg->getString() : StringRef())
16314 << Args[0]->getSourceRange() << Range),
16315 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16316 return ExprError();
16317 }
16318 }
16319
16320 // We matched a built-in operator; build it.
16321 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16322}
16323
16324ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16325 SourceLocation LParenLoc,
16326 MultiExprArg Args,
16327 SourceLocation RParenLoc,
16328 Expr *ExecConfig, bool IsExecConfig,
16329 bool AllowRecovery) {
16330 assert(MemExprE->getType() == Context.BoundMemberTy ||
16331 MemExprE->getType() == Context.OverloadTy);
16332
16333 // Dig out the member expression. This holds both the object
16334 // argument and the member function we're referring to.
16335 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16336
16337 // Determine whether this is a call to a pointer-to-member function.
16338 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16339 assert(op->getType() == Context.BoundMemberTy);
16340 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16341
16342 QualType fnType =
16343 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16344
16345 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16346 QualType resultType = proto->getCallResultType(Context);
16347 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16348
16349 // Check that the object type isn't more qualified than the
16350 // member function we're calling.
16351 Qualifiers funcQuals = proto->getMethodQuals();
16352
16353 QualType objectType = op->getLHS()->getType();
16354 if (op->getOpcode() == BO_PtrMemI)
16355 objectType = objectType->castAs<PointerType>()->getPointeeType();
16356 Qualifiers objectQuals = objectType.getQualifiers();
16357
16358 Qualifiers difference = objectQuals - funcQuals;
16359 difference.removeObjCGCAttr();
16360 difference.removeAddressSpace();
16361 if (difference) {
16362 std::string qualsString = difference.getAsString();
16363 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16364 << fnType.getUnqualifiedType()
16365 << qualsString
16366 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16367 }
16368
16369 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16370 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16371 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16372
16373 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16374 CE: call, FD: nullptr))
16375 return ExprError();
16376
16377 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16378 return ExprError();
16379
16380 if (CheckOtherCall(TheCall: call, Proto: proto))
16381 return ExprError();
16382
16383 return MaybeBindToTemporary(E: call);
16384 }
16385
16386 // We only try to build a recovery expr at this level if we can preserve
16387 // the return type, otherwise we return ExprError() and let the caller
16388 // recover.
16389 auto BuildRecoveryExpr = [&](QualType Type) {
16390 if (!AllowRecovery)
16391 return ExprError();
16392 std::vector<Expr *> SubExprs = {MemExprE};
16393 llvm::append_range(C&: SubExprs, R&: Args);
16394 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16395 T: Type);
16396 };
16397 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16398 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16399 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16400
16401 UnbridgedCastsSet UnbridgedCasts;
16402 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16403 return ExprError();
16404
16405 MemberExpr *MemExpr;
16406 CXXMethodDecl *Method = nullptr;
16407 bool HadMultipleCandidates = false;
16408 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16409 NestedNameSpecifier Qualifier = std::nullopt;
16410 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16411 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16412 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16413 FoundDecl = MemExpr->getFoundDecl();
16414 Qualifier = MemExpr->getQualifier();
16415 UnbridgedCasts.restore();
16416 } else {
16417 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16418 Qualifier = UnresExpr->getQualifier();
16419
16420 QualType ObjectType = UnresExpr->getBaseType();
16421 Expr::Classification ObjectClassification
16422 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16423 : UnresExpr->getBase()->Classify(Ctx&: Context);
16424
16425 // Add overload candidates
16426 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16427 OverloadCandidateSet::CSK_Normal);
16428
16429 // FIXME: avoid copy.
16430 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16431 if (UnresExpr->hasExplicitTemplateArgs()) {
16432 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16433 TemplateArgs = &TemplateArgsBuffer;
16434 }
16435
16436 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16437 E = UnresExpr->decls_end(); I != E; ++I) {
16438
16439 QualType ExplicitObjectType = ObjectType;
16440
16441 NamedDecl *Func = *I;
16442 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16443 if (isa<UsingShadowDecl>(Val: Func))
16444 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16445
16446 bool HasExplicitParameter = false;
16447 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16448 M && M->hasCXXExplicitFunctionObjectParameter())
16449 HasExplicitParameter = true;
16450 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16451 M &&
16452 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16453 HasExplicitParameter = true;
16454
16455 if (HasExplicitParameter)
16456 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16457
16458 // Microsoft supports direct constructor calls.
16459 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16460 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16461 CandidateSet,
16462 /*SuppressUserConversions*/ false);
16463 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16464 // If explicit template arguments were provided, we can't call a
16465 // non-template member function.
16466 if (TemplateArgs)
16467 continue;
16468
16469 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16470 ObjectClassification, Args, CandidateSet,
16471 /*SuppressUserConversions=*/false);
16472 } else {
16473 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16474 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16475 ObjectType: ExplicitObjectType, ObjectClassification,
16476 Args, CandidateSet,
16477 /*SuppressUserConversions=*/false);
16478 }
16479 }
16480
16481 HadMultipleCandidates = (CandidateSet.size() > 1);
16482
16483 DeclarationName DeclName = UnresExpr->getMemberName();
16484
16485 UnbridgedCasts.restore();
16486
16487 OverloadCandidateSet::iterator Best;
16488 bool Succeeded = false;
16489 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16490 Best)) {
16491 case OR_Success:
16492 Method = cast<CXXMethodDecl>(Val: Best->Function);
16493 FoundDecl = Best->FoundDecl;
16494 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16495 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16496 break;
16497 // If FoundDecl is different from Method (such as if one is a template
16498 // and the other a specialization), make sure DiagnoseUseOfDecl is
16499 // called on both.
16500 // FIXME: This would be more comprehensively addressed by modifying
16501 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16502 // being used.
16503 if (Method != FoundDecl.getDecl() &&
16504 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16505 break;
16506 Succeeded = true;
16507 break;
16508
16509 case OR_No_Viable_Function:
16510 CandidateSet.NoteCandidates(
16511 PD: PartialDiagnosticAt(
16512 UnresExpr->getMemberLoc(),
16513 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16514 << DeclName << MemExprE->getSourceRange()),
16515 S&: *this, OCD: OCD_AllCandidates, Args);
16516 break;
16517 case OR_Ambiguous:
16518 CandidateSet.NoteCandidates(
16519 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16520 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16521 << DeclName << MemExprE->getSourceRange()),
16522 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16523 break;
16524 case OR_Deleted:
16525 DiagnoseUseOfDeletedFunction(
16526 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16527 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16528 break;
16529 }
16530 // Overload resolution fails, try to recover.
16531 if (!Succeeded)
16532 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16533
16534 ExprResult Res =
16535 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16536 if (Res.isInvalid())
16537 return ExprError();
16538 MemExprE = Res.get();
16539
16540 // If overload resolution picked a static member
16541 // build a non-member call based on that function.
16542 if (Method->isStatic()) {
16543 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16544 Config: ExecConfig, IsExecConfig);
16545 }
16546
16547 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16548 }
16549
16550 QualType ResultType = Method->getReturnType();
16551 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16552 ResultType = ResultType.getNonLValueExprType(Context);
16553
16554 assert(Method && "Member call to something that isn't a method?");
16555 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16556
16557 CallExpr *TheCall = nullptr;
16558 llvm::SmallVector<Expr *, 8> NewArgs;
16559 if (Method->isExplicitObjectMemberFunction()) {
16560 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16561 NewArgs))
16562 return ExprError();
16563
16564 // Build the actual expression node.
16565 ExprResult FnExpr =
16566 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16567 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16568 if (FnExpr.isInvalid())
16569 return ExprError();
16570
16571 TheCall =
16572 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16573 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16574 TheCall->setUsesMemberSyntax(true);
16575 } else {
16576 // Convert the object argument (for a non-static member function call).
16577 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16578 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16579 if (ObjectArg.isInvalid())
16580 return ExprError();
16581 MemExpr->setBase(ObjectArg.get());
16582 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16583 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16584 MinNumArgs: Proto->getNumParams());
16585 }
16586
16587 // Check for a valid return type.
16588 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16589 CE: TheCall, FD: Method))
16590 return BuildRecoveryExpr(ResultType);
16591
16592 // Convert the rest of the arguments
16593 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16594 RParenLoc))
16595 return BuildRecoveryExpr(ResultType);
16596
16597 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16598
16599 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16600 return ExprError();
16601
16602 // In the case the method to call was not selected by the overloading
16603 // resolution process, we still need to handle the enable_if attribute. Do
16604 // that here, so it will not hide previous -- and more relevant -- errors.
16605 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16606 if (const EnableIfAttr *Attr =
16607 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16608 Diag(Loc: MemE->getMemberLoc(),
16609 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16610 << Method << Method->getSourceRange();
16611 Diag(Loc: Method->getLocation(),
16612 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16613 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16614 return ExprError();
16615 }
16616 }
16617
16618 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16619 TheCall->getDirectCallee()->isPureVirtual()) {
16620 const FunctionDecl *MD = TheCall->getDirectCallee();
16621
16622 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16623 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16624 Diag(Loc: MemExpr->getBeginLoc(),
16625 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16626 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16627 << MD->getParent();
16628
16629 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16630 if (getLangOpts().AppleKext)
16631 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16632 << MD->getParent() << MD->getDeclName();
16633 }
16634 }
16635
16636 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16637 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16638 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16639 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16640 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16641 DtorLoc: MemExpr->getMemberLoc());
16642 }
16643
16644 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16645 Decl: TheCall->getDirectCallee());
16646}
16647
16648ExprResult
16649Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16650 SourceLocation LParenLoc,
16651 MultiExprArg Args,
16652 SourceLocation RParenLoc) {
16653 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16654 return ExprError();
16655 ExprResult Object = Obj;
16656
16657 UnbridgedCastsSet UnbridgedCasts;
16658 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16659 return ExprError();
16660
16661 assert(Object.get()->getType()->isRecordType() &&
16662 "Requires object type argument");
16663
16664 // C++ [over.call.object]p1:
16665 // If the primary-expression E in the function call syntax
16666 // evaluates to a class object of type "cv T", then the set of
16667 // candidate functions includes at least the function call
16668 // operators of T. The function call operators of T are obtained by
16669 // ordinary lookup of the name operator() in the context of
16670 // (E).operator().
16671 OverloadCandidateSet CandidateSet(LParenLoc,
16672 OverloadCandidateSet::CSK_Operator);
16673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16674
16675 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16676 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16677 return true;
16678
16679 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16680 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16681 LookupQualifiedName(R, LookupCtx: Record);
16682 R.suppressAccessDiagnostics();
16683
16684 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16685 Oper != OperEnd; ++Oper) {
16686 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16687 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16688 /*SuppressUserConversion=*/SuppressUserConversions: false);
16689 }
16690
16691 // When calling a lambda, both the call operator, and
16692 // the conversion operator to function pointer
16693 // are considered. But when constraint checking
16694 // on the call operator fails, it will also fail on the
16695 // conversion operator as the constraints are always the same.
16696 // As the user probably does not intend to perform a surrogate call,
16697 // we filter them out to produce better error diagnostics, ie to avoid
16698 // showing 2 failed overloads instead of one.
16699 bool IgnoreSurrogateFunctions = false;
16700 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16701 const OverloadCandidate &Candidate = *CandidateSet.begin();
16702 if (!Candidate.Viable &&
16703 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16704 IgnoreSurrogateFunctions = true;
16705 }
16706
16707 // C++ [over.call.object]p2:
16708 // In addition, for each (non-explicit in C++0x) conversion function
16709 // declared in T of the form
16710 //
16711 // operator conversion-type-id () cv-qualifier;
16712 //
16713 // where cv-qualifier is the same cv-qualification as, or a
16714 // greater cv-qualification than, cv, and where conversion-type-id
16715 // denotes the type "pointer to function of (P1,...,Pn) returning
16716 // R", or the type "reference to pointer to function of
16717 // (P1,...,Pn) returning R", or the type "reference to function
16718 // of (P1,...,Pn) returning R", a surrogate call function [...]
16719 // is also considered as a candidate function. Similarly,
16720 // surrogate call functions are added to the set of candidate
16721 // functions for each conversion function declared in an
16722 // accessible base class provided the function is not hidden
16723 // within T by another intervening declaration.
16724 const auto &Conversions = Record->getVisibleConversionFunctions();
16725 for (auto I = Conversions.begin(), E = Conversions.end();
16726 !IgnoreSurrogateFunctions && I != E; ++I) {
16727 NamedDecl *D = *I;
16728 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16729 if (isa<UsingShadowDecl>(Val: D))
16730 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16731
16732 // Skip over templated conversion functions; they aren't
16733 // surrogates.
16734 if (isa<FunctionTemplateDecl>(Val: D))
16735 continue;
16736
16737 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16738 if (!Conv->isExplicit()) {
16739 // Strip the reference type (if any) and then the pointer type (if
16740 // any) to get down to what might be a function type.
16741 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16742 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16743 ConvType = ConvPtrType->getPointeeType();
16744
16745 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16746 {
16747 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16748 Object: Object.get(), Args, CandidateSet);
16749 }
16750 }
16751 }
16752
16753 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16754
16755 // Perform overload resolution.
16756 OverloadCandidateSet::iterator Best;
16757 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16758 Best)) {
16759 case OR_Success:
16760 // Overload resolution succeeded; we'll build the appropriate call
16761 // below.
16762 break;
16763
16764 case OR_No_Viable_Function: {
16765 PartialDiagnostic PD =
16766 CandidateSet.empty()
16767 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16768 << Object.get()->getType() << /*call*/ 1
16769 << Object.get()->getSourceRange())
16770 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16771 << Object.get()->getType() << Object.get()->getSourceRange());
16772 CandidateSet.NoteCandidates(
16773 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16774 OCD: OCD_AllCandidates, Args);
16775 break;
16776 }
16777 case OR_Ambiguous:
16778 if (!R.isAmbiguous())
16779 CandidateSet.NoteCandidates(
16780 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16781 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16782 << Object.get()->getType()
16783 << Object.get()->getSourceRange()),
16784 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16785 break;
16786
16787 case OR_Deleted: {
16788 // FIXME: Is this diagnostic here really necessary? It seems that
16789 // 1. we don't have any tests for this diagnostic, and
16790 // 2. we already issue err_deleted_function_use for this later on anyway.
16791 StringLiteral *Msg = Best->Function->getDeletedMessage();
16792 CandidateSet.NoteCandidates(
16793 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16794 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16795 << Object.get()->getType() << (Msg != nullptr)
16796 << (Msg ? Msg->getString() : StringRef())
16797 << Object.get()->getSourceRange()),
16798 S&: *this, OCD: OCD_AllCandidates, Args);
16799 break;
16800 }
16801 }
16802
16803 if (Best == CandidateSet.end())
16804 return true;
16805
16806 UnbridgedCasts.restore();
16807
16808 if (Best->Function == nullptr) {
16809 // Since there is no function declaration, this is one of the
16810 // surrogate candidates. Dig out the conversion function.
16811 CXXConversionDecl *Conv
16812 = cast<CXXConversionDecl>(
16813 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16814
16815 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16816 FoundDecl: Best->FoundDecl);
16817 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16818 return ExprError();
16819 assert(Conv == Best->FoundDecl.getDecl() &&
16820 "Found Decl & conversion-to-functionptr should be same, right?!");
16821 // We selected one of the surrogate functions that converts the
16822 // object parameter to a function pointer. Perform the conversion
16823 // on the object argument, then let BuildCallExpr finish the job.
16824
16825 // Create an implicit member expr to refer to the conversion operator.
16826 // and then call it.
16827 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16828 Method: Conv, HadMultipleCandidates);
16829 if (Call.isInvalid())
16830 return ExprError();
16831 // Record usage of conversion in an implicit cast.
16832 Call = ImplicitCastExpr::Create(
16833 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16834 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16835
16836 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16837 }
16838
16839 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16840
16841 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16842 // that calls this method, using Object for the implicit object
16843 // parameter and passing along the remaining arguments.
16844 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16845
16846 // An error diagnostic has already been printed when parsing the declaration.
16847 if (Method->isInvalidDecl())
16848 return ExprError();
16849
16850 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16851 unsigned NumParams = Proto->getNumParams();
16852
16853 DeclarationNameInfo OpLocInfo(
16854 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16855 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16856 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16857 Base: Obj, HadMultipleCandidates,
16858 Loc: OpLocInfo.getLoc(),
16859 LocInfo: OpLocInfo.getInfo());
16860 if (NewFn.isInvalid())
16861 return true;
16862
16863 SmallVector<Expr *, 8> MethodArgs;
16864 MethodArgs.reserve(N: NumParams + 1);
16865
16866 bool IsError = false;
16867
16868 // Initialize the object parameter.
16869 llvm::SmallVector<Expr *, 8> NewArgs;
16870 if (Method->isExplicitObjectMemberFunction()) {
16871 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16872 } else {
16873 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16874 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16875 if (ObjRes.isInvalid())
16876 IsError = true;
16877 else
16878 Object = ObjRes;
16879 MethodArgs.push_back(Elt: Object.get());
16880 }
16881
16882 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16883 S&: *this, MethodArgs, Method, Args, LParenLoc);
16884
16885 // If this is a variadic call, handle args passed through "...".
16886 if (Proto->isVariadic()) {
16887 // Promote the arguments (C99 6.5.2.2p7).
16888 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16889 ExprResult Arg = DefaultVariadicArgumentPromotion(
16890 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16891 IsError |= Arg.isInvalid();
16892 MethodArgs.push_back(Elt: Arg.get());
16893 }
16894 }
16895
16896 if (IsError)
16897 return true;
16898
16899 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16900
16901 // Once we've built TheCall, all of the expressions are properly owned.
16902 QualType ResultTy = Method->getReturnType();
16903 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16904 ResultTy = ResultTy.getNonLValueExprType(Context);
16905
16906 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16907 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16908 FPFeatures: CurFPFeatureOverrides());
16909
16910 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16911 return true;
16912
16913 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16914 return true;
16915
16916 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16917}
16918
16919ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16920 SourceLocation OpLoc,
16921 bool *NoArrowOperatorFound) {
16922 assert(Base->getType()->isRecordType() &&
16923 "left-hand side must have class type");
16924
16925 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16926 return ExprError();
16927
16928 SourceLocation Loc = Base->getExprLoc();
16929
16930 // C++ [over.ref]p1:
16931 //
16932 // [...] An expression x->m is interpreted as (x.operator->())->m
16933 // for a class object x of type T if T::operator->() exists and if
16934 // the operator is selected as the best match function by the
16935 // overload resolution mechanism (13.3).
16936 DeclarationName OpName =
16937 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16938 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16939
16940 if (RequireCompleteType(Loc, T: Base->getType(),
16941 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16942 return ExprError();
16943
16944 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16945 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16946 R.suppressAccessDiagnostics();
16947
16948 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16949 Oper != OperEnd; ++Oper) {
16950 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16951 Args: {}, CandidateSet,
16952 /*SuppressUserConversion=*/SuppressUserConversions: false);
16953 }
16954
16955 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16956
16957 // Perform overload resolution.
16958 OverloadCandidateSet::iterator Best;
16959 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16960 case OR_Success:
16961 // Overload resolution succeeded; we'll build the call below.
16962 break;
16963
16964 case OR_No_Viable_Function: {
16965 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16966 if (CandidateSet.empty()) {
16967 QualType BaseType = Base->getType();
16968 if (NoArrowOperatorFound) {
16969 // Report this specific error to the caller instead of emitting a
16970 // diagnostic, as requested.
16971 *NoArrowOperatorFound = true;
16972 return ExprError();
16973 }
16974 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16975 << BaseType << Base->getSourceRange();
16976 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16977 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16978 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16979 }
16980 } else
16981 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16982 << "operator->" << Base->getSourceRange();
16983 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16984 return ExprError();
16985 }
16986 case OR_Ambiguous:
16987 if (!R.isAmbiguous())
16988 CandidateSet.NoteCandidates(
16989 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16990 << "->" << Base->getType()
16991 << Base->getSourceRange()),
16992 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16993 return ExprError();
16994
16995 case OR_Deleted: {
16996 StringLiteral *Msg = Best->Function->getDeletedMessage();
16997 CandidateSet.NoteCandidates(
16998 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16999 << "->" << (Msg != nullptr)
17000 << (Msg ? Msg->getString() : StringRef())
17001 << Base->getSourceRange()),
17002 S&: *this, OCD: OCD_AllCandidates, Args: Base);
17003 return ExprError();
17004 }
17005 }
17006
17007 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
17008
17009 // Convert the object parameter.
17010 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
17011
17012 if (Method->isExplicitObjectMemberFunction()) {
17013 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
17014 if (R.isInvalid())
17015 return ExprError();
17016 Base = R.get();
17017 } else {
17018 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
17019 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
17020 if (BaseResult.isInvalid())
17021 return ExprError();
17022 Base = BaseResult.get();
17023 }
17024
17025 // Build the operator call.
17026 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
17027 Base, HadMultipleCandidates, Loc: OpLoc);
17028 if (FnExpr.isInvalid())
17029 return ExprError();
17030
17031 QualType ResultTy = Method->getReturnType();
17032 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17033 ResultTy = ResultTy.getNonLValueExprType(Context);
17034
17035 CallExpr *TheCall =
17036 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
17037 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
17038
17039 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
17040 return ExprError();
17041
17042 if (CheckFunctionCall(FDecl: Method, TheCall,
17043 Proto: Method->getType()->castAs<FunctionProtoType>()))
17044 return ExprError();
17045
17046 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17047}
17048
17049ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
17050 DeclarationNameInfo &SuffixInfo,
17051 ArrayRef<Expr*> Args,
17052 SourceLocation LitEndLoc,
17053 TemplateArgumentListInfo *TemplateArgs) {
17054 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17055
17056 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17057 OverloadCandidateSet::CSK_Normal);
17058 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
17059 ExplicitTemplateArgs: TemplateArgs);
17060
17061 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17062
17063 // Perform overload resolution. This will usually be trivial, but might need
17064 // to perform substitutions for a literal operator template.
17065 OverloadCandidateSet::iterator Best;
17066 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
17067 case OR_Success:
17068 case OR_Deleted:
17069 break;
17070
17071 case OR_No_Viable_Function:
17072 CandidateSet.NoteCandidates(
17073 PD: PartialDiagnosticAt(UDSuffixLoc,
17074 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
17075 << R.getLookupName()),
17076 S&: *this, OCD: OCD_AllCandidates, Args);
17077 return ExprError();
17078
17079 case OR_Ambiguous:
17080 CandidateSet.NoteCandidates(
17081 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
17082 << R.getLookupName()),
17083 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
17084 return ExprError();
17085 }
17086
17087 FunctionDecl *FD = Best->Function;
17088 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
17089 Base: nullptr, HadMultipleCandidates,
17090 Loc: SuffixInfo.getLoc(),
17091 LocInfo: SuffixInfo.getInfo());
17092 if (Fn.isInvalid())
17093 return true;
17094
17095 // Check the argument types. This should almost always be a no-op, except
17096 // that array-to-pointer decay is applied to string literals.
17097 Expr *ConvArgs[2];
17098 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17099 ExprResult InputInit = PerformCopyInitialization(
17100 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17101 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17102 if (InputInit.isInvalid())
17103 return true;
17104 ConvArgs[ArgIdx] = InputInit.get();
17105 }
17106
17107 QualType ResultTy = FD->getReturnType();
17108 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17109 ResultTy = ResultTy.getNonLValueExprType(Context);
17110
17111 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17112 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17113 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17114
17115 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17116 return ExprError();
17117
17118 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17119 return ExprError();
17120
17121 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17122}
17123
17124Sema::ForRangeStatus
17125Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17126 SourceLocation RangeLoc,
17127 const DeclarationNameInfo &NameInfo,
17128 LookupResult &MemberLookup,
17129 OverloadCandidateSet *CandidateSet,
17130 Expr *Range, ExprResult *CallExpr) {
17131 Scope *S = nullptr;
17132
17133 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17134 if (!MemberLookup.empty()) {
17135 ExprResult MemberRef =
17136 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17137 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17138 /*TemplateKWLoc=*/SourceLocation(),
17139 /*FirstQualifierInScope=*/nullptr,
17140 R&: MemberLookup,
17141 /*TemplateArgs=*/nullptr, S);
17142 if (MemberRef.isInvalid()) {
17143 *CallExpr = ExprError();
17144 return FRS_DiagnosticIssued;
17145 }
17146 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17147 if (CallExpr->isInvalid()) {
17148 *CallExpr = ExprError();
17149 return FRS_DiagnosticIssued;
17150 }
17151 } else {
17152 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17153 NNSLoc: NestedNameSpecifierLoc(),
17154 DNI: NameInfo, Fns: UnresolvedSet<0>());
17155 if (FnR.isInvalid())
17156 return FRS_DiagnosticIssued;
17157 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17158
17159 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17160 CandidateSet, Result: CallExpr);
17161 if (CandidateSet->empty() || CandidateSetError) {
17162 *CallExpr = ExprError();
17163 return FRS_NoViableFunction;
17164 }
17165 OverloadCandidateSet::iterator Best;
17166 OverloadingResult OverloadResult =
17167 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17168
17169 if (OverloadResult == OR_No_Viable_Function) {
17170 *CallExpr = ExprError();
17171 return FRS_NoViableFunction;
17172 }
17173 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17174 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17175 OverloadResult,
17176 /*AllowTypoCorrection=*/false);
17177 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17178 *CallExpr = ExprError();
17179 return FRS_DiagnosticIssued;
17180 }
17181 }
17182 return FRS_Success;
17183}
17184
17185ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17186 FunctionDecl *Fn) {
17187 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17188 ExprResult SubExpr =
17189 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17190 if (SubExpr.isInvalid())
17191 return ExprError();
17192 if (SubExpr.get() == PE->getSubExpr())
17193 return PE;
17194
17195 return new (Context)
17196 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17197 }
17198
17199 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17200 ExprResult SubExpr =
17201 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17202 if (SubExpr.isInvalid())
17203 return ExprError();
17204 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17205 SubExpr.get()->getType()) &&
17206 "Implicit cast type cannot be determined from overload");
17207 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17208 if (SubExpr.get() == ICE->getSubExpr())
17209 return ICE;
17210
17211 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17212 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17213 FPO: CurFPFeatureOverrides());
17214 }
17215
17216 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17217 if (!GSE->isResultDependent()) {
17218 ExprResult SubExpr =
17219 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17220 if (SubExpr.isInvalid())
17221 return ExprError();
17222 if (SubExpr.get() == GSE->getResultExpr())
17223 return GSE;
17224
17225 // Replace the resulting type information before rebuilding the generic
17226 // selection expression.
17227 ArrayRef<Expr *> A = GSE->getAssocExprs();
17228 SmallVector<Expr *, 4> AssocExprs(A);
17229 unsigned ResultIdx = GSE->getResultIndex();
17230 AssocExprs[ResultIdx] = SubExpr.get();
17231
17232 if (GSE->isExprPredicate())
17233 return GenericSelectionExpr::Create(
17234 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17235 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17236 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17237 ResultIndex: ResultIdx);
17238 return GenericSelectionExpr::Create(
17239 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17240 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17241 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17242 ResultIndex: ResultIdx);
17243 }
17244 // Rather than fall through to the unreachable, return the original generic
17245 // selection expression.
17246 return GSE;
17247 }
17248
17249 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17250 assert(UnOp->getOpcode() == UO_AddrOf &&
17251 "Can only take the address of an overloaded function");
17252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17253 if (!Method->isImplicitObjectMemberFunction()) {
17254 // Do nothing: the address of static and
17255 // explicit object member functions is a (non-member) function pointer.
17256 } else {
17257 // Fix the subexpression, which really has to be an
17258 // UnresolvedLookupExpr holding an overloaded member function
17259 // or template.
17260 ExprResult SubExpr =
17261 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17262 if (SubExpr.isInvalid())
17263 return ExprError();
17264 if (SubExpr.get() == UnOp->getSubExpr())
17265 return UnOp;
17266
17267 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17268 Op: SubExpr.get(), MD: Method))
17269 return ExprError();
17270
17271 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17272 "fixed to something other than a decl ref");
17273 NestedNameSpecifier Qualifier =
17274 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17275 assert(Qualifier &&
17276 "fixed to a member ref with no nested name qualifier");
17277
17278 // We have taken the address of a pointer to member
17279 // function. Perform the computation here so that we get the
17280 // appropriate pointer to member type.
17281 QualType MemPtrType = Context.getMemberPointerType(
17282 T: Fn->getType(), Qualifier,
17283 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17284 // Under the MS ABI, lock down the inheritance model now.
17285 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17286 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17287
17288 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17289 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17290 l: UnOp->getOperatorLoc(), CanOverflow: false,
17291 FPFeatures: CurFPFeatureOverrides());
17292 }
17293 }
17294 ExprResult SubExpr =
17295 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17296 if (SubExpr.isInvalid())
17297 return ExprError();
17298 if (SubExpr.get() == UnOp->getSubExpr())
17299 return UnOp;
17300
17301 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17302 InputExpr: SubExpr.get());
17303 }
17304
17305 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17306 if (Found.getAccess() == AS_none) {
17307 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17308 }
17309 // FIXME: avoid copy.
17310 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17311 if (ULE->hasExplicitTemplateArgs()) {
17312 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17313 TemplateArgs = &TemplateArgsBuffer;
17314 }
17315
17316 QualType Type = Fn->getType();
17317 ExprValueKind ValueKind =
17318 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17319 ? VK_LValue
17320 : VK_PRValue;
17321
17322 // FIXME: Duplicated from BuildDeclarationNameExpr.
17323 if (unsigned BID = Fn->getBuiltinID()) {
17324 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17325 Type = Context.BuiltinFnTy;
17326 ValueKind = VK_PRValue;
17327 }
17328 }
17329
17330 DeclRefExpr *DRE = BuildDeclRefExpr(
17331 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17332 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17333 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17334 return DRE;
17335 }
17336
17337 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17338 // FIXME: avoid copy.
17339 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17340 if (MemExpr->hasExplicitTemplateArgs()) {
17341 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17342 TemplateArgs = &TemplateArgsBuffer;
17343 }
17344
17345 Expr *Base;
17346
17347 // If we're filling in a static method where we used to have an
17348 // implicit member access, rewrite to a simple decl ref.
17349 if (MemExpr->isImplicitAccess()) {
17350 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17351 DeclRefExpr *DRE = BuildDeclRefExpr(
17352 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17353 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17354 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17355 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17356 return DRE;
17357 } else {
17358 SourceLocation Loc = MemExpr->getMemberLoc();
17359 if (MemExpr->getQualifier())
17360 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17361 Base =
17362 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17363 }
17364 } else
17365 Base = MemExpr->getBase();
17366
17367 ExprValueKind valueKind;
17368 QualType type;
17369 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17370 valueKind = VK_LValue;
17371 type = Fn->getType();
17372 } else {
17373 valueKind = VK_PRValue;
17374 type = Context.BoundMemberTy;
17375 }
17376
17377 return BuildMemberExpr(
17378 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17379 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17380 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17381 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17382 }
17383
17384 llvm_unreachable("Invalid reference to overloaded function");
17385}
17386
17387ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17388 DeclAccessPair Found,
17389 FunctionDecl *Fn) {
17390 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17391}
17392
17393bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17394 FunctionDecl *Function) {
17395 if (!PartialOverloading || !Function)
17396 return true;
17397 if (Function->isVariadic())
17398 return false;
17399 if (const auto *Proto =
17400 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17401 if (Proto->isTemplateVariadic())
17402 return false;
17403 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17404 if (const auto *Proto =
17405 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17406 if (Proto->isTemplateVariadic())
17407 return false;
17408 return true;
17409}
17410
17411void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17412 DeclarationName Name,
17413 OverloadCandidateSet &CandidateSet,
17414 FunctionDecl *Fn, MultiExprArg Args,
17415 bool IsMember) {
17416 StringLiteral *Msg = Fn->getDeletedMessage();
17417 CandidateSet.NoteCandidates(
17418 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17419 << IsMember << Name << (Msg != nullptr)
17420 << (Msg ? Msg->getString() : StringRef())
17421 << Range),
17422 S&: *this, OCD: OCD_AllCandidates, Args);
17423}
17424