1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/DiagnosticOptions.h"
25#include "clang/Basic/OperatorKinds.h"
26#include "clang/Basic/PartialDiagnostic.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaAMDGPU.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaInternal.h"
37#include "clang/Sema/SemaObjC.h"
38#include "clang/Sema/Template.h"
39#include "clang/Sema/TemplateDeduction.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/STLForwardCompat.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdlib>
50#include <optional>
51
52using namespace clang;
53using namespace sema;
54
55using AllowedExplicit = Sema::AllowedExplicit;
56
57static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
58 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
59 return P->hasAttr<PassObjectSizeAttr>();
60 });
61}
62
63/// A convenience routine for creating a decayed reference to a function.
64static ExprResult CreateFunctionRefExpr(
65 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
66 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
67 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
68 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
69 return ExprError();
70 // If FoundDecl is different from Fn (such as if one is a template
71 // and the other a specialization), make sure DiagnoseUseOfDecl is
72 // called on both.
73 // FIXME: This would be more comprehensively addressed by modifying
74 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
75 // being used.
76 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
77 return ExprError();
78 DeclRefExpr *DRE = new (S.Context)
79 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
80 if (HadMultipleCandidates)
81 DRE->setHadMultipleCandidates(true);
82
83 S.MarkDeclRefReferenced(E: DRE, Base);
84 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
85 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
86 S.ResolveExceptionSpec(Loc, FPT);
87 DRE->setType(Fn->getType());
88 }
89 }
90 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
91 CK: CK_FunctionToPointerDecay);
92}
93
94static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
95 bool InOverloadResolution,
96 StandardConversionSequence &SCS,
97 bool CStyle,
98 bool AllowObjCWritebackConversion);
99
100static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
101 QualType &ToType,
102 bool InOverloadResolution,
103 StandardConversionSequence &SCS,
104 bool CStyle);
105static OverloadingResult
106IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
107 UserDefinedConversionSequence& User,
108 OverloadCandidateSet& Conversions,
109 AllowedExplicit AllowExplicit,
110 bool AllowObjCConversionOnExplicit);
111
112static ImplicitConversionSequence::CompareKind
113CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
114 const StandardConversionSequence& SCS1,
115 const StandardConversionSequence& SCS2);
116
117static ImplicitConversionSequence::CompareKind
118CompareQualificationConversions(Sema &S,
119 const StandardConversionSequence& SCS1,
120 const StandardConversionSequence& SCS2);
121
122static ImplicitConversionSequence::CompareKind
123CompareOverflowBehaviorConversions(Sema &S,
124 const StandardConversionSequence &SCS1,
125 const StandardConversionSequence &SCS2);
126
127static ImplicitConversionSequence::CompareKind
128CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
129 const StandardConversionSequence& SCS1,
130 const StandardConversionSequence& SCS2);
131
132/// GetConversionRank - Retrieve the implicit conversion rank
133/// corresponding to the given implicit conversion kind.
134ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
135 static const ImplicitConversionRank Rank[] = {
136 ICR_Exact_Match,
137 ICR_Exact_Match,
138 ICR_Exact_Match,
139 ICR_Exact_Match,
140 ICR_Exact_Match,
141 ICR_Exact_Match,
142 ICR_Promotion,
143 ICR_Promotion,
144 ICR_Promotion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_Conversion,
151 ICR_Conversion,
152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_OCL_Scalar_Widening,
158 ICR_Complex_Real_Conversion,
159 ICR_Conversion,
160 ICR_Conversion,
161 ICR_Writeback_Conversion,
162 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
163 // it was omitted by the patch that added
164 // ICK_Zero_Event_Conversion
165 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
166 // it was omitted by the patch that added
167 // ICK_Zero_Queue_Conversion
168 ICR_C_Conversion,
169 ICR_C_Conversion_Extension,
170 ICR_Conversion,
171 ICR_HLSL_Dimension_Reduction,
172 ICR_HLSL_Dimension_Reduction,
173 ICR_Conversion,
174 ICR_HLSL_Scalar_Widening,
175 ICR_HLSL_Scalar_Widening,
176 };
177 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
178 return Rank[(int)Kind];
179}
180
181ImplicitConversionRank
182clang::GetDimensionConversionRank(ImplicitConversionRank Base,
183 ImplicitConversionKind Dimension) {
184 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
185 if (Rank == ICR_HLSL_Scalar_Widening) {
186 if (Base == ICR_Promotion)
187 return ICR_HLSL_Scalar_Widening_Promotion;
188 if (Base == ICR_Conversion)
189 return ICR_HLSL_Scalar_Widening_Conversion;
190 }
191 if (Rank == ICR_HLSL_Dimension_Reduction) {
192 if (Base == ICR_Promotion)
193 return ICR_HLSL_Dimension_Reduction_Promotion;
194 if (Base == ICR_Conversion)
195 return ICR_HLSL_Dimension_Reduction_Conversion;
196 }
197 return Rank;
198}
199
200/// GetImplicitConversionName - Return the name of this kind of
201/// implicit conversion.
202static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
203 static const char *const Name[] = {
204 "No conversion",
205 "Lvalue-to-rvalue",
206 "Array-to-pointer",
207 "Function-to-pointer",
208 "Function pointer conversion",
209 "Qualification",
210 "Integral promotion",
211 "Floating point promotion",
212 "Complex promotion",
213 "Integral conversion",
214 "Floating conversion",
215 "Complex conversion",
216 "Floating-integral conversion",
217 "Pointer conversion",
218 "Pointer-to-member conversion",
219 "Boolean conversion",
220 "Compatible-types conversion",
221 "Derived-to-base conversion",
222 "Vector conversion",
223 "SVE Vector conversion",
224 "RVV Vector conversion",
225 "Vector splat",
226 "Complex-real conversion",
227 "Block Pointer conversion",
228 "Transparent Union Conversion",
229 "Writeback conversion",
230 "OpenCL Zero Event Conversion",
231 "OpenCL Zero Queue Conversion",
232 "C specific type conversion",
233 "Incompatible pointer conversion",
234 "Fixed point conversion",
235 "HLSL vector truncation",
236 "HLSL matrix truncation",
237 "Non-decaying array conversion",
238 "HLSL vector splat",
239 "HLSL matrix splat",
240 };
241 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
242 return Name[Kind];
243}
244
245/// StandardConversionSequence - Set the standard conversion
246/// sequence to the identity conversion.
247void StandardConversionSequence::setAsIdentityConversion() {
248 First = ICK_Identity;
249 Second = ICK_Identity;
250 Dimension = ICK_Identity;
251 Third = ICK_Identity;
252 DeprecatedStringLiteralToCharPtr = false;
253 QualificationIncludesObjCLifetime = false;
254 ReferenceBinding = false;
255 DirectBinding = false;
256 IsLvalueReference = true;
257 BindsToFunctionLvalue = false;
258 BindsToRvalue = false;
259 BindsImplicitObjectArgumentWithoutRefQualifier = false;
260 ObjCLifetimeConversionBinding = false;
261 FromBracedInitList = false;
262 CopyConstructor = nullptr;
263}
264
265/// getRank - Retrieve the rank of this standard conversion sequence
266/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
267/// implicit conversions.
268ImplicitConversionRank StandardConversionSequence::getRank() const {
269 ImplicitConversionRank Rank = ICR_Exact_Match;
270 if (GetConversionRank(Kind: First) > Rank)
271 Rank = GetConversionRank(Kind: First);
272 if (GetConversionRank(Kind: Second) > Rank)
273 Rank = GetConversionRank(Kind: Second);
274 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
275 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
276 if (GetConversionRank(Kind: Third) > Rank)
277 Rank = GetConversionRank(Kind: Third);
278 return Rank;
279}
280
281/// isPointerConversionToBool - Determines whether this conversion is
282/// a conversion of a pointer or pointer-to-member to bool. This is
283/// used as part of the ranking of standard conversion sequences
284/// (C++ 13.3.3.2p4).
285bool StandardConversionSequence::isPointerConversionToBool() const {
286 // Note that FromType has not necessarily been transformed by the
287 // array-to-pointer or function-to-pointer implicit conversions, so
288 // check for their presence as well as checking whether FromType is
289 // a pointer.
290 if (getToType(Idx: 1)->isBooleanType() &&
291 (getFromType()->isPointerType() ||
292 getFromType()->isMemberPointerType() ||
293 getFromType()->isObjCObjectPointerType() ||
294 getFromType()->isBlockPointerType() ||
295 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
296 return true;
297
298 return false;
299}
300
301/// isPointerConversionToVoidPointer - Determines whether this
302/// conversion is a conversion of a pointer to a void pointer. This is
303/// used as part of the ranking of standard conversion sequences (C++
304/// 13.3.3.2p4).
305bool
306StandardConversionSequence::
307isPointerConversionToVoidPointer(ASTContext& Context) const {
308 QualType FromType = getFromType();
309 QualType ToType = getToType(Idx: 1);
310
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer implicit conversion, so check for its presence
313 // and redo the conversion to get a pointer.
314 if (First == ICK_Array_To_Pointer)
315 FromType = Context.getArrayDecayedType(T: FromType);
316
317 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
318 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
319 return ToPtrType->getPointeeType()->isVoidType();
320
321 return false;
322}
323
324/// Skip any implicit casts which could be either part of a narrowing conversion
325/// or after one in an implicit conversion.
326static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
327 const Expr *Converted) {
328 // We can have cleanups wrapping the converted expression; these need to be
329 // preserved so that destructors run if necessary.
330 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
331 Expr *Inner =
332 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
333 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
334 objects: EWC->getObjects());
335 }
336
337 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
338 switch (ICE->getCastKind()) {
339 case CK_NoOp:
340 case CK_IntegralCast:
341 case CK_IntegralToBoolean:
342 case CK_IntegralToFloating:
343 case CK_BooleanToSignedIntegral:
344 case CK_FloatingToIntegral:
345 case CK_FloatingToBoolean:
346 case CK_FloatingCast:
347 Converted = ICE->getSubExpr();
348 continue;
349
350 default:
351 return Converted;
352 }
353 }
354
355 return Converted;
356}
357
358/// Check if this standard conversion sequence represents a narrowing
359/// conversion, according to C++11 [dcl.init.list]p7.
360///
361/// \param Ctx The AST context.
362/// \param Converted The result of applying this standard conversion sequence.
363/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
364/// value of the expression prior to the narrowing conversion.
365/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
366/// type of the expression prior to the narrowing conversion.
367/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
368/// from floating point types to integral types should be ignored.
369NarrowingKind StandardConversionSequence::getNarrowingKind(
370 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
371 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
372 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
373 "narrowing check outside C++");
374
375 // C++11 [dcl.init.list]p7:
376 // A narrowing conversion is an implicit conversion ...
377 QualType FromType = getToType(Idx: 0);
378 QualType ToType = getToType(Idx: 1);
379
380 // A conversion to an enumeration type is narrowing if the conversion to
381 // the underlying type is narrowing. This only arises for expressions of
382 // the form 'Enum{init}'.
383 if (const auto *ED = ToType->getAsEnumDecl())
384 ToType = ED->getIntegerType();
385
386 switch (Second) {
387 // 'bool' is an integral type; dispatch to the right place to handle it.
388 case ICK_Boolean_Conversion:
389 if (FromType->isRealFloatingType())
390 goto FloatingIntegralConversion;
391 if (FromType->isIntegralOrUnscopedEnumerationType())
392 goto IntegralConversion;
393 // -- from a pointer type or pointer-to-member type to bool, or
394 return NK_Type_Narrowing;
395
396 // -- from a floating-point type to an integer type, or
397 //
398 // -- from an integer type or unscoped enumeration type to a floating-point
399 // type, except where the source is a constant expression and the actual
400 // value after conversion will fit into the target type and will produce
401 // the original value when converted back to the original type, or
402 case ICK_Floating_Integral:
403 FloatingIntegralConversion:
404 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
405 return NK_Type_Narrowing;
406 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
407 ToType->isRealFloatingType()) {
408 if (IgnoreFloatToIntegralConversion)
409 return NK_Not_Narrowing;
410 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
411 assert(Initializer && "Unknown conversion expression");
412
413 // If it's value-dependent, we can't tell whether it's narrowing.
414 if (Initializer->isValueDependent())
415 return NK_Dependent_Narrowing;
416
417 if (std::optional<llvm::APSInt> IntConstantValue =
418 Initializer->getIntegerConstantExpr(Ctx)) {
419 // Convert the integer to the floating type.
420 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
421 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
422 RM: llvm::APFloat::rmNearestTiesToEven);
423 // And back.
424 llvm::APSInt ConvertedValue = *IntConstantValue;
425 bool ignored;
426 llvm::APFloat::opStatus Status = Result.convertToInteger(
427 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
428 // If the converted-back integer has unspecified value, or if the
429 // resulting value is different, this was a narrowing conversion.
430 if (Status == llvm::APFloat::opInvalidOp ||
431 *IntConstantValue != ConvertedValue) {
432 ConstantValue = APValue(*IntConstantValue);
433 ConstantType = Initializer->getType();
434 return NK_Constant_Narrowing;
435 }
436 } else {
437 // Variables are always narrowings.
438 return NK_Variable_Narrowing;
439 }
440 }
441 return NK_Not_Narrowing;
442
443 // -- from long double to double or float, or from double to float, except
444 // where the source is a constant expression and the actual value after
445 // conversion is within the range of values that can be represented (even
446 // if it cannot be represented exactly), or
447 case ICK_Floating_Conversion:
448 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
449 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
450 // FromType is larger than ToType.
451 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
452
453 // If it's value-dependent, we can't tell whether it's narrowing.
454 if (Initializer->isValueDependent())
455 return NK_Dependent_Narrowing;
456
457 Expr::EvalResult R;
458 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
459 ((Ctx.getLangOpts().CPlusPlus &&
460 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)))) {
461 // Constant!
462 if (Ctx.getLangOpts().C23)
463 ConstantValue = R.Val;
464 assert(ConstantValue.isFloat());
465 llvm::APFloat FloatVal = ConstantValue.getFloat();
466 // Convert the source value into the target type.
467 bool ignored;
468 llvm::APFloat Converted = FloatVal;
469 llvm::APFloat::opStatus ConvertStatus =
470 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
471 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
472 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
473 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
474 if (Ctx.getLangOpts().C23) {
475 if (FloatVal.isNaN() && Converted.isNaN() &&
476 !FloatVal.isSignaling() && !Converted.isSignaling()) {
477 // Quiet NaNs are considered the same value, regardless of
478 // payloads.
479 return NK_Not_Narrowing;
480 }
481 // For normal values, check exact equality.
482 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
483 ConstantType = Initializer->getType();
484 return NK_Constant_Narrowing;
485 }
486 } else {
487 // If there was no overflow, the source value is within the range of
488 // values that can be represented.
489 if (ConvertStatus & llvm::APFloat::opOverflow) {
490 ConstantType = Initializer->getType();
491 return NK_Constant_Narrowing;
492 }
493 }
494 } else {
495 return NK_Variable_Narrowing;
496 }
497 }
498 return NK_Not_Narrowing;
499
500 // -- from an integer type or unscoped enumeration type to an integer type
501 // that cannot represent all the values of the original type, except where
502 // (CWG2627) -- the source is a bit-field whose width w is less than that
503 // of its type (or, for an enumeration type, its underlying type) and the
504 // target type can represent all the values of a hypothetical extended
505 // integer type with width w and with the same signedness as the original
506 // type or
507 // -- the source is a constant expression and the actual value after
508 // conversion will fit into the target type and will produce the original
509 // value when converted back to the original type.
510 case ICK_Integral_Conversion:
511 IntegralConversion: {
512 assert(FromType->isIntegralOrUnscopedEnumerationType());
513 assert(ToType->isIntegralOrUnscopedEnumerationType());
514 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
515 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
516 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
517 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
518
519 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
520 bool ToSigned, unsigned ToWidth) {
521 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
522 !(FromSigned && !ToSigned);
523 };
524
525 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // Not all values of FromType can be represented in ToType.
529 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
530
531 bool DependentBitField = false;
532 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
533 if (BitField->getBitWidth()->isValueDependent())
534 DependentBitField = true;
535 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
536 BitFieldWidth < FromWidth) {
537 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
538 return NK_Not_Narrowing;
539
540 // The initializer will be truncated to the bit-field width
541 FromWidth = BitFieldWidth;
542 }
543 }
544
545 // If it's value-dependent, we can't tell whether it's narrowing.
546 if (Initializer->isValueDependent())
547 return NK_Dependent_Narrowing;
548
549 std::optional<llvm::APSInt> OptInitializerValue =
550 Initializer->getIntegerConstantExpr(Ctx);
551 if (!OptInitializerValue) {
552 // If the bit-field width was dependent, it might end up being small
553 // enough to fit in the target type (unless the target type is unsigned
554 // and the source type is signed, in which case it will never fit)
555 if (DependentBitField && !(FromSigned && !ToSigned))
556 return NK_Dependent_Narrowing;
557
558 // Otherwise, such a conversion is always narrowing
559 return NK_Variable_Narrowing;
560 }
561 llvm::APSInt &InitializerValue = *OptInitializerValue;
562 bool Narrowing = false;
563 if (FromWidth < ToWidth) {
564 // Negative -> unsigned is narrowing. Otherwise, more bits is never
565 // narrowing.
566 if (InitializerValue.isSigned() && InitializerValue.isNegative())
567 Narrowing = true;
568 } else {
569 // Add a bit to the InitializerValue so we don't have to worry about
570 // signed vs. unsigned comparisons.
571 InitializerValue =
572 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
573 // Convert the initializer to and from the target width and signed-ness.
574 llvm::APSInt ConvertedValue = InitializerValue;
575 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
576 ConvertedValue.setIsSigned(ToSigned);
577 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
578 ConvertedValue.setIsSigned(InitializerValue.isSigned());
579 // If the result is different, this was a narrowing conversion.
580 if (ConvertedValue != InitializerValue)
581 Narrowing = true;
582 }
583 if (Narrowing) {
584 ConstantType = Initializer->getType();
585 ConstantValue = APValue(InitializerValue);
586 return NK_Constant_Narrowing;
587 }
588
589 return NK_Not_Narrowing;
590 }
591 case ICK_Complex_Real:
592 if (FromType->isComplexType() && !ToType->isComplexType())
593 return NK_Type_Narrowing;
594 return NK_Not_Narrowing;
595
596 case ICK_Floating_Promotion:
597 if (Ctx.getLangOpts().C23) {
598 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
599 Expr::EvalResult R;
600 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
601 ConstantValue = R.Val;
602 assert(ConstantValue.isFloat());
603 llvm::APFloat FloatVal = ConstantValue.getFloat();
604 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
605 // value, the unqualified versions of the type of the initializer and
606 // the corresponding real type of the object declared shall be
607 // compatible.
608 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
609 ConstantType = Initializer->getType();
610 return NK_Constant_Narrowing;
611 }
612 }
613 }
614 return NK_Not_Narrowing;
615 default:
616 // Other kinds of conversions are not narrowings.
617 return NK_Not_Narrowing;
618 }
619}
620
621/// dump - Print this standard conversion sequence to standard
622/// error. Useful for debugging overloading issues.
623LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
624 raw_ostream &OS = llvm::errs();
625 bool PrintedSomething = false;
626 if (First != ICK_Identity) {
627 OS << GetImplicitConversionName(Kind: First);
628 PrintedSomething = true;
629 }
630
631 if (Second != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
635 OS << GetImplicitConversionName(Kind: Second);
636
637 if (CopyConstructor) {
638 OS << " (by copy constructor)";
639 } else if (DirectBinding) {
640 OS << " (direct reference binding)";
641 } else if (ReferenceBinding) {
642 OS << " (reference binding)";
643 }
644 PrintedSomething = true;
645 }
646
647 if (Third != ICK_Identity) {
648 if (PrintedSomething) {
649 OS << " -> ";
650 }
651 OS << GetImplicitConversionName(Kind: Third);
652 PrintedSomething = true;
653 }
654
655 if (!PrintedSomething) {
656 OS << "No conversions required";
657 }
658}
659
660/// dump - Print this user-defined conversion sequence to standard
661/// error. Useful for debugging overloading issues.
662void UserDefinedConversionSequence::dump() const {
663 raw_ostream &OS = llvm::errs();
664 if (Before.First || Before.Second || Before.Third) {
665 Before.dump();
666 OS << " -> ";
667 }
668 if (ConversionFunction)
669 OS << '\'' << *ConversionFunction << '\'';
670 else
671 OS << "aggregate initialization";
672 if (After.First || After.Second || After.Third) {
673 OS << " -> ";
674 After.dump();
675 }
676}
677
678/// dump - Print this implicit conversion sequence to standard
679/// error. Useful for debugging overloading issues.
680void ImplicitConversionSequence::dump() const {
681 raw_ostream &OS = llvm::errs();
682 if (hasInitializerListContainerType())
683 OS << "Worst list element conversion: ";
684 switch (ConversionKind) {
685 case StandardConversion:
686 OS << "Standard conversion: ";
687 Standard.dump();
688 break;
689 case UserDefinedConversion:
690 OS << "User-defined conversion: ";
691 UserDefined.dump();
692 break;
693 case EllipsisConversion:
694 OS << "Ellipsis conversion";
695 break;
696 case AmbiguousConversion:
697 OS << "Ambiguous conversion";
698 break;
699 case BadConversion:
700 OS << "Bad conversion";
701 break;
702 }
703
704 OS << "\n";
705}
706
707void AmbiguousConversionSequence::construct() {
708 new (&conversions()) ConversionSet();
709}
710
711void AmbiguousConversionSequence::destruct() {
712 conversions().~ConversionSet();
713}
714
715void
716AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
717 FromTypePtr = O.FromTypePtr;
718 ToTypePtr = O.ToTypePtr;
719 new (&conversions()) ConversionSet(O.conversions());
720}
721
722namespace {
723 // Structure used by DeductionFailureInfo to store
724 // template argument information.
725 struct DFIArguments {
726 TemplateArgument FirstArg;
727 TemplateArgument SecondArg;
728 };
729 // Structure used by DeductionFailureInfo to store
730 // template parameter and template argument information.
731 struct DFIParamWithArguments : DFIArguments {
732 TemplateParameter Param;
733 };
734 // Structure used by DeductionFailureInfo to store template argument
735 // information and the index of the problematic call argument.
736 struct DFIDeducedMismatchArgs : DFIArguments {
737 TemplateArgumentList *TemplateArgs;
738 unsigned CallArgIndex;
739 };
740 // Structure used by DeductionFailureInfo to store information about
741 // unsatisfied constraints.
742 struct CNSInfo {
743 TemplateArgumentList *TemplateArgs;
744 ConstraintSatisfaction Satisfaction;
745 };
746}
747
748/// Convert from Sema's representation of template deduction information
749/// to the form used in overload-candidate information.
750DeductionFailureInfo
751clang::MakeDeductionFailureInfo(ASTContext &Context,
752 TemplateDeductionResult TDK,
753 TemplateDeductionInfo &Info) {
754 DeductionFailureInfo Result;
755 Result.Result = static_cast<unsigned>(TDK);
756 Result.HasDiagnostic = false;
757 switch (TDK) {
758 case TemplateDeductionResult::Invalid:
759 case TemplateDeductionResult::InstantiationDepth:
760 case TemplateDeductionResult::TooManyArguments:
761 case TemplateDeductionResult::TooFewArguments:
762 case TemplateDeductionResult::MiscellaneousDeductionFailure:
763 case TemplateDeductionResult::CUDATargetMismatch:
764 Result.Data = nullptr;
765 break;
766
767 case TemplateDeductionResult::Incomplete:
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
770 case TemplateDeductionResult::InvalidExplicitArguments:
771 Result.Data = Info.Param.getOpaqueValue();
772 if (Info.hasSFINAEDiagnostic()) {
773 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
774 SourceLocation(), PartialDiagnostic::NullDiagnostic());
775 Info.takeSFINAEDiagnostic(PD&: *Diag);
776 Result.HasDiagnostic = true;
777 }
778 break;
779
780 case TemplateDeductionResult::DeducedMismatch:
781 case TemplateDeductionResult::DeducedMismatchNested: {
782 // FIXME: Should allocate from normal heap so that we can free this later.
783 auto *Saved = new (Context) DFIDeducedMismatchArgs;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Saved->TemplateArgs = Info.takeSugared();
787 Saved->CallArgIndex = Info.CallArgIndex;
788 Result.Data = Saved;
789 break;
790 }
791
792 case TemplateDeductionResult::NonDeducedMismatch: {
793 // FIXME: Should allocate from normal heap so that we can free this later.
794 DFIArguments *Saved = new (Context) DFIArguments;
795 Saved->FirstArg = Info.FirstArg;
796 Saved->SecondArg = Info.SecondArg;
797 Result.Data = Saved;
798 break;
799 }
800
801 case TemplateDeductionResult::IncompletePack:
802 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
803 case TemplateDeductionResult::Inconsistent:
804 case TemplateDeductionResult::Underqualified: {
805 // FIXME: Should allocate from normal heap so that we can free this later.
806 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
807 Saved->Param = Info.Param;
808 Saved->FirstArg = Info.FirstArg;
809 Saved->SecondArg = Info.SecondArg;
810 Result.Data = Saved;
811 break;
812 }
813
814 case TemplateDeductionResult::SubstitutionFailure:
815 Result.Data = Info.takeSugared();
816 if (Info.hasSFINAEDiagnostic()) {
817 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
818 SourceLocation(), PartialDiagnostic::NullDiagnostic());
819 Info.takeSFINAEDiagnostic(PD&: *Diag);
820 Result.HasDiagnostic = true;
821 }
822 break;
823
824 case TemplateDeductionResult::ConstraintsNotSatisfied: {
825 CNSInfo *Saved = new (Context) CNSInfo;
826 Saved->TemplateArgs = Info.takeSugared();
827 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
828 Result.Data = Saved;
829 break;
830 }
831
832 case TemplateDeductionResult::Success:
833 case TemplateDeductionResult::NonDependentConversionFailure:
834 case TemplateDeductionResult::AlreadyDiagnosed:
835 llvm_unreachable("not a deduction failure");
836 }
837
838 return Result;
839}
840
841void DeductionFailureInfo::Destroy() {
842 switch (static_cast<TemplateDeductionResult>(Result)) {
843 case TemplateDeductionResult::Success:
844 case TemplateDeductionResult::Invalid:
845 case TemplateDeductionResult::InstantiationDepth:
846 case TemplateDeductionResult::Incomplete:
847 case TemplateDeductionResult::TooManyArguments:
848 case TemplateDeductionResult::TooFewArguments:
849 case TemplateDeductionResult::CUDATargetMismatch:
850 case TemplateDeductionResult::NonDependentConversionFailure:
851 break;
852
853 case TemplateDeductionResult::IncompletePack:
854 case TemplateDeductionResult::Inconsistent:
855 case TemplateDeductionResult::Underqualified:
856 case TemplateDeductionResult::DeducedMismatch:
857 case TemplateDeductionResult::DeducedMismatchNested:
858 case TemplateDeductionResult::NonDeducedMismatch:
859 // FIXME: Destroy the data?
860 Data = nullptr;
861 break;
862
863 case TemplateDeductionResult::InvalidExplicitArguments:
864 case TemplateDeductionResult::SubstitutionFailure:
865 // FIXME: Destroy the template argument list?
866 Data = nullptr;
867 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
873 case TemplateDeductionResult::ConstraintsNotSatisfied:
874 // FIXME: Destroy the template argument list?
875 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
876 Data = nullptr;
877 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
878 Diag->~PartialDiagnosticAt();
879 HasDiagnostic = false;
880 }
881 break;
882
883 // Unhandled
884 case TemplateDeductionResult::MiscellaneousDeductionFailure:
885 case TemplateDeductionResult::AlreadyDiagnosed:
886 break;
887 }
888}
889
890PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
891 if (HasDiagnostic)
892 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
893 return nullptr;
894}
895
896TemplateParameter DeductionFailureInfo::getTemplateParameter() {
897 switch (static_cast<TemplateDeductionResult>(Result)) {
898 case TemplateDeductionResult::Success:
899 case TemplateDeductionResult::Invalid:
900 case TemplateDeductionResult::InstantiationDepth:
901 case TemplateDeductionResult::TooManyArguments:
902 case TemplateDeductionResult::TooFewArguments:
903 case TemplateDeductionResult::SubstitutionFailure:
904 case TemplateDeductionResult::DeducedMismatch:
905 case TemplateDeductionResult::DeducedMismatchNested:
906 case TemplateDeductionResult::NonDeducedMismatch:
907 case TemplateDeductionResult::CUDATargetMismatch:
908 case TemplateDeductionResult::NonDependentConversionFailure:
909 case TemplateDeductionResult::ConstraintsNotSatisfied:
910 return TemplateParameter();
911
912 case TemplateDeductionResult::Incomplete:
913 case TemplateDeductionResult::InvalidExplicitArguments:
914 return TemplateParameter::getFromOpaqueValue(VP: Data);
915
916 case TemplateDeductionResult::IncompletePack:
917 case TemplateDeductionResult::Inconsistent:
918 case TemplateDeductionResult::Underqualified:
919 return static_cast<DFIParamWithArguments*>(Data)->Param;
920
921 // Unhandled
922 case TemplateDeductionResult::MiscellaneousDeductionFailure:
923 case TemplateDeductionResult::AlreadyDiagnosed:
924 break;
925 }
926
927 return TemplateParameter();
928}
929
930TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
931 switch (static_cast<TemplateDeductionResult>(Result)) {
932 case TemplateDeductionResult::Success:
933 case TemplateDeductionResult::Invalid:
934 case TemplateDeductionResult::InstantiationDepth:
935 case TemplateDeductionResult::TooManyArguments:
936 case TemplateDeductionResult::TooFewArguments:
937 case TemplateDeductionResult::Incomplete:
938 case TemplateDeductionResult::IncompletePack:
939 case TemplateDeductionResult::InvalidExplicitArguments:
940 case TemplateDeductionResult::Inconsistent:
941 case TemplateDeductionResult::Underqualified:
942 case TemplateDeductionResult::NonDeducedMismatch:
943 case TemplateDeductionResult::CUDATargetMismatch:
944 case TemplateDeductionResult::NonDependentConversionFailure:
945 return nullptr;
946
947 case TemplateDeductionResult::DeducedMismatch:
948 case TemplateDeductionResult::DeducedMismatchNested:
949 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
950
951 case TemplateDeductionResult::SubstitutionFailure:
952 return static_cast<TemplateArgumentList*>(Data);
953
954 case TemplateDeductionResult::ConstraintsNotSatisfied:
955 return static_cast<CNSInfo*>(Data)->TemplateArgs;
956
957 // Unhandled
958 case TemplateDeductionResult::MiscellaneousDeductionFailure:
959 case TemplateDeductionResult::AlreadyDiagnosed:
960 break;
961 }
962
963 return nullptr;
964}
965
966const TemplateArgument *DeductionFailureInfo::getFirstArg() {
967 switch (static_cast<TemplateDeductionResult>(Result)) {
968 case TemplateDeductionResult::Success:
969 case TemplateDeductionResult::Invalid:
970 case TemplateDeductionResult::InstantiationDepth:
971 case TemplateDeductionResult::Incomplete:
972 case TemplateDeductionResult::TooManyArguments:
973 case TemplateDeductionResult::TooFewArguments:
974 case TemplateDeductionResult::InvalidExplicitArguments:
975 case TemplateDeductionResult::SubstitutionFailure:
976 case TemplateDeductionResult::CUDATargetMismatch:
977 case TemplateDeductionResult::NonDependentConversionFailure:
978 case TemplateDeductionResult::ConstraintsNotSatisfied:
979 return nullptr;
980
981 case TemplateDeductionResult::IncompletePack:
982 case TemplateDeductionResult::Inconsistent:
983 case TemplateDeductionResult::Underqualified:
984 case TemplateDeductionResult::DeducedMismatch:
985 case TemplateDeductionResult::DeducedMismatchNested:
986 case TemplateDeductionResult::NonDeducedMismatch:
987 return &static_cast<DFIArguments*>(Data)->FirstArg;
988
989 // Unhandled
990 case TemplateDeductionResult::MiscellaneousDeductionFailure:
991 case TemplateDeductionResult::AlreadyDiagnosed:
992 break;
993 }
994
995 return nullptr;
996}
997
998const TemplateArgument *DeductionFailureInfo::getSecondArg() {
999 switch (static_cast<TemplateDeductionResult>(Result)) {
1000 case TemplateDeductionResult::Success:
1001 case TemplateDeductionResult::Invalid:
1002 case TemplateDeductionResult::InstantiationDepth:
1003 case TemplateDeductionResult::Incomplete:
1004 case TemplateDeductionResult::IncompletePack:
1005 case TemplateDeductionResult::TooManyArguments:
1006 case TemplateDeductionResult::TooFewArguments:
1007 case TemplateDeductionResult::InvalidExplicitArguments:
1008 case TemplateDeductionResult::SubstitutionFailure:
1009 case TemplateDeductionResult::CUDATargetMismatch:
1010 case TemplateDeductionResult::NonDependentConversionFailure:
1011 case TemplateDeductionResult::ConstraintsNotSatisfied:
1012 return nullptr;
1013
1014 case TemplateDeductionResult::Inconsistent:
1015 case TemplateDeductionResult::Underqualified:
1016 case TemplateDeductionResult::DeducedMismatch:
1017 case TemplateDeductionResult::DeducedMismatchNested:
1018 case TemplateDeductionResult::NonDeducedMismatch:
1019 return &static_cast<DFIArguments*>(Data)->SecondArg;
1020
1021 // Unhandled
1022 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1023 case TemplateDeductionResult::AlreadyDiagnosed:
1024 break;
1025 }
1026
1027 return nullptr;
1028}
1029
1030UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1031 switch (static_cast<TemplateDeductionResult>(Result)) {
1032 case TemplateDeductionResult::DeducedMismatch:
1033 case TemplateDeductionResult::DeducedMismatchNested:
1034 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1035
1036 default:
1037 return std::nullopt;
1038 }
1039}
1040
1041static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1042 const FunctionDecl *Y) {
1043 if (!X || !Y)
1044 return false;
1045 if (X->getNumParams() != Y->getNumParams())
1046 return false;
1047 // FIXME: when do rewritten comparison operators
1048 // with explicit object parameters correspond?
1049 // https://cplusplus.github.io/CWG/issues/2797.html
1050 for (unsigned I = 0; I < X->getNumParams(); ++I)
1051 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1052 T2: Y->getParamDecl(i: I)->getType()))
1053 return false;
1054 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1055 auto *FTY = Y->getDescribedFunctionTemplate();
1056 if (!FTY)
1057 return false;
1058 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1059 Y: FTY->getTemplateParameters()))
1060 return false;
1061 }
1062 return true;
1063}
1064
1065static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1066 Expr *FirstOperand, FunctionDecl *EqFD) {
1067 assert(EqFD->getOverloadedOperator() ==
1068 OverloadedOperatorKind::OO_EqualEqual);
1069 // C++2a [over.match.oper]p4:
1070 // A non-template function or function template F named operator== is a
1071 // rewrite target with first operand o unless a search for the name operator!=
1072 // in the scope S from the instantiation context of the operator expression
1073 // finds a function or function template that would correspond
1074 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1075 // scope of the class type of o if F is a class member, and the namespace
1076 // scope of which F is a member otherwise. A function template specialization
1077 // named operator== is a rewrite target if its function template is a rewrite
1078 // target.
1079 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1080 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1081 if (isa<CXXMethodDecl>(Val: EqFD)) {
1082 // If F is a class member, search scope is class type of first operand.
1083 QualType RHS = FirstOperand->getType();
1084 auto *RHSRec = RHS->getAsCXXRecordDecl();
1085 if (!RHSRec)
1086 return true;
1087 LookupResult Members(S, NotEqOp, OpLoc,
1088 Sema::LookupNameKind::LookupMemberName);
1089 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1090 Members.suppressAccessDiagnostics();
1091 for (NamedDecl *Op : Members)
1092 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1093 return false;
1094 return true;
1095 }
1096 // Otherwise the search scope is the namespace scope of which F is a member.
1097 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1098 auto *NotEqFD = Op->getAsFunction();
1099 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1100 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1101 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1102 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1103 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1104 return false;
1105 }
1106 return true;
1107}
1108
1109bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1110 OverloadedOperatorKind Op) const {
1111 if (!AllowRewrittenCandidates)
1112 return false;
1113 return Op == OO_EqualEqual || Op == OO_Spaceship;
1114}
1115
1116bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1117 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1118 auto Op = FD->getOverloadedOperator();
1119 if (!allowsReversed(Op))
1120 return false;
1121 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1122 assert(OriginalArgs.size() == 2);
1123 if (!shouldAddReversedEqEq(
1124 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1125 return false;
1126 }
1127 // Don't bother adding a reversed candidate that can never be a better
1128 // match than the non-reversed version.
1129 return FD->getNumNonObjectParams() != 2 ||
1130 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1131 T2: FD->getParamDecl(i: 1)->getType()) ||
1132 FD->hasAttr<EnableIfAttr>();
1133}
1134
1135void OverloadCandidateSet::destroyCandidates() {
1136 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1137 for (auto &C : i->Conversions)
1138 C.~ImplicitConversionSequence();
1139 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1140 i->DeductionFailure.Destroy();
1141 }
1142}
1143
1144void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1145 destroyCandidates();
1146 SlabAllocator.Reset();
1147 NumInlineBytesUsed = 0;
1148 Candidates.clear();
1149 Functions.clear();
1150 Kind = CSK;
1151 FirstDeferredCandidate = nullptr;
1152 DeferredCandidatesCount = 0;
1153 HasDeferredTemplateConstructors = false;
1154 ResolutionByPerfectCandidateIsDisabled = false;
1155}
1156
1157namespace {
1158 class UnbridgedCastsSet {
1159 struct Entry {
1160 Expr **Addr;
1161 Expr *Saved;
1162 };
1163 SmallVector<Entry, 2> Entries;
1164
1165 public:
1166 void save(Sema &S, Expr *&E) {
1167 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1168 Entry entry = { .Addr: &E, .Saved: E };
1169 Entries.push_back(Elt: entry);
1170 E = S.ObjC().stripARCUnbridgedCast(e: E);
1171 }
1172
1173 void restore() {
1174 for (SmallVectorImpl<Entry>::iterator
1175 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1176 *i->Addr = i->Saved;
1177 }
1178 };
1179}
1180
1181/// checkPlaceholderForOverload - Do any interesting placeholder-like
1182/// preprocessing on the given expression.
1183///
1184/// \param unbridgedCasts a collection to which to add unbridged casts;
1185/// without this, they will be immediately diagnosed as errors
1186///
1187/// Return true on unrecoverable error.
1188static bool
1189checkPlaceholderForOverload(Sema &S, Expr *&E,
1190 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1191 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1192 // We can't handle overloaded expressions here because overload
1193 // resolution might reasonably tweak them.
1194 if (placeholder->getKind() == BuiltinType::Overload) return false;
1195
1196 // If the context potentially accepts unbridged ARC casts, strip
1197 // the unbridged cast and add it to the collection for later restoration.
1198 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1199 unbridgedCasts) {
1200 unbridgedCasts->save(S, E);
1201 return false;
1202 }
1203
1204 // Go ahead and check everything else.
1205 ExprResult result = S.CheckPlaceholderExpr(E);
1206 if (result.isInvalid())
1207 return true;
1208
1209 E = result.get();
1210 return false;
1211 }
1212
1213 // Nothing to do.
1214 return false;
1215}
1216
1217/// checkArgPlaceholdersForOverload - Check a set of call operands for
1218/// placeholders.
1219static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1220 UnbridgedCastsSet &unbridged) {
1221 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1222 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1223 return true;
1224
1225 return false;
1226}
1227
1228OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1229 const LookupResult &Old, NamedDecl *&Match,
1230 bool NewIsUsingDecl) {
1231 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1232 I != E; ++I) {
1233 NamedDecl *OldD = *I;
1234
1235 bool OldIsUsingDecl = false;
1236 if (isa<UsingShadowDecl>(Val: OldD)) {
1237 OldIsUsingDecl = true;
1238
1239 // We can always introduce two using declarations into the same
1240 // context, even if they have identical signatures.
1241 if (NewIsUsingDecl) continue;
1242
1243 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1244 }
1245
1246 // A using-declaration does not conflict with another declaration
1247 // if one of them is hidden.
1248 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1249 continue;
1250
1251 // If either declaration was introduced by a using declaration,
1252 // we'll need to use slightly different rules for matching.
1253 // Essentially, these rules are the normal rules, except that
1254 // function templates hide function templates with different
1255 // return types or template parameter lists.
1256 bool UseMemberUsingDeclRules =
1257 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1258 !New->getFriendObjectKind();
1259
1260 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1261 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1262 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1263 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1264 continue;
1265 }
1266
1267 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1268 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1269 continue;
1270
1271 Match = *I;
1272 return OverloadKind::Match;
1273 }
1274
1275 // Builtins that have custom typechecking or have a reference should
1276 // not be overloadable or redeclarable.
1277 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1278 Match = *I;
1279 return OverloadKind::NonFunction;
1280 }
1281 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1282 // We can overload with these, which can show up when doing
1283 // redeclaration checks for UsingDecls.
1284 assert(Old.getLookupKind() == LookupUsingDeclName);
1285 } else if (isa<TagDecl>(Val: OldD)) {
1286 // We can always overload with tags by hiding them.
1287 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1288 // Optimistically assume that an unresolved using decl will
1289 // overload; if it doesn't, we'll have to diagnose during
1290 // template instantiation.
1291 //
1292 // Exception: if the scope is dependent and this is not a class
1293 // member, the using declaration can only introduce an enumerator.
1294 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1295 Match = *I;
1296 return OverloadKind::NonFunction;
1297 }
1298 } else {
1299 // (C++ 13p1):
1300 // Only function declarations can be overloaded; object and type
1301 // declarations cannot be overloaded.
1302 Match = *I;
1303 return OverloadKind::NonFunction;
1304 }
1305 }
1306
1307 // C++ [temp.friend]p1:
1308 // For a friend function declaration that is not a template declaration:
1309 // -- if the name of the friend is a qualified or unqualified template-id,
1310 // [...], otherwise
1311 // -- if the name of the friend is a qualified-id and a matching
1312 // non-template function is found in the specified class or namespace,
1313 // the friend declaration refers to that function, otherwise,
1314 // -- if the name of the friend is a qualified-id and a matching function
1315 // template is found in the specified class or namespace, the friend
1316 // declaration refers to the deduced specialization of that function
1317 // template, otherwise
1318 // -- the name shall be an unqualified-id [...]
1319 // If we get here for a qualified friend declaration, we've just reached the
1320 // third bullet. If the type of the friend is dependent, skip this lookup
1321 // until instantiation.
1322 if (New->getFriendObjectKind() && New->getQualifier() &&
1323 !New->getDescribedFunctionTemplate() &&
1324 !New->getDependentSpecializationInfo() &&
1325 !New->getType()->isDependentType()) {
1326 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1327 TemplateSpecResult.addAllDecls(Other: Old);
1328 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1329 /*QualifiedFriend*/true)) {
1330 New->setInvalidDecl();
1331 return OverloadKind::Overload;
1332 }
1333
1334 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1335 return OverloadKind::Match;
1336 }
1337
1338 return OverloadKind::Overload;
1339}
1340
1341template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1342 assert(D && "function decl should not be null");
1343 if (auto *A = D->getAttr<AttrT>())
1344 return !A->isImplicit();
1345 return false;
1346}
1347
1348static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1349 FunctionDecl *Old,
1350 bool UseMemberUsingDeclRules,
1351 bool ConsiderCudaAttrs,
1352 bool UseOverrideRules = false) {
1353 // C++ [basic.start.main]p2: This function shall not be overloaded.
1354 if (New->isMain())
1355 return false;
1356
1357 // MSVCRT user defined entry points cannot be overloaded.
1358 if (New->isMSVCRTEntryPoint())
1359 return false;
1360
1361 NamedDecl *OldDecl = Old;
1362 NamedDecl *NewDecl = New;
1363 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1364 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1365
1366 // C++ [temp.fct]p2:
1367 // A function template can be overloaded with other function templates
1368 // and with normal (non-template) functions.
1369 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1370 return true;
1371
1372 // Is the function New an overload of the function Old?
1373 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1374 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1375
1376 // Compare the signatures (C++ 1.3.10) of the two functions to
1377 // determine whether they are overloads. If we find any mismatch
1378 // in the signature, they are overloads.
1379
1380 // If either of these functions is a K&R-style function (no
1381 // prototype), then we consider them to have matching signatures.
1382 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1383 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1384 return false;
1385
1386 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1387 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1388
1389 // The signature of a function includes the types of its
1390 // parameters (C++ 1.3.10), which includes the presence or absence
1391 // of the ellipsis; see C++ DR 357).
1392 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1393 return true;
1394
1395 // For member-like friends, the enclosing class is part of the signature.
1396 if ((New->isMemberLikeConstrainedFriend() ||
1397 Old->isMemberLikeConstrainedFriend()) &&
1398 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1399 return true;
1400
1401 // Compare the parameter lists.
1402 // This can only be done once we have establish that friend functions
1403 // inhabit the same context, otherwise we might tried to instantiate
1404 // references to non-instantiated entities during constraint substitution.
1405 // GH78101.
1406 if (NewTemplate) {
1407 OldDecl = OldTemplate;
1408 NewDecl = NewTemplate;
1409 // C++ [temp.over.link]p4:
1410 // The signature of a function template consists of its function
1411 // signature, its return type and its template parameter list. The names
1412 // of the template parameters are significant only for establishing the
1413 // relationship between the template parameters and the rest of the
1414 // signature.
1415 //
1416 // We check the return type and template parameter lists for function
1417 // templates first; the remaining checks follow.
1418 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1419 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1420 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1421 bool SameReturnType = SemaRef.Context.hasSameType(
1422 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1423 // FIXME(GH58571): Match template parameter list even for non-constrained
1424 // template heads. This currently ensures that the code prior to C++20 is
1425 // not newly broken.
1426 bool ConstraintsInTemplateHead =
1427 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1428 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1429 // C++ [namespace.udecl]p11:
1430 // The set of declarations named by a using-declarator that inhabits a
1431 // class C does not include member functions and member function
1432 // templates of a base class that "correspond" to (and thus would
1433 // conflict with) a declaration of a function or function template in
1434 // C.
1435 // Comparing return types is not required for the "correspond" check to
1436 // decide whether a member introduced by a shadow declaration is hidden.
1437 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1438 !SameTemplateParameterList)
1439 return true;
1440 if (!UseMemberUsingDeclRules &&
1441 (!SameTemplateParameterList || !SameReturnType))
1442 return true;
1443 }
1444
1445 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1446 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1447
1448 int OldParamsOffset = 0;
1449 int NewParamsOffset = 0;
1450
1451 // When determining if a method is an overload from a base class, act as if
1452 // the implicit object parameter are of the same type.
1453
1454 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1455 if (M->isExplicitObjectMemberFunction()) {
1456 auto ThisType = M->getFunctionObjectParameterReferenceType();
1457 if (ThisType.isConstQualified())
1458 Q.removeConst();
1459 return Q;
1460 }
1461
1462 // We do not allow overloading based off of '__restrict'.
1463 Q.removeRestrict();
1464
1465 // We may not have applied the implicit const for a constexpr member
1466 // function yet (because we haven't yet resolved whether this is a static
1467 // or non-static member function). Add it now, on the assumption that this
1468 // is a redeclaration of OldMethod.
1469 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1470 (M->isConstexpr() || M->isConsteval()) &&
1471 !isa<CXXConstructorDecl>(Val: NewMethod))
1472 Q.addConst();
1473 return Q;
1474 };
1475
1476 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1477 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1478 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1479
1480 if (OldMethod->isExplicitObjectMemberFunction()) {
1481 BS.Quals.removeVolatile();
1482 DS.Quals.removeVolatile();
1483 }
1484
1485 return BS.Quals == DS.Quals;
1486 };
1487
1488 auto CompareType = [&](QualType Base, QualType D) {
1489 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1490 auto DS = D.getNonReferenceType().getCanonicalType().split();
1491
1492 if (!AreQualifiersEqual(BS, DS))
1493 return false;
1494
1495 if (OldMethod->isImplicitObjectMemberFunction() &&
1496 OldMethod->getParent() != NewMethod->getParent()) {
1497 CanQualType ParentType =
1498 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1499 if (ParentType.getTypePtr() != BS.Ty)
1500 return false;
1501 BS.Ty = DS.Ty;
1502 }
1503
1504 // FIXME: should we ignore some type attributes here?
1505 if (BS.Ty != DS.Ty)
1506 return false;
1507
1508 if (Base->isLValueReferenceType())
1509 return D->isLValueReferenceType();
1510 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1511 };
1512
1513 // If the function is a class member, its signature includes the
1514 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1515 auto DiagnoseInconsistentRefQualifiers = [&]() {
1516 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1517 return false;
1518 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1519 return false;
1520 if (OldMethod->isExplicitObjectMemberFunction() ||
1521 NewMethod->isExplicitObjectMemberFunction())
1522 return false;
1523 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1524 NewMethod->getRefQualifier() == RQ_None)) {
1525 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1526 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1527 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1528 return true;
1529 }
1530 return false;
1531 };
1532
1533 // We look at the parameters first, as it is the common case.
1534 // However we should not emit diagnostic before checking
1535 // the overloads do not differ by constraints or other discriminant.
1536 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1537 bool HaveInconsistentQualifiers = false;
1538
1539 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1540 OldParamsOffset++;
1541 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1542 NewParamsOffset++;
1543
1544 if (OldType->getNumParams() - OldParamsOffset !=
1545 NewType->getNumParams() - NewParamsOffset ||
1546 !SemaRef.FunctionParamTypesAreEqual(
1547 Old: {OldType->param_type_begin() + OldParamsOffset,
1548 OldType->param_type_end()},
1549 New: {NewType->param_type_begin() + NewParamsOffset,
1550 NewType->param_type_end()},
1551 ArgPos: nullptr)) {
1552 return true;
1553 }
1554
1555 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1556 !NewMethod->isStatic()) {
1557 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1558 const CXXMethodDecl *New) {
1559 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1560 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1561
1562 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1563 return F->getRefQualifier() == RQ_None &&
1564 !F->isExplicitObjectMemberFunction();
1565 };
1566
1567 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1568 CompareType(OldObjectType.getNonReferenceType(),
1569 NewObjectType.getNonReferenceType()))
1570 return true;
1571 return CompareType(OldObjectType, NewObjectType);
1572 }(OldMethod, NewMethod);
1573
1574 if (!HaveCorrespondingObjectParameters) {
1575 ShouldDiagnoseInconsistentRefQualifiers = true;
1576 // CWG2554
1577 // and, if at least one is an explicit object member function, ignoring
1578 // object parameters
1579 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1580 !OldMethod->isExplicitObjectMemberFunction()))
1581 HaveInconsistentQualifiers = true;
1582 }
1583 }
1584
1585 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1586 NewMethod->isImplicitObjectMemberFunction())
1587 ShouldDiagnoseInconsistentRefQualifiers = true;
1588
1589 if (!UseOverrideRules &&
1590 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1591 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1592 OldRC = Old->getTrailingRequiresClause();
1593 if (!NewRC != !OldRC)
1594 return true;
1595 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1596 return true;
1597 if (NewRC &&
1598 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1599 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1600 return true;
1601 }
1602
1603 // Though pass_object_size is placed on parameters and takes an argument, we
1604 // consider it to be a function-level modifier for the sake of function
1605 // identity. Either the function has one or more parameters with
1606 // pass_object_size or it doesn't.
1607 if (functionHasPassObjectSizeParams(FD: New) !=
1608 functionHasPassObjectSizeParams(FD: Old))
1609 return true;
1610
1611 // enable_if attributes are an order-sensitive part of the signature.
1612 for (specific_attr_iterator<EnableIfAttr>
1613 NewI = New->specific_attr_begin<EnableIfAttr>(),
1614 NewE = New->specific_attr_end<EnableIfAttr>(),
1615 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1616 OldE = Old->specific_attr_end<EnableIfAttr>();
1617 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1618 if (NewI == NewE || OldI == OldE)
1619 return true;
1620 llvm::FoldingSetNodeID NewID, OldID;
1621 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1622 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1623 if (NewID != OldID)
1624 return true;
1625 }
1626
1627 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1628 DiagnoseInconsistentRefQualifiers()) ||
1629 HaveInconsistentQualifiers)
1630 return true;
1631
1632 // At this point, it is known that the two functions have the same signature.
1633 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1634 // Don't allow overloading of destructors. (In theory we could, but it
1635 // would be a giant change to clang.)
1636 if (!isa<CXXDestructorDecl>(Val: New)) {
1637 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1638 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1639 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1640 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1641 "Unexpected invalid target.");
1642
1643 // Allow overloading of functions with same signature and different CUDA
1644 // target attributes.
1645 if (NewTarget != OldTarget) {
1646 // Special case: non-constexpr function is allowed to override
1647 // constexpr virtual function
1648 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1649 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1650 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1651 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1652 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1653 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1654 return false;
1655 }
1656 return true;
1657 }
1658 }
1659 }
1660 }
1661
1662 // The signatures match; this is not an overload.
1663 return false;
1664}
1665
1666bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1667 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1668 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1669 ConsiderCudaAttrs);
1670}
1671
1672bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1673 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1674 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1675 /*UseMemberUsingDeclRules=*/false,
1676 /*ConsiderCudaAttrs=*/true,
1677 /*UseOverrideRules=*/true);
1678}
1679
1680/// Tries a user-defined conversion from From to ToType.
1681///
1682/// Produces an implicit conversion sequence for when a standard conversion
1683/// is not an option. See TryImplicitConversion for more information.
1684static ImplicitConversionSequence
1685TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1686 bool SuppressUserConversions,
1687 AllowedExplicit AllowExplicit,
1688 bool InOverloadResolution,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion,
1691 bool AllowObjCConversionOnExplicit) {
1692 ImplicitConversionSequence ICS;
1693
1694 if (SuppressUserConversions) {
1695 // We're not in the case above, so there is no conversion that
1696 // we can perform.
1697 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1698 return ICS;
1699 }
1700
1701 // Attempt user-defined conversion.
1702 OverloadCandidateSet Conversions(From->getExprLoc(),
1703 OverloadCandidateSet::CSK_Normal);
1704 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1705 Conversions, AllowExplicit,
1706 AllowObjCConversionOnExplicit)) {
1707 case OR_Success:
1708 case OR_Deleted:
1709 ICS.setUserDefined();
1710 // C++ [over.ics.user]p4:
1711 // A conversion of an expression of class type to the same class
1712 // type is given Exact Match rank, and a conversion of an
1713 // expression of class type to a base class of that type is
1714 // given Conversion rank, in spite of the fact that a copy
1715 // constructor (i.e., a user-defined conversion function) is
1716 // called for those cases.
1717 if (CXXConstructorDecl *Constructor
1718 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1719 QualType FromType;
1720 SourceLocation FromLoc;
1721 // C++11 [over.ics.list]p6, per DR2137:
1722 // C++17 [over.ics.list]p6:
1723 // If C is not an initializer-list constructor and the initializer list
1724 // has a single element of type cv U, where U is X or a class derived
1725 // from X, the implicit conversion sequence has Exact Match rank if U is
1726 // X, or Conversion rank if U is derived from X.
1727 bool FromListInit = false;
1728 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1729 InitList && InitList->getNumInits() == 1 &&
1730 !S.isInitListConstructor(Ctor: Constructor)) {
1731 const Expr *SingleInit = InitList->getInit(Init: 0);
1732 FromType = SingleInit->getType();
1733 FromLoc = SingleInit->getBeginLoc();
1734 FromListInit = true;
1735 } else {
1736 FromType = From->getType();
1737 FromLoc = From->getBeginLoc();
1738 }
1739 QualType FromCanon =
1740 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1741 QualType ToCanon
1742 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1743 if ((FromCanon == ToCanon ||
1744 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1745 // Turn this into a "standard" conversion sequence, so that it
1746 // gets ranked with standard conversion sequences.
1747 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1748 ICS.setStandard();
1749 ICS.Standard.setAsIdentityConversion();
1750 ICS.Standard.setFromType(FromType);
1751 ICS.Standard.setAllToTypes(ToType);
1752 ICS.Standard.FromBracedInitList = FromListInit;
1753 ICS.Standard.CopyConstructor = Constructor;
1754 ICS.Standard.FoundCopyConstructor = Found;
1755 if (ToCanon != FromCanon)
1756 ICS.Standard.Second = ICK_Derived_To_Base;
1757 }
1758 }
1759 break;
1760
1761 case OR_Ambiguous:
1762 ICS.setAmbiguous();
1763 ICS.Ambiguous.setFromType(From->getType());
1764 ICS.Ambiguous.setToType(ToType);
1765 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1766 Cand != Conversions.end(); ++Cand)
1767 if (Cand->Best)
1768 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1769 break;
1770
1771 // Fall through.
1772 case OR_No_Viable_Function:
1773 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1774 break;
1775 }
1776
1777 return ICS;
1778}
1779
1780/// TryImplicitConversion - Attempt to perform an implicit conversion
1781/// from the given expression (Expr) to the given type (ToType). This
1782/// function returns an implicit conversion sequence that can be used
1783/// to perform the initialization. Given
1784///
1785/// void f(float f);
1786/// void g(int i) { f(i); }
1787///
1788/// this routine would produce an implicit conversion sequence to
1789/// describe the initialization of f from i, which will be a standard
1790/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1791/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1792//
1793/// Note that this routine only determines how the conversion can be
1794/// performed; it does not actually perform the conversion. As such,
1795/// it will not produce any diagnostics if no conversion is available,
1796/// but will instead return an implicit conversion sequence of kind
1797/// "BadConversion".
1798///
1799/// If @p SuppressUserConversions, then user-defined conversions are
1800/// not permitted.
1801/// If @p AllowExplicit, then explicit user-defined conversions are
1802/// permitted.
1803///
1804/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1805/// writeback conversion, which allows __autoreleasing id* parameters to
1806/// be initialized with __strong id* or __weak id* arguments.
1807static ImplicitConversionSequence
1808TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1809 bool SuppressUserConversions,
1810 AllowedExplicit AllowExplicit,
1811 bool InOverloadResolution,
1812 bool CStyle,
1813 bool AllowObjCWritebackConversion,
1814 bool AllowObjCConversionOnExplicit) {
1815 ImplicitConversionSequence ICS;
1816 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1817 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1818 ICS.setStandard();
1819 return ICS;
1820 }
1821
1822 if (!S.getLangOpts().CPlusPlus) {
1823 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1824 return ICS;
1825 }
1826
1827 // C++ [over.ics.user]p4:
1828 // A conversion of an expression of class type to the same class
1829 // type is given Exact Match rank, and a conversion of an
1830 // expression of class type to a base class of that type is
1831 // given Conversion rank, in spite of the fact that a copy/move
1832 // constructor (i.e., a user-defined conversion function) is
1833 // called for those cases.
1834 QualType FromType = From->getType();
1835 if (ToType->isRecordType() &&
1836 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1837 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1838 ICS.setStandard();
1839 ICS.Standard.setAsIdentityConversion();
1840 ICS.Standard.setFromType(FromType);
1841 ICS.Standard.setAllToTypes(ToType);
1842
1843 // We don't actually check at this point whether there is a valid
1844 // copy/move constructor, since overloading just assumes that it
1845 // exists. When we actually perform initialization, we'll find the
1846 // appropriate constructor to copy the returned object, if needed.
1847 ICS.Standard.CopyConstructor = nullptr;
1848
1849 // In HLSL, a conversion of an expression of class type to the same class
1850 // type needs implicit LvaluetoRvalue conversion.
1851 if (S.getLangOpts().HLSL)
1852 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
1853
1854 // Determine whether this is considered a derived-to-base conversion.
1855 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1856 ICS.Standard.Second = ICK_Derived_To_Base;
1857
1858 return ICS;
1859 }
1860
1861 if (S.getLangOpts().HLSL) {
1862 // Handle conversion of the HLSL resource types.
1863 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1864 if (FromTy->isHLSLAttributedResourceType()) {
1865 // Attributed resource types can convert to other attributed
1866 // resource types with the same attributes and contained types,
1867 // or to __hlsl_resource_t without any attributes.
1868 bool CanConvert = false;
1869 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1870 if (ToTy->isHLSLAttributedResourceType()) {
1871 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1872 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1873 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1874 T2: FromResType->getWrappedType()) &&
1875 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1876 T2: FromResType->getContainedType()) &&
1877 ToResType->getAttrs() == FromResType->getAttrs())
1878 CanConvert = true;
1879 } else if (ToTy->isHLSLResourceType()) {
1880 CanConvert = true;
1881 }
1882 if (CanConvert) {
1883 ICS.setStandard();
1884 ICS.Standard.setAsIdentityConversion();
1885 ICS.Standard.setFromType(FromType);
1886 ICS.Standard.setAllToTypes(ToType);
1887 return ICS;
1888 }
1889 }
1890 }
1891
1892 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1893 AllowExplicit, InOverloadResolution, CStyle,
1894 AllowObjCWritebackConversion,
1895 AllowObjCConversionOnExplicit);
1896}
1897
1898ImplicitConversionSequence
1899Sema::TryImplicitConversion(Expr *From, QualType ToType,
1900 bool SuppressUserConversions,
1901 AllowedExplicit AllowExplicit,
1902 bool InOverloadResolution,
1903 bool CStyle,
1904 bool AllowObjCWritebackConversion) {
1905 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1906 AllowExplicit, InOverloadResolution, CStyle,
1907 AllowObjCWritebackConversion,
1908 /*AllowObjCConversionOnExplicit=*/false);
1909}
1910
1911ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1912 AssignmentAction Action,
1913 bool AllowExplicit) {
1914 if (checkPlaceholderForOverload(S&: *this, E&: From))
1915 return ExprError();
1916
1917 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1918 bool AllowObjCWritebackConversion =
1919 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1920 Action == AssignmentAction::Sending);
1921 if (getLangOpts().ObjC)
1922 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1923 SrcType: From->getType(), SrcExpr&: From);
1924 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1925 S&: *this, From, ToType,
1926 /*SuppressUserConversions=*/false,
1927 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1928 /*InOverloadResolution=*/false,
1929 /*CStyle=*/false, AllowObjCWritebackConversion,
1930 /*AllowObjCConversionOnExplicit=*/false);
1931 return PerformImplicitConversion(From, ToType, ICS, Action);
1932}
1933
1934bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1935 QualType &ResultTy) const {
1936 bool Changed = IsFunctionConversion(FromType, ToType);
1937 if (Changed)
1938 ResultTy = ToType;
1939 return Changed;
1940}
1941
1942bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1943 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1944 return false;
1945
1946 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1947 // or F(t noexcept) -> F(t)
1948 // where F adds one of the following at most once:
1949 // - a pointer
1950 // - a member pointer
1951 // - a block pointer
1952 // Changes here need matching changes in FindCompositePointerType.
1953 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1954 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1955 Type::TypeClass TyClass = CanTo->getTypeClass();
1956 if (TyClass != CanFrom->getTypeClass()) return false;
1957 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1958 if (TyClass == Type::Pointer) {
1959 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1960 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1961 } else if (TyClass == Type::BlockPointer) {
1962 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1963 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1964 } else if (TyClass == Type::MemberPointer) {
1965 auto ToMPT = CanTo.castAs<MemberPointerType>();
1966 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1967 // A function pointer conversion cannot change the class of the function.
1968 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1969 D2: FromMPT->getMostRecentCXXRecordDecl()))
1970 return false;
1971 CanTo = ToMPT->getPointeeType();
1972 CanFrom = FromMPT->getPointeeType();
1973 } else {
1974 return false;
1975 }
1976
1977 TyClass = CanTo->getTypeClass();
1978 if (TyClass != CanFrom->getTypeClass()) return false;
1979 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1980 return false;
1981 }
1982
1983 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1984 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1985
1986 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1987 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1988
1989 bool Changed = false;
1990
1991 // Drop 'noreturn' if not present in target type.
1992 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1993 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1994 Changed = true;
1995 }
1996
1997 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1998 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1999
2000 if (FromFPT && ToFPT) {
2001 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2002 QualType NewTy = Context.getFunctionType(
2003 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
2004 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2005 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
2006 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
2007 FromFn = FromFPT;
2008 Changed = true;
2009 }
2010 }
2011
2012 // Drop 'noexcept' if not present in target type.
2013 if (FromFPT && ToFPT) {
2014 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2015 FromFn = cast<FunctionType>(
2016 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
2017 ESI: EST_None)
2018 .getTypePtr());
2019 Changed = true;
2020 }
2021
2022 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2023 // only if the ExtParameterInfo lists of the two function prototypes can be
2024 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2025 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2026 bool CanUseToFPT, CanUseFromFPT;
2027 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2028 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2029 CanUseToFPT && !CanUseFromFPT) {
2030 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2031 ExtInfo.ExtParameterInfos =
2032 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2033 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2034 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2035 FromFn = QT->getAs<FunctionType>();
2036 Changed = true;
2037 }
2038
2039 if (Context.hasAnyFunctionEffects()) {
2040 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2041
2042 // Transparently add/drop effects; here we are concerned with
2043 // language rules/canonicalization. Adding/dropping effects is a warning.
2044 const auto FromFX = FromFPT->getFunctionEffects();
2045 const auto ToFX = ToFPT->getFunctionEffects();
2046 if (FromFX != ToFX) {
2047 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2048 ExtInfo.FunctionEffects = ToFX;
2049 QualType QT = Context.getFunctionType(
2050 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2051 FromFn = QT->getAs<FunctionType>();
2052 Changed = true;
2053 }
2054 }
2055 }
2056
2057 if (!Changed)
2058 return false;
2059
2060 assert(QualType(FromFn, 0).isCanonical());
2061 if (QualType(FromFn, 0) != CanTo) return false;
2062
2063 return true;
2064}
2065
2066/// Determine whether the conversion from FromType to ToType is a valid
2067/// floating point conversion.
2068///
2069static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2070 QualType ToType) {
2071 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2072 return false;
2073 // FIXME: disable conversions between long double, __ibm128 and __float128
2074 // if their representation is different until there is back end support
2075 // We of course allow this conversion if long double is really double.
2076
2077 // Conversions between bfloat16 and float16 are currently not supported.
2078 if ((FromType->isBFloat16Type() &&
2079 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2080 (ToType->isBFloat16Type() &&
2081 (FromType->isFloat16Type() || FromType->isHalfType())))
2082 return false;
2083
2084 // Conversions between IEEE-quad and IBM-extended semantics are not
2085 // permitted.
2086 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2087 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2088 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2089 &ToSem == &llvm::APFloat::IEEEquad()) ||
2090 (&FromSem == &llvm::APFloat::IEEEquad() &&
2091 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2092 return false;
2093 return true;
2094}
2095
2096static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2097 QualType ToType,
2098 ImplicitConversionKind &ICK,
2099 Expr *From) {
2100 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2101 return true;
2102
2103 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2104 ICK = ICK_Floating_Promotion;
2105 return true;
2106 }
2107
2108 if (IsFloatingPointConversion(S, FromType, ToType)) {
2109 ICK = ICK_Floating_Conversion;
2110 return true;
2111 }
2112
2113 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2114 ICK = ICK_Boolean_Conversion;
2115 return true;
2116 }
2117
2118 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2119 (FromType->isIntegralOrUnscopedEnumerationType() &&
2120 ToType->isRealFloatingType())) {
2121 ICK = ICK_Floating_Integral;
2122 return true;
2123 }
2124
2125 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2126 ICK = ICK_Integral_Promotion;
2127 return true;
2128 }
2129
2130 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2131 ToType->isIntegralType(Ctx: S.Context)) {
2132 ICK = ICK_Integral_Conversion;
2133 return true;
2134 }
2135
2136 return false;
2137}
2138
2139/// Determine whether the conversion from FromType to ToType is a valid
2140/// matrix conversion.
2141///
2142/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2143/// conversion.
2144static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2145 ImplicitConversionKind &ICK,
2146 ImplicitConversionKind &ElConv, Expr *From,
2147 bool InOverloadResolution, bool CStyle) {
2148 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2149 if (!S.getLangOpts().HLSL)
2150 return false;
2151
2152 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2153 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2154
2155 // If both arguments are matrix, handle possible matrix truncation and
2156 // element conversion.
2157 if (ToMatrixType && FromMatrixType) {
2158 unsigned FromCols = FromMatrixType->getNumColumns();
2159 unsigned ToCols = ToMatrixType->getNumColumns();
2160 if (FromCols < ToCols)
2161 return false;
2162
2163 unsigned FromRows = FromMatrixType->getNumRows();
2164 unsigned ToRows = ToMatrixType->getNumRows();
2165 if (FromRows < ToRows)
2166 return false;
2167
2168 if (FromRows == ToRows && FromCols == ToCols)
2169 ElConv = ICK_Identity;
2170 else
2171 ElConv = ICK_HLSL_Matrix_Truncation;
2172
2173 QualType FromElTy = FromMatrixType->getElementType();
2174 QualType ToElTy = ToMatrixType->getElementType();
2175 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2176 return true;
2177 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2178 }
2179
2180 // Matrix splat from any arithmetic type to a matrix.
2181 if (ToMatrixType && FromType->isArithmeticType()) {
2182 ElConv = ICK_HLSL_Matrix_Splat;
2183 QualType ToElTy = ToMatrixType->getElementType();
2184 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2185 }
2186 if (FromMatrixType && !ToMatrixType) {
2187 ElConv = ICK_HLSL_Matrix_Truncation;
2188 QualType FromElTy = FromMatrixType->getElementType();
2189 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2190 return true;
2191 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2192 }
2193
2194 return false;
2195}
2196
2197/// Determine whether the conversion from FromType to ToType is a valid
2198/// vector conversion.
2199///
2200/// \param ICK Will be set to the vector conversion kind, if this is a vector
2201/// conversion.
2202static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2203 ImplicitConversionKind &ICK,
2204 ImplicitConversionKind &ElConv, Expr *From,
2205 bool InOverloadResolution, bool CStyle) {
2206 // We need at least one of these types to be a vector type to have a vector
2207 // conversion.
2208 if (!ToType->isVectorType() && !FromType->isVectorType())
2209 return false;
2210
2211 // Identical types require no conversions.
2212 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2213 return false;
2214
2215 // HLSL allows implicit truncation of vector types.
2216 if (S.getLangOpts().HLSL) {
2217 auto *ToExtType = ToType->getAs<ExtVectorType>();
2218 auto *FromExtType = FromType->getAs<ExtVectorType>();
2219
2220 // If both arguments are vectors, handle possible vector truncation and
2221 // element conversion.
2222 if (ToExtType && FromExtType) {
2223 unsigned FromElts = FromExtType->getNumElements();
2224 unsigned ToElts = ToExtType->getNumElements();
2225 if (FromElts < ToElts)
2226 return false;
2227 if (FromElts == ToElts)
2228 ElConv = ICK_Identity;
2229 else
2230 ElConv = ICK_HLSL_Vector_Truncation;
2231
2232 QualType FromElTy = FromExtType->getElementType();
2233 QualType ToElTy = ToExtType->getElementType();
2234 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2235 return true;
2236 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2237 }
2238 if (FromExtType && !ToExtType) {
2239 ElConv = ICK_HLSL_Vector_Truncation;
2240 QualType FromElTy = FromExtType->getElementType();
2241 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2242 return true;
2243 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2244 }
2245 // Fallthrough for the case where ToType is a vector and FromType is not.
2246 }
2247
2248 // There are no conversions between extended vector types, only identity.
2249 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2250 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2251 // Implicit conversions require the same number of elements.
2252 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2253 return false;
2254
2255 // Permit implicit conversions from integral values to boolean vectors.
2256 if (ToType->isExtVectorBoolType() &&
2257 FromExtType->getElementType()->isIntegerType()) {
2258 ICK = ICK_Boolean_Conversion;
2259 return true;
2260 }
2261 // There are no other conversions between extended vector types.
2262 return false;
2263 }
2264
2265 // Vector splat from any arithmetic type to a vector.
2266 if (FromType->isArithmeticType()) {
2267 if (S.getLangOpts().HLSL) {
2268 ElConv = ICK_HLSL_Vector_Splat;
2269 QualType ToElTy = ToExtType->getElementType();
2270 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2271 From);
2272 }
2273 ICK = ICK_Vector_Splat;
2274 return true;
2275 }
2276 }
2277
2278 if (ToType->isSVESizelessBuiltinType() ||
2279 FromType->isSVESizelessBuiltinType())
2280 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2281 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2282 ICK = ICK_SVE_Vector_Conversion;
2283 return true;
2284 }
2285
2286 if (ToType->isRVVSizelessBuiltinType() ||
2287 FromType->isRVVSizelessBuiltinType())
2288 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2289 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2290 ICK = ICK_RVV_Vector_Conversion;
2291 return true;
2292 }
2293
2294 // We can perform the conversion between vector types in the following cases:
2295 // 1)vector types are equivalent AltiVec and GCC vector types
2296 // 2)lax vector conversions are permitted and the vector types are of the
2297 // same size
2298 // 3)the destination type does not have the ARM MVE strict-polymorphism
2299 // attribute, which inhibits lax vector conversion for overload resolution
2300 // only
2301 if (ToType->isVectorType() && FromType->isVectorType()) {
2302 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2303 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2304 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2305 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2306 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2307 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2308 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2309 !InOverloadResolution && !CStyle) {
2310 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2311 << FromType << ToType;
2312 }
2313 ICK = ICK_Vector_Conversion;
2314 return true;
2315 }
2316 }
2317
2318 return false;
2319}
2320
2321static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2322 bool InOverloadResolution,
2323 StandardConversionSequence &SCS,
2324 bool CStyle);
2325
2326static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2327 QualType ToType,
2328 bool InOverloadResolution,
2329 StandardConversionSequence &SCS,
2330 bool CStyle);
2331
2332/// IsStandardConversion - Determines whether there is a standard
2333/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2334/// expression From to the type ToType. Standard conversion sequences
2335/// only consider non-class types; for conversions that involve class
2336/// types, use TryImplicitConversion. If a conversion exists, SCS will
2337/// contain the standard conversion sequence required to perform this
2338/// conversion and this routine will return true. Otherwise, this
2339/// routine will return false and the value of SCS is unspecified.
2340static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2341 bool InOverloadResolution,
2342 StandardConversionSequence &SCS,
2343 bool CStyle,
2344 bool AllowObjCWritebackConversion) {
2345 QualType FromType = From->getType();
2346
2347 // Standard conversions (C++ [conv])
2348 SCS.setAsIdentityConversion();
2349 SCS.IncompatibleObjC = false;
2350 SCS.setFromType(FromType);
2351 SCS.CopyConstructor = nullptr;
2352
2353 // There are no standard conversions for class types in C++, so
2354 // abort early. When overloading in C, however, we do permit them.
2355 if (S.getLangOpts().CPlusPlus &&
2356 (FromType->isRecordType() || ToType->isRecordType()))
2357 return false;
2358
2359 // The first conversion can be an lvalue-to-rvalue conversion,
2360 // array-to-pointer conversion, or function-to-pointer conversion
2361 // (C++ 4p1).
2362
2363 if (FromType == S.Context.OverloadTy) {
2364 DeclAccessPair AccessPair;
2365 if (FunctionDecl *Fn
2366 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2367 Found&: AccessPair)) {
2368 // We were able to resolve the address of the overloaded function,
2369 // so we can convert to the type of that function.
2370 FromType = Fn->getType();
2371 SCS.setFromType(FromType);
2372
2373 // we can sometimes resolve &foo<int> regardless of ToType, so check
2374 // if the type matches (identity) or we are converting to bool
2375 if (!S.Context.hasSameUnqualifiedType(
2376 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2377 // if the function type matches except for [[noreturn]], it's ok
2378 if (!S.IsFunctionConversion(FromType,
2379 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2380 // otherwise, only a boolean conversion is standard
2381 if (!ToType->isBooleanType())
2382 return false;
2383 }
2384
2385 // Check if the "from" expression is taking the address of an overloaded
2386 // function and recompute the FromType accordingly. Take advantage of the
2387 // fact that non-static member functions *must* have such an address-of
2388 // expression.
2389 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2390 if (Method && !Method->isStatic() &&
2391 !Method->isExplicitObjectMemberFunction()) {
2392 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2393 "Non-unary operator on non-static member address");
2394 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2395 == UO_AddrOf &&
2396 "Non-address-of operator on non-static member address");
2397 FromType = S.Context.getMemberPointerType(
2398 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2399 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2400 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2401 UO_AddrOf &&
2402 "Non-address-of operator for overloaded function expression");
2403 FromType = S.Context.getPointerType(T: FromType);
2404 }
2405 } else {
2406 return false;
2407 }
2408 }
2409
2410 bool argIsLValue = From->isGLValue();
2411 // To handle conversion from ArrayParameterType to ConstantArrayType
2412 // this block must be above the one below because Array parameters
2413 // do not decay and when handling HLSLOutArgExprs and
2414 // the From expression is an LValue.
2415 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2416 ToType->isConstantArrayType()) {
2417 // HLSL constant array parameters do not decay, so if the argument is a
2418 // constant array and the parameter is an ArrayParameterType we have special
2419 // handling here.
2420 if (ToType->isArrayParameterType()) {
2421 FromType = S.Context.getArrayParameterType(Ty: FromType);
2422 } else if (FromType->isArrayParameterType()) {
2423 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2424 FromType = APT->getConstantArrayType(Ctx: S.Context);
2425 }
2426
2427 SCS.First = ICK_HLSL_Array_RValue;
2428
2429 // Don't consider qualifiers, which include things like address spaces
2430 if (FromType.getCanonicalType().getUnqualifiedType() !=
2431 ToType.getCanonicalType().getUnqualifiedType())
2432 return false;
2433
2434 SCS.setAllToTypes(ToType);
2435 return true;
2436 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2437 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2438 // Lvalue-to-rvalue conversion (C++11 4.1):
2439 // A glvalue (3.10) of a non-function, non-array type T can
2440 // be converted to a prvalue.
2441
2442 SCS.First = ICK_Lvalue_To_Rvalue;
2443
2444 // C11 6.3.2.1p2:
2445 // ... if the lvalue has atomic type, the value has the non-atomic version
2446 // of the type of the lvalue ...
2447 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2448 FromType = Atomic->getValueType();
2449
2450 // If T is a non-class type, the type of the rvalue is the
2451 // cv-unqualified version of T. Otherwise, the type of the rvalue
2452 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2453 // just strip the qualifiers because they don't matter.
2454 FromType = FromType.getUnqualifiedType();
2455 } else if (FromType->isArrayType()) {
2456 // Array-to-pointer conversion (C++ 4.2)
2457 SCS.First = ICK_Array_To_Pointer;
2458
2459 // An lvalue or rvalue of type "array of N T" or "array of unknown
2460 // bound of T" can be converted to an rvalue of type "pointer to
2461 // T" (C++ 4.2p1).
2462 FromType = S.Context.getArrayDecayedType(T: FromType);
2463
2464 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2465 // This conversion is deprecated in C++03 (D.4)
2466 SCS.DeprecatedStringLiteralToCharPtr = true;
2467
2468 // For the purpose of ranking in overload resolution
2469 // (13.3.3.1.1), this conversion is considered an
2470 // array-to-pointer conversion followed by a qualification
2471 // conversion (4.4). (C++ 4.2p2)
2472 SCS.Second = ICK_Identity;
2473 SCS.Third = ICK_Qualification;
2474 SCS.QualificationIncludesObjCLifetime = false;
2475 SCS.setAllToTypes(FromType);
2476 return true;
2477 }
2478 } else if (FromType->isFunctionType() && argIsLValue) {
2479 // Function-to-pointer conversion (C++ 4.3).
2480 SCS.First = ICK_Function_To_Pointer;
2481
2482 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2483 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2484 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2485 return false;
2486
2487 // An lvalue of function type T can be converted to an rvalue of
2488 // type "pointer to T." The result is a pointer to the
2489 // function. (C++ 4.3p1).
2490 FromType = S.Context.getPointerType(T: FromType);
2491 } else {
2492 // We don't require any conversions for the first step.
2493 SCS.First = ICK_Identity;
2494 }
2495 SCS.setToType(Idx: 0, T: FromType);
2496
2497 // The second conversion can be an integral promotion, floating
2498 // point promotion, integral conversion, floating point conversion,
2499 // floating-integral conversion, pointer conversion,
2500 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2501 // For overloading in C, this can also be a "compatible-type"
2502 // conversion.
2503 bool IncompatibleObjC = false;
2504 ImplicitConversionKind SecondICK = ICK_Identity;
2505 ImplicitConversionKind DimensionICK = ICK_Identity;
2506 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2507 // The unqualified versions of the types are the same: there's no
2508 // conversion to do.
2509 SCS.Second = ICK_Identity;
2510 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2511 // Integral promotion (C++ 4.5).
2512 SCS.Second = ICK_Integral_Promotion;
2513 FromType = ToType.getUnqualifiedType();
2514 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2515 // Floating point promotion (C++ 4.6).
2516 SCS.Second = ICK_Floating_Promotion;
2517 FromType = ToType.getUnqualifiedType();
2518 } else if (S.IsComplexPromotion(FromType, ToType)) {
2519 // Complex promotion (Clang extension)
2520 SCS.Second = ICK_Complex_Promotion;
2521 FromType = ToType.getUnqualifiedType();
2522 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2523 // OverflowBehaviorType promotions
2524 SCS.Second = ICK_Integral_Promotion;
2525 FromType = ToType.getUnqualifiedType();
2526 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2527 // OverflowBehaviorType conversions
2528 SCS.Second = ICK_Integral_Conversion;
2529 FromType = ToType.getUnqualifiedType();
2530 } else if (ToType->isBooleanType() &&
2531 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2532 FromType->isBlockPointerType() ||
2533 FromType->isMemberPointerType())) {
2534 // Boolean conversions (C++ 4.12).
2535 SCS.Second = ICK_Boolean_Conversion;
2536 FromType = S.Context.BoolTy;
2537 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2538 ToType->isIntegralType(Ctx: S.Context)) {
2539 // Integral conversions (C++ 4.7).
2540 SCS.Second = ICK_Integral_Conversion;
2541 FromType = ToType.getUnqualifiedType();
2542 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2543 // Complex conversions (C99 6.3.1.6)
2544 SCS.Second = ICK_Complex_Conversion;
2545 FromType = ToType.getUnqualifiedType();
2546 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2547 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2548 // Complex-real conversions (C99 6.3.1.7)
2549 SCS.Second = ICK_Complex_Real;
2550 FromType = ToType.getUnqualifiedType();
2551 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2552 // Floating point conversions (C++ 4.8).
2553 SCS.Second = ICK_Floating_Conversion;
2554 FromType = ToType.getUnqualifiedType();
2555 } else if ((FromType->isRealFloatingType() &&
2556 ToType->isIntegralType(Ctx: S.Context)) ||
2557 (FromType->isIntegralOrUnscopedEnumerationType() &&
2558 ToType->isRealFloatingType())) {
2559
2560 // Floating-integral conversions (C++ 4.9).
2561 SCS.Second = ICK_Floating_Integral;
2562 FromType = ToType.getUnqualifiedType();
2563 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2564 SCS.Second = ICK_Block_Pointer_Conversion;
2565 } else if (AllowObjCWritebackConversion &&
2566 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2567 SCS.Second = ICK_Writeback_Conversion;
2568 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2569 ConvertedType&: FromType, IncompatibleObjC)) {
2570 // Pointer conversions (C++ 4.10).
2571 SCS.Second = ICK_Pointer_Conversion;
2572 SCS.IncompatibleObjC = IncompatibleObjC;
2573 FromType = FromType.getUnqualifiedType();
2574 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2575 InOverloadResolution, ConvertedType&: FromType)) {
2576 // Pointer to member conversions (4.11).
2577 SCS.Second = ICK_Pointer_Member;
2578 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2579 From, InOverloadResolution, CStyle)) {
2580 SCS.Second = SecondICK;
2581 SCS.Dimension = DimensionICK;
2582 FromType = ToType.getUnqualifiedType();
2583 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2584 From, InOverloadResolution, CStyle)) {
2585 SCS.Second = SecondICK;
2586 SCS.Dimension = DimensionICK;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (!S.getLangOpts().CPlusPlus &&
2589 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2590 // Compatible conversions (Clang extension for C function overloading)
2591 SCS.Second = ICK_Compatible_Conversion;
2592 FromType = ToType.getUnqualifiedType();
2593 } else if (IsTransparentUnionStandardConversion(
2594 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2595 SCS.Second = ICK_TransparentUnionConversion;
2596 FromType = ToType;
2597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2598 CStyle)) {
2599 // tryAtomicConversion has updated the standard conversion sequence
2600 // appropriately.
2601 return true;
2602 } else if (tryOverflowBehaviorTypeConversion(
2603 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2604 return true;
2605 } else if (ToType->isEventT() &&
2606 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2607 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2608 SCS.Second = ICK_Zero_Event_Conversion;
2609 FromType = ToType;
2610 } else if (ToType->isQueueT() &&
2611 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2612 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2613 SCS.Second = ICK_Zero_Queue_Conversion;
2614 FromType = ToType;
2615 } else if (ToType->isSamplerT() &&
2616 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2617 SCS.Second = ICK_Compatible_Conversion;
2618 FromType = ToType;
2619 } else if ((ToType->isFixedPointType() &&
2620 FromType->isConvertibleToFixedPointType()) ||
2621 (FromType->isFixedPointType() &&
2622 ToType->isConvertibleToFixedPointType())) {
2623 SCS.Second = ICK_Fixed_Point_Conversion;
2624 FromType = ToType;
2625 } else {
2626 // No second conversion required.
2627 SCS.Second = ICK_Identity;
2628 }
2629 SCS.setToType(Idx: 1, T: FromType);
2630
2631 // The third conversion can be a function pointer conversion or a
2632 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2633 bool ObjCLifetimeConversion;
2634 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2635 // Function pointer conversions (removing 'noexcept') including removal of
2636 // 'noreturn' (Clang extension).
2637 SCS.Third = ICK_Function_Conversion;
2638 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2639 ObjCLifetimeConversion)) {
2640 SCS.Third = ICK_Qualification;
2641 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2642 FromType = ToType;
2643 } else {
2644 // No conversion required
2645 SCS.Third = ICK_Identity;
2646 }
2647
2648 // C++ [over.best.ics]p6:
2649 // [...] Any difference in top-level cv-qualification is
2650 // subsumed by the initialization itself and does not constitute
2651 // a conversion. [...]
2652 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2653 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2654 if (CanonFrom.getLocalUnqualifiedType()
2655 == CanonTo.getLocalUnqualifiedType() &&
2656 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2657 FromType = ToType;
2658 CanonFrom = CanonTo;
2659 }
2660
2661 SCS.setToType(Idx: 2, T: FromType);
2662
2663 if (CanonFrom == CanonTo)
2664 return true;
2665
2666 // If we have not converted the argument type to the parameter type,
2667 // this is a bad conversion sequence, unless we're resolving an overload in C.
2668 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2669 return false;
2670
2671 ExprResult ER = ExprResult{From};
2672 AssignConvertType Conv =
2673 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2674 /*Diagnose=*/false,
2675 /*DiagnoseCFAudited=*/false,
2676 /*ConvertRHS=*/false);
2677 ImplicitConversionKind SecondConv;
2678 switch (Conv) {
2679 case AssignConvertType::Compatible:
2680 case AssignConvertType::
2681 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2682 SecondConv = ICK_C_Only_Conversion;
2683 break;
2684 // For our purposes, discarding qualifiers is just as bad as using an
2685 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2686 // qualifiers, as well.
2687 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2688 case AssignConvertType::IncompatiblePointer:
2689 case AssignConvertType::IncompatiblePointerSign:
2690 SecondConv = ICK_Incompatible_Pointer_Conversion;
2691 break;
2692 default:
2693 return false;
2694 }
2695
2696 // First can only be an lvalue conversion, so we pretend that this was the
2697 // second conversion. First should already be valid from earlier in the
2698 // function.
2699 SCS.Second = SecondConv;
2700 SCS.setToType(Idx: 1, T: ToType);
2701
2702 // Third is Identity, because Second should rank us worse than any other
2703 // conversion. This could also be ICK_Qualification, but it's simpler to just
2704 // lump everything in with the second conversion, and we don't gain anything
2705 // from making this ICK_Qualification.
2706 SCS.Third = ICK_Identity;
2707 SCS.setToType(Idx: 2, T: ToType);
2708 return true;
2709}
2710
2711static bool
2712IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2713 QualType &ToType,
2714 bool InOverloadResolution,
2715 StandardConversionSequence &SCS,
2716 bool CStyle) {
2717
2718 const RecordType *UT = ToType->getAsUnionType();
2719 if (!UT)
2720 return false;
2721 // The field to initialize within the transparent union.
2722 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2723 if (!UD->hasAttr<TransparentUnionAttr>())
2724 return false;
2725 // It's compatible if the expression matches any of the fields.
2726 for (const auto *it : UD->fields()) {
2727 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2728 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2729 ToType = it->getType();
2730 return true;
2731 }
2732 }
2733 return false;
2734}
2735
2736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2737 const BuiltinType *To = ToType->getAs<BuiltinType>();
2738 // All integers are built-in.
2739 if (!To) {
2740 return false;
2741 }
2742
2743 // An rvalue of type char, signed char, unsigned char, short int, or
2744 // unsigned short int can be converted to an rvalue of type int if
2745 // int can represent all the values of the source type; otherwise,
2746 // the source rvalue can be converted to an rvalue of type unsigned
2747 // int (C++ 4.5p1).
2748 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2749 !FromType->isEnumeralType()) {
2750 if ( // We can promote any signed, promotable integer type to an int
2751 (FromType->isSignedIntegerType() ||
2752 // We can promote any unsigned integer type whose size is
2753 // less than int to an int.
2754 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2755 return To->getKind() == BuiltinType::Int;
2756 }
2757
2758 return To->getKind() == BuiltinType::UInt;
2759 }
2760
2761 // C++11 [conv.prom]p3:
2762 // A prvalue of an unscoped enumeration type whose underlying type is not
2763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2764 // following types that can represent all the values of the enumeration
2765 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2766 // unsigned int, long int, unsigned long int, long long int, or unsigned
2767 // long long int. If none of the types in that list can represent all the
2768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2769 // type can be converted to an rvalue a prvalue of the extended integer type
2770 // with lowest integer conversion rank (4.13) greater than the rank of long
2771 // long in which all the values of the enumeration can be represented. If
2772 // there are two such extended types, the signed one is chosen.
2773 // C++11 [conv.prom]p4:
2774 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2775 // can be converted to a prvalue of its underlying type. Moreover, if
2776 // integral promotion can be applied to its underlying type, a prvalue of an
2777 // unscoped enumeration type whose underlying type is fixed can also be
2778 // converted to a prvalue of the promoted underlying type.
2779 if (const auto *FromED = FromType->getAsEnumDecl()) {
2780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2781 // provided for a scoped enumeration.
2782 if (FromED->isScoped())
2783 return false;
2784
2785 // We can perform an integral promotion to the underlying type of the enum,
2786 // even if that's not the promoted type. Note that the check for promoting
2787 // the underlying type is based on the type alone, and does not consider
2788 // the bitfield-ness of the actual source expression.
2789 if (FromED->isFixed()) {
2790 QualType Underlying = FromED->getIntegerType();
2791 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2792 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2793 }
2794
2795 // We have already pre-calculated the promotion type, so this is trivial.
2796 if (ToType->isIntegerType() &&
2797 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2798 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2799
2800 // C++ [conv.prom]p5:
2801 // If the bit-field has an enumerated type, it is treated as any other
2802 // value of that type for promotion purposes.
2803 //
2804 // ... so do not fall through into the bit-field checks below in C++.
2805 if (getLangOpts().CPlusPlus)
2806 return false;
2807 }
2808
2809 // C++0x [conv.prom]p2:
2810 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2811 // to an rvalue a prvalue of the first of the following types that can
2812 // represent all the values of its underlying type: int, unsigned int,
2813 // long int, unsigned long int, long long int, or unsigned long long int.
2814 // If none of the types in that list can represent all the values of its
2815 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2816 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2817 // type.
2818 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2819 ToType->isIntegerType()) {
2820 // Determine whether the type we're converting from is signed or
2821 // unsigned.
2822 bool FromIsSigned = FromType->isSignedIntegerType();
2823 uint64_t FromSize = Context.getTypeSize(T: FromType);
2824
2825 // The types we'll try to promote to, in the appropriate
2826 // order. Try each of these types.
2827 QualType PromoteTypes[6] = {
2828 Context.IntTy, Context.UnsignedIntTy,
2829 Context.LongTy, Context.UnsignedLongTy ,
2830 Context.LongLongTy, Context.UnsignedLongLongTy
2831 };
2832 for (int Idx = 0; Idx < 6; ++Idx) {
2833 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2834 if (FromSize < ToSize ||
2835 (FromSize == ToSize &&
2836 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2837 // We found the type that we can promote to. If this is the
2838 // type we wanted, we have a promotion. Otherwise, no
2839 // promotion.
2840 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2841 }
2842 }
2843 }
2844
2845 // An rvalue for an integral bit-field (9.6) can be converted to an
2846 // rvalue of type int if int can represent all the values of the
2847 // bit-field; otherwise, it can be converted to unsigned int if
2848 // unsigned int can represent all the values of the bit-field. If
2849 // the bit-field is larger yet, no integral promotion applies to
2850 // it. If the bit-field has an enumerated type, it is treated as any
2851 // other value of that type for promotion purposes (C++ 4.5p3).
2852 // FIXME: We should delay checking of bit-fields until we actually perform the
2853 // conversion.
2854 //
2855 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2856 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2857 // bit-fields and those whose underlying type is larger than int) for GCC
2858 // compatibility.
2859 if (From) {
2860 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2861 std::optional<llvm::APSInt> BitWidth;
2862 if (FromType->isIntegralType(Ctx: Context) &&
2863 (BitWidth =
2864 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2865 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2866 ToSize = Context.getTypeSize(T: ToType);
2867
2868 // Are we promoting to an int from a bitfield that fits in an int?
2869 if (*BitWidth < ToSize ||
2870 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2871 return To->getKind() == BuiltinType::Int;
2872 }
2873
2874 // Are we promoting to an unsigned int from an unsigned bitfield
2875 // that fits into an unsigned int?
2876 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2877 return To->getKind() == BuiltinType::UInt;
2878 }
2879
2880 return false;
2881 }
2882 }
2883 }
2884
2885 // An rvalue of type bool can be converted to an rvalue of type int,
2886 // with false becoming zero and true becoming one (C++ 4.5p4).
2887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2888 return true;
2889 }
2890
2891 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2892 // integral type.
2893 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2894 ToType->isIntegerType())
2895 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2896
2897 return false;
2898}
2899
2900bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2901 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2902 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2903 /// An rvalue of type float can be converted to an rvalue of type
2904 /// double. (C++ 4.6p1).
2905 if (FromBuiltin->getKind() == BuiltinType::Float &&
2906 ToBuiltin->getKind() == BuiltinType::Double)
2907 return true;
2908
2909 // C99 6.3.1.5p1:
2910 // When a float is promoted to double or long double, or a
2911 // double is promoted to long double [...].
2912 if (!getLangOpts().CPlusPlus &&
2913 (FromBuiltin->getKind() == BuiltinType::Float ||
2914 FromBuiltin->getKind() == BuiltinType::Double) &&
2915 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2916 ToBuiltin->getKind() == BuiltinType::Float128 ||
2917 ToBuiltin->getKind() == BuiltinType::Ibm128))
2918 return true;
2919
2920 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2921 // or not native half types are enabled.
2922 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2923 (ToBuiltin->getKind() == BuiltinType::Float ||
2924 ToBuiltin->getKind() == BuiltinType::Double))
2925 return true;
2926
2927 // Half can be promoted to float.
2928 if (!getLangOpts().NativeHalfType &&
2929 FromBuiltin->getKind() == BuiltinType::Half &&
2930 ToBuiltin->getKind() == BuiltinType::Float)
2931 return true;
2932 }
2933
2934 return false;
2935}
2936
2937bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2938 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2939 if (!FromComplex)
2940 return false;
2941
2942 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2943 if (!ToComplex)
2944 return false;
2945
2946 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2947 ToType: ToComplex->getElementType()) ||
2948 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2949 ToType: ToComplex->getElementType());
2950}
2951
2952bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
2953 if (!getLangOpts().OverflowBehaviorTypes)
2954 return false;
2955
2956 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2957 return false;
2958
2959 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2960}
2961
2962bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
2963 QualType ToType) {
2964 if (!getLangOpts().OverflowBehaviorTypes)
2965 return false;
2966
2967 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2968 if (ToType->isBooleanType())
2969 return false;
2970 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2971 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2972 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2973 if (ToED->isScoped())
2974 return false;
2975 }
2976 return true;
2977 }
2978
2979 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2980 return true;
2981
2982 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2983 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
2984
2985 return false;
2986}
2987
2988/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2989/// the pointer type FromPtr to a pointer to type ToPointee, with the
2990/// same type qualifiers as FromPtr has on its pointee type. ToType,
2991/// if non-empty, will be a pointer to ToType that may or may not have
2992/// the right set of qualifiers on its pointee.
2993///
2994static QualType
2995BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2996 QualType ToPointee, QualType ToType,
2997 ASTContext &Context,
2998 bool StripObjCLifetime = false) {
2999 assert((FromPtr->getTypeClass() == Type::Pointer ||
3000 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3001 "Invalid similarly-qualified pointer type");
3002
3003 /// Conversions to 'id' subsume cv-qualifier conversions.
3004 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3005 return ToType.getUnqualifiedType();
3006
3007 QualType CanonFromPointee
3008 = Context.getCanonicalType(T: FromPtr->getPointeeType());
3009 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
3010 Qualifiers Quals = CanonFromPointee.getQualifiers();
3011
3012 if (StripObjCLifetime)
3013 Quals.removeObjCLifetime();
3014
3015 // Exact qualifier match -> return the pointer type we're converting to.
3016 if (CanonToPointee.getLocalQualifiers() == Quals) {
3017 // ToType is exactly what we need. Return it.
3018 if (!ToType.isNull())
3019 return ToType.getUnqualifiedType();
3020
3021 // Build a pointer to ToPointee. It has the right qualifiers
3022 // already.
3023 if (isa<ObjCObjectPointerType>(Val: ToType))
3024 return Context.getObjCObjectPointerType(OIT: ToPointee);
3025 return Context.getPointerType(T: ToPointee);
3026 }
3027
3028 // Just build a canonical type that has the right qualifiers.
3029 QualType QualifiedCanonToPointee
3030 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3031
3032 if (isa<ObjCObjectPointerType>(Val: ToType))
3033 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3034 return Context.getPointerType(T: QualifiedCanonToPointee);
3035}
3036
3037static bool isNullPointerConstantForConversion(Expr *Expr,
3038 bool InOverloadResolution,
3039 ASTContext &Context) {
3040 // Handle value-dependent integral null pointer constants correctly.
3041 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3042 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3043 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3044 return !InOverloadResolution;
3045
3046 return Expr->isNullPointerConstant(Ctx&: Context,
3047 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3048 : Expr::NPC_ValueDependentIsNull);
3049}
3050
3051bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3052 bool InOverloadResolution,
3053 QualType& ConvertedType,
3054 bool &IncompatibleObjC) {
3055 IncompatibleObjC = false;
3056 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3057 IncompatibleObjC))
3058 return true;
3059
3060 // Conversion from a null pointer constant to any Objective-C pointer type.
3061 if (ToType->isObjCObjectPointerType() &&
3062 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3063 ConvertedType = ToType;
3064 return true;
3065 }
3066
3067 // Blocks: Block pointers can be converted to void*.
3068 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3069 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073 // Blocks: A null pointer constant can be converted to a block
3074 // pointer type.
3075 if (ToType->isBlockPointerType() &&
3076 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3077 ConvertedType = ToType;
3078 return true;
3079 }
3080
3081 // If the left-hand-side is nullptr_t, the right side can be a null
3082 // pointer constant.
3083 if (ToType->isNullPtrType() &&
3084 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3085 ConvertedType = ToType;
3086 return true;
3087 }
3088
3089 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3090 if (!ToTypePtr)
3091 return false;
3092
3093 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3094 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3095 ConvertedType = ToType;
3096 return true;
3097 }
3098
3099 // Beyond this point, both types need to be pointers
3100 // , including objective-c pointers.
3101 QualType ToPointeeType = ToTypePtr->getPointeeType();
3102 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3103 !getLangOpts().ObjCAutoRefCount) {
3104 ConvertedType = BuildSimilarlyQualifiedPointerType(
3105 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3106 Context);
3107 return true;
3108 }
3109 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3110 if (!FromTypePtr)
3111 return false;
3112
3113 QualType FromPointeeType = FromTypePtr->getPointeeType();
3114
3115 // If the unqualified pointee types are the same, this can't be a
3116 // pointer conversion, so don't do all of the work below.
3117 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3118 return false;
3119
3120 // An rvalue of type "pointer to cv T," where T is an object type,
3121 // can be converted to an rvalue of type "pointer to cv void" (C++
3122 // 4.10p2).
3123 if (FromPointeeType->isIncompleteOrObjectType() &&
3124 ToPointeeType->isVoidType()) {
3125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3126 ToPointee: ToPointeeType,
3127 ToType, Context,
3128 /*StripObjCLifetime=*/true);
3129 return true;
3130 }
3131
3132 // MSVC allows implicit function to void* type conversion.
3133 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3134 ToPointeeType->isVoidType()) {
3135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3136 ToPointee: ToPointeeType,
3137 ToType, Context);
3138 return true;
3139 }
3140
3141 // When we're overloading in C, we allow a special kind of pointer
3142 // conversion for compatible-but-not-identical pointee types.
3143 if (!getLangOpts().CPlusPlus &&
3144 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3146 ToPointee: ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 // C++ [conv.ptr]p3:
3152 //
3153 // An rvalue of type "pointer to cv D," where D is a class type,
3154 // can be converted to an rvalue of type "pointer to cv B," where
3155 // B is a base class (clause 10) of D. If B is an inaccessible
3156 // (clause 11) or ambiguous (10.2) base class of D, a program that
3157 // necessitates this conversion is ill-formed. The result of the
3158 // conversion is a pointer to the base class sub-object of the
3159 // derived class object. The null pointer value is converted to
3160 // the null pointer value of the destination type.
3161 //
3162 // Note that we do not check for ambiguity or inaccessibility
3163 // here. That is handled by CheckPointerConversion.
3164 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3165 ToPointeeType->isRecordType() &&
3166 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3167 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3169 ToPointee: ToPointeeType,
3170 ToType, Context);
3171 return true;
3172 }
3173
3174 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3175 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3176 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3177 ToPointee: ToPointeeType,
3178 ToType, Context);
3179 return true;
3180 }
3181
3182 return false;
3183}
3184
3185/// Adopt the given qualifiers for the given type.
3186static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3187 Qualifiers TQs = T.getQualifiers();
3188
3189 // Check whether qualifiers already match.
3190 if (TQs == Qs)
3191 return T;
3192
3193 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3194 return Context.getQualifiedType(T, Qs);
3195
3196 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3197}
3198
3199bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3200 QualType& ConvertedType,
3201 bool &IncompatibleObjC) {
3202 if (!getLangOpts().ObjC)
3203 return false;
3204
3205 // The set of qualifiers on the type we're converting from.
3206 Qualifiers FromQualifiers = FromType.getQualifiers();
3207
3208 // First, we handle all conversions on ObjC object pointer types.
3209 const ObjCObjectPointerType* ToObjCPtr =
3210 ToType->getAs<ObjCObjectPointerType>();
3211 const ObjCObjectPointerType *FromObjCPtr =
3212 FromType->getAs<ObjCObjectPointerType>();
3213
3214 if (ToObjCPtr && FromObjCPtr) {
3215 // If the pointee types are the same (ignoring qualifications),
3216 // then this is not a pointer conversion.
3217 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3218 T2: FromObjCPtr->getPointeeType()))
3219 return false;
3220
3221 // Conversion between Objective-C pointers.
3222 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3223 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3224 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3225 if (getLangOpts().CPlusPlus && LHS && RHS &&
3226 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3227 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3228 return false;
3229 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3230 ToPointee: ToObjCPtr->getPointeeType(),
3231 ToType, Context);
3232 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3233 return true;
3234 }
3235
3236 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3237 // Okay: this is some kind of implicit downcast of Objective-C
3238 // interfaces, which is permitted. However, we're going to
3239 // complain about it.
3240 IncompatibleObjC = true;
3241 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3242 ToPointee: ToObjCPtr->getPointeeType(),
3243 ToType, Context);
3244 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3245 return true;
3246 }
3247 }
3248 // Beyond this point, both types need to be C pointers or block pointers.
3249 QualType ToPointeeType;
3250 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3251 ToPointeeType = ToCPtr->getPointeeType();
3252 else if (const BlockPointerType *ToBlockPtr =
3253 ToType->getAs<BlockPointerType>()) {
3254 // Objective C++: We're able to convert from a pointer to any object
3255 // to a block pointer type.
3256 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3257 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3258 return true;
3259 }
3260 ToPointeeType = ToBlockPtr->getPointeeType();
3261 }
3262 else if (FromType->getAs<BlockPointerType>() &&
3263 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3264 // Objective C++: We're able to convert from a block pointer type to a
3265 // pointer to any object.
3266 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3267 return true;
3268 }
3269 else
3270 return false;
3271
3272 QualType FromPointeeType;
3273 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3274 FromPointeeType = FromCPtr->getPointeeType();
3275 else if (const BlockPointerType *FromBlockPtr =
3276 FromType->getAs<BlockPointerType>())
3277 FromPointeeType = FromBlockPtr->getPointeeType();
3278 else
3279 return false;
3280
3281 // If we have pointers to pointers, recursively check whether this
3282 // is an Objective-C conversion.
3283 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3284 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3285 IncompatibleObjC)) {
3286 // We always complain about this conversion.
3287 IncompatibleObjC = true;
3288 ConvertedType = Context.getPointerType(T: ConvertedType);
3289 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3290 return true;
3291 }
3292 // Allow conversion of pointee being objective-c pointer to another one;
3293 // as in I* to id.
3294 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3295 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3296 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3297 IncompatibleObjC)) {
3298
3299 ConvertedType = Context.getPointerType(T: ConvertedType);
3300 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3301 return true;
3302 }
3303
3304 // If we have pointers to functions or blocks, check whether the only
3305 // differences in the argument and result types are in Objective-C
3306 // pointer conversions. If so, we permit the conversion (but
3307 // complain about it).
3308 const FunctionProtoType *FromFunctionType
3309 = FromPointeeType->getAs<FunctionProtoType>();
3310 const FunctionProtoType *ToFunctionType
3311 = ToPointeeType->getAs<FunctionProtoType>();
3312 if (FromFunctionType && ToFunctionType) {
3313 // If the function types are exactly the same, this isn't an
3314 // Objective-C pointer conversion.
3315 if (Context.getCanonicalType(T: FromPointeeType)
3316 == Context.getCanonicalType(T: ToPointeeType))
3317 return false;
3318
3319 // Perform the quick checks that will tell us whether these
3320 // function types are obviously different.
3321 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3322 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3323 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3324 return false;
3325
3326 bool HasObjCConversion = false;
3327 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3328 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3329 // Okay, the types match exactly. Nothing to do.
3330 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3331 ToType: ToFunctionType->getReturnType(),
3332 ConvertedType, IncompatibleObjC)) {
3333 // Okay, we have an Objective-C pointer conversion.
3334 HasObjCConversion = true;
3335 } else {
3336 // Function types are too different. Abort.
3337 return false;
3338 }
3339
3340 // Check argument types.
3341 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3342 ArgIdx != NumArgs; ++ArgIdx) {
3343 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3344 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3345 if (Context.getCanonicalType(T: FromArgType)
3346 == Context.getCanonicalType(T: ToArgType)) {
3347 // Okay, the types match exactly. Nothing to do.
3348 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3349 ConvertedType, IncompatibleObjC)) {
3350 // Okay, we have an Objective-C pointer conversion.
3351 HasObjCConversion = true;
3352 } else {
3353 // Argument types are too different. Abort.
3354 return false;
3355 }
3356 }
3357
3358 if (HasObjCConversion) {
3359 // We had an Objective-C conversion. Allow this pointer
3360 // conversion, but complain about it.
3361 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3362 IncompatibleObjC = true;
3363 return true;
3364 }
3365 }
3366
3367 return false;
3368}
3369
3370bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3371 QualType& ConvertedType) {
3372 QualType ToPointeeType;
3373 if (const BlockPointerType *ToBlockPtr =
3374 ToType->getAs<BlockPointerType>())
3375 ToPointeeType = ToBlockPtr->getPointeeType();
3376 else
3377 return false;
3378
3379 QualType FromPointeeType;
3380 if (const BlockPointerType *FromBlockPtr =
3381 FromType->getAs<BlockPointerType>())
3382 FromPointeeType = FromBlockPtr->getPointeeType();
3383 else
3384 return false;
3385 // We have pointer to blocks, check whether the only
3386 // differences in the argument and result types are in Objective-C
3387 // pointer conversions. If so, we permit the conversion.
3388
3389 const FunctionProtoType *FromFunctionType
3390 = FromPointeeType->getAs<FunctionProtoType>();
3391 const FunctionProtoType *ToFunctionType
3392 = ToPointeeType->getAs<FunctionProtoType>();
3393
3394 if (!FromFunctionType || !ToFunctionType)
3395 return false;
3396
3397 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3398 return true;
3399
3400 // Perform the quick checks that will tell us whether these
3401 // function types are obviously different.
3402 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3403 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3404 return false;
3405
3406 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3407 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3408 if (FromEInfo != ToEInfo)
3409 return false;
3410
3411 bool IncompatibleObjC = false;
3412 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3413 T2: ToFunctionType->getReturnType())) {
3414 // Okay, the types match exactly. Nothing to do.
3415 } else {
3416 QualType RHS = FromFunctionType->getReturnType();
3417 QualType LHS = ToFunctionType->getReturnType();
3418 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3419 !RHS.hasQualifiers() && LHS.hasQualifiers())
3420 LHS = LHS.getUnqualifiedType();
3421
3422 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3423 // OK exact match.
3424 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3425 ConvertedType, IncompatibleObjC)) {
3426 if (IncompatibleObjC)
3427 return false;
3428 // Okay, we have an Objective-C pointer conversion.
3429 }
3430 else
3431 return false;
3432 }
3433
3434 // Check argument types.
3435 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3436 ArgIdx != NumArgs; ++ArgIdx) {
3437 IncompatibleObjC = false;
3438 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3439 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3440 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3441 // Okay, the types match exactly. Nothing to do.
3442 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3443 ConvertedType, IncompatibleObjC)) {
3444 if (IncompatibleObjC)
3445 return false;
3446 // Okay, we have an Objective-C pointer conversion.
3447 } else
3448 // Argument types are too different. Abort.
3449 return false;
3450 }
3451
3452 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3453 bool CanUseToFPT, CanUseFromFPT;
3454 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3455 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3456 NewParamInfos))
3457 return false;
3458
3459 ConvertedType = ToType;
3460 return true;
3461}
3462
3463enum {
3464 ft_default,
3465 ft_different_class,
3466 ft_parameter_arity,
3467 ft_parameter_mismatch,
3468 ft_return_type,
3469 ft_qualifer_mismatch,
3470 ft_noexcept
3471};
3472
3473/// Attempts to get the FunctionProtoType from a Type. Handles
3474/// MemberFunctionPointers properly.
3475static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3476 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3477 return FPT;
3478
3479 if (auto *MPT = FromType->getAs<MemberPointerType>())
3480 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3481
3482 return nullptr;
3483}
3484
3485void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3486 QualType FromType, QualType ToType) {
3487 // If either type is not valid, include no extra info.
3488 if (FromType.isNull() || ToType.isNull()) {
3489 PDiag << ft_default;
3490 return;
3491 }
3492
3493 // Get the function type from the pointers.
3494 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3495 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3496 *ToMember = ToType->castAs<MemberPointerType>();
3497 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3498 D2: ToMember->getMostRecentCXXRecordDecl())) {
3499 PDiag << ft_different_class;
3500 if (ToMember->isSugared())
3501 PDiag << Context.getCanonicalTagType(
3502 TD: ToMember->getMostRecentCXXRecordDecl());
3503 else
3504 PDiag << ToMember->getQualifier();
3505 if (FromMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 TD: FromMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << FromMember->getQualifier();
3510 return;
3511 }
3512 FromType = FromMember->getPointeeType();
3513 ToType = ToMember->getPointeeType();
3514 }
3515
3516 if (FromType->isPointerType())
3517 FromType = FromType->getPointeeType();
3518 if (ToType->isPointerType())
3519 ToType = ToType->getPointeeType();
3520
3521 // Remove references.
3522 FromType = FromType.getNonReferenceType();
3523 ToType = ToType.getNonReferenceType();
3524
3525 // Don't print extra info for non-specialized template functions.
3526 if (FromType->isInstantiationDependentType() &&
3527 !FromType->getAs<TemplateSpecializationType>()) {
3528 PDiag << ft_default;
3529 return;
3530 }
3531
3532 // No extra info for same types.
3533 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3534 PDiag << ft_default;
3535 return;
3536 }
3537
3538 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3539 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3540
3541 // Both types need to be function types.
3542 if (!FromFunction || !ToFunction) {
3543 PDiag << ft_default;
3544 return;
3545 }
3546
3547 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3548 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3549 << FromFunction->getNumParams();
3550 return;
3551 }
3552
3553 // Handle different parameter types.
3554 unsigned ArgPos;
3555 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3556 PDiag << ft_parameter_mismatch << ArgPos + 1
3557 << ToFunction->getParamType(i: ArgPos)
3558 << FromFunction->getParamType(i: ArgPos);
3559 return;
3560 }
3561
3562 // Handle different return type.
3563 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3564 T2: ToFunction->getReturnType())) {
3565 PDiag << ft_return_type << ToFunction->getReturnType()
3566 << FromFunction->getReturnType();
3567 return;
3568 }
3569
3570 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3571 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3572 << FromFunction->getMethodQuals();
3573 return;
3574 }
3575
3576 // Handle exception specification differences on canonical type (in C++17
3577 // onwards).
3578 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3579 ->isNothrow() !=
3580 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3581 ->isNothrow()) {
3582 PDiag << ft_noexcept;
3583 return;
3584 }
3585
3586 // Unable to find a difference, so add no extra info.
3587 PDiag << ft_default;
3588}
3589
3590bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3591 ArrayRef<QualType> New, unsigned *ArgPos,
3592 bool Reversed) {
3593 assert(llvm::size(Old) == llvm::size(New) &&
3594 "Can't compare parameters of functions with different number of "
3595 "parameters!");
3596
3597 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3598 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3599 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3600
3601 // Ignore address spaces in pointee type. This is to disallow overloading
3602 // on __ptr32/__ptr64 address spaces.
3603 QualType OldType =
3604 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3605 QualType NewType =
3606 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3607
3608 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3609 if (ArgPos)
3610 *ArgPos = Idx;
3611 return false;
3612 }
3613 }
3614 return true;
3615}
3616
3617bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3618 const FunctionProtoType *NewType,
3619 unsigned *ArgPos, bool Reversed) {
3620 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3621 New: NewType->param_types(), ArgPos, Reversed);
3622}
3623
3624bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3625 const FunctionDecl *NewFunction,
3626 unsigned *ArgPos,
3627 bool Reversed) {
3628
3629 if (OldFunction->getNumNonObjectParams() !=
3630 NewFunction->getNumNonObjectParams())
3631 return false;
3632
3633 unsigned OldIgnore =
3634 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3635 unsigned NewIgnore =
3636 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3637
3638 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3639 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3640
3641 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3642 New: NewPT->param_types().slice(N: NewIgnore),
3643 ArgPos, Reversed);
3644}
3645
3646bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3647 CastKind &Kind,
3648 CXXCastPath& BasePath,
3649 bool IgnoreBaseAccess,
3650 bool Diagnose) {
3651 QualType FromType = From->getType();
3652 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3653
3654 Kind = CK_BitCast;
3655
3656 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3657 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3658 Expr::NPCK_ZeroExpression) {
3659 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3660 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3661 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3662 << ToType << From->getSourceRange());
3663 else if (!isUnevaluatedContext())
3664 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3665 << ToType << From->getSourceRange();
3666 }
3667 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3668 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3669 QualType FromPointeeType = FromPtrType->getPointeeType(),
3670 ToPointeeType = ToPtrType->getPointeeType();
3671
3672 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3673 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3674 // We must have a derived-to-base conversion. Check an
3675 // ambiguous or inaccessible conversion.
3676 unsigned InaccessibleID = 0;
3677 unsigned AmbiguousID = 0;
3678 if (Diagnose) {
3679 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3680 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3681 }
3682 if (CheckDerivedToBaseConversion(
3683 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3684 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3685 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3686 return true;
3687
3688 // The conversion was successful.
3689 Kind = CK_DerivedToBase;
3690 }
3691
3692 if (Diagnose && !IsCStyleOrFunctionalCast &&
3693 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3694 assert(getLangOpts().MSVCCompat &&
3695 "this should only be possible with MSVCCompat!");
3696 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3697 << From->getSourceRange();
3698 }
3699 }
3700 } else if (const ObjCObjectPointerType *ToPtrType =
3701 ToType->getAs<ObjCObjectPointerType>()) {
3702 if (const ObjCObjectPointerType *FromPtrType =
3703 FromType->getAs<ObjCObjectPointerType>()) {
3704 // Objective-C++ conversions are always okay.
3705 // FIXME: We should have a different class of conversions for the
3706 // Objective-C++ implicit conversions.
3707 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3708 return false;
3709 } else if (FromType->isBlockPointerType()) {
3710 Kind = CK_BlockPointerToObjCPointerCast;
3711 } else {
3712 Kind = CK_CPointerToObjCPointerCast;
3713 }
3714 } else if (ToType->isBlockPointerType()) {
3715 if (!FromType->isBlockPointerType())
3716 Kind = CK_AnyPointerToBlockPointerCast;
3717 }
3718
3719 // We shouldn't fall into this case unless it's valid for other
3720 // reasons.
3721 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3722 Kind = CK_NullToPointer;
3723
3724 return false;
3725}
3726
3727bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3728 QualType ToType,
3729 bool InOverloadResolution,
3730 QualType &ConvertedType) {
3731 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3732 if (!ToTypePtr)
3733 return false;
3734
3735 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3736 if (From->isNullPointerConstant(Ctx&: Context,
3737 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3738 : Expr::NPC_ValueDependentIsNull)) {
3739 ConvertedType = ToType;
3740 return true;
3741 }
3742
3743 // Otherwise, both types have to be member pointers.
3744 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3745 if (!FromTypePtr)
3746 return false;
3747
3748 // A pointer to member of B can be converted to a pointer to member of D,
3749 // where D is derived from B (C++ 4.11p2).
3750 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3751 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3752
3753 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3754 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3755 ConvertedType = Context.getMemberPointerType(
3756 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3757 return true;
3758 }
3759
3760 return false;
3761}
3762
3763Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3764 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3765 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3766 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3767 // Lock down the inheritance model right now in MS ABI, whether or not the
3768 // pointee types are the same.
3769 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3770 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3771 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3772 }
3773
3774 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3775 if (!FromPtrType) {
3776 // This must be a null pointer to member pointer conversion
3777 Kind = CK_NullToMemberPointer;
3778 return MemberPointerConversionResult::Success;
3779 }
3780
3781 // T == T, modulo cv
3782 if (Direction == MemberPointerConversionDirection::Upcast &&
3783 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3784 T2: ToPtrType->getPointeeType()))
3785 return MemberPointerConversionResult::DifferentPointee;
3786
3787 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3788 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3789
3790 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3791 const CXXRecordDecl *Cls) {
3792 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3793 PD << Qual;
3794 else
3795 PD << Context.getCanonicalTagType(TD: Cls);
3796 };
3797 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3798 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3799 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3800 return PD;
3801 };
3802
3803 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3804 if (Direction == MemberPointerConversionDirection::Upcast)
3805 std::swap(a&: Base, b&: Derived);
3806
3807 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3808 /*DetectVirtual=*/true);
3809 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3810 return MemberPointerConversionResult::NotDerived;
3811
3812 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3813 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3814 PD << int(Direction);
3815 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3816 Diag(Loc: CheckLoc, PD);
3817 return MemberPointerConversionResult::Ambiguous;
3818 }
3819
3820 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3821 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3822 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3823 Diag(Loc: CheckLoc, PD);
3824 return MemberPointerConversionResult::Virtual;
3825 }
3826
3827 // Must be a base to derived member conversion.
3828 BuildBasePathArray(Paths, BasePath);
3829 Kind = Direction == MemberPointerConversionDirection::Upcast
3830 ? CK_DerivedToBaseMemberPointer
3831 : CK_BaseToDerivedMemberPointer;
3832
3833 if (!IgnoreBaseAccess)
3834 switch (CheckBaseClassAccess(
3835 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3836 DiagID: Direction == MemberPointerConversionDirection::Upcast
3837 ? diag::err_upcast_to_inaccessible_base
3838 : diag::err_downcast_from_inaccessible_base,
3839 SetupPDiag: [&](PartialDiagnostic &PD) {
3840 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3841 DerivedQual = ToPtrType->getQualifier();
3842 if (Direction == MemberPointerConversionDirection::Upcast)
3843 std::swap(a&: BaseQual, b&: DerivedQual);
3844 DiagCls(PD, DerivedQual, Derived);
3845 DiagCls(PD, BaseQual, Base);
3846 })) {
3847 case Sema::AR_accessible:
3848 case Sema::AR_delayed:
3849 case Sema::AR_dependent:
3850 // Optimistically assume that the delayed and dependent cases
3851 // will work out.
3852 break;
3853
3854 case Sema::AR_inaccessible:
3855 return MemberPointerConversionResult::Inaccessible;
3856 }
3857
3858 return MemberPointerConversionResult::Success;
3859}
3860
3861/// Determine whether the lifetime conversion between the two given
3862/// qualifiers sets is nontrivial.
3863static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3864 Qualifiers ToQuals) {
3865 // Converting anything to const __unsafe_unretained is trivial.
3866 if (ToQuals.hasConst() &&
3867 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3868 return false;
3869
3870 return true;
3871}
3872
3873/// Perform a single iteration of the loop for checking if a qualification
3874/// conversion is valid.
3875///
3876/// Specifically, check whether any change between the qualifiers of \p
3877/// FromType and \p ToType is permissible, given knowledge about whether every
3878/// outer layer is const-qualified.
3879static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3880 bool CStyle, bool IsTopLevel,
3881 bool &PreviousToQualsIncludeConst,
3882 bool &ObjCLifetimeConversion,
3883 const ASTContext &Ctx) {
3884 Qualifiers FromQuals = FromType.getQualifiers();
3885 Qualifiers ToQuals = ToType.getQualifiers();
3886
3887 // Ignore __unaligned qualifier.
3888 FromQuals.removeUnaligned();
3889
3890 // Objective-C ARC:
3891 // Check Objective-C lifetime conversions.
3892 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3893 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3894 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3895 ObjCLifetimeConversion = true;
3896 FromQuals.removeObjCLifetime();
3897 ToQuals.removeObjCLifetime();
3898 } else {
3899 // Qualification conversions cannot cast between different
3900 // Objective-C lifetime qualifiers.
3901 return false;
3902 }
3903 }
3904
3905 // Allow addition/removal of GC attributes but not changing GC attributes.
3906 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3907 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3908 FromQuals.removeObjCGCAttr();
3909 ToQuals.removeObjCGCAttr();
3910 }
3911
3912 // __ptrauth qualifiers must match exactly.
3913 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3914 return false;
3915
3916 // -- for every j > 0, if const is in cv 1,j then const is in cv
3917 // 2,j, and similarly for volatile.
3918 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3919 return false;
3920
3921 // If address spaces mismatch:
3922 // - in top level it is only valid to convert to addr space that is a
3923 // superset in all cases apart from C-style casts where we allow
3924 // conversions between overlapping address spaces.
3925 // - in non-top levels it is not a valid conversion.
3926 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3927 (!IsTopLevel ||
3928 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3929 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3930 return false;
3931
3932 // -- if the cv 1,j and cv 2,j are different, then const is in
3933 // every cv for 0 < k < j.
3934 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3935 !PreviousToQualsIncludeConst)
3936 return false;
3937
3938 // The following wording is from C++20, where the result of the conversion
3939 // is T3, not T2.
3940 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3941 // "array of unknown bound of"
3942 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3943 return false;
3944
3945 // -- if the resulting P3,i is different from P1,i [...], then const is
3946 // added to every cv 3_k for 0 < k < i.
3947 if (!CStyle && FromType->isConstantArrayType() &&
3948 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3949 return false;
3950
3951 // Keep track of whether all prior cv-qualifiers in the "to" type
3952 // include const.
3953 PreviousToQualsIncludeConst =
3954 PreviousToQualsIncludeConst && ToQuals.hasConst();
3955 return true;
3956}
3957
3958bool
3959Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3960 bool CStyle, bool &ObjCLifetimeConversion) {
3961 FromType = Context.getCanonicalType(T: FromType);
3962 ToType = Context.getCanonicalType(T: ToType);
3963 ObjCLifetimeConversion = false;
3964
3965 // If FromType and ToType are the same type, this is not a
3966 // qualification conversion.
3967 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3968 return false;
3969
3970 // (C++ 4.4p4):
3971 // A conversion can add cv-qualifiers at levels other than the first
3972 // in multi-level pointers, subject to the following rules: [...]
3973 bool PreviousToQualsIncludeConst = true;
3974 bool UnwrappedAnyPointer = false;
3975 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3976 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3977 IsTopLevel: !UnwrappedAnyPointer,
3978 PreviousToQualsIncludeConst,
3979 ObjCLifetimeConversion, Ctx: getASTContext()))
3980 return false;
3981 UnwrappedAnyPointer = true;
3982 }
3983
3984 // We are left with FromType and ToType being the pointee types
3985 // after unwrapping the original FromType and ToType the same number
3986 // of times. If we unwrapped any pointers, and if FromType and
3987 // ToType have the same unqualified type (since we checked
3988 // qualifiers above), then this is a qualification conversion.
3989 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3990}
3991
3992/// - Determine whether this is a conversion from a scalar type to an
3993/// atomic type.
3994///
3995/// If successful, updates \c SCS's second and third steps in the conversion
3996/// sequence to finish the conversion.
3997static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3998 bool InOverloadResolution,
3999 StandardConversionSequence &SCS,
4000 bool CStyle) {
4001 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4002 if (!ToAtomic)
4003 return false;
4004
4005 StandardConversionSequence InnerSCS;
4006 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
4007 InOverloadResolution, SCS&: InnerSCS,
4008 CStyle, /*AllowObjCWritebackConversion=*/false))
4009 return false;
4010
4011 SCS.Second = InnerSCS.Second;
4012 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4013 SCS.Third = InnerSCS.Third;
4014 SCS.QualificationIncludesObjCLifetime
4015 = InnerSCS.QualificationIncludesObjCLifetime;
4016 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4017 return true;
4018}
4019
4020static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
4021 QualType ToType,
4022 bool InOverloadResolution,
4023 StandardConversionSequence &SCS,
4024 bool CStyle) {
4025 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4026 if (!ToOBT)
4027 return false;
4028
4029 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4030 QualType FromType = From->getType();
4031 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4032 return false;
4033
4034 StandardConversionSequence InnerSCS;
4035 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4036 InOverloadResolution, SCS&: InnerSCS, CStyle,
4037 /*AllowObjCWritebackConversion=*/false))
4038 return false;
4039
4040 SCS.Second = InnerSCS.Second;
4041 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4042 SCS.Third = InnerSCS.Third;
4043 SCS.QualificationIncludesObjCLifetime =
4044 InnerSCS.QualificationIncludesObjCLifetime;
4045 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4046 return true;
4047}
4048
4049static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4050 CXXConstructorDecl *Constructor,
4051 QualType Type) {
4052 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4053 if (CtorType->getNumParams() > 0) {
4054 QualType FirstArg = CtorType->getParamType(i: 0);
4055 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4056 return true;
4057 }
4058 return false;
4059}
4060
4061static OverloadingResult
4062IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4063 CXXRecordDecl *To,
4064 UserDefinedConversionSequence &User,
4065 OverloadCandidateSet &CandidateSet,
4066 bool AllowExplicit) {
4067 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4068 for (auto *D : S.LookupConstructors(Class: To)) {
4069 auto Info = getConstructorInfo(ND: D);
4070 if (!Info)
4071 continue;
4072
4073 bool Usable = !Info.Constructor->isInvalidDecl() &&
4074 S.isInitListConstructor(Ctor: Info.Constructor);
4075 if (Usable) {
4076 bool SuppressUserConversions = false;
4077 if (Info.ConstructorTmpl)
4078 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4079 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4080 CandidateSet, SuppressUserConversions,
4081 /*PartialOverloading*/ false,
4082 AllowExplicit);
4083 else
4084 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false, AllowExplicit);
4087 }
4088 }
4089
4090 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4091
4092 OverloadCandidateSet::iterator Best;
4093 switch (auto Result =
4094 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4095 case OR_Deleted:
4096 case OR_Success: {
4097 // Record the standard conversion we used and the conversion function.
4098 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4099 QualType ThisType = Constructor->getFunctionObjectParameterType();
4100 // Initializer lists don't have conversions as such.
4101 User.Before.setAsIdentityConversion();
4102 User.HadMultipleCandidates = HadMultipleCandidates;
4103 User.ConversionFunction = Constructor;
4104 User.FoundConversionFunction = Best->FoundDecl;
4105 User.After.setAsIdentityConversion();
4106 User.After.setFromType(ThisType);
4107 User.After.setAllToTypes(ToType);
4108 return Result;
4109 }
4110
4111 case OR_No_Viable_Function:
4112 return OR_No_Viable_Function;
4113 case OR_Ambiguous:
4114 return OR_Ambiguous;
4115 }
4116
4117 llvm_unreachable("Invalid OverloadResult!");
4118}
4119
4120/// Determines whether there is a user-defined conversion sequence
4121/// (C++ [over.ics.user]) that converts expression From to the type
4122/// ToType. If such a conversion exists, User will contain the
4123/// user-defined conversion sequence that performs such a conversion
4124/// and this routine will return true. Otherwise, this routine returns
4125/// false and User is unspecified.
4126///
4127/// \param AllowExplicit true if the conversion should consider C++0x
4128/// "explicit" conversion functions as well as non-explicit conversion
4129/// functions (C++0x [class.conv.fct]p2).
4130///
4131/// \param AllowObjCConversionOnExplicit true if the conversion should
4132/// allow an extra Objective-C pointer conversion on uses of explicit
4133/// constructors. Requires \c AllowExplicit to also be set.
4134static OverloadingResult
4135IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4136 UserDefinedConversionSequence &User,
4137 OverloadCandidateSet &CandidateSet,
4138 AllowedExplicit AllowExplicit,
4139 bool AllowObjCConversionOnExplicit) {
4140 assert(AllowExplicit != AllowedExplicit::None ||
4141 !AllowObjCConversionOnExplicit);
4142 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4143
4144 // Whether we will only visit constructors.
4145 bool ConstructorsOnly = false;
4146
4147 // If the type we are conversion to is a class type, enumerate its
4148 // constructors.
4149 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4150 // C++ [over.match.ctor]p1:
4151 // When objects of class type are direct-initialized (8.5), or
4152 // copy-initialized from an expression of the same or a
4153 // derived class type (8.5), overload resolution selects the
4154 // constructor. [...] For copy-initialization, the candidate
4155 // functions are all the converting constructors (12.3.1) of
4156 // that class. The argument list is the expression-list within
4157 // the parentheses of the initializer.
4158 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4159 (From->getType()->isRecordType() &&
4160 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4161 ConstructorsOnly = true;
4162
4163 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4164 // We're not going to find any constructors.
4165 } else if (auto *ToRecordDecl =
4166 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4167 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4168
4169 Expr **Args = &From;
4170 unsigned NumArgs = 1;
4171 bool ListInitializing = false;
4172 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4173 // But first, see if there is an init-list-constructor that will work.
4174 OverloadingResult Result = IsInitializerListConstructorConversion(
4175 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4176 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4177 if (Result != OR_No_Viable_Function)
4178 return Result;
4179 // Never mind.
4180 CandidateSet.clear(
4181 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4182
4183 // If we're list-initializing, we pass the individual elements as
4184 // arguments, not the entire list.
4185 Args = InitList->getInits();
4186 NumArgs = InitList->getNumInits();
4187 ListInitializing = true;
4188 }
4189
4190 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4191 auto Info = getConstructorInfo(ND: D);
4192 if (!Info)
4193 continue;
4194
4195 bool Usable = !Info.Constructor->isInvalidDecl();
4196 if (!ListInitializing)
4197 Usable = Usable && Info.Constructor->isConvertingConstructor(
4198 /*AllowExplicit*/ true);
4199 if (Usable) {
4200 bool SuppressUserConversions = !ConstructorsOnly;
4201 // C++20 [over.best.ics.general]/4.5:
4202 // if the target is the first parameter of a constructor [of class
4203 // X] and the constructor [...] is a candidate by [...] the second
4204 // phase of [over.match.list] when the initializer list has exactly
4205 // one element that is itself an initializer list, [...] and the
4206 // conversion is to X or reference to cv X, user-defined conversion
4207 // sequences are not considered.
4208 if (SuppressUserConversions && ListInitializing) {
4209 SuppressUserConversions =
4210 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4211 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4212 Type: ToType);
4213 }
4214 if (Info.ConstructorTmpl)
4215 S.AddTemplateOverloadCandidate(
4216 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4217 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4218 CandidateSet, SuppressUserConversions,
4219 /*PartialOverloading*/ false,
4220 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4221 else
4222 // Allow one user-defined conversion when user specifies a
4223 // From->ToType conversion via an static cast (c-style, etc).
4224 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4225 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4226 SuppressUserConversions,
4227 /*PartialOverloading*/ false,
4228 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4229 }
4230 }
4231 }
4232 }
4233
4234 // Enumerate conversion functions, if we're allowed to.
4235 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4236 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4237 // No conversion functions from incomplete types.
4238 } else if (const RecordType *FromRecordType =
4239 From->getType()->getAsCanonical<RecordType>()) {
4240 if (auto *FromRecordDecl =
4241 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4242 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4243 // Add all of the conversion functions as candidates.
4244 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4245 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4246 DeclAccessPair FoundDecl = I.getPair();
4247 NamedDecl *D = FoundDecl.getDecl();
4248 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4249 if (isa<UsingShadowDecl>(Val: D))
4250 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4251
4252 CXXConversionDecl *Conv;
4253 FunctionTemplateDecl *ConvTemplate;
4254 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4255 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4256 else
4257 Conv = cast<CXXConversionDecl>(Val: D);
4258
4259 if (ConvTemplate)
4260 S.AddTemplateConversionCandidate(
4261 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4262 CandidateSet, AllowObjCConversionOnExplicit,
4263 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4264 else
4265 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4266 CandidateSet, AllowObjCConversionOnExplicit,
4267 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4268 }
4269 }
4270 }
4271
4272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4273
4274 OverloadCandidateSet::iterator Best;
4275 switch (auto Result =
4276 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4277 case OR_Success:
4278 case OR_Deleted:
4279 // Record the standard conversion we used and the conversion function.
4280 if (CXXConstructorDecl *Constructor
4281 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4282 // C++ [over.ics.user]p1:
4283 // If the user-defined conversion is specified by a
4284 // constructor (12.3.1), the initial standard conversion
4285 // sequence converts the source type to the type required by
4286 // the argument of the constructor.
4287 //
4288 if (isa<InitListExpr>(Val: From)) {
4289 // Initializer lists don't have conversions as such.
4290 User.Before.setAsIdentityConversion();
4291 User.Before.FromBracedInitList = true;
4292 } else {
4293 if (Best->Conversions[0].isEllipsis())
4294 User.EllipsisConversion = true;
4295 else {
4296 User.Before = Best->Conversions[0].Standard;
4297 User.EllipsisConversion = false;
4298 }
4299 }
4300 User.HadMultipleCandidates = HadMultipleCandidates;
4301 User.ConversionFunction = Constructor;
4302 User.FoundConversionFunction = Best->FoundDecl;
4303 User.After.setAsIdentityConversion();
4304 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4305 User.After.setAllToTypes(ToType);
4306 return Result;
4307 }
4308 if (CXXConversionDecl *Conversion
4309 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4310
4311 assert(Best->HasFinalConversion);
4312
4313 // C++ [over.ics.user]p1:
4314 //
4315 // [...] If the user-defined conversion is specified by a
4316 // conversion function (12.3.2), the initial standard
4317 // conversion sequence converts the source type to the
4318 // implicit object parameter of the conversion function.
4319 User.Before = Best->Conversions[0].Standard;
4320 User.HadMultipleCandidates = HadMultipleCandidates;
4321 User.ConversionFunction = Conversion;
4322 User.FoundConversionFunction = Best->FoundDecl;
4323 User.EllipsisConversion = false;
4324
4325 // C++ [over.ics.user]p2:
4326 // The second standard conversion sequence converts the
4327 // result of the user-defined conversion to the target type
4328 // for the sequence. Since an implicit conversion sequence
4329 // is an initialization, the special rules for
4330 // initialization by user-defined conversion apply when
4331 // selecting the best user-defined conversion for a
4332 // user-defined conversion sequence (see 13.3.3 and
4333 // 13.3.3.1).
4334 User.After = Best->FinalConversion;
4335 return Result;
4336 }
4337 llvm_unreachable("Not a constructor or conversion function?");
4338
4339 case OR_No_Viable_Function:
4340 return OR_No_Viable_Function;
4341
4342 case OR_Ambiguous:
4343 return OR_Ambiguous;
4344 }
4345
4346 llvm_unreachable("Invalid OverloadResult!");
4347}
4348
4349bool
4350Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4351 ImplicitConversionSequence ICS;
4352 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4353 OverloadCandidateSet::CSK_Normal);
4354 OverloadingResult OvResult =
4355 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4356 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4357
4358 if (!(OvResult == OR_Ambiguous ||
4359 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4360 return false;
4361
4362 auto Cands = CandidateSet.CompleteCandidates(
4363 S&: *this,
4364 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4365 Args: From);
4366 if (OvResult == OR_Ambiguous)
4367 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4368 << From->getType() << ToType << From->getSourceRange();
4369 else { // OR_No_Viable_Function && !CandidateSet.empty()
4370 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4371 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4372 Args: From->getType(), Args: From->getSourceRange()))
4373 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4374 << false << From->getType() << From->getSourceRange() << ToType;
4375 }
4376
4377 CandidateSet.NoteCandidates(
4378 S&: *this, Args: From, Cands);
4379 return true;
4380}
4381
4382// Helper for compareConversionFunctions that gets the FunctionType that the
4383// conversion-operator return value 'points' to, or nullptr.
4384static const FunctionType *
4385getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4386 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4387 const PointerType *RetPtrTy =
4388 ConvFuncTy->getReturnType()->getAs<PointerType>();
4389
4390 if (!RetPtrTy)
4391 return nullptr;
4392
4393 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4394}
4395
4396/// Compare the user-defined conversion functions or constructors
4397/// of two user-defined conversion sequences to determine whether any ordering
4398/// is possible.
4399static ImplicitConversionSequence::CompareKind
4400compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4401 FunctionDecl *Function2) {
4402 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4403 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4404 if (!Conv1 || !Conv2)
4405 return ImplicitConversionSequence::Indistinguishable;
4406
4407 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4408 return ImplicitConversionSequence::Indistinguishable;
4409
4410 // Objective-C++:
4411 // If both conversion functions are implicitly-declared conversions from
4412 // a lambda closure type to a function pointer and a block pointer,
4413 // respectively, always prefer the conversion to a function pointer,
4414 // because the function pointer is more lightweight and is more likely
4415 // to keep code working.
4416 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4417 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4418 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4419 if (Block1 != Block2)
4420 return Block1 ? ImplicitConversionSequence::Worse
4421 : ImplicitConversionSequence::Better;
4422 }
4423
4424 // In order to support multiple calling conventions for the lambda conversion
4425 // operator (such as when the free and member function calling convention is
4426 // different), prefer the 'free' mechanism, followed by the calling-convention
4427 // of operator(). The latter is in place to support the MSVC-like solution of
4428 // defining ALL of the possible conversions in regards to calling-convention.
4429 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4430 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4431
4432 if (Conv1FuncRet && Conv2FuncRet &&
4433 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4434 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4435 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4436
4437 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4438 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4439
4440 CallingConv CallOpCC =
4441 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4442 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4443 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4444 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4445 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4446
4447 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4448 for (CallingConv CC : PrefOrder) {
4449 if (Conv1CC == CC)
4450 return ImplicitConversionSequence::Better;
4451 if (Conv2CC == CC)
4452 return ImplicitConversionSequence::Worse;
4453 }
4454 }
4455
4456 return ImplicitConversionSequence::Indistinguishable;
4457}
4458
4459static bool hasDeprecatedStringLiteralToCharPtrConversion(
4460 const ImplicitConversionSequence &ICS) {
4461 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4462 (ICS.isUserDefined() &&
4463 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4464}
4465
4466/// CompareImplicitConversionSequences - Compare two implicit
4467/// conversion sequences to determine whether one is better than the
4468/// other or if they are indistinguishable (C++ 13.3.3.2).
4469static ImplicitConversionSequence::CompareKind
4470CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4471 const ImplicitConversionSequence& ICS1,
4472 const ImplicitConversionSequence& ICS2)
4473{
4474 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4475 // conversion sequences (as defined in 13.3.3.1)
4476 // -- a standard conversion sequence (13.3.3.1.1) is a better
4477 // conversion sequence than a user-defined conversion sequence or
4478 // an ellipsis conversion sequence, and
4479 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4480 // conversion sequence than an ellipsis conversion sequence
4481 // (13.3.3.1.3).
4482 //
4483 // C++0x [over.best.ics]p10:
4484 // For the purpose of ranking implicit conversion sequences as
4485 // described in 13.3.3.2, the ambiguous conversion sequence is
4486 // treated as a user-defined sequence that is indistinguishable
4487 // from any other user-defined conversion sequence.
4488
4489 // String literal to 'char *' conversion has been deprecated in C++03. It has
4490 // been removed from C++11. We still accept this conversion, if it happens at
4491 // the best viable function. Otherwise, this conversion is considered worse
4492 // than ellipsis conversion. Consider this as an extension; this is not in the
4493 // standard. For example:
4494 //
4495 // int &f(...); // #1
4496 // void f(char*); // #2
4497 // void g() { int &r = f("foo"); }
4498 //
4499 // In C++03, we pick #2 as the best viable function.
4500 // In C++11, we pick #1 as the best viable function, because ellipsis
4501 // conversion is better than string-literal to char* conversion (since there
4502 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4503 // convert arguments, #2 would be the best viable function in C++11.
4504 // If the best viable function has this conversion, a warning will be issued
4505 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4506
4507 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4508 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4509 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4510 // Ill-formedness must not differ
4511 ICS1.isBad() == ICS2.isBad())
4512 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4513 ? ImplicitConversionSequence::Worse
4514 : ImplicitConversionSequence::Better;
4515
4516 if (ICS1.getKindRank() < ICS2.getKindRank())
4517 return ImplicitConversionSequence::Better;
4518 if (ICS2.getKindRank() < ICS1.getKindRank())
4519 return ImplicitConversionSequence::Worse;
4520
4521 // The following checks require both conversion sequences to be of
4522 // the same kind.
4523 if (ICS1.getKind() != ICS2.getKind())
4524 return ImplicitConversionSequence::Indistinguishable;
4525
4526 ImplicitConversionSequence::CompareKind Result =
4527 ImplicitConversionSequence::Indistinguishable;
4528
4529 // Two implicit conversion sequences of the same form are
4530 // indistinguishable conversion sequences unless one of the
4531 // following rules apply: (C++ 13.3.3.2p3):
4532
4533 // List-initialization sequence L1 is a better conversion sequence than
4534 // list-initialization sequence L2 if:
4535 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4536 // if not that,
4537 // — L1 and L2 convert to arrays of the same element type, and either the
4538 // number of elements n_1 initialized by L1 is less than the number of
4539 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4540 // an array of unknown bound and L1 does not,
4541 // even if one of the other rules in this paragraph would otherwise apply.
4542 if (!ICS1.isBad()) {
4543 bool StdInit1 = false, StdInit2 = false;
4544 if (ICS1.hasInitializerListContainerType())
4545 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4546 Element: nullptr);
4547 if (ICS2.hasInitializerListContainerType())
4548 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4549 Element: nullptr);
4550 if (StdInit1 != StdInit2)
4551 return StdInit1 ? ImplicitConversionSequence::Better
4552 : ImplicitConversionSequence::Worse;
4553
4554 if (ICS1.hasInitializerListContainerType() &&
4555 ICS2.hasInitializerListContainerType())
4556 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4557 T: ICS1.getInitializerListContainerType()))
4558 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4559 T: ICS2.getInitializerListContainerType())) {
4560 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4561 T2: CAT2->getElementType())) {
4562 // Both to arrays of the same element type
4563 if (CAT1->getSize() != CAT2->getSize())
4564 // Different sized, the smaller wins
4565 return CAT1->getSize().ult(RHS: CAT2->getSize())
4566 ? ImplicitConversionSequence::Better
4567 : ImplicitConversionSequence::Worse;
4568 if (ICS1.isInitializerListOfIncompleteArray() !=
4569 ICS2.isInitializerListOfIncompleteArray())
4570 // One is incomplete, it loses
4571 return ICS2.isInitializerListOfIncompleteArray()
4572 ? ImplicitConversionSequence::Better
4573 : ImplicitConversionSequence::Worse;
4574 }
4575 }
4576 }
4577
4578 if (ICS1.isStandard())
4579 // Standard conversion sequence S1 is a better conversion sequence than
4580 // standard conversion sequence S2 if [...]
4581 Result = CompareStandardConversionSequences(S, Loc,
4582 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4583 else if (ICS1.isUserDefined()) {
4584 // With lazy template loading, it is possible to find non-canonical
4585 // FunctionDecls, depending on when redecl chains are completed. Make sure
4586 // to compare the canonical decls of conversion functions. This avoids
4587 // ambiguity problems for templated conversion operators.
4588 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4589 if (ConvFunc1)
4590 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4591 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4592 if (ConvFunc2)
4593 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4594 // User-defined conversion sequence U1 is a better conversion
4595 // sequence than another user-defined conversion sequence U2 if
4596 // they contain the same user-defined conversion function or
4597 // constructor and if the second standard conversion sequence of
4598 // U1 is better than the second standard conversion sequence of
4599 // U2 (C++ 13.3.3.2p3).
4600 if (ConvFunc1 == ConvFunc2)
4601 Result = CompareStandardConversionSequences(S, Loc,
4602 SCS1: ICS1.UserDefined.After,
4603 SCS2: ICS2.UserDefined.After);
4604 else
4605 Result = compareConversionFunctions(S,
4606 Function1: ICS1.UserDefined.ConversionFunction,
4607 Function2: ICS2.UserDefined.ConversionFunction);
4608 }
4609
4610 return Result;
4611}
4612
4613// Per 13.3.3.2p3, compare the given standard conversion sequences to
4614// determine if one is a proper subset of the other.
4615static ImplicitConversionSequence::CompareKind
4616compareStandardConversionSubsets(ASTContext &Context,
4617 const StandardConversionSequence& SCS1,
4618 const StandardConversionSequence& SCS2) {
4619 ImplicitConversionSequence::CompareKind Result
4620 = ImplicitConversionSequence::Indistinguishable;
4621
4622 // the identity conversion sequence is considered to be a subsequence of
4623 // any non-identity conversion sequence
4624 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4625 return ImplicitConversionSequence::Better;
4626 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4627 return ImplicitConversionSequence::Worse;
4628
4629 if (SCS1.Second != SCS2.Second) {
4630 if (SCS1.Second == ICK_Identity)
4631 Result = ImplicitConversionSequence::Better;
4632 else if (SCS2.Second == ICK_Identity)
4633 Result = ImplicitConversionSequence::Worse;
4634 else
4635 return ImplicitConversionSequence::Indistinguishable;
4636 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4637 return ImplicitConversionSequence::Indistinguishable;
4638
4639 if (SCS1.Third == SCS2.Third) {
4640 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4641 : ImplicitConversionSequence::Indistinguishable;
4642 }
4643
4644 if (SCS1.Third == ICK_Identity)
4645 return Result == ImplicitConversionSequence::Worse
4646 ? ImplicitConversionSequence::Indistinguishable
4647 : ImplicitConversionSequence::Better;
4648
4649 if (SCS2.Third == ICK_Identity)
4650 return Result == ImplicitConversionSequence::Better
4651 ? ImplicitConversionSequence::Indistinguishable
4652 : ImplicitConversionSequence::Worse;
4653
4654 return ImplicitConversionSequence::Indistinguishable;
4655}
4656
4657/// Determine whether one of the given reference bindings is better
4658/// than the other based on what kind of bindings they are.
4659static bool
4660isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4661 const StandardConversionSequence &SCS2) {
4662 // C++0x [over.ics.rank]p3b4:
4663 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4664 // implicit object parameter of a non-static member function declared
4665 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4666 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4667 // lvalue reference to a function lvalue and S2 binds an rvalue
4668 // reference*.
4669 //
4670 // FIXME: Rvalue references. We're going rogue with the above edits,
4671 // because the semantics in the current C++0x working paper (N3225 at the
4672 // time of this writing) break the standard definition of std::forward
4673 // and std::reference_wrapper when dealing with references to functions.
4674 // Proposed wording changes submitted to CWG for consideration.
4675 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4676 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4677 return false;
4678
4679 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4680 SCS2.IsLvalueReference) ||
4681 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4682 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4683}
4684
4685enum class FixedEnumPromotion {
4686 None,
4687 ToUnderlyingType,
4688 ToPromotedUnderlyingType
4689};
4690
4691/// Returns kind of fixed enum promotion the \a SCS uses.
4692static FixedEnumPromotion
4693getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4694
4695 if (SCS.Second != ICK_Integral_Promotion)
4696 return FixedEnumPromotion::None;
4697
4698 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4699 if (!Enum)
4700 return FixedEnumPromotion::None;
4701
4702 if (!Enum->isFixed())
4703 return FixedEnumPromotion::None;
4704
4705 QualType UnderlyingType = Enum->getIntegerType();
4706 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4707 return FixedEnumPromotion::ToUnderlyingType;
4708
4709 return FixedEnumPromotion::ToPromotedUnderlyingType;
4710}
4711
4712/// CompareStandardConversionSequences - Compare two standard
4713/// conversion sequences to determine whether one is better than the
4714/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4715static ImplicitConversionSequence::CompareKind
4716CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4717 const StandardConversionSequence& SCS1,
4718 const StandardConversionSequence& SCS2)
4719{
4720 // Standard conversion sequence S1 is a better conversion sequence
4721 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4722
4723 // -- S1 is a proper subsequence of S2 (comparing the conversion
4724 // sequences in the canonical form defined by 13.3.3.1.1,
4725 // excluding any Lvalue Transformation; the identity conversion
4726 // sequence is considered to be a subsequence of any
4727 // non-identity conversion sequence) or, if not that,
4728 if (ImplicitConversionSequence::CompareKind CK
4729 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4730 return CK;
4731
4732 // -- the rank of S1 is better than the rank of S2 (by the rules
4733 // defined below), or, if not that,
4734 ImplicitConversionRank Rank1 = SCS1.getRank();
4735 ImplicitConversionRank Rank2 = SCS2.getRank();
4736 if (Rank1 < Rank2)
4737 return ImplicitConversionSequence::Better;
4738 else if (Rank2 < Rank1)
4739 return ImplicitConversionSequence::Worse;
4740
4741 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4742 // are indistinguishable unless one of the following rules
4743 // applies:
4744
4745 // A conversion that is not a conversion of a pointer, or
4746 // pointer to member, to bool is better than another conversion
4747 // that is such a conversion.
4748 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4749 return SCS2.isPointerConversionToBool()
4750 ? ImplicitConversionSequence::Better
4751 : ImplicitConversionSequence::Worse;
4752
4753 // C++14 [over.ics.rank]p4b2:
4754 // This is retroactively applied to C++11 by CWG 1601.
4755 //
4756 // A conversion that promotes an enumeration whose underlying type is fixed
4757 // to its underlying type is better than one that promotes to the promoted
4758 // underlying type, if the two are different.
4759 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4760 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4761 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4762 FEP1 != FEP2)
4763 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4764 ? ImplicitConversionSequence::Better
4765 : ImplicitConversionSequence::Worse;
4766
4767 // C++ [over.ics.rank]p4b2:
4768 //
4769 // If class B is derived directly or indirectly from class A,
4770 // conversion of B* to A* is better than conversion of B* to
4771 // void*, and conversion of A* to void* is better than conversion
4772 // of B* to void*.
4773 bool SCS1ConvertsToVoid
4774 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4775 bool SCS2ConvertsToVoid
4776 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4777 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4778 // Exactly one of the conversion sequences is a conversion to
4779 // a void pointer; it's the worse conversion.
4780 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4781 : ImplicitConversionSequence::Worse;
4782 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4783 // Neither conversion sequence converts to a void pointer; compare
4784 // their derived-to-base conversions.
4785 if (ImplicitConversionSequence::CompareKind DerivedCK
4786 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4787 return DerivedCK;
4788 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4789 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4790 // Both conversion sequences are conversions to void
4791 // pointers. Compare the source types to determine if there's an
4792 // inheritance relationship in their sources.
4793 QualType FromType1 = SCS1.getFromType();
4794 QualType FromType2 = SCS2.getFromType();
4795
4796 // Adjust the types we're converting from via the array-to-pointer
4797 // conversion, if we need to.
4798 if (SCS1.First == ICK_Array_To_Pointer)
4799 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4800 if (SCS2.First == ICK_Array_To_Pointer)
4801 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4802
4803 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4804 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4805
4806 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4807 return ImplicitConversionSequence::Better;
4808 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4809 return ImplicitConversionSequence::Worse;
4810
4811 // Objective-C++: If one interface is more specific than the
4812 // other, it is the better one.
4813 const ObjCObjectPointerType* FromObjCPtr1
4814 = FromType1->getAs<ObjCObjectPointerType>();
4815 const ObjCObjectPointerType* FromObjCPtr2
4816 = FromType2->getAs<ObjCObjectPointerType>();
4817 if (FromObjCPtr1 && FromObjCPtr2) {
4818 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4819 RHSOPT: FromObjCPtr2);
4820 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4821 RHSOPT: FromObjCPtr1);
4822 if (AssignLeft != AssignRight) {
4823 return AssignLeft? ImplicitConversionSequence::Better
4824 : ImplicitConversionSequence::Worse;
4825 }
4826 }
4827 }
4828
4829 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4830 // Check for a better reference binding based on the kind of bindings.
4831 if (isBetterReferenceBindingKind(SCS1, SCS2))
4832 return ImplicitConversionSequence::Better;
4833 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4834 return ImplicitConversionSequence::Worse;
4835 }
4836
4837 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4838 // bullet 3).
4839 if (ImplicitConversionSequence::CompareKind QualCK
4840 = CompareQualificationConversions(S, SCS1, SCS2))
4841 return QualCK;
4842
4843 if (ImplicitConversionSequence::CompareKind ObtCK =
4844 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4845 return ObtCK;
4846
4847 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4848 // C++ [over.ics.rank]p3b4:
4849 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4850 // which the references refer are the same type except for
4851 // top-level cv-qualifiers, and the type to which the reference
4852 // initialized by S2 refers is more cv-qualified than the type
4853 // to which the reference initialized by S1 refers.
4854 QualType T1 = SCS1.getToType(Idx: 2);
4855 QualType T2 = SCS2.getToType(Idx: 2);
4856 T1 = S.Context.getCanonicalType(T: T1);
4857 T2 = S.Context.getCanonicalType(T: T2);
4858 Qualifiers T1Quals, T2Quals;
4859 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4860 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4861 if (UnqualT1 == UnqualT2) {
4862 // Objective-C++ ARC: If the references refer to objects with different
4863 // lifetimes, prefer bindings that don't change lifetime.
4864 if (SCS1.ObjCLifetimeConversionBinding !=
4865 SCS2.ObjCLifetimeConversionBinding) {
4866 return SCS1.ObjCLifetimeConversionBinding
4867 ? ImplicitConversionSequence::Worse
4868 : ImplicitConversionSequence::Better;
4869 }
4870
4871 // If the type is an array type, promote the element qualifiers to the
4872 // type for comparison.
4873 if (isa<ArrayType>(Val: T1) && T1Quals)
4874 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4875 if (isa<ArrayType>(Val: T2) && T2Quals)
4876 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4877 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4878 return ImplicitConversionSequence::Better;
4879 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4880 return ImplicitConversionSequence::Worse;
4881 }
4882 }
4883
4884 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4885 // floating-to-integral conversion if the integral conversion
4886 // is between types of the same size.
4887 // For example:
4888 // void f(float);
4889 // void f(int);
4890 // int main {
4891 // long a;
4892 // f(a);
4893 // }
4894 // Here, MSVC will call f(int) instead of generating a compile error
4895 // as clang will do in standard mode.
4896 if (S.getLangOpts().MSVCCompat &&
4897 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4898 SCS1.Second == ICK_Integral_Conversion &&
4899 SCS2.Second == ICK_Floating_Integral &&
4900 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4901 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4902 return ImplicitConversionSequence::Better;
4903
4904 // Prefer a compatible vector conversion over a lax vector conversion
4905 // For example:
4906 //
4907 // typedef float __v4sf __attribute__((__vector_size__(16)));
4908 // void f(vector float);
4909 // void f(vector signed int);
4910 // int main() {
4911 // __v4sf a;
4912 // f(a);
4913 // }
4914 // Here, we'd like to choose f(vector float) and not
4915 // report an ambiguous call error
4916 if (SCS1.Second == ICK_Vector_Conversion &&
4917 SCS2.Second == ICK_Vector_Conversion) {
4918 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4919 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4920 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4921 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4922
4923 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4924 return SCS1IsCompatibleVectorConversion
4925 ? ImplicitConversionSequence::Better
4926 : ImplicitConversionSequence::Worse;
4927 }
4928
4929 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4930 SCS2.Second == ICK_SVE_Vector_Conversion) {
4931 bool SCS1IsCompatibleSVEVectorConversion =
4932 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4933 bool SCS2IsCompatibleSVEVectorConversion =
4934 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4935
4936 if (SCS1IsCompatibleSVEVectorConversion !=
4937 SCS2IsCompatibleSVEVectorConversion)
4938 return SCS1IsCompatibleSVEVectorConversion
4939 ? ImplicitConversionSequence::Better
4940 : ImplicitConversionSequence::Worse;
4941 }
4942
4943 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4944 SCS2.Second == ICK_RVV_Vector_Conversion) {
4945 bool SCS1IsCompatibleRVVVectorConversion =
4946 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4947 bool SCS2IsCompatibleRVVVectorConversion =
4948 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4949
4950 if (SCS1IsCompatibleRVVVectorConversion !=
4951 SCS2IsCompatibleRVVVectorConversion)
4952 return SCS1IsCompatibleRVVVectorConversion
4953 ? ImplicitConversionSequence::Better
4954 : ImplicitConversionSequence::Worse;
4955 }
4956 return ImplicitConversionSequence::Indistinguishable;
4957}
4958
4959/// CompareOverflowBehaviorConversions - Compares two standard conversion
4960/// sequences to determine whether they can be ranked based on their
4961/// OverflowBehaviorType's underlying type.
4962static ImplicitConversionSequence::CompareKind
4963CompareOverflowBehaviorConversions(Sema &S,
4964 const StandardConversionSequence &SCS1,
4965 const StandardConversionSequence &SCS2) {
4966
4967 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4968 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4969 return ImplicitConversionSequence::Better;
4970
4971 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4972 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
4973 return ImplicitConversionSequence::Worse;
4974
4975 return ImplicitConversionSequence::Indistinguishable;
4976}
4977
4978/// CompareQualificationConversions - Compares two standard conversion
4979/// sequences to determine whether they can be ranked based on their
4980/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4981static ImplicitConversionSequence::CompareKind
4982CompareQualificationConversions(Sema &S,
4983 const StandardConversionSequence& SCS1,
4984 const StandardConversionSequence& SCS2) {
4985 // C++ [over.ics.rank]p3:
4986 // -- S1 and S2 differ only in their qualification conversion and
4987 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4988 // [C++98]
4989 // [...] and the cv-qualification signature of type T1 is a proper subset
4990 // of the cv-qualification signature of type T2, and S1 is not the
4991 // deprecated string literal array-to-pointer conversion (4.2).
4992 // [C++2a]
4993 // [...] where T1 can be converted to T2 by a qualification conversion.
4994 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4995 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4996 return ImplicitConversionSequence::Indistinguishable;
4997
4998 // FIXME: the example in the standard doesn't use a qualification
4999 // conversion (!)
5000 QualType T1 = SCS1.getToType(Idx: 2);
5001 QualType T2 = SCS2.getToType(Idx: 2);
5002 T1 = S.Context.getCanonicalType(T: T1);
5003 T2 = S.Context.getCanonicalType(T: T2);
5004 assert(!T1->isReferenceType() && !T2->isReferenceType());
5005 Qualifiers T1Quals, T2Quals;
5006 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5007 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5008
5009 // If the types are the same, we won't learn anything by unwrapping
5010 // them.
5011 if (UnqualT1 == UnqualT2)
5012 return ImplicitConversionSequence::Indistinguishable;
5013
5014 // Don't ever prefer a standard conversion sequence that uses the deprecated
5015 // string literal array to pointer conversion.
5016 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5017 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5018
5019 // Objective-C++ ARC:
5020 // Prefer qualification conversions not involving a change in lifetime
5021 // to qualification conversions that do change lifetime.
5022 if (SCS1.QualificationIncludesObjCLifetime &&
5023 !SCS2.QualificationIncludesObjCLifetime)
5024 CanPick1 = false;
5025 if (SCS2.QualificationIncludesObjCLifetime &&
5026 !SCS1.QualificationIncludesObjCLifetime)
5027 CanPick2 = false;
5028
5029 bool ObjCLifetimeConversion;
5030 if (CanPick1 &&
5031 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5032 CanPick1 = false;
5033 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5034 // directions, so we can't short-cut this second check in general.
5035 if (CanPick2 &&
5036 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5037 CanPick2 = false;
5038
5039 if (CanPick1 != CanPick2)
5040 return CanPick1 ? ImplicitConversionSequence::Better
5041 : ImplicitConversionSequence::Worse;
5042 return ImplicitConversionSequence::Indistinguishable;
5043}
5044
5045/// CompareDerivedToBaseConversions - Compares two standard conversion
5046/// sequences to determine whether they can be ranked based on their
5047/// various kinds of derived-to-base conversions (C++
5048/// [over.ics.rank]p4b3). As part of these checks, we also look at
5049/// conversions between Objective-C interface types.
5050static ImplicitConversionSequence::CompareKind
5051CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5052 const StandardConversionSequence& SCS1,
5053 const StandardConversionSequence& SCS2) {
5054 QualType FromType1 = SCS1.getFromType();
5055 QualType ToType1 = SCS1.getToType(Idx: 1);
5056 QualType FromType2 = SCS2.getFromType();
5057 QualType ToType2 = SCS2.getToType(Idx: 1);
5058
5059 // Adjust the types we're converting from via the array-to-pointer
5060 // conversion, if we need to.
5061 if (SCS1.First == ICK_Array_To_Pointer)
5062 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5063 if (SCS2.First == ICK_Array_To_Pointer)
5064 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5065
5066 // Canonicalize all of the types.
5067 FromType1 = S.Context.getCanonicalType(T: FromType1);
5068 ToType1 = S.Context.getCanonicalType(T: ToType1);
5069 FromType2 = S.Context.getCanonicalType(T: FromType2);
5070 ToType2 = S.Context.getCanonicalType(T: ToType2);
5071
5072 // C++ [over.ics.rank]p4b3:
5073 //
5074 // If class B is derived directly or indirectly from class A and
5075 // class C is derived directly or indirectly from B,
5076 //
5077 // Compare based on pointer conversions.
5078 if (SCS1.Second == ICK_Pointer_Conversion &&
5079 SCS2.Second == ICK_Pointer_Conversion &&
5080 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5081 FromType1->isPointerType() && FromType2->isPointerType() &&
5082 ToType1->isPointerType() && ToType2->isPointerType()) {
5083 QualType FromPointee1 =
5084 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5085 QualType ToPointee1 =
5086 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5087 QualType FromPointee2 =
5088 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5089 QualType ToPointee2 =
5090 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5091
5092 // -- conversion of C* to B* is better than conversion of C* to A*,
5093 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5094 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5095 return ImplicitConversionSequence::Better;
5096 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5097 return ImplicitConversionSequence::Worse;
5098 }
5099
5100 // -- conversion of B* to A* is better than conversion of C* to A*,
5101 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5102 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5103 return ImplicitConversionSequence::Better;
5104 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5105 return ImplicitConversionSequence::Worse;
5106 }
5107 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5108 SCS2.Second == ICK_Pointer_Conversion) {
5109 const ObjCObjectPointerType *FromPtr1
5110 = FromType1->getAs<ObjCObjectPointerType>();
5111 const ObjCObjectPointerType *FromPtr2
5112 = FromType2->getAs<ObjCObjectPointerType>();
5113 const ObjCObjectPointerType *ToPtr1
5114 = ToType1->getAs<ObjCObjectPointerType>();
5115 const ObjCObjectPointerType *ToPtr2
5116 = ToType2->getAs<ObjCObjectPointerType>();
5117
5118 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5119 // Apply the same conversion ranking rules for Objective-C pointer types
5120 // that we do for C++ pointers to class types. However, we employ the
5121 // Objective-C pseudo-subtyping relationship used for assignment of
5122 // Objective-C pointer types.
5123 bool FromAssignLeft
5124 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5125 bool FromAssignRight
5126 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5127 bool ToAssignLeft
5128 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5129 bool ToAssignRight
5130 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5131
5132 // A conversion to an a non-id object pointer type or qualified 'id'
5133 // type is better than a conversion to 'id'.
5134 if (ToPtr1->isObjCIdType() &&
5135 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5136 return ImplicitConversionSequence::Worse;
5137 if (ToPtr2->isObjCIdType() &&
5138 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5139 return ImplicitConversionSequence::Better;
5140
5141 // A conversion to a non-id object pointer type is better than a
5142 // conversion to a qualified 'id' type
5143 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5144 return ImplicitConversionSequence::Worse;
5145 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5146 return ImplicitConversionSequence::Better;
5147
5148 // A conversion to an a non-Class object pointer type or qualified 'Class'
5149 // type is better than a conversion to 'Class'.
5150 if (ToPtr1->isObjCClassType() &&
5151 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5152 return ImplicitConversionSequence::Worse;
5153 if (ToPtr2->isObjCClassType() &&
5154 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5155 return ImplicitConversionSequence::Better;
5156
5157 // A conversion to a non-Class object pointer type is better than a
5158 // conversion to a qualified 'Class' type.
5159 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5160 return ImplicitConversionSequence::Worse;
5161 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5162 return ImplicitConversionSequence::Better;
5163
5164 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5165 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5166 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5167 (ToAssignLeft != ToAssignRight)) {
5168 if (FromPtr1->isSpecialized()) {
5169 // "conversion of B<A> * to B * is better than conversion of B * to
5170 // C *.
5171 bool IsFirstSame =
5172 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5173 bool IsSecondSame =
5174 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5175 if (IsFirstSame) {
5176 if (!IsSecondSame)
5177 return ImplicitConversionSequence::Better;
5178 } else if (IsSecondSame)
5179 return ImplicitConversionSequence::Worse;
5180 }
5181 return ToAssignLeft? ImplicitConversionSequence::Worse
5182 : ImplicitConversionSequence::Better;
5183 }
5184
5185 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5186 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5187 (FromAssignLeft != FromAssignRight))
5188 return FromAssignLeft? ImplicitConversionSequence::Better
5189 : ImplicitConversionSequence::Worse;
5190 }
5191 }
5192
5193 // Ranking of member-pointer types.
5194 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5195 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5196 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5197 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5198 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5199 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5200 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5201 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5202 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5203 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5204 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5205 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5206 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5207 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5208 return ImplicitConversionSequence::Worse;
5209 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5210 return ImplicitConversionSequence::Better;
5211 }
5212 // conversion of B::* to C::* is better than conversion of A::* to C::*
5213 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5214 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5215 return ImplicitConversionSequence::Better;
5216 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5217 return ImplicitConversionSequence::Worse;
5218 }
5219 }
5220
5221 if (SCS1.Second == ICK_Derived_To_Base) {
5222 // -- conversion of C to B is better than conversion of C to A,
5223 // -- binding of an expression of type C to a reference of type
5224 // B& is better than binding an expression of type C to a
5225 // reference of type A&,
5226 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5227 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5228 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5229 return ImplicitConversionSequence::Better;
5230 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5231 return ImplicitConversionSequence::Worse;
5232 }
5233
5234 // -- conversion of B to A is better than conversion of C to A.
5235 // -- binding of an expression of type B to a reference of type
5236 // A& is better than binding an expression of type C to a
5237 // reference of type A&,
5238 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5239 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5240 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5241 return ImplicitConversionSequence::Better;
5242 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5243 return ImplicitConversionSequence::Worse;
5244 }
5245 }
5246
5247 return ImplicitConversionSequence::Indistinguishable;
5248}
5249
5250static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5251 if (!T.getQualifiers().hasUnaligned())
5252 return T;
5253
5254 Qualifiers Q;
5255 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5256 Q.removeUnaligned();
5257 return Ctx.getQualifiedType(T, Qs: Q);
5258}
5259
5260Sema::ReferenceCompareResult
5261Sema::CompareReferenceRelationship(SourceLocation Loc,
5262 QualType OrigT1, QualType OrigT2,
5263 ReferenceConversions *ConvOut) {
5264 assert(!OrigT1->isReferenceType() &&
5265 "T1 must be the pointee type of the reference type");
5266 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5267
5268 QualType T1 = Context.getCanonicalType(T: OrigT1);
5269 QualType T2 = Context.getCanonicalType(T: OrigT2);
5270 Qualifiers T1Quals, T2Quals;
5271 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5272 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5273
5274 ReferenceConversions ConvTmp;
5275 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5276 Conv = ReferenceConversions();
5277
5278 // C++2a [dcl.init.ref]p4:
5279 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5280 // reference-related to "cv2 T2" if T1 is similar to T2, or
5281 // T1 is a base class of T2.
5282 // "cv1 T1" is reference-compatible with "cv2 T2" if
5283 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5284 // "pointer to cv1 T1" via a standard conversion sequence.
5285
5286 // Check for standard conversions we can apply to pointers: derived-to-base
5287 // conversions, ObjC pointer conversions, and function pointer conversions.
5288 // (Qualification conversions are checked last.)
5289 if (UnqualT1 == UnqualT2) {
5290 // Nothing to do.
5291 } else if (isCompleteType(Loc, T: OrigT2) &&
5292 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5293 Conv |= ReferenceConversions::DerivedToBase;
5294 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5295 UnqualT2->isObjCObjectOrInterfaceType() &&
5296 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5297 Conv |= ReferenceConversions::ObjC;
5298 else if (UnqualT2->isFunctionType() &&
5299 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5300 Conv |= ReferenceConversions::Function;
5301 // No need to check qualifiers; function types don't have them.
5302 return Ref_Compatible;
5303 }
5304 bool ConvertedReferent = Conv != 0;
5305
5306 // We can have a qualification conversion. Compute whether the types are
5307 // similar at the same time.
5308 bool PreviousToQualsIncludeConst = true;
5309 bool TopLevel = true;
5310 do {
5311 if (T1 == T2)
5312 break;
5313
5314 // We will need a qualification conversion.
5315 Conv |= ReferenceConversions::Qualification;
5316
5317 // Track whether we performed a qualification conversion anywhere other
5318 // than the top level. This matters for ranking reference bindings in
5319 // overload resolution.
5320 if (!TopLevel)
5321 Conv |= ReferenceConversions::NestedQualification;
5322
5323 // MS compiler ignores __unaligned qualifier for references; do the same.
5324 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5325 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5326
5327 // If we find a qualifier mismatch, the types are not reference-compatible,
5328 // but are still be reference-related if they're similar.
5329 bool ObjCLifetimeConversion = false;
5330 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5331 PreviousToQualsIncludeConst,
5332 ObjCLifetimeConversion, Ctx: getASTContext()))
5333 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5334 ? Ref_Related
5335 : Ref_Incompatible;
5336
5337 // FIXME: Should we track this for any level other than the first?
5338 if (ObjCLifetimeConversion)
5339 Conv |= ReferenceConversions::ObjCLifetime;
5340
5341 TopLevel = false;
5342 } while (Context.UnwrapSimilarTypes(T1, T2));
5343
5344 // At this point, if the types are reference-related, we must either have the
5345 // same inner type (ignoring qualifiers), or must have already worked out how
5346 // to convert the referent.
5347 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5348 ? Ref_Compatible
5349 : Ref_Incompatible;
5350}
5351
5352/// Look for a user-defined conversion to a value reference-compatible
5353/// with DeclType. Return true if something definite is found.
5354static bool
5355FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5356 QualType DeclType, SourceLocation DeclLoc,
5357 Expr *Init, QualType T2, bool AllowRvalues,
5358 bool AllowExplicit) {
5359 assert(T2->isRecordType() && "Can only find conversions of record types.");
5360 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5361 OverloadCandidateSet CandidateSet(
5362 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5363 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5364 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5365 NamedDecl *D = *I;
5366 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5367 if (isa<UsingShadowDecl>(Val: D))
5368 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5369
5370 FunctionTemplateDecl *ConvTemplate
5371 = dyn_cast<FunctionTemplateDecl>(Val: D);
5372 CXXConversionDecl *Conv;
5373 if (ConvTemplate)
5374 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5375 else
5376 Conv = cast<CXXConversionDecl>(Val: D);
5377
5378 if (AllowRvalues) {
5379 // If we are initializing an rvalue reference, don't permit conversion
5380 // functions that return lvalues.
5381 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5382 const ReferenceType *RefType
5383 = Conv->getConversionType()->getAs<LValueReferenceType>();
5384 if (RefType && !RefType->getPointeeType()->isFunctionType())
5385 continue;
5386 }
5387
5388 if (!ConvTemplate &&
5389 S.CompareReferenceRelationship(
5390 Loc: DeclLoc,
5391 OrigT1: Conv->getConversionType()
5392 .getNonReferenceType()
5393 .getUnqualifiedType(),
5394 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5395 Sema::Ref_Incompatible)
5396 continue;
5397 } else {
5398 // If the conversion function doesn't return a reference type,
5399 // it can't be considered for this conversion. An rvalue reference
5400 // is only acceptable if its referencee is a function type.
5401
5402 const ReferenceType *RefType =
5403 Conv->getConversionType()->getAs<ReferenceType>();
5404 if (!RefType ||
5405 (!RefType->isLValueReferenceType() &&
5406 !RefType->getPointeeType()->isFunctionType()))
5407 continue;
5408 }
5409
5410 if (ConvTemplate)
5411 S.AddTemplateConversionCandidate(
5412 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5413 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5414 else
5415 S.AddConversionCandidate(
5416 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5417 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5418 }
5419
5420 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5421
5422 OverloadCandidateSet::iterator Best;
5423 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5424 case OR_Success:
5425
5426 assert(Best->HasFinalConversion);
5427
5428 // C++ [over.ics.ref]p1:
5429 //
5430 // [...] If the parameter binds directly to the result of
5431 // applying a conversion function to the argument
5432 // expression, the implicit conversion sequence is a
5433 // user-defined conversion sequence (13.3.3.1.2), with the
5434 // second standard conversion sequence either an identity
5435 // conversion or, if the conversion function returns an
5436 // entity of a type that is a derived class of the parameter
5437 // type, a derived-to-base Conversion.
5438 if (!Best->FinalConversion.DirectBinding)
5439 return false;
5440
5441 ICS.setUserDefined();
5442 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5443 ICS.UserDefined.After = Best->FinalConversion;
5444 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5445 ICS.UserDefined.ConversionFunction = Best->Function;
5446 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5447 ICS.UserDefined.EllipsisConversion = false;
5448 assert(ICS.UserDefined.After.ReferenceBinding &&
5449 ICS.UserDefined.After.DirectBinding &&
5450 "Expected a direct reference binding!");
5451 return true;
5452
5453 case OR_Ambiguous:
5454 ICS.setAmbiguous();
5455 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5456 Cand != CandidateSet.end(); ++Cand)
5457 if (Cand->Best)
5458 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5459 return true;
5460
5461 case OR_No_Viable_Function:
5462 case OR_Deleted:
5463 // There was no suitable conversion, or we found a deleted
5464 // conversion; continue with other checks.
5465 return false;
5466 }
5467
5468 llvm_unreachable("Invalid OverloadResult!");
5469}
5470
5471/// Compute an implicit conversion sequence for reference
5472/// initialization.
5473static ImplicitConversionSequence
5474TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5475 SourceLocation DeclLoc,
5476 bool SuppressUserConversions,
5477 bool AllowExplicit) {
5478 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5479
5480 // Most paths end in a failed conversion.
5481 ImplicitConversionSequence ICS;
5482 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5483
5484 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5485 QualType T2 = Init->getType();
5486
5487 // If the initializer is the address of an overloaded function, try
5488 // to resolve the overloaded function. If all goes well, T2 is the
5489 // type of the resulting function.
5490 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5491 DeclAccessPair Found;
5492 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5493 Complain: false, Found))
5494 T2 = Fn->getType();
5495 }
5496
5497 // Compute some basic properties of the types and the initializer.
5498 bool isRValRef = DeclType->isRValueReferenceType();
5499 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5500
5501 Sema::ReferenceConversions RefConv;
5502 Sema::ReferenceCompareResult RefRelationship =
5503 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5504
5505 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5506 ICS.setStandard();
5507 ICS.Standard.First = ICK_Identity;
5508 // FIXME: A reference binding can be a function conversion too. We should
5509 // consider that when ordering reference-to-function bindings.
5510 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5511 ? ICK_Derived_To_Base
5512 : (RefConv & Sema::ReferenceConversions::ObjC)
5513 ? ICK_Compatible_Conversion
5514 : ICK_Identity;
5515 ICS.Standard.Dimension = ICK_Identity;
5516 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5517 // a reference binding that performs a non-top-level qualification
5518 // conversion as a qualification conversion, not as an identity conversion.
5519 ICS.Standard.Third = (RefConv &
5520 Sema::ReferenceConversions::NestedQualification)
5521 ? ICK_Qualification
5522 : ICK_Identity;
5523 ICS.Standard.setFromType(T2);
5524 ICS.Standard.setToType(Idx: 0, T: T2);
5525 ICS.Standard.setToType(Idx: 1, T: T1);
5526 ICS.Standard.setToType(Idx: 2, T: T1);
5527 ICS.Standard.ReferenceBinding = true;
5528 ICS.Standard.DirectBinding = BindsDirectly;
5529 ICS.Standard.IsLvalueReference = !isRValRef;
5530 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5531 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5532 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5533 ICS.Standard.ObjCLifetimeConversionBinding =
5534 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5535 ICS.Standard.FromBracedInitList = false;
5536 ICS.Standard.CopyConstructor = nullptr;
5537 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5538 };
5539
5540 // C++0x [dcl.init.ref]p5:
5541 // A reference to type "cv1 T1" is initialized by an expression
5542 // of type "cv2 T2" as follows:
5543
5544 // -- If reference is an lvalue reference and the initializer expression
5545 if (!isRValRef) {
5546 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5547 // reference-compatible with "cv2 T2," or
5548 //
5549 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5550 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5551 // C++ [over.ics.ref]p1:
5552 // When a parameter of reference type binds directly (8.5.3)
5553 // to an argument expression, the implicit conversion sequence
5554 // is the identity conversion, unless the argument expression
5555 // has a type that is a derived class of the parameter type,
5556 // in which case the implicit conversion sequence is a
5557 // derived-to-base Conversion (13.3.3.1).
5558 SetAsReferenceBinding(/*BindsDirectly=*/true);
5559
5560 // Nothing more to do: the inaccessibility/ambiguity check for
5561 // derived-to-base conversions is suppressed when we're
5562 // computing the implicit conversion sequence (C++
5563 // [over.best.ics]p2).
5564 return ICS;
5565 }
5566
5567 // -- has a class type (i.e., T2 is a class type), where T1 is
5568 // not reference-related to T2, and can be implicitly
5569 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5570 // is reference-compatible with "cv3 T3" 92) (this
5571 // conversion is selected by enumerating the applicable
5572 // conversion functions (13.3.1.6) and choosing the best
5573 // one through overload resolution (13.3)),
5574 if (!SuppressUserConversions && T2->isRecordType() &&
5575 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5576 RefRelationship == Sema::Ref_Incompatible) {
5577 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5578 Init, T2, /*AllowRvalues=*/false,
5579 AllowExplicit))
5580 return ICS;
5581 }
5582 }
5583
5584 // -- Otherwise, the reference shall be an lvalue reference to a
5585 // non-volatile const type (i.e., cv1 shall be const), or the reference
5586 // shall be an rvalue reference.
5587 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5588 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5589 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5590 return ICS;
5591 }
5592
5593 // -- If the initializer expression
5594 //
5595 // -- is an xvalue, class prvalue, array prvalue or function
5596 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5597 if (RefRelationship == Sema::Ref_Compatible &&
5598 (InitCategory.isXValue() ||
5599 (InitCategory.isPRValue() &&
5600 (T2->isRecordType() || T2->isArrayType())) ||
5601 (InitCategory.isLValue() && T2->isFunctionType()))) {
5602 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5603 // binding unless we're binding to a class prvalue.
5604 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5605 // allow the use of rvalue references in C++98/03 for the benefit of
5606 // standard library implementors; therefore, we need the xvalue check here.
5607 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5608 !(InitCategory.isPRValue() || T2->isRecordType()));
5609 return ICS;
5610 }
5611
5612 // -- has a class type (i.e., T2 is a class type), where T1 is not
5613 // reference-related to T2, and can be implicitly converted to
5614 // an xvalue, class prvalue, or function lvalue of type
5615 // "cv3 T3", where "cv1 T1" is reference-compatible with
5616 // "cv3 T3",
5617 //
5618 // then the reference is bound to the value of the initializer
5619 // expression in the first case and to the result of the conversion
5620 // in the second case (or, in either case, to an appropriate base
5621 // class subobject).
5622 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5623 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5624 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5625 Init, T2, /*AllowRvalues=*/true,
5626 AllowExplicit)) {
5627 // In the second case, if the reference is an rvalue reference
5628 // and the second standard conversion sequence of the
5629 // user-defined conversion sequence includes an lvalue-to-rvalue
5630 // conversion, the program is ill-formed.
5631 if (ICS.isUserDefined() && isRValRef &&
5632 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5633 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5634
5635 return ICS;
5636 }
5637
5638 // A temporary of function type cannot be created; don't even try.
5639 if (T1->isFunctionType())
5640 return ICS;
5641
5642 // -- Otherwise, a temporary of type "cv1 T1" is created and
5643 // initialized from the initializer expression using the
5644 // rules for a non-reference copy initialization (8.5). The
5645 // reference is then bound to the temporary. If T1 is
5646 // reference-related to T2, cv1 must be the same
5647 // cv-qualification as, or greater cv-qualification than,
5648 // cv2; otherwise, the program is ill-formed.
5649 if (RefRelationship == Sema::Ref_Related) {
5650 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5651 // we would be reference-compatible or reference-compatible with
5652 // added qualification. But that wasn't the case, so the reference
5653 // initialization fails.
5654 //
5655 // Note that we only want to check address spaces and cvr-qualifiers here.
5656 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5657 Qualifiers T1Quals = T1.getQualifiers();
5658 Qualifiers T2Quals = T2.getQualifiers();
5659 T1Quals.removeObjCGCAttr();
5660 T1Quals.removeObjCLifetime();
5661 T2Quals.removeObjCGCAttr();
5662 T2Quals.removeObjCLifetime();
5663 // MS compiler ignores __unaligned qualifier for references; do the same.
5664 T1Quals.removeUnaligned();
5665 T2Quals.removeUnaligned();
5666 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5667 return ICS;
5668 }
5669
5670 // If at least one of the types is a class type, the types are not
5671 // related, and we aren't allowed any user conversions, the
5672 // reference binding fails. This case is important for breaking
5673 // recursion, since TryImplicitConversion below will attempt to
5674 // create a temporary through the use of a copy constructor.
5675 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5676 (T1->isRecordType() || T2->isRecordType()))
5677 return ICS;
5678
5679 // If T1 is reference-related to T2 and the reference is an rvalue
5680 // reference, the initializer expression shall not be an lvalue.
5681 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5682 Init->Classify(Ctx&: S.Context).isLValue()) {
5683 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5684 return ICS;
5685 }
5686
5687 // C++ [over.ics.ref]p2:
5688 // When a parameter of reference type is not bound directly to
5689 // an argument expression, the conversion sequence is the one
5690 // required to convert the argument expression to the
5691 // underlying type of the reference according to
5692 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5693 // to copy-initializing a temporary of the underlying type with
5694 // the argument expression. Any difference in top-level
5695 // cv-qualification is subsumed by the initialization itself
5696 // and does not constitute a conversion.
5697 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5698 AllowExplicit: AllowedExplicit::None,
5699 /*InOverloadResolution=*/false,
5700 /*CStyle=*/false,
5701 /*AllowObjCWritebackConversion=*/false,
5702 /*AllowObjCConversionOnExplicit=*/false);
5703
5704 // Of course, that's still a reference binding.
5705 if (ICS.isStandard()) {
5706 ICS.Standard.ReferenceBinding = true;
5707 ICS.Standard.IsLvalueReference = !isRValRef;
5708 ICS.Standard.BindsToFunctionLvalue = false;
5709 ICS.Standard.BindsToRvalue = true;
5710 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5711 ICS.Standard.ObjCLifetimeConversionBinding = false;
5712 } else if (ICS.isUserDefined()) {
5713 const ReferenceType *LValRefType =
5714 ICS.UserDefined.ConversionFunction->getReturnType()
5715 ->getAs<LValueReferenceType>();
5716
5717 // C++ [over.ics.ref]p3:
5718 // Except for an implicit object parameter, for which see 13.3.1, a
5719 // standard conversion sequence cannot be formed if it requires [...]
5720 // binding an rvalue reference to an lvalue other than a function
5721 // lvalue.
5722 // Note that the function case is not possible here.
5723 if (isRValRef && LValRefType) {
5724 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5725 return ICS;
5726 }
5727
5728 ICS.UserDefined.After.ReferenceBinding = true;
5729 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5730 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5731 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5732 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5733 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5734 ICS.UserDefined.After.FromBracedInitList = false;
5735 }
5736
5737 return ICS;
5738}
5739
5740static ImplicitConversionSequence
5741TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5742 bool SuppressUserConversions,
5743 bool InOverloadResolution,
5744 bool AllowObjCWritebackConversion,
5745 bool AllowExplicit = false);
5746
5747/// TryListConversion - Try to copy-initialize a value of type ToType from the
5748/// initializer list From.
5749static ImplicitConversionSequence
5750TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5751 bool SuppressUserConversions,
5752 bool InOverloadResolution,
5753 bool AllowObjCWritebackConversion) {
5754 // C++11 [over.ics.list]p1:
5755 // When an argument is an initializer list, it is not an expression and
5756 // special rules apply for converting it to a parameter type.
5757
5758 ImplicitConversionSequence Result;
5759 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5760
5761 // We need a complete type for what follows. With one C++20 exception,
5762 // incomplete types can never be initialized from init lists.
5763 QualType InitTy = ToType;
5764 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5765 if (AT && S.getLangOpts().CPlusPlus20)
5766 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5767 // C++20 allows list initialization of an incomplete array type.
5768 InitTy = IAT->getElementType();
5769 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5770 return Result;
5771
5772 // C++20 [over.ics.list]/2:
5773 // If the initializer list is a designated-initializer-list, a conversion
5774 // is only possible if the parameter has an aggregate type
5775 //
5776 // FIXME: The exception for reference initialization here is not part of the
5777 // language rules, but follow other compilers in adding it as a tentative DR
5778 // resolution.
5779 bool IsDesignatedInit = From->hasDesignatedInit();
5780 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5781 IsDesignatedInit)
5782 return Result;
5783
5784 // Per DR1467 and DR2137:
5785 // If the parameter type is an aggregate class X and the initializer list
5786 // has a single element of type cv U, where U is X or a class derived from
5787 // X, the implicit conversion sequence is the one required to convert the
5788 // element to the parameter type.
5789 //
5790 // Otherwise, if the parameter type is a character array [... ]
5791 // and the initializer list has a single element that is an
5792 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5793 // implicit conversion sequence is the identity conversion.
5794 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5795 if (ToType->isRecordType() && ToType->isAggregateType()) {
5796 QualType InitType = From->getInit(Init: 0)->getType();
5797 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5798 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5799 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5800 SuppressUserConversions,
5801 InOverloadResolution,
5802 AllowObjCWritebackConversion);
5803 }
5804
5805 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5806 InitializedEntity Entity =
5807 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5808 /*Consumed=*/false);
5809 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5810 Result.setStandard();
5811 Result.Standard.setAsIdentityConversion();
5812 Result.Standard.setFromType(ToType);
5813 Result.Standard.setAllToTypes(ToType);
5814 return Result;
5815 }
5816 }
5817 }
5818
5819 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5820 // C++11 [over.ics.list]p2:
5821 // If the parameter type is std::initializer_list<X> or "array of X" and
5822 // all the elements can be implicitly converted to X, the implicit
5823 // conversion sequence is the worst conversion necessary to convert an
5824 // element of the list to X.
5825 //
5826 // C++14 [over.ics.list]p3:
5827 // Otherwise, if the parameter type is "array of N X", if the initializer
5828 // list has exactly N elements or if it has fewer than N elements and X is
5829 // default-constructible, and if all the elements of the initializer list
5830 // can be implicitly converted to X, the implicit conversion sequence is
5831 // the worst conversion necessary to convert an element of the list to X.
5832 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5833 unsigned e = From->getNumInits();
5834 ImplicitConversionSequence DfltElt;
5835 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5836 ToType: QualType());
5837 QualType ContTy = ToType;
5838 bool IsUnbounded = false;
5839 if (AT) {
5840 InitTy = AT->getElementType();
5841 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5842 if (CT->getSize().ult(RHS: e)) {
5843 // Too many inits, fatally bad
5844 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5845 ToType);
5846 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5847 return Result;
5848 }
5849 if (CT->getSize().ugt(RHS: e)) {
5850 // Need an init from empty {}, is there one?
5851 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5852 From->getEndLoc(), /*isExplicit=*/false);
5853 EmptyList.setType(S.Context.VoidTy);
5854 DfltElt = TryListConversion(
5855 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5856 InOverloadResolution, AllowObjCWritebackConversion);
5857 if (DfltElt.isBad()) {
5858 // No {} init, fatally bad
5859 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5860 ToType);
5861 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5862 return Result;
5863 }
5864 }
5865 } else {
5866 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5867 IsUnbounded = true;
5868 if (!e) {
5869 // Cannot convert to zero-sized.
5870 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5871 ToType);
5872 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5873 return Result;
5874 }
5875 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5876 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5877 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5878 }
5879 }
5880
5881 Result.setStandard();
5882 Result.Standard.setAsIdentityConversion();
5883 Result.Standard.setFromType(InitTy);
5884 Result.Standard.setAllToTypes(InitTy);
5885 for (unsigned i = 0; i < e; ++i) {
5886 Expr *Init = From->getInit(Init: i);
5887 ImplicitConversionSequence ICS = TryCopyInitialization(
5888 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5889 AllowObjCWritebackConversion);
5890
5891 // Keep the worse conversion seen so far.
5892 // FIXME: Sequences are not totally ordered, so 'worse' can be
5893 // ambiguous. CWG has been informed.
5894 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5895 ICS2: Result) ==
5896 ImplicitConversionSequence::Worse) {
5897 Result = ICS;
5898 // Bail as soon as we find something unconvertible.
5899 if (Result.isBad()) {
5900 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5901 return Result;
5902 }
5903 }
5904 }
5905
5906 // If we needed any implicit {} initialization, compare that now.
5907 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5908 // has been informed that this might not be the best thing.
5909 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5910 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5911 ImplicitConversionSequence::Worse)
5912 Result = DfltElt;
5913 // Record the type being initialized so that we may compare sequences
5914 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5915 return Result;
5916 }
5917
5918 // C++14 [over.ics.list]p4:
5919 // C++11 [over.ics.list]p3:
5920 // Otherwise, if the parameter is a non-aggregate class X and overload
5921 // resolution chooses a single best constructor [...] the implicit
5922 // conversion sequence is a user-defined conversion sequence. If multiple
5923 // constructors are viable but none is better than the others, the
5924 // implicit conversion sequence is a user-defined conversion sequence.
5925 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5926 // This function can deal with initializer lists.
5927 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5928 AllowExplicit: AllowedExplicit::None,
5929 InOverloadResolution, /*CStyle=*/false,
5930 AllowObjCWritebackConversion,
5931 /*AllowObjCConversionOnExplicit=*/false);
5932 }
5933
5934 // C++14 [over.ics.list]p5:
5935 // C++11 [over.ics.list]p4:
5936 // Otherwise, if the parameter has an aggregate type which can be
5937 // initialized from the initializer list [...] the implicit conversion
5938 // sequence is a user-defined conversion sequence.
5939 if (ToType->isAggregateType()) {
5940 // Type is an aggregate, argument is an init list. At this point it comes
5941 // down to checking whether the initialization works.
5942 // FIXME: Find out whether this parameter is consumed or not.
5943 InitializedEntity Entity =
5944 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5945 /*Consumed=*/false);
5946 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5947 From)) {
5948 Result.setUserDefined();
5949 Result.UserDefined.Before.setAsIdentityConversion();
5950 // Initializer lists don't have a type.
5951 Result.UserDefined.Before.setFromType(QualType());
5952 Result.UserDefined.Before.setAllToTypes(QualType());
5953
5954 Result.UserDefined.After.setAsIdentityConversion();
5955 Result.UserDefined.After.setFromType(ToType);
5956 Result.UserDefined.After.setAllToTypes(ToType);
5957 Result.UserDefined.ConversionFunction = nullptr;
5958 }
5959 return Result;
5960 }
5961
5962 // C++14 [over.ics.list]p6:
5963 // C++11 [over.ics.list]p5:
5964 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5965 if (ToType->isReferenceType()) {
5966 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5967 // mention initializer lists in any way. So we go by what list-
5968 // initialization would do and try to extrapolate from that.
5969
5970 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5971
5972 // If the initializer list has a single element that is reference-related
5973 // to the parameter type, we initialize the reference from that.
5974 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5975 Expr *Init = From->getInit(Init: 0);
5976
5977 QualType T2 = Init->getType();
5978
5979 // If the initializer is the address of an overloaded function, try
5980 // to resolve the overloaded function. If all goes well, T2 is the
5981 // type of the resulting function.
5982 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5983 DeclAccessPair Found;
5984 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5985 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5986 T2 = Fn->getType();
5987 }
5988
5989 // Compute some basic properties of the types and the initializer.
5990 Sema::ReferenceCompareResult RefRelationship =
5991 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5992
5993 if (RefRelationship >= Sema::Ref_Related) {
5994 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5995 SuppressUserConversions,
5996 /*AllowExplicit=*/false);
5997 }
5998 }
5999
6000 // Otherwise, we bind the reference to a temporary created from the
6001 // initializer list.
6002 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
6003 InOverloadResolution,
6004 AllowObjCWritebackConversion);
6005 if (Result.isFailure())
6006 return Result;
6007 assert(!Result.isEllipsis() &&
6008 "Sub-initialization cannot result in ellipsis conversion.");
6009
6010 // Can we even bind to a temporary?
6011 if (ToType->isRValueReferenceType() ||
6012 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6013 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6014 Result.UserDefined.After;
6015 SCS.ReferenceBinding = true;
6016 SCS.IsLvalueReference = ToType->isLValueReferenceType();
6017 SCS.BindsToRvalue = true;
6018 SCS.BindsToFunctionLvalue = false;
6019 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
6020 SCS.ObjCLifetimeConversionBinding = false;
6021 SCS.FromBracedInitList = false;
6022
6023 } else
6024 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6025 FromExpr: From, ToType);
6026 return Result;
6027 }
6028
6029 // C++14 [over.ics.list]p7:
6030 // C++11 [over.ics.list]p6:
6031 // Otherwise, if the parameter type is not a class:
6032 if (!ToType->isRecordType()) {
6033 // - if the initializer list has one element that is not itself an
6034 // initializer list, the implicit conversion sequence is the one
6035 // required to convert the element to the parameter type.
6036 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6037 // single integer.
6038 unsigned NumInits = From->getNumInits();
6039 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6040 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6041 Result = TryCopyInitialization(
6042 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6043 InOverloadResolution, AllowObjCWritebackConversion);
6044 if (Result.isStandard())
6045 Result.Standard.FromBracedInitList = true;
6046 }
6047 // - if the initializer list has no elements, the implicit conversion
6048 // sequence is the identity conversion.
6049 else if (NumInits == 0) {
6050 Result.setStandard();
6051 Result.Standard.setAsIdentityConversion();
6052 Result.Standard.setFromType(ToType);
6053 Result.Standard.setAllToTypes(ToType);
6054 }
6055 return Result;
6056 }
6057
6058 // C++14 [over.ics.list]p8:
6059 // C++11 [over.ics.list]p7:
6060 // In all cases other than those enumerated above, no conversion is possible
6061 return Result;
6062}
6063
6064/// TryCopyInitialization - Try to copy-initialize a value of type
6065/// ToType from the expression From. Return the implicit conversion
6066/// sequence required to pass this argument, which may be a bad
6067/// conversion sequence (meaning that the argument cannot be passed to
6068/// a parameter of this type). If @p SuppressUserConversions, then we
6069/// do not permit any user-defined conversion sequences.
6070static ImplicitConversionSequence
6071TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6072 bool SuppressUserConversions,
6073 bool InOverloadResolution,
6074 bool AllowObjCWritebackConversion,
6075 bool AllowExplicit) {
6076 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6077 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6078 InOverloadResolution,AllowObjCWritebackConversion);
6079
6080 if (ToType->isReferenceType())
6081 return TryReferenceInit(S, Init: From, DeclType: ToType,
6082 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6083 SuppressUserConversions, AllowExplicit);
6084
6085 return TryImplicitConversion(S, From, ToType,
6086 SuppressUserConversions,
6087 AllowExplicit: AllowedExplicit::None,
6088 InOverloadResolution,
6089 /*CStyle=*/false,
6090 AllowObjCWritebackConversion,
6091 /*AllowObjCConversionOnExplicit=*/false);
6092}
6093
6094static bool TryCopyInitialization(const CanQualType FromQTy,
6095 const CanQualType ToQTy,
6096 Sema &S,
6097 SourceLocation Loc,
6098 ExprValueKind FromVK) {
6099 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6100 ImplicitConversionSequence ICS =
6101 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6102
6103 return !ICS.isBad();
6104}
6105
6106/// TryObjectArgumentInitialization - Try to initialize the object
6107/// parameter of the given member function (@c Method) from the
6108/// expression @p From.
6109static ImplicitConversionSequence TryObjectArgumentInitialization(
6110 Sema &S, SourceLocation Loc, QualType FromType,
6111 Expr::Classification FromClassification, CXXMethodDecl *Method,
6112 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6113 QualType ExplicitParameterType = QualType(),
6114 bool SuppressUserConversion = false) {
6115
6116 // We need to have an object of class type.
6117 if (const auto *PT = FromType->getAs<PointerType>()) {
6118 FromType = PT->getPointeeType();
6119
6120 // When we had a pointer, it's implicitly dereferenced, so we
6121 // better have an lvalue.
6122 assert(FromClassification.isLValue());
6123 }
6124
6125 auto ValueKindFromClassification = [](Expr::Classification C) {
6126 if (C.isPRValue())
6127 return clang::VK_PRValue;
6128 if (C.isXValue())
6129 return VK_XValue;
6130 return clang::VK_LValue;
6131 };
6132
6133 if (Method->isExplicitObjectMemberFunction()) {
6134 if (ExplicitParameterType.isNull())
6135 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6136 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6137 ValueKindFromClassification(FromClassification));
6138 ImplicitConversionSequence ICS = TryCopyInitialization(
6139 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6140 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6141 if (ICS.isBad())
6142 ICS.Bad.FromExpr = nullptr;
6143 return ICS;
6144 }
6145
6146 assert(FromType->isRecordType());
6147
6148 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6149 // C++98 [class.dtor]p2:
6150 // A destructor can be invoked for a const, volatile or const volatile
6151 // object.
6152 // C++98 [over.match.funcs]p4:
6153 // For static member functions, the implicit object parameter is considered
6154 // to match any object (since if the function is selected, the object is
6155 // discarded).
6156 Qualifiers Quals = Method->getMethodQualifiers();
6157 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6158 Quals.addConst();
6159 Quals.addVolatile();
6160 }
6161
6162 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6163
6164 // Set up the conversion sequence as a "bad" conversion, to allow us
6165 // to exit early.
6166 ImplicitConversionSequence ICS;
6167
6168 // C++0x [over.match.funcs]p4:
6169 // For non-static member functions, the type of the implicit object
6170 // parameter is
6171 //
6172 // - "lvalue reference to cv X" for functions declared without a
6173 // ref-qualifier or with the & ref-qualifier
6174 // - "rvalue reference to cv X" for functions declared with the &&
6175 // ref-qualifier
6176 //
6177 // where X is the class of which the function is a member and cv is the
6178 // cv-qualification on the member function declaration.
6179 //
6180 // However, when finding an implicit conversion sequence for the argument, we
6181 // are not allowed to perform user-defined conversions
6182 // (C++ [over.match.funcs]p5). We perform a simplified version of
6183 // reference binding here, that allows class rvalues to bind to
6184 // non-constant references.
6185
6186 // First check the qualifiers.
6187 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6188 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6189 if (ImplicitParamType.getCVRQualifiers() !=
6190 FromTypeCanon.getLocalCVRQualifiers() &&
6191 !ImplicitParamType.isAtLeastAsQualifiedAs(
6192 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6193 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6194 FromType, ToType: ImplicitParamType);
6195 return ICS;
6196 }
6197
6198 if (FromTypeCanon.hasAddressSpace()) {
6199 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6200 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6201 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6202 Ctx: S.getASTContext())) {
6203 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6204 FromType, ToType: ImplicitParamType);
6205 return ICS;
6206 }
6207 }
6208
6209 // Check that we have either the same type or a derived type. It
6210 // affects the conversion rank.
6211 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6212 ImplicitConversionKind SecondKind;
6213 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6214 SecondKind = ICK_Identity;
6215 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6216 SecondKind = ICK_Derived_To_Base;
6217 } else if (!Method->isExplicitObjectMemberFunction()) {
6218 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6219 FromType, ToType: ImplicitParamType);
6220 return ICS;
6221 }
6222
6223 // Check the ref-qualifier.
6224 switch (Method->getRefQualifier()) {
6225 case RQ_None:
6226 // Do nothing; we don't care about lvalueness or rvalueness.
6227 break;
6228
6229 case RQ_LValue:
6230 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6231 // non-const lvalue reference cannot bind to an rvalue
6232 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6233 ToType: ImplicitParamType);
6234 return ICS;
6235 }
6236 break;
6237
6238 case RQ_RValue:
6239 if (!FromClassification.isRValue()) {
6240 // rvalue reference cannot bind to an lvalue
6241 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6242 ToType: ImplicitParamType);
6243 return ICS;
6244 }
6245 break;
6246 }
6247
6248 // Success. Mark this as a reference binding.
6249 ICS.setStandard();
6250 ICS.Standard.setAsIdentityConversion();
6251 ICS.Standard.Second = SecondKind;
6252 ICS.Standard.setFromType(FromType);
6253 ICS.Standard.setAllToTypes(ImplicitParamType);
6254 ICS.Standard.ReferenceBinding = true;
6255 ICS.Standard.DirectBinding = true;
6256 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6257 ICS.Standard.BindsToFunctionLvalue = false;
6258 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6259 ICS.Standard.FromBracedInitList = false;
6260 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6261 = (Method->getRefQualifier() == RQ_None);
6262 return ICS;
6263}
6264
6265/// PerformObjectArgumentInitialization - Perform initialization of
6266/// the implicit object parameter for the given Method with the given
6267/// expression.
6268ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6269 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6270 CXXMethodDecl *Method) {
6271 QualType FromRecordType, DestType;
6272 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6273
6274 Expr::Classification FromClassification;
6275 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6276 FromRecordType = PT->getPointeeType();
6277 DestType = Method->getThisType();
6278 FromClassification = Expr::Classification::makeSimpleLValue();
6279 } else {
6280 FromRecordType = From->getType();
6281 DestType = ImplicitParamRecordType;
6282 FromClassification = From->Classify(Ctx&: Context);
6283
6284 // CWG2813 [expr.call]p6:
6285 // If the function is an implicit object member function, the object
6286 // expression of the class member access shall be a glvalue [...]
6287 if (From->isPRValue()) {
6288 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6289 BoundToLvalueReference: Method->getRefQualifier() !=
6290 RefQualifierKind::RQ_RValue);
6291 }
6292 }
6293
6294 // Note that we always use the true parent context when performing
6295 // the actual argument initialization.
6296 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6297 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6298 ActingContext: Method->getParent());
6299 if (ICS.isBad()) {
6300 switch (ICS.Bad.Kind) {
6301 case BadConversionSequence::bad_qualifiers: {
6302 Qualifiers FromQs = FromRecordType.getQualifiers();
6303 Qualifiers ToQs = DestType.getQualifiers();
6304 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6305 if (CVR) {
6306 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6307 << Method->getDeclName() << FromRecordType << (CVR - 1)
6308 << From->getSourceRange();
6309 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6310 << Method->getDeclName();
6311 return ExprError();
6312 }
6313 break;
6314 }
6315
6316 case BadConversionSequence::lvalue_ref_to_rvalue:
6317 case BadConversionSequence::rvalue_ref_to_lvalue: {
6318 bool IsRValueQualified =
6319 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6320 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6321 << Method->getDeclName() << FromClassification.isRValue()
6322 << IsRValueQualified;
6323 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6324 << Method->getDeclName();
6325 return ExprError();
6326 }
6327
6328 case BadConversionSequence::no_conversion:
6329 case BadConversionSequence::unrelated_class:
6330 break;
6331
6332 case BadConversionSequence::too_few_initializers:
6333 case BadConversionSequence::too_many_initializers:
6334 llvm_unreachable("Lists are not objects");
6335 }
6336
6337 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6338 << ImplicitParamRecordType << FromRecordType
6339 << From->getSourceRange();
6340 }
6341
6342 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6343 ExprResult FromRes =
6344 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6345 if (FromRes.isInvalid())
6346 return ExprError();
6347 From = FromRes.get();
6348 }
6349
6350 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6351 CastKind CK;
6352 QualType PteeTy = DestType->getPointeeType();
6353 LangAS DestAS =
6354 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6355 if (FromRecordType.getAddressSpace() != DestAS)
6356 CK = CK_AddressSpaceConversion;
6357 else
6358 CK = CK_NoOp;
6359 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6360 }
6361 return From;
6362}
6363
6364/// TryContextuallyConvertToBool - Attempt to contextually convert the
6365/// expression From to bool (C++0x [conv]p3).
6366static ImplicitConversionSequence
6367TryContextuallyConvertToBool(Sema &S, Expr *From) {
6368 // C++ [dcl.init]/17.8:
6369 // - Otherwise, if the initialization is direct-initialization, the source
6370 // type is std::nullptr_t, and the destination type is bool, the initial
6371 // value of the object being initialized is false.
6372 if (From->getType()->isNullPtrType())
6373 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6374 DestType: S.Context.BoolTy,
6375 NeedLValToRVal: From->isGLValue());
6376
6377 // All other direct-initialization of bool is equivalent to an implicit
6378 // conversion to bool in which explicit conversions are permitted.
6379 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6380 /*SuppressUserConversions=*/false,
6381 AllowExplicit: AllowedExplicit::Conversions,
6382 /*InOverloadResolution=*/false,
6383 /*CStyle=*/false,
6384 /*AllowObjCWritebackConversion=*/false,
6385 /*AllowObjCConversionOnExplicit=*/false);
6386}
6387
6388ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6389 if (checkPlaceholderForOverload(S&: *this, E&: From))
6390 return ExprError();
6391 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6392 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6393
6394 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6395 if (!ICS.isBad())
6396 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6397 Action: AssignmentAction::Converting);
6398 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6399 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6400 << From->getType() << From->getSourceRange();
6401 return ExprError();
6402}
6403
6404/// Check that the specified conversion is permitted in a converted constant
6405/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6406/// is acceptable.
6407static bool CheckConvertedConstantConversions(Sema &S,
6408 StandardConversionSequence &SCS) {
6409 // Since we know that the target type is an integral or unscoped enumeration
6410 // type, most conversion kinds are impossible. All possible First and Third
6411 // conversions are fine.
6412 switch (SCS.Second) {
6413 case ICK_Identity:
6414 case ICK_Integral_Promotion:
6415 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6416 case ICK_Zero_Queue_Conversion:
6417 return true;
6418
6419 case ICK_Boolean_Conversion:
6420 // Conversion from an integral or unscoped enumeration type to bool is
6421 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6422 // conversion, so we allow it in a converted constant expression.
6423 //
6424 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6425 // a lot of popular code. We should at least add a warning for this
6426 // (non-conforming) extension.
6427 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6428 SCS.getToType(Idx: 2)->isBooleanType();
6429
6430 case ICK_Pointer_Conversion:
6431 case ICK_Pointer_Member:
6432 // C++1z: null pointer conversions and null member pointer conversions are
6433 // only permitted if the source type is std::nullptr_t.
6434 return SCS.getFromType()->isNullPtrType();
6435
6436 case ICK_Floating_Promotion:
6437 case ICK_Complex_Promotion:
6438 case ICK_Floating_Conversion:
6439 case ICK_Complex_Conversion:
6440 case ICK_Floating_Integral:
6441 case ICK_Compatible_Conversion:
6442 case ICK_Derived_To_Base:
6443 case ICK_Vector_Conversion:
6444 case ICK_SVE_Vector_Conversion:
6445 case ICK_RVV_Vector_Conversion:
6446 case ICK_HLSL_Vector_Splat:
6447 case ICK_HLSL_Matrix_Splat:
6448 case ICK_Vector_Splat:
6449 case ICK_Complex_Real:
6450 case ICK_Block_Pointer_Conversion:
6451 case ICK_TransparentUnionConversion:
6452 case ICK_Writeback_Conversion:
6453 case ICK_Zero_Event_Conversion:
6454 case ICK_C_Only_Conversion:
6455 case ICK_Incompatible_Pointer_Conversion:
6456 case ICK_Fixed_Point_Conversion:
6457 case ICK_HLSL_Vector_Truncation:
6458 case ICK_HLSL_Matrix_Truncation:
6459 return false;
6460
6461 case ICK_Lvalue_To_Rvalue:
6462 case ICK_Array_To_Pointer:
6463 case ICK_Function_To_Pointer:
6464 case ICK_HLSL_Array_RValue:
6465 llvm_unreachable("found a first conversion kind in Second");
6466
6467 case ICK_Function_Conversion:
6468 case ICK_Qualification:
6469 llvm_unreachable("found a third conversion kind in Second");
6470
6471 case ICK_Num_Conversion_Kinds:
6472 break;
6473 }
6474
6475 llvm_unreachable("unknown conversion kind");
6476}
6477
6478/// BuildConvertedConstantExpression - Check that the expression From is a
6479/// converted constant expression of type T, perform the conversion but
6480/// does not evaluate the expression
6481static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6482 QualType T, CCEKind CCE,
6483 NamedDecl *Dest,
6484 APValue &PreNarrowingValue) {
6485 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6486 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6487 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6488 "converted constant expression outside C++11 or TTP matching");
6489
6490 if (checkPlaceholderForOverload(S, E&: From))
6491 return ExprError();
6492
6493 if (From->containsErrors()) {
6494 // The expression already has errors, so the correct cast kind can't be
6495 // determined. Use RecoveryExpr to keep the expected type T and mark the
6496 // result as invalid, preventing further cascading errors.
6497 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6498 T);
6499 }
6500
6501 // C++1z [expr.const]p3:
6502 // A converted constant expression of type T is an expression,
6503 // implicitly converted to type T, where the converted
6504 // expression is a constant expression and the implicit conversion
6505 // sequence contains only [... list of conversions ...].
6506 ImplicitConversionSequence ICS =
6507 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6508 ? TryContextuallyConvertToBool(S, From)
6509 : TryCopyInitialization(S, From, ToType: T,
6510 /*SuppressUserConversions=*/false,
6511 /*InOverloadResolution=*/false,
6512 /*AllowObjCWritebackConversion=*/false,
6513 /*AllowExplicit=*/false);
6514 StandardConversionSequence *SCS = nullptr;
6515 switch (ICS.getKind()) {
6516 case ImplicitConversionSequence::StandardConversion:
6517 SCS = &ICS.Standard;
6518 break;
6519 case ImplicitConversionSequence::UserDefinedConversion:
6520 if (T->isRecordType())
6521 SCS = &ICS.UserDefined.Before;
6522 else
6523 SCS = &ICS.UserDefined.After;
6524 break;
6525 case ImplicitConversionSequence::AmbiguousConversion:
6526 case ImplicitConversionSequence::BadConversion:
6527 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6528 return S.Diag(Loc: From->getBeginLoc(),
6529 DiagID: diag::err_typecheck_converted_constant_expression)
6530 << From->getType() << From->getSourceRange() << T;
6531 return ExprError();
6532
6533 case ImplicitConversionSequence::EllipsisConversion:
6534 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6535 llvm_unreachable("bad conversion in converted constant expression");
6536 }
6537
6538 // Check that we would only use permitted conversions.
6539 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6540 return S.Diag(Loc: From->getBeginLoc(),
6541 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6542 << From->getType() << From->getSourceRange() << T;
6543 }
6544 // [...] and where the reference binding (if any) binds directly.
6545 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6546 return S.Diag(Loc: From->getBeginLoc(),
6547 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6548 << From->getType() << From->getSourceRange() << T;
6549 }
6550 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6551 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6552 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6553 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6554 // case explicitly.
6555 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6556 return S.Diag(Loc: From->getBeginLoc(),
6557 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6558 << From->getSourceRange();
6559 }
6560
6561 // Usually we can simply apply the ImplicitConversionSequence we formed
6562 // earlier, but that's not guaranteed to work when initializing an object of
6563 // class type.
6564 ExprResult Result;
6565 bool IsTemplateArgument =
6566 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6567 if (T->isRecordType()) {
6568 assert(IsTemplateArgument &&
6569 "unexpected class type converted constant expr");
6570 Result = S.PerformCopyInitialization(
6571 Entity: InitializedEntity::InitializeTemplateParameter(
6572 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6573 EqualLoc: SourceLocation(), Init: From);
6574 } else {
6575 Result =
6576 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6577 }
6578 if (Result.isInvalid())
6579 return Result;
6580
6581 // C++2a [intro.execution]p5:
6582 // A full-expression is [...] a constant-expression [...]
6583 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6584 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6585 IsTemplateArgument);
6586 if (Result.isInvalid())
6587 return Result;
6588
6589 // Check for a narrowing implicit conversion.
6590 bool ReturnPreNarrowingValue = false;
6591 QualType PreNarrowingType;
6592 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6593 ConstantType&: PreNarrowingType)) {
6594 case NK_Variable_Narrowing:
6595 // Implicit conversion to a narrower type, and the value is not a constant
6596 // expression. We'll diagnose this in a moment.
6597 case NK_Not_Narrowing:
6598 break;
6599
6600 case NK_Constant_Narrowing:
6601 if (CCE == CCEKind::ArrayBound &&
6602 PreNarrowingType->isIntegralOrEnumerationType() &&
6603 PreNarrowingValue.isInt()) {
6604 // Don't diagnose array bound narrowing here; we produce more precise
6605 // errors by allowing the un-narrowed value through.
6606 ReturnPreNarrowingValue = true;
6607 break;
6608 }
6609 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6610 << CCE << /*Constant*/ 1
6611 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6612 // If this is an SFINAE Context, treat the result as invalid so it stops
6613 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6614 // FIXME: Should do this whenever the above diagnostic is an error, but
6615 // without further changes this would degrade some other diagnostics.
6616 if (S.isSFINAEContext())
6617 return ExprError();
6618 break;
6619
6620 case NK_Dependent_Narrowing:
6621 // Implicit conversion to a narrower type, but the expression is
6622 // value-dependent so we can't tell whether it's actually narrowing.
6623 // For matching the parameters of a TTP, the conversion is ill-formed
6624 // if it may narrow.
6625 if (CCE != CCEKind::TempArgStrict)
6626 break;
6627 [[fallthrough]];
6628 case NK_Type_Narrowing:
6629 // FIXME: It would be better to diagnose that the expression is not a
6630 // constant expression.
6631 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6632 << CCE << /*Constant*/ 0 << From->getType() << T;
6633 if (S.isSFINAEContext())
6634 return ExprError();
6635 break;
6636 }
6637 if (!ReturnPreNarrowingValue)
6638 PreNarrowingValue = {};
6639
6640 return Result;
6641}
6642
6643/// CheckConvertedConstantExpression - Check that the expression From is a
6644/// converted constant expression of type T, perform the conversion and produce
6645/// the converted expression, per C++11 [expr.const]p3.
6646static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6647 QualType T, APValue &Value,
6648 CCEKind CCE, bool RequireInt,
6649 NamedDecl *Dest) {
6650
6651 APValue PreNarrowingValue;
6652 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6653 PreNarrowingValue);
6654 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6655 Value = APValue();
6656 return Result;
6657 }
6658 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6659 RequireInt, PreNarrowingValue);
6660}
6661
6662ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6663 CCEKind CCE,
6664 NamedDecl *Dest) {
6665 APValue PreNarrowingValue;
6666 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6667 PreNarrowingValue);
6668}
6669
6670ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6671 APValue &Value, CCEKind CCE,
6672 NamedDecl *Dest) {
6673 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6674 Dest);
6675}
6676
6677ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6678 llvm::APSInt &Value,
6679 CCEKind CCE) {
6680 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6681
6682 APValue V;
6683 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6684 /*Dest=*/nullptr);
6685 if (!R.isInvalid() && !R.get()->isValueDependent())
6686 Value = V.getInt();
6687 return R;
6688}
6689
6690ExprResult
6691Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6692 CCEKind CCE, bool RequireInt,
6693 const APValue &PreNarrowingValue) {
6694
6695 ExprResult Result = E;
6696 // Check the expression is a constant expression.
6697 SmallVector<PartialDiagnosticAt, 8> Notes;
6698 Expr::EvalResult Eval;
6699 Eval.Diag = &Notes;
6700
6701 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6702
6703 ConstantExprKind Kind;
6704 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6705 Kind = ConstantExprKind::ClassTemplateArgument;
6706 else if (CCE == CCEKind::TemplateArg)
6707 Kind = ConstantExprKind::NonClassTemplateArgument;
6708 else
6709 Kind = ConstantExprKind::Normal;
6710
6711 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6712 (RequireInt && !Eval.Val.isInt())) {
6713 // The expression can't be folded, so we can't keep it at this position in
6714 // the AST.
6715 Result = ExprError();
6716 } else {
6717 Value = Eval.Val;
6718
6719 if (Notes.empty()) {
6720 // It's a constant expression.
6721 Expr *E = Result.get();
6722 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6723 // We expect a ConstantExpr to have a value associated with it
6724 // by this point.
6725 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6726 "ConstantExpr has no value associated with it");
6727 (void)CE;
6728 } else {
6729 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6730 }
6731 if (!PreNarrowingValue.isAbsent())
6732 Value = std::move(PreNarrowingValue);
6733 return E;
6734 }
6735 }
6736
6737 // It's not a constant expression. Produce an appropriate diagnostic.
6738 if (Notes.size() == 1 &&
6739 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6740 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6741 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6742 diag::note_constexpr_invalid_template_arg) {
6743 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6744 for (unsigned I = 0; I < Notes.size(); ++I)
6745 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6746 } else {
6747 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6748 << CCE << E->getSourceRange();
6749 for (unsigned I = 0; I < Notes.size(); ++I)
6750 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6751 }
6752 return ExprError();
6753}
6754
6755/// dropPointerConversions - If the given standard conversion sequence
6756/// involves any pointer conversions, remove them. This may change
6757/// the result type of the conversion sequence.
6758static void dropPointerConversion(StandardConversionSequence &SCS) {
6759 if (SCS.Second == ICK_Pointer_Conversion) {
6760 SCS.Second = ICK_Identity;
6761 SCS.Dimension = ICK_Identity;
6762 SCS.Third = ICK_Identity;
6763 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6764 }
6765}
6766
6767/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6768/// convert the expression From to an Objective-C pointer type.
6769static ImplicitConversionSequence
6770TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6771 // Do an implicit conversion to 'id'.
6772 QualType Ty = S.Context.getObjCIdType();
6773 ImplicitConversionSequence ICS
6774 = TryImplicitConversion(S, From, ToType: Ty,
6775 // FIXME: Are these flags correct?
6776 /*SuppressUserConversions=*/false,
6777 AllowExplicit: AllowedExplicit::Conversions,
6778 /*InOverloadResolution=*/false,
6779 /*CStyle=*/false,
6780 /*AllowObjCWritebackConversion=*/false,
6781 /*AllowObjCConversionOnExplicit=*/true);
6782
6783 // Strip off any final conversions to 'id'.
6784 switch (ICS.getKind()) {
6785 case ImplicitConversionSequence::BadConversion:
6786 case ImplicitConversionSequence::AmbiguousConversion:
6787 case ImplicitConversionSequence::EllipsisConversion:
6788 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6789 break;
6790
6791 case ImplicitConversionSequence::UserDefinedConversion:
6792 dropPointerConversion(SCS&: ICS.UserDefined.After);
6793 break;
6794
6795 case ImplicitConversionSequence::StandardConversion:
6796 dropPointerConversion(SCS&: ICS.Standard);
6797 break;
6798 }
6799
6800 return ICS;
6801}
6802
6803ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6804 if (checkPlaceholderForOverload(S&: *this, E&: From))
6805 return ExprError();
6806
6807 QualType Ty = Context.getObjCIdType();
6808 ImplicitConversionSequence ICS =
6809 TryContextuallyConvertToObjCPointer(S&: *this, From);
6810 if (!ICS.isBad())
6811 return PerformImplicitConversion(From, ToType: Ty, ICS,
6812 Action: AssignmentAction::Converting);
6813 return ExprResult();
6814}
6815
6816static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6817 const Expr *Base = nullptr;
6818 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6819 "expected a member expression");
6820
6821 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6822 M && !M->isImplicitAccess())
6823 Base = M->getBase();
6824 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6825 M && !M->isImplicitAccess())
6826 Base = M->getBase();
6827
6828 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6829
6830 if (T->isPointerType())
6831 T = T->getPointeeType();
6832
6833 return T;
6834}
6835
6836static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6837 const FunctionDecl *Fun) {
6838 QualType ObjType = Obj->getType();
6839 if (ObjType->isPointerType()) {
6840 ObjType = ObjType->getPointeeType();
6841 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6842 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6843 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6844 }
6845 return Obj;
6846}
6847
6848ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6849 FunctionDecl *Fun) {
6850 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6851 return S.PerformCopyInitialization(
6852 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6853 EqualLoc: Obj->getExprLoc(), Init: Obj);
6854}
6855
6856static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6857 Expr *Object, MultiExprArg &Args,
6858 SmallVectorImpl<Expr *> &NewArgs) {
6859 assert(Method->isExplicitObjectMemberFunction() &&
6860 "Method is not an explicit member function");
6861 assert(NewArgs.empty() && "NewArgs should be empty");
6862
6863 NewArgs.reserve(N: Args.size() + 1);
6864 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6865 NewArgs.push_back(Elt: This);
6866 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6867 Args = NewArgs;
6868 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6869 Method, CallLoc: Object->getBeginLoc());
6870}
6871
6872/// Determine whether the provided type is an integral type, or an enumeration
6873/// type of a permitted flavor.
6874bool Sema::ICEConvertDiagnoser::match(QualType T) {
6875 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6876 : T->isIntegralOrUnscopedEnumerationType();
6877}
6878
6879static ExprResult
6880diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6881 Sema::ContextualImplicitConverter &Converter,
6882 QualType T, UnresolvedSetImpl &ViableConversions) {
6883
6884 if (Converter.Suppress)
6885 return ExprError();
6886
6887 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6888 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6889 CXXConversionDecl *Conv =
6890 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6891 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6892 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6893 }
6894 return From;
6895}
6896
6897static bool
6898diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6899 Sema::ContextualImplicitConverter &Converter,
6900 QualType T, bool HadMultipleCandidates,
6901 UnresolvedSetImpl &ExplicitConversions) {
6902 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6903 DeclAccessPair Found = ExplicitConversions[0];
6904 CXXConversionDecl *Conversion =
6905 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6906
6907 // The user probably meant to invoke the given explicit
6908 // conversion; use it.
6909 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6910 std::string TypeStr;
6911 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6912
6913 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6914 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6915 Code: "static_cast<" + TypeStr + ">(")
6916 << FixItHint::CreateInsertion(
6917 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6918 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6919
6920 // If we aren't in a SFINAE context, build a call to the
6921 // explicit conversion function.
6922 if (SemaRef.isSFINAEContext())
6923 return true;
6924
6925 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6926 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6927 HadMultipleCandidates);
6928 if (Result.isInvalid())
6929 return true;
6930
6931 // Replace the conversion with a RecoveryExpr, so we don't try to
6932 // instantiate it later, but can further diagnose here.
6933 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6934 SubExprs: From, T: Result.get()->getType());
6935 if (Result.isInvalid())
6936 return true;
6937 From = Result.get();
6938 }
6939 return false;
6940}
6941
6942static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6943 Sema::ContextualImplicitConverter &Converter,
6944 QualType T, bool HadMultipleCandidates,
6945 DeclAccessPair &Found) {
6946 CXXConversionDecl *Conversion =
6947 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6948 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6949
6950 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6951 if (!Converter.SuppressConversion) {
6952 if (SemaRef.isSFINAEContext())
6953 return true;
6954
6955 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6956 << From->getSourceRange();
6957 }
6958
6959 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6960 HadMultipleCandidates);
6961 if (Result.isInvalid())
6962 return true;
6963 // Record usage of conversion in an implicit cast.
6964 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6965 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6966 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6967 FPO: SemaRef.CurFPFeatureOverrides());
6968 return false;
6969}
6970
6971static ExprResult finishContextualImplicitConversion(
6972 Sema &SemaRef, SourceLocation Loc, Expr *From,
6973 Sema::ContextualImplicitConverter &Converter) {
6974 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6975 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6976 << From->getSourceRange();
6977
6978 return SemaRef.DefaultLvalueConversion(E: From);
6979}
6980
6981static void
6982collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6983 UnresolvedSetImpl &ViableConversions,
6984 OverloadCandidateSet &CandidateSet) {
6985 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6986 NamedDecl *D = FoundDecl.getDecl();
6987 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6988 if (isa<UsingShadowDecl>(Val: D))
6989 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6990
6991 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6992 SemaRef.AddTemplateConversionCandidate(
6993 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6994 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6995 continue;
6996 }
6997 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6998 SemaRef.AddConversionCandidate(
6999 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7000 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7001 }
7002}
7003
7004/// Attempt to convert the given expression to a type which is accepted
7005/// by the given converter.
7006///
7007/// This routine will attempt to convert an expression of class type to a
7008/// type accepted by the specified converter. In C++11 and before, the class
7009/// must have a single non-explicit conversion function converting to a matching
7010/// type. In C++1y, there can be multiple such conversion functions, but only
7011/// one target type.
7012///
7013/// \param Loc The source location of the construct that requires the
7014/// conversion.
7015///
7016/// \param From The expression we're converting from.
7017///
7018/// \param Converter Used to control and diagnose the conversion process.
7019///
7020/// \returns The expression, converted to an integral or enumeration type if
7021/// successful.
7022ExprResult Sema::PerformContextualImplicitConversion(
7023 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7024 // We can't perform any more checking for type-dependent expressions.
7025 if (From->isTypeDependent())
7026 return From;
7027
7028 // Process placeholders immediately.
7029 if (From->hasPlaceholderType()) {
7030 ExprResult result = CheckPlaceholderExpr(E: From);
7031 if (result.isInvalid())
7032 return result;
7033 From = result.get();
7034 }
7035
7036 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7037 ExprResult Converted = DefaultLvalueConversion(E: From);
7038 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7039 From = Converted.isUsable() ? Converted.get() : nullptr;
7040 // If the expression already has a matching type, we're golden.
7041 if (Converter.match(T))
7042 return Converted;
7043
7044 // FIXME: Check for missing '()' if T is a function type?
7045
7046 // We can only perform contextual implicit conversions on objects of class
7047 // type.
7048 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7049 if (!RecordTy || !getLangOpts().CPlusPlus) {
7050 if (!Converter.Suppress)
7051 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7052 return From;
7053 }
7054
7055 // We must have a complete class type.
7056 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7057 ContextualImplicitConverter &Converter;
7058 Expr *From;
7059
7060 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7061 : Converter(Converter), From(From) {}
7062
7063 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7064 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7065 }
7066 } IncompleteDiagnoser(Converter, From);
7067
7068 if (Converter.Suppress ? !isCompleteType(Loc, T)
7069 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7070 return From;
7071
7072 // Look for a conversion to an integral or enumeration type.
7073 UnresolvedSet<4>
7074 ViableConversions; // These are *potentially* viable in C++1y.
7075 UnresolvedSet<4> ExplicitConversions;
7076 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7077 ->getDefinitionOrSelf()
7078 ->getVisibleConversionFunctions();
7079
7080 bool HadMultipleCandidates =
7081 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7082
7083 // To check that there is only one target type, in C++1y:
7084 QualType ToType;
7085 bool HasUniqueTargetType = true;
7086
7087 // Collect explicit or viable (potentially in C++1y) conversions.
7088 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7089 NamedDecl *D = (*I)->getUnderlyingDecl();
7090 CXXConversionDecl *Conversion;
7091 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7092 if (ConvTemplate) {
7093 if (getLangOpts().CPlusPlus14)
7094 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7095 else
7096 continue; // C++11 does not consider conversion operator templates(?).
7097 } else
7098 Conversion = cast<CXXConversionDecl>(Val: D);
7099
7100 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7101 "Conversion operator templates are considered potentially "
7102 "viable in C++1y");
7103
7104 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7105 if (Converter.match(T: CurToType) || ConvTemplate) {
7106
7107 if (Conversion->isExplicit()) {
7108 // FIXME: For C++1y, do we need this restriction?
7109 // cf. diagnoseNoViableConversion()
7110 if (!ConvTemplate)
7111 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7112 } else {
7113 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7114 if (ToType.isNull())
7115 ToType = CurToType.getUnqualifiedType();
7116 else if (HasUniqueTargetType &&
7117 (CurToType.getUnqualifiedType() != ToType))
7118 HasUniqueTargetType = false;
7119 }
7120 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7121 }
7122 }
7123 }
7124
7125 if (getLangOpts().CPlusPlus14) {
7126 // C++1y [conv]p6:
7127 // ... An expression e of class type E appearing in such a context
7128 // is said to be contextually implicitly converted to a specified
7129 // type T and is well-formed if and only if e can be implicitly
7130 // converted to a type T that is determined as follows: E is searched
7131 // for conversion functions whose return type is cv T or reference to
7132 // cv T such that T is allowed by the context. There shall be
7133 // exactly one such T.
7134
7135 // If no unique T is found:
7136 if (ToType.isNull()) {
7137 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7138 HadMultipleCandidates,
7139 ExplicitConversions))
7140 return ExprError();
7141 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7142 }
7143
7144 // If more than one unique Ts are found:
7145 if (!HasUniqueTargetType)
7146 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7147 ViableConversions);
7148
7149 // If one unique T is found:
7150 // First, build a candidate set from the previously recorded
7151 // potentially viable conversions.
7152 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7153 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7154 CandidateSet);
7155
7156 // Then, perform overload resolution over the candidate set.
7157 OverloadCandidateSet::iterator Best;
7158 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7159 case OR_Success: {
7160 // Apply this conversion.
7161 DeclAccessPair Found =
7162 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7163 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7164 HadMultipleCandidates, Found))
7165 return ExprError();
7166 break;
7167 }
7168 case OR_Ambiguous:
7169 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7170 ViableConversions);
7171 case OR_No_Viable_Function:
7172 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7173 HadMultipleCandidates,
7174 ExplicitConversions))
7175 return ExprError();
7176 [[fallthrough]];
7177 case OR_Deleted:
7178 // We'll complain below about a non-integral condition type.
7179 break;
7180 }
7181 } else {
7182 switch (ViableConversions.size()) {
7183 case 0: {
7184 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7185 HadMultipleCandidates,
7186 ExplicitConversions))
7187 return ExprError();
7188
7189 // We'll complain below about a non-integral condition type.
7190 break;
7191 }
7192 case 1: {
7193 // Apply this conversion.
7194 DeclAccessPair Found = ViableConversions[0];
7195 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7196 HadMultipleCandidates, Found))
7197 return ExprError();
7198 break;
7199 }
7200 default:
7201 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7202 ViableConversions);
7203 }
7204 }
7205
7206 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7207}
7208
7209/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7210/// an acceptable non-member overloaded operator for a call whose
7211/// arguments have types T1 (and, if non-empty, T2). This routine
7212/// implements the check in C++ [over.match.oper]p3b2 concerning
7213/// enumeration types.
7214static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7215 FunctionDecl *Fn,
7216 ArrayRef<Expr *> Args) {
7217 QualType T1 = Args[0]->getType();
7218 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7219
7220 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7221 return true;
7222
7223 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7224 return true;
7225
7226 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7227 if (Proto->getNumParams() < 1)
7228 return false;
7229
7230 if (T1->isEnumeralType()) {
7231 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7232 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7233 return true;
7234 }
7235
7236 if (Proto->getNumParams() < 2)
7237 return false;
7238
7239 if (!T2.isNull() && T2->isEnumeralType()) {
7240 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7241 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7242 return true;
7243 }
7244
7245 return false;
7246}
7247
7248static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7249 if (FD->isTargetMultiVersionDefault())
7250 return false;
7251
7252 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7253 return FD->isTargetMultiVersion();
7254
7255 if (!FD->isMultiVersion())
7256 return false;
7257
7258 // Among multiple target versions consider either the default,
7259 // or the first non-default in the absence of default version.
7260 unsigned SeenAt = 0;
7261 unsigned I = 0;
7262 bool HasDefault = false;
7263 FD->getASTContext().forEachMultiversionedFunctionVersion(
7264 FD, Pred: [&](const FunctionDecl *CurFD) {
7265 if (FD == CurFD)
7266 SeenAt = I;
7267 else if (CurFD->isTargetMultiVersionDefault())
7268 HasDefault = true;
7269 ++I;
7270 });
7271 return HasDefault || SeenAt != 0;
7272}
7273
7274void Sema::AddOverloadCandidate(
7275 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7276 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7277 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7278 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7279 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7280 bool StrictPackMatch) {
7281 const FunctionProtoType *Proto
7282 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7283 assert(Proto && "Functions without a prototype cannot be overloaded");
7284 assert(!Function->getDescribedFunctionTemplate() &&
7285 "Use AddTemplateOverloadCandidate for function templates");
7286
7287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7288 if (!isa<CXXConstructorDecl>(Val: Method)) {
7289 // If we get here, it's because we're calling a member function
7290 // that is named without a member access expression (e.g.,
7291 // "this->f") that was either written explicitly or created
7292 // implicitly. This can happen with a qualified call to a member
7293 // function, e.g., X::f(). We use an empty type for the implied
7294 // object argument (C++ [over.call.func]p3), and the acting context
7295 // is irrelevant.
7296 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7297 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7298 CandidateSet, SuppressUserConversions,
7299 PartialOverloading, EarlyConversions, PO,
7300 StrictPackMatch);
7301 return;
7302 }
7303 // We treat a constructor like a non-member function, since its object
7304 // argument doesn't participate in overload resolution.
7305 }
7306
7307 if (!CandidateSet.isNewCandidate(F: Function, PO))
7308 return;
7309
7310 // C++11 [class.copy]p11: [DR1402]
7311 // A defaulted move constructor that is defined as deleted is ignored by
7312 // overload resolution.
7313 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7314 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7315 Constructor->isMoveConstructor())
7316 return;
7317
7318 // Overload resolution is always an unevaluated context.
7319 EnterExpressionEvaluationContext Unevaluated(
7320 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7321
7322 // C++ [over.match.oper]p3:
7323 // if no operand has a class type, only those non-member functions in the
7324 // lookup set that have a first parameter of type T1 or "reference to
7325 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7326 // is a right operand) a second parameter of type T2 or "reference to
7327 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7328 // candidate functions.
7329 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7330 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7331 return;
7332
7333 // Add this candidate
7334 OverloadCandidate &Candidate =
7335 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7336 Candidate.FoundDecl = FoundDecl;
7337 Candidate.Function = Function;
7338 Candidate.Viable = true;
7339 Candidate.RewriteKind =
7340 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7341 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7342 Candidate.ExplicitCallArguments = Args.size();
7343 Candidate.StrictPackMatch = StrictPackMatch;
7344
7345 // Explicit functions are not actually candidates at all if we're not
7346 // allowing them in this context, but keep them around so we can point
7347 // to them in diagnostics.
7348 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7349 Candidate.Viable = false;
7350 Candidate.FailureKind = ovl_fail_explicit;
7351 return;
7352 }
7353
7354 // Functions with internal linkage are only viable in the same module unit.
7355 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7356 /// FIXME: Currently, the semantics of linkage in clang is slightly
7357 /// different from the semantics in C++ spec. In C++ spec, only names
7358 /// have linkage. So that all entities of the same should share one
7359 /// linkage. But in clang, different entities of the same could have
7360 /// different linkage.
7361 const NamedDecl *ND = Function;
7362 bool IsImplicitlyInstantiated = false;
7363 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7364 ND = SpecInfo->getTemplate();
7365 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7366 TSK_ImplicitInstantiation;
7367 }
7368
7369 /// Don't remove inline functions with internal linkage from the overload
7370 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7371 /// However:
7372 /// - Inline functions with internal linkage are a common pattern in
7373 /// headers to avoid ODR issues.
7374 /// - The global module is meant to be a transition mechanism for C and C++
7375 /// headers, and the current rules as written work against that goal.
7376 const bool IsInlineFunctionInGMF =
7377 Function->isFromGlobalModule() &&
7378 (IsImplicitlyInstantiated || Function->isInlined());
7379
7380 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7381 Candidate.Viable = false;
7382 Candidate.FailureKind = ovl_fail_module_mismatched;
7383 return;
7384 }
7385 }
7386
7387 if (isNonViableMultiVersionOverload(FD: Function)) {
7388 Candidate.Viable = false;
7389 Candidate.FailureKind = ovl_non_default_multiversion_function;
7390 return;
7391 }
7392
7393 if (Constructor) {
7394 // C++ [class.copy]p3:
7395 // A member function template is never instantiated to perform the copy
7396 // of a class object to an object of its class type.
7397 CanQualType ClassType =
7398 Context.getCanonicalTagType(TD: Constructor->getParent());
7399 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7400 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7401 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7402 Base: ClassType))) {
7403 Candidate.Viable = false;
7404 Candidate.FailureKind = ovl_fail_illegal_constructor;
7405 return;
7406 }
7407
7408 // C++ [over.match.funcs]p8: (proposed DR resolution)
7409 // A constructor inherited from class type C that has a first parameter
7410 // of type "reference to P" (including such a constructor instantiated
7411 // from a template) is excluded from the set of candidate functions when
7412 // constructing an object of type cv D if the argument list has exactly
7413 // one argument and D is reference-related to P and P is reference-related
7414 // to C.
7415 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7416 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7417 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7418 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7419 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7420 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7421 SourceLocation Loc = Args.front()->getExprLoc();
7422 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7423 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7424 Candidate.Viable = false;
7425 Candidate.FailureKind = ovl_fail_inhctor_slice;
7426 return;
7427 }
7428 }
7429
7430 // Check that the constructor is capable of constructing an object in the
7431 // destination address space.
7432 if (!Qualifiers::isAddressSpaceSupersetOf(
7433 A: Constructor->getMethodQualifiers().getAddressSpace(),
7434 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7435 Candidate.Viable = false;
7436 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7437 }
7438 }
7439
7440 unsigned NumParams = Proto->getNumParams();
7441
7442 // (C++ 13.3.2p2): A candidate function having fewer than m
7443 // parameters is viable only if it has an ellipsis in its parameter
7444 // list (8.3.5).
7445 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7446 !Proto->isVariadic() &&
7447 shouldEnforceArgLimit(PartialOverloading, Function)) {
7448 Candidate.Viable = false;
7449 Candidate.FailureKind = ovl_fail_too_many_arguments;
7450 return;
7451 }
7452
7453 // (C++ 13.3.2p2): A candidate function having more than m parameters
7454 // is viable only if the (m+1)st parameter has a default argument
7455 // (8.3.6). For the purposes of overload resolution, the
7456 // parameter list is truncated on the right, so that there are
7457 // exactly m parameters.
7458 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7459 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7460 !PartialOverloading) {
7461 // Not enough arguments.
7462 Candidate.Viable = false;
7463 Candidate.FailureKind = ovl_fail_too_few_arguments;
7464 return;
7465 }
7466
7467 // (CUDA B.1): Check for invalid calls between targets.
7468 if (getLangOpts().CUDA) {
7469 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7470 // Skip the check for callers that are implicit members, because in this
7471 // case we may not yet know what the member's target is; the target is
7472 // inferred for the member automatically, based on the bases and fields of
7473 // the class.
7474 if (!(Caller && Caller->isImplicit()) &&
7475 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7476 Candidate.Viable = false;
7477 Candidate.FailureKind = ovl_fail_bad_target;
7478 return;
7479 }
7480 }
7481
7482 if (Function->getTrailingRequiresClause()) {
7483 ConstraintSatisfaction Satisfaction;
7484 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7485 /*ForOverloadResolution*/ true) ||
7486 !Satisfaction.IsSatisfied) {
7487 Candidate.Viable = false;
7488 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7489 return;
7490 }
7491 }
7492
7493 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7494 // Determine the implicit conversion sequences for each of the
7495 // arguments.
7496 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7497 unsigned ConvIdx =
7498 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7499 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7500 // We already formed a conversion sequence for this parameter during
7501 // template argument deduction.
7502 } else if (ArgIdx < NumParams) {
7503 // (C++ 13.3.2p3): for F to be a viable function, there shall
7504 // exist for each argument an implicit conversion sequence
7505 // (13.3.3.1) that converts that argument to the corresponding
7506 // parameter of F.
7507 QualType ParamType = Proto->getParamType(i: ArgIdx);
7508 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7509 if (ParamABI == ParameterABI::HLSLOut ||
7510 ParamABI == ParameterABI::HLSLInOut) {
7511 ParamType = ParamType.getNonReferenceType();
7512 if (ParamABI == ParameterABI::HLSLInOut &&
7513 Args[ArgIdx]->getType().getAddressSpace() ==
7514 LangAS::hlsl_groupshared)
7515 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7516 }
7517 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7518 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7519 /*InOverloadResolution=*/true,
7520 /*AllowObjCWritebackConversion=*/
7521 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7522 if (Candidate.Conversions[ConvIdx].isBad()) {
7523 Candidate.Viable = false;
7524 Candidate.FailureKind = ovl_fail_bad_conversion;
7525 return;
7526 }
7527 } else {
7528 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7529 // argument for which there is no corresponding parameter is
7530 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7531 Candidate.Conversions[ConvIdx].setEllipsis();
7532 }
7533 }
7534
7535 if (EnableIfAttr *FailedAttr =
7536 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7537 Candidate.Viable = false;
7538 Candidate.FailureKind = ovl_fail_enable_if;
7539 Candidate.DeductionFailure.Data = FailedAttr;
7540 return;
7541 }
7542}
7543
7544ObjCMethodDecl *
7545Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7546 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7547 if (Methods.size() <= 1)
7548 return nullptr;
7549
7550 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7551 bool Match = true;
7552 ObjCMethodDecl *Method = Methods[b];
7553 unsigned NumNamedArgs = Sel.getNumArgs();
7554 // Method might have more arguments than selector indicates. This is due
7555 // to addition of c-style arguments in method.
7556 if (Method->param_size() > NumNamedArgs)
7557 NumNamedArgs = Method->param_size();
7558 if (Args.size() < NumNamedArgs)
7559 continue;
7560
7561 for (unsigned i = 0; i < NumNamedArgs; i++) {
7562 // We can't do any type-checking on a type-dependent argument.
7563 if (Args[i]->isTypeDependent()) {
7564 Match = false;
7565 break;
7566 }
7567
7568 ParmVarDecl *param = Method->parameters()[i];
7569 Expr *argExpr = Args[i];
7570 assert(argExpr && "SelectBestMethod(): missing expression");
7571
7572 // Strip the unbridged-cast placeholder expression off unless it's
7573 // a consumed argument.
7574 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7575 !param->hasAttr<CFConsumedAttr>())
7576 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7577
7578 // If the parameter is __unknown_anytype, move on to the next method.
7579 if (param->getType() == Context.UnknownAnyTy) {
7580 Match = false;
7581 break;
7582 }
7583
7584 ImplicitConversionSequence ConversionState
7585 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7586 /*SuppressUserConversions*/false,
7587 /*InOverloadResolution=*/true,
7588 /*AllowObjCWritebackConversion=*/
7589 getLangOpts().ObjCAutoRefCount,
7590 /*AllowExplicit*/false);
7591 // This function looks for a reasonably-exact match, so we consider
7592 // incompatible pointer conversions to be a failure here.
7593 if (ConversionState.isBad() ||
7594 (ConversionState.isStandard() &&
7595 ConversionState.Standard.Second ==
7596 ICK_Incompatible_Pointer_Conversion)) {
7597 Match = false;
7598 break;
7599 }
7600 }
7601 // Promote additional arguments to variadic methods.
7602 if (Match && Method->isVariadic()) {
7603 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7604 if (Args[i]->isTypeDependent()) {
7605 Match = false;
7606 break;
7607 }
7608 ExprResult Arg = DefaultVariadicArgumentPromotion(
7609 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7610 if (Arg.isInvalid()) {
7611 Match = false;
7612 break;
7613 }
7614 }
7615 } else {
7616 // Check for extra arguments to non-variadic methods.
7617 if (Args.size() != NumNamedArgs)
7618 Match = false;
7619 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7620 // Special case when selectors have no argument. In this case, select
7621 // one with the most general result type of 'id'.
7622 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7623 QualType ReturnT = Methods[b]->getReturnType();
7624 if (ReturnT->isObjCIdType())
7625 return Methods[b];
7626 }
7627 }
7628 }
7629
7630 if (Match)
7631 return Method;
7632 }
7633 return nullptr;
7634}
7635
7636static bool convertArgsForAvailabilityChecks(
7637 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7638 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7639 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7640 if (ThisArg) {
7641 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7642 assert(!isa<CXXConstructorDecl>(Method) &&
7643 "Shouldn't have `this` for ctors!");
7644 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7645 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7646 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7647 if (R.isInvalid())
7648 return false;
7649 ConvertedThis = R.get();
7650 } else {
7651 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7652 (void)MD;
7653 assert((MissingImplicitThis || MD->isStatic() ||
7654 isa<CXXConstructorDecl>(MD)) &&
7655 "Expected `this` for non-ctor instance methods");
7656 }
7657 ConvertedThis = nullptr;
7658 }
7659
7660 // Ignore any variadic arguments. Converting them is pointless, since the
7661 // user can't refer to them in the function condition.
7662 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7663
7664 // Convert the arguments.
7665 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7666 ExprResult R;
7667 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7668 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7669 EqualLoc: SourceLocation(), Init: Args[I]);
7670
7671 if (R.isInvalid())
7672 return false;
7673
7674 ConvertedArgs.push_back(Elt: R.get());
7675 }
7676
7677 if (Trap.hasErrorOccurred())
7678 return false;
7679
7680 // Push default arguments if needed.
7681 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7682 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7683 ParmVarDecl *P = Function->getParamDecl(i);
7684 if (!P->hasDefaultArg())
7685 return false;
7686 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7687 if (R.isInvalid())
7688 return false;
7689 ConvertedArgs.push_back(Elt: R.get());
7690 }
7691
7692 if (Trap.hasErrorOccurred())
7693 return false;
7694 }
7695 return true;
7696}
7697
7698EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7699 SourceLocation CallLoc,
7700 ArrayRef<Expr *> Args,
7701 bool MissingImplicitThis) {
7702 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7703 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7704 return nullptr;
7705
7706 SFINAETrap Trap(*this);
7707 // Perform the access checking immediately so any access diagnostics are
7708 // caught by the SFINAE trap.
7709 llvm::scope_exit UndelayDiags(
7710 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7711 DelayedDiagnostics.popUndelayed(state: CurrentState);
7712 });
7713 SmallVector<Expr *, 16> ConvertedArgs;
7714 // FIXME: We should look into making enable_if late-parsed.
7715 Expr *DiscardedThis;
7716 if (!convertArgsForAvailabilityChecks(
7717 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7718 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7719 return *EnableIfAttrs.begin();
7720
7721 for (auto *EIA : EnableIfAttrs) {
7722 APValue Result;
7723 // FIXME: This doesn't consider value-dependent cases, because doing so is
7724 // very difficult. Ideally, we should handle them more gracefully.
7725 if (EIA->getCond()->isValueDependent() ||
7726 !EIA->getCond()->EvaluateWithSubstitution(
7727 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7728 return EIA;
7729
7730 if (!Result.isInt() || !Result.getInt().getBoolValue())
7731 return EIA;
7732 }
7733 return nullptr;
7734}
7735
7736template <typename CheckFn>
7737static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7738 bool ArgDependent, SourceLocation Loc,
7739 CheckFn &&IsSuccessful) {
7740 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7741 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7742 if (ArgDependent == DIA->getArgDependent())
7743 Attrs.push_back(Elt: DIA);
7744 }
7745
7746 // Common case: No diagnose_if attributes, so we can quit early.
7747 if (Attrs.empty())
7748 return false;
7749
7750 auto WarningBegin = std::stable_partition(
7751 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7752 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7753 DIA->getWarningGroup().empty();
7754 });
7755
7756 // Note that diagnose_if attributes are late-parsed, so they appear in the
7757 // correct order (unlike enable_if attributes).
7758 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7759 IsSuccessful);
7760 if (ErrAttr != WarningBegin) {
7761 const DiagnoseIfAttr *DIA = *ErrAttr;
7762 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7763 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7764 << DIA->getParent() << DIA->getCond()->getSourceRange();
7765 return true;
7766 }
7767
7768 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7769 switch (Sev) {
7770 case DiagnoseIfAttr::DS_warning:
7771 return diag::Severity::Warning;
7772 case DiagnoseIfAttr::DS_error:
7773 return diag::Severity::Error;
7774 }
7775 llvm_unreachable("Fully covered switch above!");
7776 };
7777
7778 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7779 if (IsSuccessful(DIA)) {
7780 if (DIA->getWarningGroup().empty() &&
7781 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7782 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7783 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7784 << DIA->getParent() << DIA->getCond()->getSourceRange();
7785 } else {
7786 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7787 DIA->getWarningGroup());
7788 assert(DiagGroup);
7789 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7790 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7791 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7792 S.Diag(Loc, DiagID) << DIA->getMessage();
7793 }
7794 }
7795
7796 return false;
7797}
7798
7799bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7800 const Expr *ThisArg,
7801 ArrayRef<const Expr *> Args,
7802 SourceLocation Loc) {
7803 return diagnoseDiagnoseIfAttrsWith(
7804 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7805 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7806 APValue Result;
7807 // It's sane to use the same Args for any redecl of this function, since
7808 // EvaluateWithSubstitution only cares about the position of each
7809 // argument in the arg list, not the ParmVarDecl* it maps to.
7810 if (!DIA->getCond()->EvaluateWithSubstitution(
7811 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7812 return false;
7813 return Result.isInt() && Result.getInt().getBoolValue();
7814 });
7815}
7816
7817bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7818 SourceLocation Loc) {
7819 return diagnoseDiagnoseIfAttrsWith(
7820 S&: *this, ND, /*ArgDependent=*/false, Loc,
7821 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7822 bool Result;
7823 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7824 Result;
7825 });
7826}
7827
7828void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7829 ArrayRef<Expr *> Args,
7830 OverloadCandidateSet &CandidateSet,
7831 TemplateArgumentListInfo *ExplicitTemplateArgs,
7832 bool SuppressUserConversions,
7833 bool PartialOverloading,
7834 bool FirstArgumentIsBase) {
7835 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7836 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7837 ArrayRef<Expr *> FunctionArgs = Args;
7838
7839 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7840 FunctionDecl *FD =
7841 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7842
7843 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7844 QualType ObjectType;
7845 Expr::Classification ObjectClassification;
7846 if (Args.size() > 0) {
7847 if (Expr *E = Args[0]) {
7848 // Use the explicit base to restrict the lookup:
7849 ObjectType = E->getType();
7850 // Pointers in the object arguments are implicitly dereferenced, so we
7851 // always classify them as l-values.
7852 if (!ObjectType.isNull() && ObjectType->isPointerType())
7853 ObjectClassification = Expr::Classification::makeSimpleLValue();
7854 else
7855 ObjectClassification = E->Classify(Ctx&: Context);
7856 } // .. else there is an implicit base.
7857 FunctionArgs = Args.slice(N: 1);
7858 }
7859 if (FunTmpl) {
7860 AddMethodTemplateCandidate(
7861 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7862 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7863 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7864 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7865 PartialOverloading);
7866 } else {
7867 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7868 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7869 ObjectClassification, Args: FunctionArgs, CandidateSet,
7870 SuppressUserConversions, PartialOverloading);
7871 }
7872 } else {
7873 // This branch handles both standalone functions and static methods.
7874
7875 // Slice the first argument (which is the base) when we access
7876 // static method as non-static.
7877 if (Args.size() > 0 &&
7878 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7879 !isa<CXXConstructorDecl>(Val: FD)))) {
7880 assert(cast<CXXMethodDecl>(FD)->isStatic());
7881 FunctionArgs = Args.slice(N: 1);
7882 }
7883 if (FunTmpl) {
7884 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7885 ExplicitTemplateArgs, Args: FunctionArgs,
7886 CandidateSet, SuppressUserConversions,
7887 PartialOverloading);
7888 } else {
7889 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7890 SuppressUserConversions, PartialOverloading);
7891 }
7892 }
7893 }
7894}
7895
7896void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7897 Expr::Classification ObjectClassification,
7898 ArrayRef<Expr *> Args,
7899 OverloadCandidateSet &CandidateSet,
7900 bool SuppressUserConversions,
7901 OverloadCandidateParamOrder PO) {
7902 NamedDecl *Decl = FoundDecl.getDecl();
7903 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7904
7905 if (isa<UsingShadowDecl>(Val: Decl))
7906 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7907
7908 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7909 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7910 "Expected a member function template");
7911 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7912 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7913 ObjectClassification, Args, CandidateSet,
7914 SuppressUserConversions, PartialOverloading: false, PO);
7915 } else {
7916 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7917 ObjectType, ObjectClassification, Args, CandidateSet,
7918 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7919 }
7920}
7921
7922void Sema::AddMethodCandidate(
7923 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7924 CXXRecordDecl *ActingContext, QualType ObjectType,
7925 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7926 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7927 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7928 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7929 const FunctionProtoType *Proto
7930 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7931 assert(Proto && "Methods without a prototype cannot be overloaded");
7932 assert(!isa<CXXConstructorDecl>(Method) &&
7933 "Use AddOverloadCandidate for constructors");
7934
7935 if (!CandidateSet.isNewCandidate(F: Method, PO))
7936 return;
7937
7938 // C++11 [class.copy]p23: [DR1402]
7939 // A defaulted move assignment operator that is defined as deleted is
7940 // ignored by overload resolution.
7941 if (Method->isDefaulted() && Method->isDeleted() &&
7942 Method->isMoveAssignmentOperator())
7943 return;
7944
7945 // Overload resolution is always an unevaluated context.
7946 EnterExpressionEvaluationContext Unevaluated(
7947 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7948
7949 bool IgnoreExplicitObject =
7950 (Method->isExplicitObjectMemberFunction() &&
7951 CandidateSet.getKind() ==
7952 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7953 bool ImplicitObjectMethodTreatedAsStatic =
7954 CandidateSet.getKind() ==
7955 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7956 Method->isImplicitObjectMemberFunction();
7957
7958 unsigned ExplicitOffset =
7959 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7960
7961 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7962 int(ImplicitObjectMethodTreatedAsStatic);
7963
7964 unsigned ExtraArgs =
7965 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7966 ? 0
7967 : 1;
7968
7969 // Add this candidate
7970 OverloadCandidate &Candidate =
7971 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
7972 Candidate.FoundDecl = FoundDecl;
7973 Candidate.Function = Method;
7974 Candidate.RewriteKind =
7975 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7976 Candidate.TookAddressOfOverload =
7977 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7978 Candidate.ExplicitCallArguments = Args.size();
7979 Candidate.StrictPackMatch = StrictPackMatch;
7980
7981 // (C++ 13.3.2p2): A candidate function having fewer than m
7982 // parameters is viable only if it has an ellipsis in its parameter
7983 // list (8.3.5).
7984 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7985 !Proto->isVariadic() &&
7986 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7987 Candidate.Viable = false;
7988 Candidate.FailureKind = ovl_fail_too_many_arguments;
7989 return;
7990 }
7991
7992 // (C++ 13.3.2p2): A candidate function having more than m parameters
7993 // is viable only if the (m+1)st parameter has a default argument
7994 // (8.3.6). For the purposes of overload resolution, the
7995 // parameter list is truncated on the right, so that there are
7996 // exactly m parameters.
7997 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7998 ExplicitOffset +
7999 int(ImplicitObjectMethodTreatedAsStatic);
8000
8001 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8002 // Not enough arguments.
8003 Candidate.Viable = false;
8004 Candidate.FailureKind = ovl_fail_too_few_arguments;
8005 return;
8006 }
8007
8008 Candidate.Viable = true;
8009
8010 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8011 if (!IgnoreExplicitObject) {
8012 if (ObjectType.isNull())
8013 Candidate.IgnoreObjectArgument = true;
8014 else if (Method->isStatic()) {
8015 // [over.best.ics.general]p8
8016 // When the parameter is the implicit object parameter of a static member
8017 // function, the implicit conversion sequence is a standard conversion
8018 // sequence that is neither better nor worse than any other standard
8019 // conversion sequence.
8020 //
8021 // This is a rule that was introduced in C++23 to support static lambdas.
8022 // We apply it retroactively because we want to support static lambdas as
8023 // an extension and it doesn't hurt previous code.
8024 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8025 } else {
8026 // Determine the implicit conversion sequence for the object
8027 // parameter.
8028 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8029 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8030 Method, ActingContext, /*InOverloadResolution=*/true);
8031 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8032 Candidate.Viable = false;
8033 Candidate.FailureKind = ovl_fail_bad_conversion;
8034 return;
8035 }
8036 }
8037 }
8038
8039 // (CUDA B.1): Check for invalid calls between targets.
8040 if (getLangOpts().CUDA)
8041 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8042 Callee: Method)) {
8043 Candidate.Viable = false;
8044 Candidate.FailureKind = ovl_fail_bad_target;
8045 return;
8046 }
8047
8048 if (Method->getTrailingRequiresClause()) {
8049 ConstraintSatisfaction Satisfaction;
8050 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8051 /*ForOverloadResolution*/ true) ||
8052 !Satisfaction.IsSatisfied) {
8053 Candidate.Viable = false;
8054 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8055 return;
8056 }
8057 }
8058
8059 // Determine the implicit conversion sequences for each of the
8060 // arguments.
8061 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8062 unsigned ConvIdx =
8063 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8064 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8065 // We already formed a conversion sequence for this parameter during
8066 // template argument deduction.
8067 } else if (ArgIdx < NumParams) {
8068 // (C++ 13.3.2p3): for F to be a viable function, there shall
8069 // exist for each argument an implicit conversion sequence
8070 // (13.3.3.1) that converts that argument to the corresponding
8071 // parameter of F.
8072 QualType ParamType;
8073 if (ImplicitObjectMethodTreatedAsStatic) {
8074 ParamType = ArgIdx == 0
8075 ? Method->getFunctionObjectParameterReferenceType()
8076 : Proto->getParamType(i: ArgIdx - 1);
8077 } else {
8078 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8079 }
8080 Candidate.Conversions[ConvIdx]
8081 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8082 SuppressUserConversions,
8083 /*InOverloadResolution=*/true,
8084 /*AllowObjCWritebackConversion=*/
8085 getLangOpts().ObjCAutoRefCount);
8086 if (Candidate.Conversions[ConvIdx].isBad()) {
8087 Candidate.Viable = false;
8088 Candidate.FailureKind = ovl_fail_bad_conversion;
8089 return;
8090 }
8091 } else {
8092 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8093 // argument for which there is no corresponding parameter is
8094 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8095 Candidate.Conversions[ConvIdx].setEllipsis();
8096 }
8097 }
8098
8099 if (EnableIfAttr *FailedAttr =
8100 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8101 Candidate.Viable = false;
8102 Candidate.FailureKind = ovl_fail_enable_if;
8103 Candidate.DeductionFailure.Data = FailedAttr;
8104 return;
8105 }
8106
8107 if (isNonViableMultiVersionOverload(FD: Method)) {
8108 Candidate.Viable = false;
8109 Candidate.FailureKind = ovl_non_default_multiversion_function;
8110 }
8111}
8112
8113static void AddMethodTemplateCandidateImmediately(
8114 Sema &S, OverloadCandidateSet &CandidateSet,
8115 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8116 CXXRecordDecl *ActingContext,
8117 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8118 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8119 bool SuppressUserConversions, bool PartialOverloading,
8120 OverloadCandidateParamOrder PO) {
8121
8122 // C++ [over.match.funcs]p7:
8123 // In each case where a candidate is a function template, candidate
8124 // function template specializations are generated using template argument
8125 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8126 // candidate functions in the usual way.113) A given name can refer to one
8127 // or more function templates and also to a set of overloaded non-template
8128 // functions. In such a case, the candidate functions generated from each
8129 // function template are combined with the set of non-template candidate
8130 // functions.
8131 TemplateDeductionInfo Info(CandidateSet.getLocation());
8132 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8133 FunctionDecl *Specialization = nullptr;
8134 ConversionSequenceList Conversions;
8135 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8136 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8137 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8138 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8139 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8140 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8141 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8142 bool OnlyInitializeNonUserDefinedConversions) {
8143 return S.CheckNonDependentConversions(
8144 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8145 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8146 SuppressUserConversions,
8147 OnlyInitializeNonUserDefinedConversions),
8148 ActingContext, ObjectType, ObjectClassification, PO);
8149 });
8150 Result != TemplateDeductionResult::Success) {
8151 OverloadCandidate &Candidate =
8152 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8153 Candidate.FoundDecl = FoundDecl;
8154 Candidate.Function = Method;
8155 Candidate.Viable = false;
8156 Candidate.RewriteKind =
8157 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8158 Candidate.IsSurrogate = false;
8159 Candidate.TookAddressOfOverload =
8160 CandidateSet.getKind() ==
8161 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8162
8163 Candidate.IgnoreObjectArgument =
8164 Method->isStatic() ||
8165 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8166 Candidate.ExplicitCallArguments = Args.size();
8167 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8168 Candidate.FailureKind = ovl_fail_bad_conversion;
8169 else {
8170 Candidate.FailureKind = ovl_fail_bad_deduction;
8171 Candidate.DeductionFailure =
8172 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8173 }
8174 return;
8175 }
8176
8177 // Add the function template specialization produced by template argument
8178 // deduction as a candidate.
8179 assert(Specialization && "Missing member function template specialization?");
8180 assert(isa<CXXMethodDecl>(Specialization) &&
8181 "Specialization is not a member function?");
8182 S.AddMethodCandidate(
8183 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8184 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8185 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8186}
8187
8188void Sema::AddMethodTemplateCandidate(
8189 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8190 CXXRecordDecl *ActingContext,
8191 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8192 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8193 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8194 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8195 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8196 return;
8197
8198 if (ExplicitTemplateArgs ||
8199 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this)) {
8200 AddMethodTemplateCandidateImmediately(
8201 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8202 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8203 SuppressUserConversions, PartialOverloading, PO);
8204 return;
8205 }
8206
8207 CandidateSet.AddDeferredMethodTemplateCandidate(
8208 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8209 Args, SuppressUserConversions, PartialOverloading, PO);
8210}
8211
8212/// Determine whether a given function template has a simple explicit specifier
8213/// or a non-value-dependent explicit-specification that evaluates to true.
8214static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8215 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8216}
8217
8218static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8219 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8220 ExplicitSpecKind::Unresolved;
8221}
8222
8223static void AddTemplateOverloadCandidateImmediately(
8224 Sema &S, OverloadCandidateSet &CandidateSet,
8225 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8226 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8227 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8228 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8229 bool AggregateCandidateDeduction) {
8230
8231 // If the function template has a non-dependent explicit specification,
8232 // exclude it now if appropriate; we are not permitted to perform deduction
8233 // and substitution in this case.
8234 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8235 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8236 Candidate.FoundDecl = FoundDecl;
8237 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8238 Candidate.Viable = false;
8239 Candidate.FailureKind = ovl_fail_explicit;
8240 return;
8241 }
8242
8243 // C++ [over.match.funcs]p7:
8244 // In each case where a candidate is a function template, candidate
8245 // function template specializations are generated using template argument
8246 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8247 // candidate functions in the usual way.113) A given name can refer to one
8248 // or more function templates and also to a set of overloaded non-template
8249 // functions. In such a case, the candidate functions generated from each
8250 // function template are combined with the set of non-template candidate
8251 // functions.
8252 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8253 FunctionTemplate->getTemplateDepth());
8254 FunctionDecl *Specialization = nullptr;
8255 ConversionSequenceList Conversions;
8256 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8257 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8258 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8259 /*PartialOrdering=*/false,
8260 /*ObjectType=*/QualType(),
8261 /*ObjectClassification=*/Expr::Classification(),
8262 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8263 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8264 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8265 bool OnlyInitializeNonUserDefinedConversions) {
8266 return S.CheckNonDependentConversions(
8267 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8268 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8269 SuppressUserConversions,
8270 OnlyInitializeNonUserDefinedConversions),
8271 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8272 });
8273 Result != TemplateDeductionResult::Success) {
8274 OverloadCandidate &Candidate =
8275 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8276 Candidate.FoundDecl = FoundDecl;
8277 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8278 Candidate.Viable = false;
8279 Candidate.RewriteKind =
8280 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8281 Candidate.IsSurrogate = false;
8282 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8283 // Ignore the object argument if there is one, since we don't have an object
8284 // type.
8285 Candidate.TookAddressOfOverload =
8286 CandidateSet.getKind() ==
8287 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8288
8289 Candidate.IgnoreObjectArgument =
8290 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8291 !cast<CXXMethodDecl>(Val: Candidate.Function)
8292 ->isExplicitObjectMemberFunction() &&
8293 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8294
8295 Candidate.ExplicitCallArguments = Args.size();
8296 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8297 Candidate.FailureKind = ovl_fail_bad_conversion;
8298 else {
8299 Candidate.FailureKind = ovl_fail_bad_deduction;
8300 Candidate.DeductionFailure =
8301 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8302 }
8303 return;
8304 }
8305
8306 // Add the function template specialization produced by template argument
8307 // deduction as a candidate.
8308 assert(Specialization && "Missing function template specialization?");
8309 S.AddOverloadCandidate(
8310 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8311 PartialOverloading, AllowExplicit,
8312 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8313 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8314 StrictPackMatch: Info.hasStrictPackMatch());
8315}
8316
8317void Sema::AddTemplateOverloadCandidate(
8318 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8319 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8320 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8321 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8322 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8323 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8324 return;
8325
8326 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8327
8328 if (ExplicitTemplateArgs ||
8329 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8330 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8331 DependentExplicitSpecifier)) {
8332
8333 AddTemplateOverloadCandidateImmediately(
8334 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8335 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8336 IsADLCandidate, PO, AggregateCandidateDeduction);
8337
8338 if (DependentExplicitSpecifier)
8339 CandidateSet.DisableResolutionByPerfectCandidate();
8340 return;
8341 }
8342
8343 CandidateSet.AddDeferredTemplateCandidate(
8344 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8345 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8346 AggregateCandidateDeduction);
8347}
8348
8349bool Sema::CheckNonDependentConversions(
8350 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8351 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8352 ConversionSequenceList &Conversions,
8353 CheckNonDependentConversionsFlag UserConversionFlag,
8354 CXXRecordDecl *ActingContext, QualType ObjectType,
8355 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8356 // FIXME: The cases in which we allow explicit conversions for constructor
8357 // arguments never consider calling a constructor template. It's not clear
8358 // that is correct.
8359 const bool AllowExplicit = false;
8360
8361 bool ForOverloadSetAddressResolution =
8362 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8363 auto *FD = FunctionTemplate->getTemplatedDecl();
8364 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8365 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8366 !isa<CXXConstructorDecl>(Val: Method);
8367 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8368
8369 if (Conversions.empty())
8370 Conversions =
8371 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8372
8373 // Overload resolution is always an unevaluated context.
8374 EnterExpressionEvaluationContext Unevaluated(
8375 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8376
8377 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8378 // require that, but this check should never result in a hard error, and
8379 // overload resolution is permitted to sidestep instantiations.
8380 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8381 !ObjectType.isNull()) {
8382 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8383 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8384 !ParamTypes[0]->isDependentType()) {
8385 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8386 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8387 Method, ActingContext, /*InOverloadResolution=*/true,
8388 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8389 : QualType());
8390 if (Conversions[ConvIdx].isBad())
8391 return true;
8392 }
8393 }
8394
8395 // A speculative workaround for self-dependent constraint bugs that manifest
8396 // after CWG2369.
8397 // FIXME: Add references to the standard once P3606 is adopted.
8398 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8399 QualType ArgType) {
8400 ParamType = ParamType.getNonReferenceType();
8401 ArgType = ArgType.getNonReferenceType();
8402 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8403 if (PointerConv) {
8404 ParamType = ParamType->getPointeeType();
8405 ArgType = ArgType->getPointeeType();
8406 }
8407
8408 if (auto *RD = ParamType->getAsCXXRecordDecl();
8409 RD && RD->hasDefinition() &&
8410 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8411 auto Info = getConstructorInfo(ND);
8412 if (!Info)
8413 return false;
8414 CXXConstructorDecl *Ctor = Info.Constructor;
8415 /// isConvertingConstructor takes copy/move constructors into
8416 /// account!
8417 return !Ctor->isCopyOrMoveConstructor() &&
8418 Ctor->isConvertingConstructor(
8419 /*AllowExplicit=*/true);
8420 }))
8421 return true;
8422 if (auto *RD = ArgType->getAsCXXRecordDecl();
8423 RD && RD->hasDefinition() &&
8424 !RD->getVisibleConversionFunctions().empty())
8425 return true;
8426
8427 return false;
8428 };
8429
8430 unsigned Offset =
8431 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8432 : 0;
8433
8434 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8435 I != N; ++I) {
8436 QualType ParamType = ParamTypes[I + Offset];
8437 if (!ParamType->isDependentType()) {
8438 unsigned ConvIdx;
8439 if (PO == OverloadCandidateParamOrder::Reversed) {
8440 ConvIdx = Args.size() - 1 - I;
8441 assert(Args.size() + ThisConversions == 2 &&
8442 "number of args (including 'this') must be exactly 2 for "
8443 "reversed order");
8444 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8445 // would also be 0. 'this' got ConvIdx = 1 previously.
8446 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8447 } else {
8448 // For members, 'this' got ConvIdx = 0 previously.
8449 ConvIdx = ThisConversions + I;
8450 }
8451 if (Conversions[ConvIdx].isInitialized())
8452 continue;
8453 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8454 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8455 continue;
8456 Conversions[ConvIdx] = TryCopyInitialization(
8457 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8458 /*InOverloadResolution=*/true,
8459 /*AllowObjCWritebackConversion=*/
8460 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8461 if (Conversions[ConvIdx].isBad())
8462 return true;
8463 }
8464 }
8465
8466 return false;
8467}
8468
8469/// Determine whether this is an allowable conversion from the result
8470/// of an explicit conversion operator to the expected type, per C++
8471/// [over.match.conv]p1 and [over.match.ref]p1.
8472///
8473/// \param ConvType The return type of the conversion function.
8474///
8475/// \param ToType The type we are converting to.
8476///
8477/// \param AllowObjCPointerConversion Allow a conversion from one
8478/// Objective-C pointer to another.
8479///
8480/// \returns true if the conversion is allowable, false otherwise.
8481static bool isAllowableExplicitConversion(Sema &S,
8482 QualType ConvType, QualType ToType,
8483 bool AllowObjCPointerConversion) {
8484 QualType ToNonRefType = ToType.getNonReferenceType();
8485
8486 // Easy case: the types are the same.
8487 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8488 return true;
8489
8490 // Allow qualification conversions.
8491 bool ObjCLifetimeConversion;
8492 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8493 ObjCLifetimeConversion))
8494 return true;
8495
8496 // If we're not allowed to consider Objective-C pointer conversions,
8497 // we're done.
8498 if (!AllowObjCPointerConversion)
8499 return false;
8500
8501 // Is this an Objective-C pointer conversion?
8502 bool IncompatibleObjC = false;
8503 QualType ConvertedType;
8504 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8505 IncompatibleObjC);
8506}
8507
8508void Sema::AddConversionCandidate(
8509 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8510 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8511 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8512 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8513 assert(!Conversion->getDescribedFunctionTemplate() &&
8514 "Conversion function templates use AddTemplateConversionCandidate");
8515 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8516 if (!CandidateSet.isNewCandidate(F: Conversion))
8517 return;
8518
8519 // If the conversion function has an undeduced return type, trigger its
8520 // deduction now.
8521 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8522 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8523 return;
8524 ConvType = Conversion->getConversionType().getNonReferenceType();
8525 }
8526
8527 // If we don't allow any conversion of the result type, ignore conversion
8528 // functions that don't convert to exactly (possibly cv-qualified) T.
8529 if (!AllowResultConversion &&
8530 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8531 return;
8532
8533 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8534 // operator is only a candidate if its return type is the target type or
8535 // can be converted to the target type with a qualification conversion.
8536 //
8537 // FIXME: Include such functions in the candidate list and explain why we
8538 // can't select them.
8539 if (Conversion->isExplicit() &&
8540 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8541 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8542 return;
8543
8544 // Overload resolution is always an unevaluated context.
8545 EnterExpressionEvaluationContext Unevaluated(
8546 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8547
8548 // Add this candidate
8549 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8550 Candidate.FoundDecl = FoundDecl;
8551 Candidate.Function = Conversion;
8552 Candidate.FinalConversion.setAsIdentityConversion();
8553 Candidate.FinalConversion.setFromType(ConvType);
8554 Candidate.FinalConversion.setAllToTypes(ToType);
8555 Candidate.HasFinalConversion = true;
8556 Candidate.Viable = true;
8557 Candidate.ExplicitCallArguments = 1;
8558 Candidate.StrictPackMatch = StrictPackMatch;
8559
8560 // Explicit functions are not actually candidates at all if we're not
8561 // allowing them in this context, but keep them around so we can point
8562 // to them in diagnostics.
8563 if (!AllowExplicit && Conversion->isExplicit()) {
8564 Candidate.Viable = false;
8565 Candidate.FailureKind = ovl_fail_explicit;
8566 return;
8567 }
8568
8569 // C++ [over.match.funcs]p4:
8570 // For conversion functions, the function is considered to be a member of
8571 // the class of the implicit implied object argument for the purpose of
8572 // defining the type of the implicit object parameter.
8573 //
8574 // Determine the implicit conversion sequence for the implicit
8575 // object parameter.
8576 QualType ObjectType = From->getType();
8577 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8578 ObjectType = FromPtrType->getPointeeType();
8579 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8580 // C++23 [over.best.ics.general]
8581 // However, if the target is [...]
8582 // - the object parameter of a user-defined conversion function
8583 // [...] user-defined conversion sequences are not considered.
8584 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8585 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8586 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8587 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8588 /*SuppressUserConversion*/ true);
8589
8590 if (Candidate.Conversions[0].isBad()) {
8591 Candidate.Viable = false;
8592 Candidate.FailureKind = ovl_fail_bad_conversion;
8593 return;
8594 }
8595
8596 if (Conversion->getTrailingRequiresClause()) {
8597 ConstraintSatisfaction Satisfaction;
8598 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8599 !Satisfaction.IsSatisfied) {
8600 Candidate.Viable = false;
8601 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8602 return;
8603 }
8604 }
8605
8606 // We won't go through a user-defined type conversion function to convert a
8607 // derived to base as such conversions are given Conversion Rank. They only
8608 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8609 QualType FromCanon
8610 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8611 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8612 if (FromCanon == ToCanon ||
8613 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8614 Candidate.Viable = false;
8615 Candidate.FailureKind = ovl_fail_trivial_conversion;
8616 return;
8617 }
8618
8619 // To determine what the conversion from the result of calling the
8620 // conversion function to the type we're eventually trying to
8621 // convert to (ToType), we need to synthesize a call to the
8622 // conversion function and attempt copy initialization from it. This
8623 // makes sure that we get the right semantics with respect to
8624 // lvalues/rvalues and the type. Fortunately, we can allocate this
8625 // call on the stack and we don't need its arguments to be
8626 // well-formed.
8627 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8628 VK_LValue, From->getBeginLoc());
8629 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8630 Context.getPointerType(T: Conversion->getType()),
8631 CK_FunctionToPointerDecay, &ConversionRef,
8632 VK_PRValue, FPOptionsOverride());
8633
8634 QualType ConversionType = Conversion->getConversionType();
8635 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8636 Candidate.Viable = false;
8637 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8638 return;
8639 }
8640
8641 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8642
8643 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8644
8645 // Introduce a temporary expression with the right type and value category
8646 // that we can use for deduction purposes.
8647 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8648
8649 ImplicitConversionSequence ICS =
8650 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8651 /*SuppressUserConversions=*/true,
8652 /*InOverloadResolution=*/false,
8653 /*AllowObjCWritebackConversion=*/false);
8654
8655 switch (ICS.getKind()) {
8656 case ImplicitConversionSequence::StandardConversion:
8657 Candidate.FinalConversion = ICS.Standard;
8658 Candidate.HasFinalConversion = true;
8659
8660 // C++ [over.ics.user]p3:
8661 // If the user-defined conversion is specified by a specialization of a
8662 // conversion function template, the second standard conversion sequence
8663 // shall have exact match rank.
8664 if (Conversion->getPrimaryTemplate() &&
8665 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8666 Candidate.Viable = false;
8667 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8668 return;
8669 }
8670
8671 // C++0x [dcl.init.ref]p5:
8672 // In the second case, if the reference is an rvalue reference and
8673 // the second standard conversion sequence of the user-defined
8674 // conversion sequence includes an lvalue-to-rvalue conversion, the
8675 // program is ill-formed.
8676 if (ToType->isRValueReferenceType() &&
8677 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8678 Candidate.Viable = false;
8679 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8680 return;
8681 }
8682 break;
8683
8684 case ImplicitConversionSequence::BadConversion:
8685 Candidate.Viable = false;
8686 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8687 return;
8688
8689 default:
8690 llvm_unreachable(
8691 "Can only end up with a standard conversion sequence or failure");
8692 }
8693
8694 if (EnableIfAttr *FailedAttr =
8695 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8696 Candidate.Viable = false;
8697 Candidate.FailureKind = ovl_fail_enable_if;
8698 Candidate.DeductionFailure.Data = FailedAttr;
8699 return;
8700 }
8701
8702 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8703 Candidate.Viable = false;
8704 Candidate.FailureKind = ovl_non_default_multiversion_function;
8705 }
8706}
8707
8708static void AddTemplateConversionCandidateImmediately(
8709 Sema &S, OverloadCandidateSet &CandidateSet,
8710 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8711 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8712 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8713 bool AllowResultConversion) {
8714
8715 // If the function template has a non-dependent explicit specification,
8716 // exclude it now if appropriate; we are not permitted to perform deduction
8717 // and substitution in this case.
8718 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8719 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8720 Candidate.FoundDecl = FoundDecl;
8721 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8722 Candidate.Viable = false;
8723 Candidate.FailureKind = ovl_fail_explicit;
8724 return;
8725 }
8726
8727 QualType ObjectType = From->getType();
8728 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8729
8730 TemplateDeductionInfo Info(CandidateSet.getLocation());
8731 CXXConversionDecl *Specialization = nullptr;
8732 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8733 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8734 Specialization, Info);
8735 Result != TemplateDeductionResult::Success) {
8736 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8737 Candidate.FoundDecl = FoundDecl;
8738 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8739 Candidate.Viable = false;
8740 Candidate.FailureKind = ovl_fail_bad_deduction;
8741 Candidate.ExplicitCallArguments = 1;
8742 Candidate.DeductionFailure =
8743 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8744 return;
8745 }
8746
8747 // Add the conversion function template specialization produced by
8748 // template argument deduction as a candidate.
8749 assert(Specialization && "Missing function template specialization?");
8750 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8751 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8752 AllowExplicit, AllowResultConversion,
8753 StrictPackMatch: Info.hasStrictPackMatch());
8754}
8755
8756void Sema::AddTemplateConversionCandidate(
8757 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8758 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8759 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8760 bool AllowExplicit, bool AllowResultConversion) {
8761 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8762 "Only conversion function templates permitted here");
8763
8764 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8765 return;
8766
8767 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8768 CandidateSet.getKind() ==
8769 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8770 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8771 AddTemplateConversionCandidateImmediately(
8772 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8773 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8774 AllowResultConversion);
8775
8776 CandidateSet.DisableResolutionByPerfectCandidate();
8777 return;
8778 }
8779
8780 CandidateSet.AddDeferredConversionTemplateCandidate(
8781 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8782 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8783}
8784
8785void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8786 DeclAccessPair FoundDecl,
8787 CXXRecordDecl *ActingContext,
8788 const FunctionProtoType *Proto,
8789 Expr *Object,
8790 ArrayRef<Expr *> Args,
8791 OverloadCandidateSet& CandidateSet) {
8792 if (!CandidateSet.isNewCandidate(F: Conversion))
8793 return;
8794
8795 // Overload resolution is always an unevaluated context.
8796 EnterExpressionEvaluationContext Unevaluated(
8797 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8798
8799 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8800 Candidate.FoundDecl = FoundDecl;
8801 Candidate.Function = nullptr;
8802 Candidate.Surrogate = Conversion;
8803 Candidate.IsSurrogate = true;
8804 Candidate.Viable = true;
8805 Candidate.ExplicitCallArguments = Args.size();
8806
8807 // Determine the implicit conversion sequence for the implicit
8808 // object parameter.
8809 ImplicitConversionSequence ObjectInit;
8810 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8811 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8812 ToType: Conversion->getParamDecl(i: 0)->getType(),
8813 /*SuppressUserConversions=*/false,
8814 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8815 } else {
8816 ObjectInit = TryObjectArgumentInitialization(
8817 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8818 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8819 }
8820
8821 if (ObjectInit.isBad()) {
8822 Candidate.Viable = false;
8823 Candidate.FailureKind = ovl_fail_bad_conversion;
8824 Candidate.Conversions[0] = ObjectInit;
8825 return;
8826 }
8827
8828 // The first conversion is actually a user-defined conversion whose
8829 // first conversion is ObjectInit's standard conversion (which is
8830 // effectively a reference binding). Record it as such.
8831 Candidate.Conversions[0].setUserDefined();
8832 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8833 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8834 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8835 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8836 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8837 Candidate.Conversions[0].UserDefined.After
8838 = Candidate.Conversions[0].UserDefined.Before;
8839 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8840
8841 // Find the
8842 unsigned NumParams = Proto->getNumParams();
8843
8844 // (C++ 13.3.2p2): A candidate function having fewer than m
8845 // parameters is viable only if it has an ellipsis in its parameter
8846 // list (8.3.5).
8847 if (Args.size() > NumParams && !Proto->isVariadic()) {
8848 Candidate.Viable = false;
8849 Candidate.FailureKind = ovl_fail_too_many_arguments;
8850 return;
8851 }
8852
8853 // Function types don't have any default arguments, so just check if
8854 // we have enough arguments.
8855 if (Args.size() < NumParams) {
8856 // Not enough arguments.
8857 Candidate.Viable = false;
8858 Candidate.FailureKind = ovl_fail_too_few_arguments;
8859 return;
8860 }
8861
8862 // Determine the implicit conversion sequences for each of the
8863 // arguments.
8864 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8865 if (ArgIdx < NumParams) {
8866 // (C++ 13.3.2p3): for F to be a viable function, there shall
8867 // exist for each argument an implicit conversion sequence
8868 // (13.3.3.1) that converts that argument to the corresponding
8869 // parameter of F.
8870 QualType ParamType = Proto->getParamType(i: ArgIdx);
8871 Candidate.Conversions[ArgIdx + 1]
8872 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8873 /*SuppressUserConversions=*/false,
8874 /*InOverloadResolution=*/false,
8875 /*AllowObjCWritebackConversion=*/
8876 getLangOpts().ObjCAutoRefCount);
8877 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8878 Candidate.Viable = false;
8879 Candidate.FailureKind = ovl_fail_bad_conversion;
8880 return;
8881 }
8882 } else {
8883 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8884 // argument for which there is no corresponding parameter is
8885 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8886 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8887 }
8888 }
8889
8890 if (Conversion->getTrailingRequiresClause()) {
8891 ConstraintSatisfaction Satisfaction;
8892 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8893 /*ForOverloadResolution*/ true) ||
8894 !Satisfaction.IsSatisfied) {
8895 Candidate.Viable = false;
8896 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8897 return;
8898 }
8899 }
8900
8901 if (EnableIfAttr *FailedAttr =
8902 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8903 Candidate.Viable = false;
8904 Candidate.FailureKind = ovl_fail_enable_if;
8905 Candidate.DeductionFailure.Data = FailedAttr;
8906 return;
8907 }
8908}
8909
8910void Sema::AddNonMemberOperatorCandidates(
8911 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8912 OverloadCandidateSet &CandidateSet,
8913 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8914 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8915 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8916 ArrayRef<Expr *> FunctionArgs = Args;
8917
8918 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8919 FunctionDecl *FD =
8920 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8921
8922 // Don't consider rewritten functions if we're not rewriting.
8923 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8924 continue;
8925
8926 assert(!isa<CXXMethodDecl>(FD) &&
8927 "unqualified operator lookup found a member function");
8928
8929 if (FunTmpl) {
8930 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8931 Args: FunctionArgs, CandidateSet);
8932 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8933
8934 // As template candidates are not deduced immediately,
8935 // persist the array in the overload set.
8936 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8937 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8938 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8939 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8940 IsADLCandidate: ADLCallKind::NotADL,
8941 PO: OverloadCandidateParamOrder::Reversed);
8942 }
8943 } else {
8944 if (ExplicitTemplateArgs)
8945 continue;
8946 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8947 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8948 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8949 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8950 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8951 PO: OverloadCandidateParamOrder::Reversed);
8952 }
8953 }
8954}
8955
8956void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8957 SourceLocation OpLoc,
8958 ArrayRef<Expr *> Args,
8959 OverloadCandidateSet &CandidateSet,
8960 OverloadCandidateParamOrder PO) {
8961 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8962
8963 // C++ [over.match.oper]p3:
8964 // For a unary operator @ with an operand of a type whose
8965 // cv-unqualified version is T1, and for a binary operator @ with
8966 // a left operand of a type whose cv-unqualified version is T1 and
8967 // a right operand of a type whose cv-unqualified version is T2,
8968 // three sets of candidate functions, designated member
8969 // candidates, non-member candidates and built-in candidates, are
8970 // constructed as follows:
8971 QualType T1 = Args[0]->getType();
8972
8973 // -- If T1 is a complete class type or a class currently being
8974 // defined, the set of member candidates is the result of the
8975 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8976 // the set of member candidates is empty.
8977 if (T1->isRecordType()) {
8978 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
8979 auto *T1RD = T1->getAsCXXRecordDecl();
8980 // Complete the type if it can be completed.
8981 // If the type is neither complete nor being defined, bail out now.
8982 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8983 return;
8984
8985 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8986 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
8987 Operators.suppressAccessDiagnostics();
8988
8989 for (LookupResult::iterator Oper = Operators.begin(),
8990 OperEnd = Operators.end();
8991 Oper != OperEnd; ++Oper) {
8992 if (Oper->getAsFunction() &&
8993 PO == OverloadCandidateParamOrder::Reversed &&
8994 !CandidateSet.getRewriteInfo().shouldAddReversed(
8995 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8996 continue;
8997 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8998 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8999 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
9000 }
9001 }
9002}
9003
9004void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
9005 OverloadCandidateSet& CandidateSet,
9006 bool IsAssignmentOperator,
9007 unsigned NumContextualBoolArguments) {
9008 // Overload resolution is always an unevaluated context.
9009 EnterExpressionEvaluationContext Unevaluated(
9010 *this, Sema::ExpressionEvaluationContext::Unevaluated);
9011
9012 // Add this candidate
9013 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
9014 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
9015 Candidate.Function = nullptr;
9016 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
9017
9018 // Determine the implicit conversion sequences for each of the
9019 // arguments.
9020 Candidate.Viable = true;
9021 Candidate.ExplicitCallArguments = Args.size();
9022 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9023 // C++ [over.match.oper]p4:
9024 // For the built-in assignment operators, conversions of the
9025 // left operand are restricted as follows:
9026 // -- no temporaries are introduced to hold the left operand, and
9027 // -- no user-defined conversions are applied to the left
9028 // operand to achieve a type match with the left-most
9029 // parameter of a built-in candidate.
9030 //
9031 // We block these conversions by turning off user-defined
9032 // conversions, since that is the only way that initialization of
9033 // a reference to a non-class type can occur from something that
9034 // is not of the same type.
9035 if (ArgIdx < NumContextualBoolArguments) {
9036 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9037 "Contextual conversion to bool requires bool type");
9038 Candidate.Conversions[ArgIdx]
9039 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9040 } else {
9041 Candidate.Conversions[ArgIdx]
9042 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9043 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9044 /*InOverloadResolution=*/false,
9045 /*AllowObjCWritebackConversion=*/
9046 getLangOpts().ObjCAutoRefCount);
9047 }
9048 if (Candidate.Conversions[ArgIdx].isBad()) {
9049 Candidate.Viable = false;
9050 Candidate.FailureKind = ovl_fail_bad_conversion;
9051 break;
9052 }
9053 }
9054}
9055
9056namespace {
9057
9058/// BuiltinCandidateTypeSet - A set of types that will be used for the
9059/// candidate operator functions for built-in operators (C++
9060/// [over.built]). The types are separated into pointer types and
9061/// enumeration types.
9062class BuiltinCandidateTypeSet {
9063 /// TypeSet - A set of types.
9064 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9065
9066 /// PointerTypes - The set of pointer types that will be used in the
9067 /// built-in candidates.
9068 TypeSet PointerTypes;
9069
9070 /// MemberPointerTypes - The set of member pointer types that will be
9071 /// used in the built-in candidates.
9072 TypeSet MemberPointerTypes;
9073
9074 /// EnumerationTypes - The set of enumeration types that will be
9075 /// used in the built-in candidates.
9076 TypeSet EnumerationTypes;
9077
9078 /// The set of vector types that will be used in the built-in
9079 /// candidates.
9080 TypeSet VectorTypes;
9081
9082 /// The set of matrix types that will be used in the built-in
9083 /// candidates.
9084 TypeSet MatrixTypes;
9085
9086 /// The set of _BitInt types that will be used in the built-in candidates.
9087 TypeSet BitIntTypes;
9088
9089 /// A flag indicating non-record types are viable candidates
9090 bool HasNonRecordTypes;
9091
9092 /// A flag indicating whether either arithmetic or enumeration types
9093 /// were present in the candidate set.
9094 bool HasArithmeticOrEnumeralTypes;
9095
9096 /// A flag indicating whether the nullptr type was present in the
9097 /// candidate set.
9098 bool HasNullPtrType;
9099
9100 /// Sema - The semantic analysis instance where we are building the
9101 /// candidate type set.
9102 Sema &SemaRef;
9103
9104 /// Context - The AST context in which we will build the type sets.
9105 ASTContext &Context;
9106
9107 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9108 const Qualifiers &VisibleQuals);
9109 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9110
9111public:
9112 /// iterator - Iterates through the types that are part of the set.
9113 typedef TypeSet::iterator iterator;
9114
9115 BuiltinCandidateTypeSet(Sema &SemaRef)
9116 : HasNonRecordTypes(false),
9117 HasArithmeticOrEnumeralTypes(false),
9118 HasNullPtrType(false),
9119 SemaRef(SemaRef),
9120 Context(SemaRef.Context) { }
9121
9122 void AddTypesConvertedFrom(QualType Ty,
9123 SourceLocation Loc,
9124 bool AllowUserConversions,
9125 bool AllowExplicitConversions,
9126 const Qualifiers &VisibleTypeConversionsQuals);
9127
9128 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9129 llvm::iterator_range<iterator> member_pointer_types() {
9130 return MemberPointerTypes;
9131 }
9132 llvm::iterator_range<iterator> enumeration_types() {
9133 return EnumerationTypes;
9134 }
9135 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9136 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9137 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9138
9139 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9140 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9141 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9142 bool hasNullPtrType() const { return HasNullPtrType; }
9143};
9144
9145} // end anonymous namespace
9146
9147/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9148/// the set of pointer types along with any more-qualified variants of
9149/// that type. For example, if @p Ty is "int const *", this routine
9150/// will add "int const *", "int const volatile *", "int const
9151/// restrict *", and "int const volatile restrict *" to the set of
9152/// pointer types. Returns true if the add of @p Ty itself succeeded,
9153/// false otherwise.
9154///
9155/// FIXME: what to do about extended qualifiers?
9156bool
9157BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9158 const Qualifiers &VisibleQuals) {
9159
9160 // Insert this type.
9161 if (!PointerTypes.insert(X: Ty))
9162 return false;
9163
9164 QualType PointeeTy;
9165 const PointerType *PointerTy = Ty->getAs<PointerType>();
9166 bool buildObjCPtr = false;
9167 if (!PointerTy) {
9168 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9169 PointeeTy = PTy->getPointeeType();
9170 buildObjCPtr = true;
9171 } else {
9172 PointeeTy = PointerTy->getPointeeType();
9173 }
9174
9175 // Don't add qualified variants of arrays. For one, they're not allowed
9176 // (the qualifier would sink to the element type), and for another, the
9177 // only overload situation where it matters is subscript or pointer +- int,
9178 // and those shouldn't have qualifier variants anyway.
9179 if (PointeeTy->isArrayType())
9180 return true;
9181
9182 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9183 bool hasVolatile = VisibleQuals.hasVolatile();
9184 bool hasRestrict = VisibleQuals.hasRestrict();
9185
9186 // Iterate through all strict supersets of BaseCVR.
9187 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9188 if ((CVR | BaseCVR) != CVR) continue;
9189 // Skip over volatile if no volatile found anywhere in the types.
9190 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9191
9192 // Skip over restrict if no restrict found anywhere in the types, or if
9193 // the type cannot be restrict-qualified.
9194 if ((CVR & Qualifiers::Restrict) &&
9195 (!hasRestrict ||
9196 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9197 continue;
9198
9199 // Build qualified pointee type.
9200 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9201
9202 // Build qualified pointer type.
9203 QualType QPointerTy;
9204 if (!buildObjCPtr)
9205 QPointerTy = Context.getPointerType(T: QPointeeTy);
9206 else
9207 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9208
9209 // Insert qualified pointer type.
9210 PointerTypes.insert(X: QPointerTy);
9211 }
9212
9213 return true;
9214}
9215
9216/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9217/// to the set of pointer types along with any more-qualified variants of
9218/// that type. For example, if @p Ty is "int const *", this routine
9219/// will add "int const *", "int const volatile *", "int const
9220/// restrict *", and "int const volatile restrict *" to the set of
9221/// pointer types. Returns true if the add of @p Ty itself succeeded,
9222/// false otherwise.
9223///
9224/// FIXME: what to do about extended qualifiers?
9225bool
9226BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9227 QualType Ty) {
9228 // Insert this type.
9229 if (!MemberPointerTypes.insert(X: Ty))
9230 return false;
9231
9232 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9233 assert(PointerTy && "type was not a member pointer type!");
9234
9235 QualType PointeeTy = PointerTy->getPointeeType();
9236 // Don't add qualified variants of arrays. For one, they're not allowed
9237 // (the qualifier would sink to the element type), and for another, the
9238 // only overload situation where it matters is subscript or pointer +- int,
9239 // and those shouldn't have qualifier variants anyway.
9240 if (PointeeTy->isArrayType())
9241 return true;
9242 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9243
9244 // Iterate through all strict supersets of the pointee type's CVR
9245 // qualifiers.
9246 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9247 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9248 if ((CVR | BaseCVR) != CVR) continue;
9249
9250 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9251 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9252 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9253 }
9254
9255 return true;
9256}
9257
9258/// AddTypesConvertedFrom - Add each of the types to which the type @p
9259/// Ty can be implicit converted to the given set of @p Types. We're
9260/// primarily interested in pointer types and enumeration types. We also
9261/// take member pointer types, for the conditional operator.
9262/// AllowUserConversions is true if we should look at the conversion
9263/// functions of a class type, and AllowExplicitConversions if we
9264/// should also include the explicit conversion functions of a class
9265/// type.
9266void
9267BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9268 SourceLocation Loc,
9269 bool AllowUserConversions,
9270 bool AllowExplicitConversions,
9271 const Qualifiers &VisibleQuals) {
9272 // Only deal with canonical types.
9273 Ty = Context.getCanonicalType(T: Ty);
9274
9275 // Look through reference types; they aren't part of the type of an
9276 // expression for the purposes of conversions.
9277 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9278 Ty = RefTy->getPointeeType();
9279
9280 // If we're dealing with an array type, decay to the pointer.
9281 if (Ty->isArrayType())
9282 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9283
9284 // Otherwise, we don't care about qualifiers on the type.
9285 Ty = Ty.getLocalUnqualifiedType();
9286
9287 // Flag if we ever add a non-record type.
9288 bool TyIsRec = Ty->isRecordType();
9289 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9290
9291 // Flag if we encounter an arithmetic type.
9292 HasArithmeticOrEnumeralTypes =
9293 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9294
9295 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9296 PointerTypes.insert(X: Ty);
9297 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9298 // Insert our type, and its more-qualified variants, into the set
9299 // of types.
9300 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9301 return;
9302 } else if (Ty->isMemberPointerType()) {
9303 // Member pointers are far easier, since the pointee can't be converted.
9304 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9305 return;
9306 } else if (Ty->isEnumeralType()) {
9307 HasArithmeticOrEnumeralTypes = true;
9308 EnumerationTypes.insert(X: Ty);
9309 } else if (Ty->isBitIntType()) {
9310 HasArithmeticOrEnumeralTypes = true;
9311 BitIntTypes.insert(X: Ty);
9312 } else if (Ty->isVectorType()) {
9313 // We treat vector types as arithmetic types in many contexts as an
9314 // extension.
9315 HasArithmeticOrEnumeralTypes = true;
9316 VectorTypes.insert(X: Ty);
9317 } else if (Ty->isMatrixType()) {
9318 // Similar to vector types, we treat vector types as arithmetic types in
9319 // many contexts as an extension.
9320 HasArithmeticOrEnumeralTypes = true;
9321 MatrixTypes.insert(X: Ty);
9322 } else if (Ty->isNullPtrType()) {
9323 HasNullPtrType = true;
9324 } else if (AllowUserConversions && TyIsRec) {
9325 // No conversion functions in incomplete types.
9326 if (!SemaRef.isCompleteType(Loc, T: Ty))
9327 return;
9328
9329 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9330 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9331 if (isa<UsingShadowDecl>(Val: D))
9332 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9333
9334 // Skip conversion function templates; they don't tell us anything
9335 // about which builtin types we can convert to.
9336 if (isa<FunctionTemplateDecl>(Val: D))
9337 continue;
9338
9339 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9340 if (AllowExplicitConversions || !Conv->isExplicit()) {
9341 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9342 VisibleQuals);
9343 }
9344 }
9345 }
9346}
9347/// Helper function for adjusting address spaces for the pointer or reference
9348/// operands of builtin operators depending on the argument.
9349static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9350 Expr *Arg) {
9351 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9352}
9353
9354/// Helper function for AddBuiltinOperatorCandidates() that adds
9355/// the volatile- and non-volatile-qualified assignment operators for the
9356/// given type to the candidate set.
9357static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9358 QualType T,
9359 ArrayRef<Expr *> Args,
9360 OverloadCandidateSet &CandidateSet) {
9361 QualType ParamTypes[2];
9362
9363 // T& operator=(T&, T)
9364 ParamTypes[0] = S.Context.getLValueReferenceType(
9365 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9366 ParamTypes[1] = T;
9367 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9368 /*IsAssignmentOperator=*/true);
9369
9370 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9371 // volatile T& operator=(volatile T&, T)
9372 ParamTypes[0] = S.Context.getLValueReferenceType(
9373 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9374 Arg: Args[0]));
9375 ParamTypes[1] = T;
9376 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9377 /*IsAssignmentOperator=*/true);
9378 }
9379}
9380
9381/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9382/// if any, found in visible type conversion functions found in ArgExpr's type.
9383static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9384 Qualifiers VRQuals;
9385 CXXRecordDecl *ClassDecl;
9386 if (const MemberPointerType *RHSMPType =
9387 ArgExpr->getType()->getAs<MemberPointerType>())
9388 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9389 else
9390 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9391 if (!ClassDecl) {
9392 // Just to be safe, assume the worst case.
9393 VRQuals.addVolatile();
9394 VRQuals.addRestrict();
9395 return VRQuals;
9396 }
9397 if (!ClassDecl->hasDefinition())
9398 return VRQuals;
9399
9400 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9401 if (isa<UsingShadowDecl>(Val: D))
9402 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9403 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9404 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9405 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9406 CanTy = ResTypeRef->getPointeeType();
9407 // Need to go down the pointer/mempointer chain and add qualifiers
9408 // as see them.
9409 bool done = false;
9410 while (!done) {
9411 if (CanTy.isRestrictQualified())
9412 VRQuals.addRestrict();
9413 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9414 CanTy = ResTypePtr->getPointeeType();
9415 else if (const MemberPointerType *ResTypeMPtr =
9416 CanTy->getAs<MemberPointerType>())
9417 CanTy = ResTypeMPtr->getPointeeType();
9418 else
9419 done = true;
9420 if (CanTy.isVolatileQualified())
9421 VRQuals.addVolatile();
9422 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9423 return VRQuals;
9424 }
9425 }
9426 }
9427 return VRQuals;
9428}
9429
9430// Note: We're currently only handling qualifiers that are meaningful for the
9431// LHS of compound assignment overloading.
9432static void forAllQualifierCombinationsImpl(
9433 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9434 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9435 // _Atomic
9436 if (Available.hasAtomic()) {
9437 Available.removeAtomic();
9438 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9439 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9440 return;
9441 }
9442
9443 // volatile
9444 if (Available.hasVolatile()) {
9445 Available.removeVolatile();
9446 assert(!Applied.hasVolatile());
9447 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9448 Callback);
9449 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9450 return;
9451 }
9452
9453 Callback(Applied);
9454}
9455
9456static void forAllQualifierCombinations(
9457 QualifiersAndAtomic Quals,
9458 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9459 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9460 Callback);
9461}
9462
9463static QualType makeQualifiedLValueReferenceType(QualType Base,
9464 QualifiersAndAtomic Quals,
9465 Sema &S) {
9466 if (Quals.hasAtomic())
9467 Base = S.Context.getAtomicType(T: Base);
9468 if (Quals.hasVolatile())
9469 Base = S.Context.getVolatileType(T: Base);
9470 return S.Context.getLValueReferenceType(T: Base);
9471}
9472
9473namespace {
9474
9475/// Helper class to manage the addition of builtin operator overload
9476/// candidates. It provides shared state and utility methods used throughout
9477/// the process, as well as a helper method to add each group of builtin
9478/// operator overloads from the standard to a candidate set.
9479class BuiltinOperatorOverloadBuilder {
9480 // Common instance state available to all overload candidate addition methods.
9481 Sema &S;
9482 ArrayRef<Expr *> Args;
9483 QualifiersAndAtomic VisibleTypeConversionsQuals;
9484 bool HasArithmeticOrEnumeralCandidateType;
9485 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9486 OverloadCandidateSet &CandidateSet;
9487
9488 static constexpr int ArithmeticTypesCap = 26;
9489 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9490
9491 // Define some indices used to iterate over the arithmetic types in
9492 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9493 // types are that preserved by promotion (C++ [over.built]p2).
9494 unsigned FirstIntegralType,
9495 LastIntegralType;
9496 unsigned FirstPromotedIntegralType,
9497 LastPromotedIntegralType;
9498 unsigned FirstPromotedArithmeticType,
9499 LastPromotedArithmeticType;
9500 unsigned NumArithmeticTypes;
9501
9502 void InitArithmeticTypes() {
9503 // Start of promoted types.
9504 FirstPromotedArithmeticType = 0;
9505 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9506 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9507 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9508 if (S.Context.getTargetInfo().hasFloat128Type())
9509 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9510 if (S.Context.getTargetInfo().hasIbm128Type())
9511 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9512
9513 // Start of integral types.
9514 FirstIntegralType = ArithmeticTypes.size();
9515 FirstPromotedIntegralType = ArithmeticTypes.size();
9516 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9517 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9518 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9519 if (S.Context.getTargetInfo().hasInt128Type() ||
9520 (S.Context.getAuxTargetInfo() &&
9521 S.Context.getAuxTargetInfo()->hasInt128Type()))
9522 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9523 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9524 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9525 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9526 if (S.Context.getTargetInfo().hasInt128Type() ||
9527 (S.Context.getAuxTargetInfo() &&
9528 S.Context.getAuxTargetInfo()->hasInt128Type()))
9529 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9530
9531 /// We add candidates for the unique, unqualified _BitInt types present in
9532 /// the candidate type set. The candidate set already handled ensuring the
9533 /// type is unqualified and canonical, but because we're adding from N
9534 /// different sets, we need to do some extra work to unique things. Insert
9535 /// the candidates into a unique set, then move from that set into the list
9536 /// of arithmetic types.
9537 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9538 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9539 for (QualType BitTy : Candidate.bitint_types())
9540 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9541 }
9542 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9543 LastPromotedIntegralType = ArithmeticTypes.size();
9544 LastPromotedArithmeticType = ArithmeticTypes.size();
9545 // End of promoted types.
9546
9547 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9548 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9549 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9550 if (S.Context.getLangOpts().Char8)
9551 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9552 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9553 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9554 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9555 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9556 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9557 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9558 LastIntegralType = ArithmeticTypes.size();
9559 NumArithmeticTypes = ArithmeticTypes.size();
9560 // End of integral types.
9561 // FIXME: What about complex? What about half?
9562
9563 // We don't know for sure how many bit-precise candidates were involved, so
9564 // we subtract those from the total when testing whether we're under the
9565 // cap or not.
9566 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9567 ArithmeticTypesCap &&
9568 "Enough inline storage for all arithmetic types.");
9569 }
9570
9571 /// Helper method to factor out the common pattern of adding overloads
9572 /// for '++' and '--' builtin operators.
9573 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9574 bool HasVolatile,
9575 bool HasRestrict) {
9576 QualType ParamTypes[2] = {
9577 S.Context.getLValueReferenceType(T: CandidateTy),
9578 S.Context.IntTy
9579 };
9580
9581 // Non-volatile version.
9582 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9583
9584 // Use a heuristic to reduce number of builtin candidates in the set:
9585 // add volatile version only if there are conversions to a volatile type.
9586 if (HasVolatile) {
9587 ParamTypes[0] =
9588 S.Context.getLValueReferenceType(
9589 T: S.Context.getVolatileType(T: CandidateTy));
9590 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9591 }
9592
9593 // Add restrict version only if there are conversions to a restrict type
9594 // and our candidate type is a non-restrict-qualified pointer.
9595 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9596 !CandidateTy.isRestrictQualified()) {
9597 ParamTypes[0]
9598 = S.Context.getLValueReferenceType(
9599 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9600 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9601
9602 if (HasVolatile) {
9603 ParamTypes[0]
9604 = S.Context.getLValueReferenceType(
9605 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9606 CVR: (Qualifiers::Volatile |
9607 Qualifiers::Restrict)));
9608 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9609 }
9610 }
9611
9612 }
9613
9614 /// Helper to add an overload candidate for a binary builtin with types \p L
9615 /// and \p R.
9616 void AddCandidate(QualType L, QualType R) {
9617 QualType LandR[2] = {L, R};
9618 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9619 }
9620
9621public:
9622 BuiltinOperatorOverloadBuilder(
9623 Sema &S, ArrayRef<Expr *> Args,
9624 QualifiersAndAtomic VisibleTypeConversionsQuals,
9625 bool HasArithmeticOrEnumeralCandidateType,
9626 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9627 OverloadCandidateSet &CandidateSet)
9628 : S(S), Args(Args),
9629 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9630 HasArithmeticOrEnumeralCandidateType(
9631 HasArithmeticOrEnumeralCandidateType),
9632 CandidateTypes(CandidateTypes),
9633 CandidateSet(CandidateSet) {
9634
9635 InitArithmeticTypes();
9636 }
9637
9638 // Increment is deprecated for bool since C++17.
9639 //
9640 // C++ [over.built]p3:
9641 //
9642 // For every pair (T, VQ), where T is an arithmetic type other
9643 // than bool, and VQ is either volatile or empty, there exist
9644 // candidate operator functions of the form
9645 //
9646 // VQ T& operator++(VQ T&);
9647 // T operator++(VQ T&, int);
9648 //
9649 // C++ [over.built]p4:
9650 //
9651 // For every pair (T, VQ), where T is an arithmetic type other
9652 // than bool, and VQ is either volatile or empty, there exist
9653 // candidate operator functions of the form
9654 //
9655 // VQ T& operator--(VQ T&);
9656 // T operator--(VQ T&, int);
9657 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9658 if (!HasArithmeticOrEnumeralCandidateType)
9659 return;
9660
9661 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9662 const auto TypeOfT = ArithmeticTypes[Arith];
9663 if (TypeOfT == S.Context.BoolTy) {
9664 if (Op == OO_MinusMinus)
9665 continue;
9666 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9667 continue;
9668 }
9669 addPlusPlusMinusMinusStyleOverloads(
9670 CandidateTy: TypeOfT,
9671 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9672 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9673 }
9674 }
9675
9676 // C++ [over.built]p5:
9677 //
9678 // For every pair (T, VQ), where T is a cv-qualified or
9679 // cv-unqualified object type, and VQ is either volatile or
9680 // empty, there exist candidate operator functions of the form
9681 //
9682 // T*VQ& operator++(T*VQ&);
9683 // T*VQ& operator--(T*VQ&);
9684 // T* operator++(T*VQ&, int);
9685 // T* operator--(T*VQ&, int);
9686 void addPlusPlusMinusMinusPointerOverloads() {
9687 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9688 // Skip pointer types that aren't pointers to object types.
9689 if (!PtrTy->getPointeeType()->isObjectType())
9690 continue;
9691
9692 addPlusPlusMinusMinusStyleOverloads(
9693 CandidateTy: PtrTy,
9694 HasVolatile: (!PtrTy.isVolatileQualified() &&
9695 VisibleTypeConversionsQuals.hasVolatile()),
9696 HasRestrict: (!PtrTy.isRestrictQualified() &&
9697 VisibleTypeConversionsQuals.hasRestrict()));
9698 }
9699 }
9700
9701 // C++ [over.built]p6:
9702 // For every cv-qualified or cv-unqualified object type T, there
9703 // exist candidate operator functions of the form
9704 //
9705 // T& operator*(T*);
9706 //
9707 // C++ [over.built]p7:
9708 // For every function type T that does not have cv-qualifiers or a
9709 // ref-qualifier, there exist candidate operator functions of the form
9710 // T& operator*(T*);
9711 void addUnaryStarPointerOverloads() {
9712 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9713 QualType PointeeTy = ParamTy->getPointeeType();
9714 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9715 continue;
9716
9717 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9718 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9719 continue;
9720
9721 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9722 }
9723 }
9724
9725 // C++ [over.built]p9:
9726 // For every promoted arithmetic type T, there exist candidate
9727 // operator functions of the form
9728 //
9729 // T operator+(T);
9730 // T operator-(T);
9731 void addUnaryPlusOrMinusArithmeticOverloads() {
9732 if (!HasArithmeticOrEnumeralCandidateType)
9733 return;
9734
9735 for (unsigned Arith = FirstPromotedArithmeticType;
9736 Arith < LastPromotedArithmeticType; ++Arith) {
9737 QualType ArithTy = ArithmeticTypes[Arith];
9738 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9739 }
9740
9741 // Extension: We also add these operators for vector types.
9742 for (QualType VecTy : CandidateTypes[0].vector_types())
9743 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9744 }
9745
9746 // C++ [over.built]p8:
9747 // For every type T, there exist candidate operator functions of
9748 // the form
9749 //
9750 // T* operator+(T*);
9751 void addUnaryPlusPointerOverloads() {
9752 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9753 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9754 }
9755
9756 // C++ [over.built]p10:
9757 // For every promoted integral type T, there exist candidate
9758 // operator functions of the form
9759 //
9760 // T operator~(T);
9761 void addUnaryTildePromotedIntegralOverloads() {
9762 if (!HasArithmeticOrEnumeralCandidateType)
9763 return;
9764
9765 for (unsigned Int = FirstPromotedIntegralType;
9766 Int < LastPromotedIntegralType; ++Int) {
9767 QualType IntTy = ArithmeticTypes[Int];
9768 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9769 }
9770
9771 // Extension: We also add this operator for vector types.
9772 for (QualType VecTy : CandidateTypes[0].vector_types())
9773 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9774 }
9775
9776 // C++ [over.match.oper]p16:
9777 // For every pointer to member type T or type std::nullptr_t, there
9778 // exist candidate operator functions of the form
9779 //
9780 // bool operator==(T,T);
9781 // bool operator!=(T,T);
9782 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9783 /// Set of (canonical) types that we've already handled.
9784 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9785
9786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9787 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9788 // Don't add the same builtin candidate twice.
9789 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9790 continue;
9791
9792 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9793 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9794 }
9795
9796 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9797 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9798 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9799 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9800 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9801 }
9802 }
9803 }
9804 }
9805
9806 // C++ [over.built]p15:
9807 //
9808 // For every T, where T is an enumeration type or a pointer type,
9809 // there exist candidate operator functions of the form
9810 //
9811 // bool operator<(T, T);
9812 // bool operator>(T, T);
9813 // bool operator<=(T, T);
9814 // bool operator>=(T, T);
9815 // bool operator==(T, T);
9816 // bool operator!=(T, T);
9817 // R operator<=>(T, T)
9818 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9819 // C++ [over.match.oper]p3:
9820 // [...]the built-in candidates include all of the candidate operator
9821 // functions defined in 13.6 that, compared to the given operator, [...]
9822 // do not have the same parameter-type-list as any non-template non-member
9823 // candidate.
9824 //
9825 // Note that in practice, this only affects enumeration types because there
9826 // aren't any built-in candidates of record type, and a user-defined operator
9827 // must have an operand of record or enumeration type. Also, the only other
9828 // overloaded operator with enumeration arguments, operator=,
9829 // cannot be overloaded for enumeration types, so this is the only place
9830 // where we must suppress candidates like this.
9831 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9832 UserDefinedBinaryOperators;
9833
9834 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9835 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9836 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9837 CEnd = CandidateSet.end();
9838 C != CEnd; ++C) {
9839 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9840 continue;
9841
9842 if (C->Function->isFunctionTemplateSpecialization())
9843 continue;
9844
9845 // We interpret "same parameter-type-list" as applying to the
9846 // "synthesized candidate, with the order of the two parameters
9847 // reversed", not to the original function.
9848 bool Reversed = C->isReversed();
9849 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9850 ->getType()
9851 .getUnqualifiedType();
9852 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9853 ->getType()
9854 .getUnqualifiedType();
9855
9856 // Skip if either parameter isn't of enumeral type.
9857 if (!FirstParamType->isEnumeralType() ||
9858 !SecondParamType->isEnumeralType())
9859 continue;
9860
9861 // Add this operator to the set of known user-defined operators.
9862 UserDefinedBinaryOperators.insert(
9863 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9864 y: S.Context.getCanonicalType(T: SecondParamType)));
9865 }
9866 }
9867 }
9868
9869 /// Set of (canonical) types that we've already handled.
9870 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9871
9872 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9873 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9874 // Don't add the same builtin candidate twice.
9875 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9876 continue;
9877 if (IsSpaceship && PtrTy->isFunctionPointerType())
9878 continue;
9879
9880 QualType ParamTypes[2] = {PtrTy, PtrTy};
9881 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9882 }
9883 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9884 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9885
9886 // Don't add the same builtin candidate twice, or if a user defined
9887 // candidate exists.
9888 if (!AddedTypes.insert(Ptr: CanonType).second ||
9889 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9890 y&: CanonType)))
9891 continue;
9892 QualType ParamTypes[2] = {EnumTy, EnumTy};
9893 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9894 }
9895 }
9896 }
9897
9898 // C++ [over.built]p13:
9899 //
9900 // For every cv-qualified or cv-unqualified object type T
9901 // there exist candidate operator functions of the form
9902 //
9903 // T* operator+(T*, ptrdiff_t);
9904 // T& operator[](T*, ptrdiff_t); [BELOW]
9905 // T* operator-(T*, ptrdiff_t);
9906 // T* operator+(ptrdiff_t, T*);
9907 // T& operator[](ptrdiff_t, T*); [BELOW]
9908 //
9909 // C++ [over.built]p14:
9910 //
9911 // For every T, where T is a pointer to object type, there
9912 // exist candidate operator functions of the form
9913 //
9914 // ptrdiff_t operator-(T, T);
9915 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9916 /// Set of (canonical) types that we've already handled.
9917 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9918
9919 for (int Arg = 0; Arg < 2; ++Arg) {
9920 QualType AsymmetricParamTypes[2] = {
9921 S.Context.getPointerDiffType(),
9922 S.Context.getPointerDiffType(),
9923 };
9924 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9925 QualType PointeeTy = PtrTy->getPointeeType();
9926 if (!PointeeTy->isObjectType())
9927 continue;
9928
9929 AsymmetricParamTypes[Arg] = PtrTy;
9930 if (Arg == 0 || Op == OO_Plus) {
9931 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9932 // T* operator+(ptrdiff_t, T*);
9933 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9934 }
9935 if (Op == OO_Minus) {
9936 // ptrdiff_t operator-(T, T);
9937 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9938 continue;
9939
9940 QualType ParamTypes[2] = {PtrTy, PtrTy};
9941 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9942 }
9943 }
9944 }
9945 }
9946
9947 // C++ [over.built]p12:
9948 //
9949 // For every pair of promoted arithmetic types L and R, there
9950 // exist candidate operator functions of the form
9951 //
9952 // LR operator*(L, R);
9953 // LR operator/(L, R);
9954 // LR operator+(L, R);
9955 // LR operator-(L, R);
9956 // bool operator<(L, R);
9957 // bool operator>(L, R);
9958 // bool operator<=(L, R);
9959 // bool operator>=(L, R);
9960 // bool operator==(L, R);
9961 // bool operator!=(L, R);
9962 //
9963 // where LR is the result of the usual arithmetic conversions
9964 // between types L and R.
9965 //
9966 // C++ [over.built]p24:
9967 //
9968 // For every pair of promoted arithmetic types L and R, there exist
9969 // candidate operator functions of the form
9970 //
9971 // LR operator?(bool, L, R);
9972 //
9973 // where LR is the result of the usual arithmetic conversions
9974 // between types L and R.
9975 // Our candidates ignore the first parameter.
9976 void addGenericBinaryArithmeticOverloads() {
9977 if (!HasArithmeticOrEnumeralCandidateType)
9978 return;
9979
9980 for (unsigned Left = FirstPromotedArithmeticType;
9981 Left < LastPromotedArithmeticType; ++Left) {
9982 for (unsigned Right = FirstPromotedArithmeticType;
9983 Right < LastPromotedArithmeticType; ++Right) {
9984 QualType LandR[2] = { ArithmeticTypes[Left],
9985 ArithmeticTypes[Right] };
9986 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9987 }
9988 }
9989
9990 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9991 // conditional operator for vector types.
9992 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9993 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9994 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9995 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9996 }
9997 }
9998
9999 /// Add binary operator overloads for each candidate matrix type M1, M2:
10000 /// * (M1, M1) -> M1
10001 /// * (M1, M1.getElementType()) -> M1
10002 /// * (M2.getElementType(), M2) -> M2
10003 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10004 void addMatrixBinaryArithmeticOverloads() {
10005 if (!HasArithmeticOrEnumeralCandidateType)
10006 return;
10007
10008 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10009 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
10010 AddCandidate(L: M1, R: M1);
10011 }
10012
10013 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10014 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
10015 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
10016 AddCandidate(L: M2, R: M2);
10017 }
10018 }
10019
10020 // C++2a [over.built]p14:
10021 //
10022 // For every integral type T there exists a candidate operator function
10023 // of the form
10024 //
10025 // std::strong_ordering operator<=>(T, T)
10026 //
10027 // C++2a [over.built]p15:
10028 //
10029 // For every pair of floating-point types L and R, there exists a candidate
10030 // operator function of the form
10031 //
10032 // std::partial_ordering operator<=>(L, R);
10033 //
10034 // FIXME: The current specification for integral types doesn't play nice with
10035 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10036 // comparisons. Under the current spec this can lead to ambiguity during
10037 // overload resolution. For example:
10038 //
10039 // enum A : int {a};
10040 // auto x = (a <=> (long)42);
10041 //
10042 // error: call is ambiguous for arguments 'A' and 'long'.
10043 // note: candidate operator<=>(int, int)
10044 // note: candidate operator<=>(long, long)
10045 //
10046 // To avoid this error, this function deviates from the specification and adds
10047 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10048 // arithmetic types (the same as the generic relational overloads).
10049 //
10050 // For now this function acts as a placeholder.
10051 void addThreeWayArithmeticOverloads() {
10052 addGenericBinaryArithmeticOverloads();
10053 }
10054
10055 // C++ [over.built]p17:
10056 //
10057 // For every pair of promoted integral types L and R, there
10058 // exist candidate operator functions of the form
10059 //
10060 // LR operator%(L, R);
10061 // LR operator&(L, R);
10062 // LR operator^(L, R);
10063 // LR operator|(L, R);
10064 // L operator<<(L, R);
10065 // L operator>>(L, R);
10066 //
10067 // where LR is the result of the usual arithmetic conversions
10068 // between types L and R.
10069 void addBinaryBitwiseArithmeticOverloads() {
10070 if (!HasArithmeticOrEnumeralCandidateType)
10071 return;
10072
10073 for (unsigned Left = FirstPromotedIntegralType;
10074 Left < LastPromotedIntegralType; ++Left) {
10075 for (unsigned Right = FirstPromotedIntegralType;
10076 Right < LastPromotedIntegralType; ++Right) {
10077 QualType LandR[2] = { ArithmeticTypes[Left],
10078 ArithmeticTypes[Right] };
10079 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10080 }
10081 }
10082 }
10083
10084 // C++ [over.built]p20:
10085 //
10086 // For every pair (T, VQ), where T is an enumeration or
10087 // pointer to member type and VQ is either volatile or
10088 // empty, there exist candidate operator functions of the form
10089 //
10090 // VQ T& operator=(VQ T&, T);
10091 void addAssignmentMemberPointerOrEnumeralOverloads() {
10092 /// Set of (canonical) types that we've already handled.
10093 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10094
10095 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10096 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10097 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10098 continue;
10099
10100 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10101 }
10102
10103 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10104 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10105 continue;
10106
10107 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10108 }
10109 }
10110 }
10111
10112 // C++ [over.built]p19:
10113 //
10114 // For every pair (T, VQ), where T is any type and VQ is either
10115 // volatile or empty, there exist candidate operator functions
10116 // of the form
10117 //
10118 // T*VQ& operator=(T*VQ&, T*);
10119 //
10120 // C++ [over.built]p21:
10121 //
10122 // For every pair (T, VQ), where T is a cv-qualified or
10123 // cv-unqualified object type and VQ is either volatile or
10124 // empty, there exist candidate operator functions of the form
10125 //
10126 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10127 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10128 void addAssignmentPointerOverloads(bool isEqualOp) {
10129 /// Set of (canonical) types that we've already handled.
10130 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10131
10132 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10133 // If this is operator=, keep track of the builtin candidates we added.
10134 if (isEqualOp)
10135 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10136 else if (!PtrTy->getPointeeType()->isObjectType())
10137 continue;
10138
10139 // non-volatile version
10140 QualType ParamTypes[2] = {
10141 S.Context.getLValueReferenceType(T: PtrTy),
10142 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10143 };
10144 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10145 /*IsAssignmentOperator=*/ isEqualOp);
10146
10147 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10148 VisibleTypeConversionsQuals.hasVolatile();
10149 if (NeedVolatile) {
10150 // volatile version
10151 ParamTypes[0] =
10152 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10153 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10154 /*IsAssignmentOperator=*/isEqualOp);
10155 }
10156
10157 if (!PtrTy.isRestrictQualified() &&
10158 VisibleTypeConversionsQuals.hasRestrict()) {
10159 // restrict version
10160 ParamTypes[0] =
10161 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10162 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10163 /*IsAssignmentOperator=*/isEqualOp);
10164
10165 if (NeedVolatile) {
10166 // volatile restrict version
10167 ParamTypes[0] =
10168 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10169 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10170 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10171 /*IsAssignmentOperator=*/isEqualOp);
10172 }
10173 }
10174 }
10175
10176 if (isEqualOp) {
10177 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10178 // Make sure we don't add the same candidate twice.
10179 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10180 continue;
10181
10182 QualType ParamTypes[2] = {
10183 S.Context.getLValueReferenceType(T: PtrTy),
10184 PtrTy,
10185 };
10186
10187 // non-volatile version
10188 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10189 /*IsAssignmentOperator=*/true);
10190
10191 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10192 VisibleTypeConversionsQuals.hasVolatile();
10193 if (NeedVolatile) {
10194 // volatile version
10195 ParamTypes[0] = S.Context.getLValueReferenceType(
10196 T: S.Context.getVolatileType(T: PtrTy));
10197 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10198 /*IsAssignmentOperator=*/true);
10199 }
10200
10201 if (!PtrTy.isRestrictQualified() &&
10202 VisibleTypeConversionsQuals.hasRestrict()) {
10203 // restrict version
10204 ParamTypes[0] = S.Context.getLValueReferenceType(
10205 T: S.Context.getRestrictType(T: PtrTy));
10206 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10207 /*IsAssignmentOperator=*/true);
10208
10209 if (NeedVolatile) {
10210 // volatile restrict version
10211 ParamTypes[0] =
10212 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10213 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10214 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10215 /*IsAssignmentOperator=*/true);
10216 }
10217 }
10218 }
10219 }
10220 }
10221
10222 // C++ [over.built]p18:
10223 //
10224 // For every triple (L, VQ, R), where L is an arithmetic type,
10225 // VQ is either volatile or empty, and R is a promoted
10226 // arithmetic type, there exist candidate operator functions of
10227 // the form
10228 //
10229 // VQ L& operator=(VQ L&, R);
10230 // VQ L& operator*=(VQ L&, R);
10231 // VQ L& operator/=(VQ L&, R);
10232 // VQ L& operator+=(VQ L&, R);
10233 // VQ L& operator-=(VQ L&, R);
10234 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10235 if (!HasArithmeticOrEnumeralCandidateType)
10236 return;
10237
10238 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10239 for (unsigned Right = FirstPromotedArithmeticType;
10240 Right < LastPromotedArithmeticType; ++Right) {
10241 QualType ParamTypes[2];
10242 ParamTypes[1] = ArithmeticTypes[Right];
10243 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10244 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10245
10246 forAllQualifierCombinations(
10247 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10248 ParamTypes[0] =
10249 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10250 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10251 /*IsAssignmentOperator=*/isEqualOp);
10252 });
10253 }
10254 }
10255
10256 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10257 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10258 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10259 QualType ParamTypes[2];
10260 ParamTypes[1] = Vec2Ty;
10261 // Add this built-in operator as a candidate (VQ is empty).
10262 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10263 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10264 /*IsAssignmentOperator=*/isEqualOp);
10265
10266 // Add this built-in operator as a candidate (VQ is 'volatile').
10267 if (VisibleTypeConversionsQuals.hasVolatile()) {
10268 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10269 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10270 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10271 /*IsAssignmentOperator=*/isEqualOp);
10272 }
10273 }
10274 }
10275
10276 // C++ [over.built]p22:
10277 //
10278 // For every triple (L, VQ, R), where L is an integral type, VQ
10279 // is either volatile or empty, and R is a promoted integral
10280 // type, there exist candidate operator functions of the form
10281 //
10282 // VQ L& operator%=(VQ L&, R);
10283 // VQ L& operator<<=(VQ L&, R);
10284 // VQ L& operator>>=(VQ L&, R);
10285 // VQ L& operator&=(VQ L&, R);
10286 // VQ L& operator^=(VQ L&, R);
10287 // VQ L& operator|=(VQ L&, R);
10288 void addAssignmentIntegralOverloads() {
10289 if (!HasArithmeticOrEnumeralCandidateType)
10290 return;
10291
10292 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10293 for (unsigned Right = FirstPromotedIntegralType;
10294 Right < LastPromotedIntegralType; ++Right) {
10295 QualType ParamTypes[2];
10296 ParamTypes[1] = ArithmeticTypes[Right];
10297 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10298 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10299
10300 forAllQualifierCombinations(
10301 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10302 ParamTypes[0] =
10303 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10304 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10305 });
10306 }
10307 }
10308 }
10309
10310 // C++ [over.operator]p23:
10311 //
10312 // There also exist candidate operator functions of the form
10313 //
10314 // bool operator!(bool);
10315 // bool operator&&(bool, bool);
10316 // bool operator||(bool, bool);
10317 void addExclaimOverload() {
10318 QualType ParamTy = S.Context.BoolTy;
10319 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10320 /*IsAssignmentOperator=*/false,
10321 /*NumContextualBoolArguments=*/1);
10322 }
10323 void addAmpAmpOrPipePipeOverload() {
10324 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10325 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10326 /*IsAssignmentOperator=*/false,
10327 /*NumContextualBoolArguments=*/2);
10328 }
10329
10330 // C++ [over.built]p13:
10331 //
10332 // For every cv-qualified or cv-unqualified object type T there
10333 // exist candidate operator functions of the form
10334 //
10335 // T* operator+(T*, ptrdiff_t); [ABOVE]
10336 // T& operator[](T*, ptrdiff_t);
10337 // T* operator-(T*, ptrdiff_t); [ABOVE]
10338 // T* operator+(ptrdiff_t, T*); [ABOVE]
10339 // T& operator[](ptrdiff_t, T*);
10340 void addSubscriptOverloads() {
10341 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10342 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10343 QualType PointeeType = PtrTy->getPointeeType();
10344 if (!PointeeType->isObjectType())
10345 continue;
10346
10347 // T& operator[](T*, ptrdiff_t)
10348 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10349 }
10350
10351 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10352 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10353 QualType PointeeType = PtrTy->getPointeeType();
10354 if (!PointeeType->isObjectType())
10355 continue;
10356
10357 // T& operator[](ptrdiff_t, T*)
10358 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10359 }
10360 }
10361
10362 // C++ [over.built]p11:
10363 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10364 // C1 is the same type as C2 or is a derived class of C2, T is an object
10365 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10366 // there exist candidate operator functions of the form
10367 //
10368 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10369 //
10370 // where CV12 is the union of CV1 and CV2.
10371 void addArrowStarOverloads() {
10372 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10373 QualType C1Ty = PtrTy;
10374 QualType C1;
10375 QualifierCollector Q1;
10376 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10377 if (!isa<RecordType>(Val: C1))
10378 continue;
10379 // heuristic to reduce number of builtin candidates in the set.
10380 // Add volatile/restrict version only if there are conversions to a
10381 // volatile/restrict type.
10382 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10383 continue;
10384 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10385 continue;
10386 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10387 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10388 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10389 *D2 = mptr->getMostRecentCXXRecordDecl();
10390 if (!declaresSameEntity(D1, D2) &&
10391 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10392 break;
10393 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10394 // build CV12 T&
10395 QualType T = mptr->getPointeeType();
10396 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10397 T.isVolatileQualified())
10398 continue;
10399 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10400 T.isRestrictQualified())
10401 continue;
10402 T = Q1.apply(Context: S.Context, QT: T);
10403 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10404 }
10405 }
10406 }
10407
10408 // Note that we don't consider the first argument, since it has been
10409 // contextually converted to bool long ago. The candidates below are
10410 // therefore added as binary.
10411 //
10412 // C++ [over.built]p25:
10413 // For every type T, where T is a pointer, pointer-to-member, or scoped
10414 // enumeration type, there exist candidate operator functions of the form
10415 //
10416 // T operator?(bool, T, T);
10417 //
10418 void addConditionalOperatorOverloads() {
10419 /// Set of (canonical) types that we've already handled.
10420 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10421
10422 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10423 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10424 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10425 continue;
10426
10427 QualType ParamTypes[2] = {PtrTy, PtrTy};
10428 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10429 }
10430
10431 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10432 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10433 continue;
10434
10435 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10436 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10437 }
10438
10439 if (S.getLangOpts().CPlusPlus11) {
10440 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10441 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10442 continue;
10443
10444 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10445 continue;
10446
10447 QualType ParamTypes[2] = {EnumTy, EnumTy};
10448 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10449 }
10450 }
10451 }
10452 }
10453};
10454
10455} // end anonymous namespace
10456
10457void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10458 SourceLocation OpLoc,
10459 ArrayRef<Expr *> Args,
10460 OverloadCandidateSet &CandidateSet) {
10461 // Find all of the types that the arguments can convert to, but only
10462 // if the operator we're looking at has built-in operator candidates
10463 // that make use of these types. Also record whether we encounter non-record
10464 // candidate types or either arithmetic or enumeral candidate types.
10465 QualifiersAndAtomic VisibleTypeConversionsQuals;
10466 VisibleTypeConversionsQuals.addConst();
10467 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10468 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10469 if (Args[ArgIdx]->getType()->isAtomicType())
10470 VisibleTypeConversionsQuals.addAtomic();
10471 }
10472
10473 bool HasNonRecordCandidateType = false;
10474 bool HasArithmeticOrEnumeralCandidateType = false;
10475 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10476 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10477 CandidateTypes.emplace_back(Args&: *this);
10478 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10479 Loc: OpLoc,
10480 AllowUserConversions: true,
10481 AllowExplicitConversions: (Op == OO_Exclaim ||
10482 Op == OO_AmpAmp ||
10483 Op == OO_PipePipe),
10484 VisibleQuals: VisibleTypeConversionsQuals);
10485 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10486 CandidateTypes[ArgIdx].hasNonRecordTypes();
10487 HasArithmeticOrEnumeralCandidateType =
10488 HasArithmeticOrEnumeralCandidateType ||
10489 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10490 }
10491
10492 // Exit early when no non-record types have been added to the candidate set
10493 // for any of the arguments to the operator.
10494 //
10495 // We can't exit early for !, ||, or &&, since there we have always have
10496 // 'bool' overloads.
10497 if (!HasNonRecordCandidateType &&
10498 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10499 return;
10500
10501 // Setup an object to manage the common state for building overloads.
10502 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10503 VisibleTypeConversionsQuals,
10504 HasArithmeticOrEnumeralCandidateType,
10505 CandidateTypes, CandidateSet);
10506
10507 // Dispatch over the operation to add in only those overloads which apply.
10508 switch (Op) {
10509 case OO_None:
10510 case NUM_OVERLOADED_OPERATORS:
10511 llvm_unreachable("Expected an overloaded operator");
10512
10513 case OO_New:
10514 case OO_Delete:
10515 case OO_Array_New:
10516 case OO_Array_Delete:
10517 case OO_Call:
10518 llvm_unreachable(
10519 "Special operators don't use AddBuiltinOperatorCandidates");
10520
10521 case OO_Comma:
10522 case OO_Arrow:
10523 case OO_Coawait:
10524 // C++ [over.match.oper]p3:
10525 // -- For the operator ',', the unary operator '&', the
10526 // operator '->', or the operator 'co_await', the
10527 // built-in candidates set is empty.
10528 break;
10529
10530 case OO_Plus: // '+' is either unary or binary
10531 if (Args.size() == 1)
10532 OpBuilder.addUnaryPlusPointerOverloads();
10533 [[fallthrough]];
10534
10535 case OO_Minus: // '-' is either unary or binary
10536 if (Args.size() == 1) {
10537 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10538 } else {
10539 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10540 OpBuilder.addGenericBinaryArithmeticOverloads();
10541 OpBuilder.addMatrixBinaryArithmeticOverloads();
10542 }
10543 break;
10544
10545 case OO_Star: // '*' is either unary or binary
10546 if (Args.size() == 1)
10547 OpBuilder.addUnaryStarPointerOverloads();
10548 else {
10549 OpBuilder.addGenericBinaryArithmeticOverloads();
10550 OpBuilder.addMatrixBinaryArithmeticOverloads();
10551 }
10552 break;
10553
10554 case OO_Slash:
10555 OpBuilder.addGenericBinaryArithmeticOverloads();
10556 break;
10557
10558 case OO_PlusPlus:
10559 case OO_MinusMinus:
10560 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10561 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10562 break;
10563
10564 case OO_EqualEqual:
10565 case OO_ExclaimEqual:
10566 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10567 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10568 OpBuilder.addGenericBinaryArithmeticOverloads();
10569 break;
10570
10571 case OO_Less:
10572 case OO_Greater:
10573 case OO_LessEqual:
10574 case OO_GreaterEqual:
10575 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10576 OpBuilder.addGenericBinaryArithmeticOverloads();
10577 break;
10578
10579 case OO_Spaceship:
10580 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10581 OpBuilder.addThreeWayArithmeticOverloads();
10582 break;
10583
10584 case OO_Percent:
10585 case OO_Caret:
10586 case OO_Pipe:
10587 case OO_LessLess:
10588 case OO_GreaterGreater:
10589 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10590 break;
10591
10592 case OO_Amp: // '&' is either unary or binary
10593 if (Args.size() == 1)
10594 // C++ [over.match.oper]p3:
10595 // -- For the operator ',', the unary operator '&', or the
10596 // operator '->', the built-in candidates set is empty.
10597 break;
10598
10599 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10600 break;
10601
10602 case OO_Tilde:
10603 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10604 break;
10605
10606 case OO_Equal:
10607 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10608 [[fallthrough]];
10609
10610 case OO_PlusEqual:
10611 case OO_MinusEqual:
10612 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10613 [[fallthrough]];
10614
10615 case OO_StarEqual:
10616 case OO_SlashEqual:
10617 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10618 break;
10619
10620 case OO_PercentEqual:
10621 case OO_LessLessEqual:
10622 case OO_GreaterGreaterEqual:
10623 case OO_AmpEqual:
10624 case OO_CaretEqual:
10625 case OO_PipeEqual:
10626 OpBuilder.addAssignmentIntegralOverloads();
10627 break;
10628
10629 case OO_Exclaim:
10630 OpBuilder.addExclaimOverload();
10631 break;
10632
10633 case OO_AmpAmp:
10634 case OO_PipePipe:
10635 OpBuilder.addAmpAmpOrPipePipeOverload();
10636 break;
10637
10638 case OO_Subscript:
10639 if (Args.size() == 2)
10640 OpBuilder.addSubscriptOverloads();
10641 break;
10642
10643 case OO_ArrowStar:
10644 OpBuilder.addArrowStarOverloads();
10645 break;
10646
10647 case OO_Conditional:
10648 OpBuilder.addConditionalOperatorOverloads();
10649 OpBuilder.addGenericBinaryArithmeticOverloads();
10650 break;
10651 }
10652}
10653
10654void
10655Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10656 SourceLocation Loc,
10657 ArrayRef<Expr *> Args,
10658 TemplateArgumentListInfo *ExplicitTemplateArgs,
10659 OverloadCandidateSet& CandidateSet,
10660 bool PartialOverloading) {
10661 ADLResult Fns;
10662
10663 // FIXME: This approach for uniquing ADL results (and removing
10664 // redundant candidates from the set) relies on pointer-equality,
10665 // which means we need to key off the canonical decl. However,
10666 // always going back to the canonical decl might not get us the
10667 // right set of default arguments. What default arguments are
10668 // we supposed to consider on ADL candidates, anyway?
10669
10670 // FIXME: Pass in the explicit template arguments?
10671 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10672
10673 ArrayRef<Expr *> ReversedArgs;
10674
10675 // Erase all of the candidates we already knew about.
10676 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10677 CandEnd = CandidateSet.end();
10678 Cand != CandEnd; ++Cand)
10679 if (Cand->Function) {
10680 FunctionDecl *Fn = Cand->Function;
10681 Fns.erase(D: Fn);
10682 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10683 Fns.erase(D: FunTmpl);
10684 }
10685
10686 // For each of the ADL candidates we found, add it to the overload
10687 // set.
10688 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10689 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10690
10691 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10692 if (ExplicitTemplateArgs)
10693 continue;
10694
10695 AddOverloadCandidate(
10696 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10697 PartialOverloading, /*AllowExplicit=*/true,
10698 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10699 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10700 AddOverloadCandidate(
10701 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10702 /*SuppressUserConversions=*/false, PartialOverloading,
10703 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10704 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10705 }
10706 } else {
10707 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10708 AddTemplateOverloadCandidate(
10709 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10710 /*SuppressUserConversions=*/false, PartialOverloading,
10711 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10712 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10713 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10714
10715 // As template candidates are not deduced immediately,
10716 // persist the array in the overload set.
10717 if (ReversedArgs.empty())
10718 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10719
10720 AddTemplateOverloadCandidate(
10721 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10722 /*SuppressUserConversions=*/false, PartialOverloading,
10723 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10724 PO: OverloadCandidateParamOrder::Reversed);
10725 }
10726 }
10727 }
10728}
10729
10730namespace {
10731enum class Comparison { Equal, Better, Worse };
10732}
10733
10734/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10735/// overload resolution.
10736///
10737/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10738/// Cand1's first N enable_if attributes have precisely the same conditions as
10739/// Cand2's first N enable_if attributes (where N = the number of enable_if
10740/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10741///
10742/// Note that you can have a pair of candidates such that Cand1's enable_if
10743/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10744/// worse than Cand1's.
10745static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10746 const FunctionDecl *Cand2) {
10747 // Common case: One (or both) decls don't have enable_if attrs.
10748 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10749 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10750 if (!Cand1Attr || !Cand2Attr) {
10751 if (Cand1Attr == Cand2Attr)
10752 return Comparison::Equal;
10753 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10754 }
10755
10756 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10757 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10758
10759 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10760 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10761 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10762 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10763
10764 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10765 // has fewer enable_if attributes than Cand2, and vice versa.
10766 if (!Cand1A)
10767 return Comparison::Worse;
10768 if (!Cand2A)
10769 return Comparison::Better;
10770
10771 Cand1ID.clear();
10772 Cand2ID.clear();
10773
10774 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10775 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10776 if (Cand1ID != Cand2ID)
10777 return Comparison::Worse;
10778 }
10779
10780 return Comparison::Equal;
10781}
10782
10783static Comparison
10784isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10785 const OverloadCandidate &Cand2) {
10786 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10787 !Cand2.Function->isMultiVersion())
10788 return Comparison::Equal;
10789
10790 // If both are invalid, they are equal. If one of them is invalid, the other
10791 // is better.
10792 if (Cand1.Function->isInvalidDecl()) {
10793 if (Cand2.Function->isInvalidDecl())
10794 return Comparison::Equal;
10795 return Comparison::Worse;
10796 }
10797 if (Cand2.Function->isInvalidDecl())
10798 return Comparison::Better;
10799
10800 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10801 // cpu_dispatch, else arbitrarily based on the identifiers.
10802 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10803 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10804 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10805 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10806
10807 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10808 return Comparison::Equal;
10809
10810 if (Cand1CPUDisp && !Cand2CPUDisp)
10811 return Comparison::Better;
10812 if (Cand2CPUDisp && !Cand1CPUDisp)
10813 return Comparison::Worse;
10814
10815 if (Cand1CPUSpec && Cand2CPUSpec) {
10816 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10817 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10818 ? Comparison::Better
10819 : Comparison::Worse;
10820
10821 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10822 FirstDiff = std::mismatch(
10823 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10824 first2: Cand2CPUSpec->cpus_begin(),
10825 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10826 return LHS->getName() == RHS->getName();
10827 });
10828
10829 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10830 "Two different cpu-specific versions should not have the same "
10831 "identifier list, otherwise they'd be the same decl!");
10832 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10833 ? Comparison::Better
10834 : Comparison::Worse;
10835 }
10836 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10837}
10838
10839/// Compute the type of the implicit object parameter for the given function,
10840/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10841/// null QualType if there is a 'matches anything' implicit object parameter.
10842static std::optional<QualType>
10843getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10844 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10845 return std::nullopt;
10846
10847 auto *M = cast<CXXMethodDecl>(Val: F);
10848 // Static member functions' object parameters match all types.
10849 if (M->isStatic())
10850 return QualType();
10851 return M->getFunctionObjectParameterReferenceType();
10852}
10853
10854// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10855// represent the same entity.
10856static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10857 const FunctionDecl *F2) {
10858 if (declaresSameEntity(D1: F1, D2: F2))
10859 return true;
10860 auto PT1 = F1->getPrimaryTemplate();
10861 auto PT2 = F2->getPrimaryTemplate();
10862 if (PT1 && PT2) {
10863 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10864 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10865 D2: PT2->getInstantiatedFromMemberTemplate()))
10866 return true;
10867 }
10868 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10869 // different functions with same params). Consider removing this (as no test
10870 // fail w/o it).
10871 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10872 if (First) {
10873 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10874 return *T;
10875 }
10876 assert(I < F->getNumParams());
10877 return F->getParamDecl(i: I++)->getType();
10878 };
10879
10880 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10881 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10882
10883 if (F1NumParams != F2NumParams)
10884 return false;
10885
10886 unsigned I1 = 0, I2 = 0;
10887 for (unsigned I = 0; I != F1NumParams; ++I) {
10888 QualType T1 = NextParam(F1, I1, I == 0);
10889 QualType T2 = NextParam(F2, I2, I == 0);
10890 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10891 if (!Context.hasSameUnqualifiedType(T1, T2))
10892 return false;
10893 }
10894 return true;
10895}
10896
10897/// We're allowed to use constraints partial ordering only if the candidates
10898/// have the same parameter types:
10899/// [over.match.best.general]p2.6
10900/// F1 and F2 are non-template functions with the same
10901/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10902static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10903 FunctionDecl *Fn2,
10904 bool IsFn1Reversed,
10905 bool IsFn2Reversed) {
10906 assert(Fn1 && Fn2);
10907 if (Fn1->isVariadic() != Fn2->isVariadic())
10908 return false;
10909
10910 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10911 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10912 return false;
10913
10914 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10915 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10916 if (Mem1 && Mem2) {
10917 // if they are member functions, both are direct members of the same class,
10918 // and
10919 if (Mem1->getParent() != Mem2->getParent())
10920 return false;
10921 // if both are non-static member functions, they have the same types for
10922 // their object parameters
10923 if (Mem1->isInstance() && Mem2->isInstance() &&
10924 !S.getASTContext().hasSameType(
10925 T1: Mem1->getFunctionObjectParameterReferenceType(),
10926 T2: Mem1->getFunctionObjectParameterReferenceType()))
10927 return false;
10928 }
10929 return true;
10930}
10931
10932static FunctionDecl *
10933getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10934 bool IsFn1Reversed, bool IsFn2Reversed) {
10935 if (!Fn1 || !Fn2)
10936 return nullptr;
10937
10938 // C++ [temp.constr.order]:
10939 // A non-template function F1 is more partial-ordering-constrained than a
10940 // non-template function F2 if:
10941 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10942 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10943
10944 if (Cand1IsSpecialization || Cand2IsSpecialization)
10945 return nullptr;
10946
10947 // - they have the same non-object-parameter-type-lists, and [...]
10948 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10949 IsFn2Reversed))
10950 return nullptr;
10951
10952 // - the declaration of F1 is more constrained than the declaration of F2.
10953 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10954}
10955
10956/// isBetterOverloadCandidate - Determines whether the first overload
10957/// candidate is a better candidate than the second (C++ 13.3.3p1).
10958bool clang::isBetterOverloadCandidate(
10959 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10960 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10961 bool PartialOverloading) {
10962 // Define viable functions to be better candidates than non-viable
10963 // functions.
10964 if (!Cand2.Viable)
10965 return Cand1.Viable;
10966 else if (!Cand1.Viable)
10967 return false;
10968
10969 // [CUDA] A function with 'never' preference is marked not viable, therefore
10970 // is never shown up here. The worst preference shown up here is 'wrong side',
10971 // e.g. an H function called by a HD function in device compilation. This is
10972 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10973 // function which is called only by an H function. A deferred diagnostic will
10974 // be triggered if it is emitted. However a wrong-sided function is still
10975 // a viable candidate here.
10976 //
10977 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10978 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10979 // can be emitted, Cand1 is not better than Cand2. This rule should have
10980 // precedence over other rules.
10981 //
10982 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10983 // other rules should be used to determine which is better. This is because
10984 // host/device based overloading resolution is mostly for determining
10985 // viability of a function. If two functions are both viable, other factors
10986 // should take precedence in preference, e.g. the standard-defined preferences
10987 // like argument conversion ranks or enable_if partial-ordering. The
10988 // preference for pass-object-size parameters is probably most similar to a
10989 // type-based-overloading decision and so should take priority.
10990 //
10991 // If other rules cannot determine which is better, CUDA preference will be
10992 // used again to determine which is better.
10993 //
10994 // TODO: Currently IdentifyPreference does not return correct values
10995 // for functions called in global variable initializers due to missing
10996 // correct context about device/host. Therefore we can only enforce this
10997 // rule when there is a caller. We should enforce this rule for functions
10998 // in global variable initializers once proper context is added.
10999 //
11000 // TODO: We can only enable the hostness based overloading resolution when
11001 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11002 // overloading resolution diagnostics.
11003 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11004 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11005 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11006 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
11007 bool IsCand1ImplicitHD =
11008 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
11009 bool IsCand2ImplicitHD =
11010 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
11011 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
11012 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11013 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11014 // The implicit HD function may be a function in a system header which
11015 // is forced by pragma. In device compilation, if we prefer HD candidates
11016 // over wrong-sided candidates, overloading resolution may change, which
11017 // may result in non-deferrable diagnostics. As a workaround, we let
11018 // implicit HD candidates take equal preference as wrong-sided candidates.
11019 // This will preserve the overloading resolution.
11020 // TODO: We still need special handling of implicit HD functions since
11021 // they may incur other diagnostics to be deferred. We should make all
11022 // host/device related diagnostics deferrable and remove special handling
11023 // of implicit HD functions.
11024 auto EmitThreshold =
11025 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11026 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11027 ? SemaCUDA::CFP_Never
11028 : SemaCUDA::CFP_WrongSide;
11029 auto Cand1Emittable = P1 > EmitThreshold;
11030 auto Cand2Emittable = P2 > EmitThreshold;
11031 if (Cand1Emittable && !Cand2Emittable)
11032 return true;
11033 if (!Cand1Emittable && Cand2Emittable)
11034 return false;
11035 }
11036 }
11037
11038 // C++ [over.match.best]p1: (Changed in C++23)
11039 //
11040 // -- if F is a static member function, ICS1(F) is defined such
11041 // that ICS1(F) is neither better nor worse than ICS1(G) for
11042 // any function G, and, symmetrically, ICS1(G) is neither
11043 // better nor worse than ICS1(F).
11044 unsigned StartArg = 0;
11045 if (!Cand1.TookAddressOfOverload &&
11046 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11047 StartArg = 1;
11048
11049 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11050 // We don't allow incompatible pointer conversions in C++.
11051 if (!S.getLangOpts().CPlusPlus)
11052 return ICS.isStandard() &&
11053 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11054
11055 // The only ill-formed conversion we allow in C++ is the string literal to
11056 // char* conversion, which is only considered ill-formed after C++11.
11057 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11058 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11059 };
11060
11061 // Define functions that don't require ill-formed conversions for a given
11062 // argument to be better candidates than functions that do.
11063 unsigned NumArgs = Cand1.Conversions.size();
11064 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11065 bool HasBetterConversion = false;
11066 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11067 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11068 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11069 if (Cand1Bad != Cand2Bad) {
11070 if (Cand1Bad)
11071 return false;
11072 HasBetterConversion = true;
11073 }
11074 }
11075
11076 if (HasBetterConversion)
11077 return true;
11078
11079 // C++ [over.match.best]p1:
11080 // A viable function F1 is defined to be a better function than another
11081 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11082 // conversion sequence than ICSi(F2), and then...
11083 bool HasWorseConversion = false;
11084 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11085 switch (CompareImplicitConversionSequences(S, Loc,
11086 ICS1: Cand1.Conversions[ArgIdx],
11087 ICS2: Cand2.Conversions[ArgIdx])) {
11088 case ImplicitConversionSequence::Better:
11089 // Cand1 has a better conversion sequence.
11090 HasBetterConversion = true;
11091 break;
11092
11093 case ImplicitConversionSequence::Worse:
11094 if (Cand1.Function && Cand2.Function &&
11095 Cand1.isReversed() != Cand2.isReversed() &&
11096 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11097 // Work around large-scale breakage caused by considering reversed
11098 // forms of operator== in C++20:
11099 //
11100 // When comparing a function against a reversed function, if we have a
11101 // better conversion for one argument and a worse conversion for the
11102 // other, the implicit conversion sequences are treated as being equally
11103 // good.
11104 //
11105 // This prevents a comparison function from being considered ambiguous
11106 // with a reversed form that is written in the same way.
11107 //
11108 // We diagnose this as an extension from CreateOverloadedBinOp.
11109 HasWorseConversion = true;
11110 break;
11111 }
11112
11113 // Cand1 can't be better than Cand2.
11114 return false;
11115
11116 case ImplicitConversionSequence::Indistinguishable:
11117 // Do nothing.
11118 break;
11119 }
11120 }
11121
11122 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11123 // ICSj(F2), or, if not that,
11124 if (HasBetterConversion && !HasWorseConversion)
11125 return true;
11126
11127 // -- the context is an initialization by user-defined conversion
11128 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11129 // from the return type of F1 to the destination type (i.e.,
11130 // the type of the entity being initialized) is a better
11131 // conversion sequence than the standard conversion sequence
11132 // from the return type of F2 to the destination type.
11133 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11134 Cand1.Function && Cand2.Function &&
11135 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11136 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11137
11138 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11139 // First check whether we prefer one of the conversion functions over the
11140 // other. This only distinguishes the results in non-standard, extension
11141 // cases such as the conversion from a lambda closure type to a function
11142 // pointer or block.
11143 ImplicitConversionSequence::CompareKind Result =
11144 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11145 if (Result == ImplicitConversionSequence::Indistinguishable)
11146 Result = CompareStandardConversionSequences(S, Loc,
11147 SCS1: Cand1.FinalConversion,
11148 SCS2: Cand2.FinalConversion);
11149
11150 if (Result != ImplicitConversionSequence::Indistinguishable)
11151 return Result == ImplicitConversionSequence::Better;
11152
11153 // FIXME: Compare kind of reference binding if conversion functions
11154 // convert to a reference type used in direct reference binding, per
11155 // C++14 [over.match.best]p1 section 2 bullet 3.
11156 }
11157
11158 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11159 // as combined with the resolution to CWG issue 243.
11160 //
11161 // When the context is initialization by constructor ([over.match.ctor] or
11162 // either phase of [over.match.list]), a constructor is preferred over
11163 // a conversion function.
11164 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11165 Cand1.Function && Cand2.Function &&
11166 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11167 isa<CXXConstructorDecl>(Val: Cand2.Function))
11168 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11169
11170 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11171 return Cand2.StrictPackMatch;
11172
11173 // -- F1 is a non-template function and F2 is a function template
11174 // specialization, or, if not that,
11175 bool Cand1IsSpecialization = Cand1.Function &&
11176 Cand1.Function->getPrimaryTemplate();
11177 bool Cand2IsSpecialization = Cand2.Function &&
11178 Cand2.Function->getPrimaryTemplate();
11179 if (Cand1IsSpecialization != Cand2IsSpecialization)
11180 return Cand2IsSpecialization;
11181
11182 // -- F1 and F2 are function template specializations, and the function
11183 // template for F1 is more specialized than the template for F2
11184 // according to the partial ordering rules described in 14.5.5.2, or,
11185 // if not that,
11186 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11187 const auto *Obj1Context =
11188 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11189 const auto *Obj2Context =
11190 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11191 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11192 FT1: Cand1.Function->getPrimaryTemplate(),
11193 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11194 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11195 : TPOC_Call,
11196 NumCallArguments1: Cand1.ExplicitCallArguments,
11197 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11198 : QualType{},
11199 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11200 : QualType{},
11201 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11202 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11203 }
11204 }
11205
11206 // -— F1 and F2 are non-template functions and F1 is more
11207 // partial-ordering-constrained than F2 [...],
11208 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11209 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11210 IsFn2Reversed: Cand2.isReversed());
11211 F && F == Cand1.Function)
11212 return true;
11213
11214 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11215 // class B of D, and for all arguments the corresponding parameters of
11216 // F1 and F2 have the same type.
11217 // FIXME: Implement the "all parameters have the same type" check.
11218 bool Cand1IsInherited =
11219 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11220 bool Cand2IsInherited =
11221 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11222 if (Cand1IsInherited != Cand2IsInherited)
11223 return Cand2IsInherited;
11224 else if (Cand1IsInherited) {
11225 assert(Cand2IsInherited);
11226 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11227 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11228 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11229 return true;
11230 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11231 return false;
11232 // Inherited from sibling base classes: still ambiguous.
11233 }
11234
11235 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11236 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11237 // with reversed order of parameters and F1 is not
11238 //
11239 // We rank reversed + different operator as worse than just reversed, but
11240 // that comparison can never happen, because we only consider reversing for
11241 // the maximally-rewritten operator (== or <=>).
11242 if (Cand1.RewriteKind != Cand2.RewriteKind)
11243 return Cand1.RewriteKind < Cand2.RewriteKind;
11244
11245 // Check C++17 tie-breakers for deduction guides.
11246 {
11247 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11248 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11249 if (Guide1 && Guide2) {
11250 // -- F1 is generated from a deduction-guide and F2 is not
11251 if (Guide1->isImplicit() != Guide2->isImplicit())
11252 return Guide2->isImplicit();
11253
11254 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11255 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11256 return true;
11257 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11258 return false;
11259
11260 // --F1 is generated from a non-template constructor and F2 is generated
11261 // from a constructor template
11262 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11263 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11264 if (Constructor1 && Constructor2) {
11265 bool isC1Templated = Constructor1->getTemplatedKind() !=
11266 FunctionDecl::TemplatedKind::TK_NonTemplate;
11267 bool isC2Templated = Constructor2->getTemplatedKind() !=
11268 FunctionDecl::TemplatedKind::TK_NonTemplate;
11269 if (isC1Templated != isC2Templated)
11270 return isC2Templated;
11271 }
11272 }
11273 }
11274
11275 // Check for enable_if value-based overload resolution.
11276 if (Cand1.Function && Cand2.Function) {
11277 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11278 if (Cmp != Comparison::Equal)
11279 return Cmp == Comparison::Better;
11280 }
11281
11282 bool HasPS1 = Cand1.Function != nullptr &&
11283 functionHasPassObjectSizeParams(FD: Cand1.Function);
11284 bool HasPS2 = Cand2.Function != nullptr &&
11285 functionHasPassObjectSizeParams(FD: Cand2.Function);
11286 if (HasPS1 != HasPS2 && HasPS1)
11287 return true;
11288
11289 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11290 if (MV == Comparison::Better)
11291 return true;
11292 if (MV == Comparison::Worse)
11293 return false;
11294
11295 // If other rules cannot determine which is better, CUDA preference is used
11296 // to determine which is better.
11297 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11298 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11299 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11300 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11301 }
11302
11303 // General member function overloading is handled above, so this only handles
11304 // constructors with address spaces.
11305 // This only handles address spaces since C++ has no other
11306 // qualifier that can be used with constructors.
11307 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11308 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11309 if (CD1 && CD2) {
11310 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11311 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11312 if (AS1 != AS2) {
11313 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11314 return true;
11315 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11316 return false;
11317 }
11318 }
11319
11320 return false;
11321}
11322
11323/// Determine whether two declarations are "equivalent" for the purposes of
11324/// name lookup and overload resolution. This applies when the same internal/no
11325/// linkage entity is defined by two modules (probably by textually including
11326/// the same header). In such a case, we don't consider the declarations to
11327/// declare the same entity, but we also don't want lookups with both
11328/// declarations visible to be ambiguous in some cases (this happens when using
11329/// a modularized libstdc++).
11330bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11331 const NamedDecl *B) {
11332 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11333 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11334 if (!VA || !VB)
11335 return false;
11336
11337 // The declarations must be declaring the same name as an internal linkage
11338 // entity in different modules.
11339 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11340 DC: VB->getDeclContext()->getRedeclContext()) ||
11341 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11342 VA->isExternallyVisible() || VB->isExternallyVisible())
11343 return false;
11344
11345 // Check that the declarations appear to be equivalent.
11346 //
11347 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11348 // For constants and functions, we should check the initializer or body is
11349 // the same. For non-constant variables, we shouldn't allow it at all.
11350 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11351 return true;
11352
11353 // Enum constants within unnamed enumerations will have different types, but
11354 // may still be similar enough to be interchangeable for our purposes.
11355 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11356 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11357 // Only handle anonymous enums. If the enumerations were named and
11358 // equivalent, they would have been merged to the same type.
11359 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11360 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11361 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11362 !Context.hasSameType(T1: EnumA->getIntegerType(),
11363 T2: EnumB->getIntegerType()))
11364 return false;
11365 // Allow this only if the value is the same for both enumerators.
11366 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11367 }
11368 }
11369
11370 // Nothing else is sufficiently similar.
11371 return false;
11372}
11373
11374void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11375 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11376 assert(D && "Unknown declaration");
11377 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11378
11379 Module *M = getOwningModule(Entity: D);
11380 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11381 << !M << (M ? M->getFullModuleName() : "");
11382
11383 for (auto *E : Equiv) {
11384 Module *M = getOwningModule(Entity: E);
11385 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11386 << !M << (M ? M->getFullModuleName() : "");
11387 }
11388}
11389
11390bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11391 return FailureKind == ovl_fail_bad_deduction &&
11392 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11393 TemplateDeductionResult::ConstraintsNotSatisfied &&
11394 static_cast<CNSInfo *>(DeductionFailure.Data)
11395 ->Satisfaction.ContainsErrors;
11396}
11397
11398void OverloadCandidateSet::AddDeferredTemplateCandidate(
11399 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11400 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11401 bool PartialOverloading, bool AllowExplicit,
11402 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11403 bool AggregateCandidateDeduction) {
11404
11405 auto *C =
11406 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11407
11408 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11409 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11410 /*AllowObjCConversionOnExplicit=*/false,
11411 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11412 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11413 .FunctionTemplate: FunctionTemplate,
11414 .FoundDecl: FoundDecl,
11415 .Args: Args,
11416 .IsADLCandidate: IsADLCandidate,
11417 .PO: PO};
11418
11419 HasDeferredTemplateConstructors |=
11420 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11421}
11422
11423void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11424 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11425 CXXRecordDecl *ActingContext, QualType ObjectType,
11426 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11427 bool SuppressUserConversions, bool PartialOverloading,
11428 OverloadCandidateParamOrder PO) {
11429
11430 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11431
11432 auto *C =
11433 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11434
11435 C = new (C) DeferredMethodTemplateOverloadCandidate{
11436 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11437 /*AllowObjCConversionOnExplicit=*/false,
11438 /*AllowResultConversion=*/false,
11439 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11440 /*AggregateCandidateDeduction=*/false},
11441 .FunctionTemplate: MethodTmpl,
11442 .FoundDecl: FoundDecl,
11443 .Args: Args,
11444 .ActingContext: ActingContext,
11445 .ObjectClassification: ObjectClassification,
11446 .ObjectType: ObjectType,
11447 .PO: PO};
11448}
11449
11450void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11451 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11452 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11453 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11454 bool AllowResultConversion) {
11455
11456 auto *C =
11457 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11458
11459 C = new (C) DeferredConversionTemplateOverloadCandidate{
11460 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11461 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11462 /*AllowExplicit=*/false,
11463 /*SuppressUserConversions=*/false,
11464 /*PartialOverloading*/ false,
11465 /*AggregateCandidateDeduction=*/false},
11466 .FunctionTemplate: FunctionTemplate,
11467 .FoundDecl: FoundDecl,
11468 .ActingContext: ActingContext,
11469 .From: From,
11470 .ToType: ToType};
11471}
11472
11473static void
11474AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11475 DeferredMethodTemplateOverloadCandidate &C) {
11476
11477 AddMethodTemplateCandidateImmediately(
11478 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11479 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11480 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11481}
11482
11483static void
11484AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11485 DeferredFunctionTemplateOverloadCandidate &C) {
11486 AddTemplateOverloadCandidateImmediately(
11487 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11488 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11489 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11490 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11491}
11492
11493static void
11494AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11495 DeferredConversionTemplateOverloadCandidate &C) {
11496 return AddTemplateConversionCandidateImmediately(
11497 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11498 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11499 AllowResultConversion: C.AllowResultConversion);
11500}
11501
11502void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11503 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11504 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11505 while (Cand) {
11506 switch (Cand->Kind) {
11507 case DeferredTemplateOverloadCandidate::Function:
11508 AddTemplateOverloadCandidate(
11509 S, CandidateSet&: *this,
11510 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11511 break;
11512 case DeferredTemplateOverloadCandidate::Method:
11513 AddTemplateOverloadCandidate(
11514 S, CandidateSet&: *this,
11515 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11516 break;
11517 case DeferredTemplateOverloadCandidate::Conversion:
11518 AddTemplateOverloadCandidate(
11519 S, CandidateSet&: *this,
11520 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11521 break;
11522 }
11523 Cand = Cand->Next;
11524 }
11525 FirstDeferredCandidate = nullptr;
11526 DeferredCandidatesCount = 0;
11527}
11528
11529OverloadingResult
11530OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11531 Best->Best = true;
11532 if (Best->Function && Best->Function->isDeleted())
11533 return OR_Deleted;
11534 return OR_Success;
11535}
11536
11537void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11538 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11539 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11540 // are accepted by both clang and NVCC. However, during a particular
11541 // compilation mode only one call variant is viable. We need to
11542 // exclude non-viable overload candidates from consideration based
11543 // only on their host/device attributes. Specifically, if one
11544 // candidate call is WrongSide and the other is SameSide, we ignore
11545 // the WrongSide candidate.
11546 // We only need to remove wrong-sided candidates here if
11547 // -fgpu-exclude-wrong-side-overloads is off. When
11548 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11549 // uniformly in isBetterOverloadCandidate.
11550 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11551 return;
11552 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11553
11554 bool ContainsSameSideCandidate =
11555 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11556 // Check viable function only.
11557 return Cand->Viable && Cand->Function &&
11558 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11559 SemaCUDA::CFP_SameSide;
11560 });
11561
11562 if (!ContainsSameSideCandidate)
11563 return;
11564
11565 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11566 // Check viable function only to avoid unnecessary data copying/moving.
11567 return Cand->Viable && Cand->Function &&
11568 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11569 SemaCUDA::CFP_WrongSide;
11570 };
11571 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11572}
11573
11574/// Computes the best viable function (C++ 13.3.3)
11575/// within an overload candidate set.
11576///
11577/// \param Loc The location of the function name (or operator symbol) for
11578/// which overload resolution occurs.
11579///
11580/// \param Best If overload resolution was successful or found a deleted
11581/// function, \p Best points to the candidate function found.
11582///
11583/// \returns The result of overload resolution.
11584OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11585 SourceLocation Loc,
11586 iterator &Best) {
11587
11588 assert((shouldDeferTemplateArgumentDeduction(S) ||
11589 DeferredCandidatesCount == 0) &&
11590 "Unexpected deferred template candidates");
11591
11592 bool TwoPhaseResolution =
11593 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11594
11595 if (TwoPhaseResolution) {
11596 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11597 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11598 if (!(HasDeferredTemplateConstructors &&
11599 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11600 return Res;
11601 }
11602 }
11603
11604 InjectNonDeducedTemplateCandidates(S);
11605 return BestViableFunctionImpl(S, Loc, Best);
11606}
11607
11608OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11609 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11610
11611 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11612 Candidates.reserve(N: this->Candidates.size());
11613 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11614 result: std::back_inserter(x&: Candidates),
11615 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11616
11617 if (S.getLangOpts().CUDA)
11618 CudaExcludeWrongSideCandidates(S, Candidates);
11619
11620 Best = end();
11621 for (auto *Cand : Candidates) {
11622 Cand->Best = false;
11623 if (Cand->Viable) {
11624 if (Best == end() ||
11625 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11626 Best = Cand;
11627 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11628 // This candidate has constraint that we were unable to evaluate because
11629 // it referenced an expression that contained an error. Rather than fall
11630 // back onto a potentially unintended candidate (made worse by
11631 // subsuming constraints), treat this as 'no viable candidate'.
11632 Best = end();
11633 return OR_No_Viable_Function;
11634 }
11635 }
11636
11637 // If we didn't find any viable functions, abort.
11638 if (Best == end())
11639 return OR_No_Viable_Function;
11640
11641 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11642 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11643 PendingBest.push_back(Elt: &*Best);
11644 Best->Best = true;
11645
11646 // Make sure that this function is better than every other viable
11647 // function. If not, we have an ambiguity.
11648 while (!PendingBest.empty()) {
11649 auto *Curr = PendingBest.pop_back_val();
11650 for (auto *Cand : Candidates) {
11651 if (Cand->Viable && !Cand->Best &&
11652 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11653 PendingBest.push_back(Elt: Cand);
11654 Cand->Best = true;
11655
11656 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11657 B: Curr->Function))
11658 EquivalentCands.push_back(Elt: Cand->Function);
11659 else
11660 Best = end();
11661 }
11662 }
11663 }
11664
11665 if (Best == end())
11666 return OR_Ambiguous;
11667
11668 OverloadingResult R = ResultForBestCandidate(Best);
11669
11670 if (!EquivalentCands.empty())
11671 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11672 Equiv: EquivalentCands);
11673 return R;
11674}
11675
11676namespace {
11677
11678enum OverloadCandidateKind {
11679 oc_function,
11680 oc_method,
11681 oc_reversed_binary_operator,
11682 oc_constructor,
11683 oc_implicit_default_constructor,
11684 oc_implicit_copy_constructor,
11685 oc_implicit_move_constructor,
11686 oc_implicit_copy_assignment,
11687 oc_implicit_move_assignment,
11688 oc_implicit_equality_comparison,
11689 oc_inherited_constructor
11690};
11691
11692enum OverloadCandidateSelect {
11693 ocs_non_template,
11694 ocs_template,
11695 ocs_described_template,
11696};
11697
11698static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11699ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11700 const FunctionDecl *Fn,
11701 OverloadCandidateRewriteKind CRK,
11702 std::string &Description) {
11703
11704 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11705 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11706 isTemplate = true;
11707 Description = S.getTemplateArgumentBindingsText(
11708 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11709 }
11710
11711 OverloadCandidateSelect Select = [&]() {
11712 if (!Description.empty())
11713 return ocs_described_template;
11714 return isTemplate ? ocs_template : ocs_non_template;
11715 }();
11716
11717 OverloadCandidateKind Kind = [&]() {
11718 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11719 return oc_implicit_equality_comparison;
11720
11721 if (CRK & CRK_Reversed)
11722 return oc_reversed_binary_operator;
11723
11724 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11725 if (!Ctor->isImplicit()) {
11726 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11727 return oc_inherited_constructor;
11728 else
11729 return oc_constructor;
11730 }
11731
11732 if (Ctor->isDefaultConstructor())
11733 return oc_implicit_default_constructor;
11734
11735 if (Ctor->isMoveConstructor())
11736 return oc_implicit_move_constructor;
11737
11738 assert(Ctor->isCopyConstructor() &&
11739 "unexpected sort of implicit constructor");
11740 return oc_implicit_copy_constructor;
11741 }
11742
11743 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11744 // This actually gets spelled 'candidate function' for now, but
11745 // it doesn't hurt to split it out.
11746 if (!Meth->isImplicit())
11747 return oc_method;
11748
11749 if (Meth->isMoveAssignmentOperator())
11750 return oc_implicit_move_assignment;
11751
11752 if (Meth->isCopyAssignmentOperator())
11753 return oc_implicit_copy_assignment;
11754
11755 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11756 return oc_method;
11757 }
11758
11759 return oc_function;
11760 }();
11761
11762 return std::make_pair(x&: Kind, y&: Select);
11763}
11764
11765void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11766 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11767 // set.
11768 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11769 S.Diag(Loc: FoundDecl->getLocation(),
11770 DiagID: diag::note_ovl_candidate_inherited_constructor)
11771 << Shadow->getNominatedBaseClass();
11772}
11773
11774} // end anonymous namespace
11775
11776static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11777 const FunctionDecl *FD) {
11778 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11779 bool AlwaysTrue;
11780 if (EnableIf->getCond()->isValueDependent() ||
11781 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11782 return false;
11783 if (!AlwaysTrue)
11784 return false;
11785 }
11786 return true;
11787}
11788
11789/// Returns true if we can take the address of the function.
11790///
11791/// \param Complain - If true, we'll emit a diagnostic
11792/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11793/// we in overload resolution?
11794/// \param Loc - The location of the statement we're complaining about. Ignored
11795/// if we're not complaining, or if we're in overload resolution.
11796static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11797 bool Complain,
11798 bool InOverloadResolution,
11799 SourceLocation Loc) {
11800 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11801 if (Complain) {
11802 if (InOverloadResolution)
11803 S.Diag(Loc: FD->getBeginLoc(),
11804 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11805 else
11806 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11807 }
11808 return false;
11809 }
11810
11811 if (FD->getTrailingRequiresClause()) {
11812 ConstraintSatisfaction Satisfaction;
11813 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11814 return false;
11815 if (!Satisfaction.IsSatisfied) {
11816 if (Complain) {
11817 if (InOverloadResolution) {
11818 SmallString<128> TemplateArgString;
11819 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11820 TemplateArgString += " ";
11821 TemplateArgString += S.getTemplateArgumentBindingsText(
11822 Params: FunTmpl->getTemplateParameters(),
11823 Args: *FD->getTemplateSpecializationArgs());
11824 }
11825
11826 S.Diag(Loc: FD->getBeginLoc(),
11827 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11828 << TemplateArgString;
11829 } else
11830 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11831 << FD;
11832 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11833 }
11834 return false;
11835 }
11836 }
11837
11838 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11839 return P->hasAttr<PassObjectSizeAttr>();
11840 });
11841 if (I == FD->param_end())
11842 return true;
11843
11844 if (Complain) {
11845 // Add one to ParamNo because it's user-facing
11846 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11847 if (InOverloadResolution)
11848 S.Diag(Loc: FD->getLocation(),
11849 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11850 << ParamNo;
11851 else
11852 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11853 << FD << ParamNo;
11854 }
11855 return false;
11856}
11857
11858static bool checkAddressOfCandidateIsAvailable(Sema &S,
11859 const FunctionDecl *FD) {
11860 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11861 /*InOverloadResolution=*/true,
11862 /*Loc=*/SourceLocation());
11863}
11864
11865bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11866 bool Complain,
11867 SourceLocation Loc) {
11868 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11869 /*InOverloadResolution=*/false,
11870 Loc);
11871}
11872
11873// Don't print candidates other than the one that matches the calling
11874// convention of the call operator, since that is guaranteed to exist.
11875static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11876 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11877
11878 if (!ConvD)
11879 return false;
11880 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11881 if (!RD->isLambda())
11882 return false;
11883
11884 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11885 CallingConv CallOpCC =
11886 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11887 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11888 CallingConv ConvToCC =
11889 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11890
11891 return ConvToCC != CallOpCC;
11892}
11893
11894// Notes the location of an overload candidate.
11895void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11896 OverloadCandidateRewriteKind RewriteKind,
11897 QualType DestType, bool TakingAddress) {
11898 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11899 return;
11900 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11901 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11902 return;
11903 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11904 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11905 return;
11906 if (shouldSkipNotingLambdaConversionDecl(Fn))
11907 return;
11908
11909 std::string FnDesc;
11910 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11911 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11912 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11913 << (unsigned)KSPair.first << (unsigned)KSPair.second
11914 << Fn << FnDesc;
11915
11916 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11917 Diag(Loc: Fn->getLocation(), PD);
11918 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11919}
11920
11921static void
11922MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11923 // Perhaps the ambiguity was caused by two atomic constraints that are
11924 // 'identical' but not equivalent:
11925 //
11926 // void foo() requires (sizeof(T) > 4) { } // #1
11927 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11928 //
11929 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11930 // #2 to subsume #1, but these constraint are not considered equivalent
11931 // according to the subsumption rules because they are not the same
11932 // source-level construct. This behavior is quite confusing and we should try
11933 // to help the user figure out what happened.
11934
11935 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11936 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11937 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11938 if (!I->Function)
11939 continue;
11940 SmallVector<AssociatedConstraint, 3> AC;
11941 if (auto *Template = I->Function->getPrimaryTemplate())
11942 Template->getAssociatedConstraints(AC);
11943 else
11944 I->Function->getAssociatedConstraints(ACs&: AC);
11945 if (AC.empty())
11946 continue;
11947 if (FirstCand == nullptr) {
11948 FirstCand = I->Function;
11949 FirstAC = AC;
11950 } else if (SecondCand == nullptr) {
11951 SecondCand = I->Function;
11952 SecondAC = AC;
11953 } else {
11954 // We have more than one pair of constrained functions - this check is
11955 // expensive and we'd rather not try to diagnose it.
11956 return;
11957 }
11958 }
11959 if (!SecondCand)
11960 return;
11961 // The diagnostic can only happen if there are associated constraints on
11962 // both sides (there needs to be some identical atomic constraint).
11963 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11964 D2: SecondCand, AC2: SecondAC))
11965 // Just show the user one diagnostic, they'll probably figure it out
11966 // from here.
11967 return;
11968}
11969
11970// Notes the location of all overload candidates designated through
11971// OverloadedExpr
11972void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11973 bool TakingAddress) {
11974 assert(OverloadedExpr->getType() == Context.OverloadTy);
11975
11976 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11977 OverloadExpr *OvlExpr = Ovl.Expression;
11978
11979 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11980 IEnd = OvlExpr->decls_end();
11981 I != IEnd; ++I) {
11982 if (FunctionTemplateDecl *FunTmpl =
11983 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11984 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11985 TakingAddress);
11986 } else if (FunctionDecl *Fun
11987 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11988 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11989 }
11990 }
11991}
11992
11993/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11994/// "lead" diagnostic; it will be given two arguments, the source and
11995/// target types of the conversion.
11996void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11997 Sema &S,
11998 SourceLocation CaretLoc,
11999 const PartialDiagnostic &PDiag) const {
12000 S.Diag(Loc: CaretLoc, PD: PDiag)
12001 << Ambiguous.getFromType() << Ambiguous.getToType();
12002 unsigned CandsShown = 0;
12003 AmbiguousConversionSequence::const_iterator I, E;
12004 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12005 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12006 break;
12007 ++CandsShown;
12008 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
12009 }
12010 S.Diags.overloadCandidatesShown(N: CandsShown);
12011 if (I != E)
12012 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12013}
12014
12015static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
12016 unsigned I, bool TakingCandidateAddress) {
12017 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12018 assert(Conv.isBad());
12019 assert(Cand->Function && "for now, candidate must be a function");
12020 FunctionDecl *Fn = Cand->Function;
12021
12022 // There's a conversion slot for the object argument if this is a
12023 // non-constructor method. Note that 'I' corresponds the
12024 // conversion-slot index.
12025 bool isObjectArgument = false;
12026 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12027 !isa<CXXConstructorDecl>(Val: Fn)) {
12028 if (I == 0)
12029 isObjectArgument = true;
12030 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12031 I--;
12032 }
12033
12034 std::string FnDesc;
12035 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12036 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12037 Description&: FnDesc);
12038
12039 Expr *FromExpr = Conv.Bad.FromExpr;
12040 QualType FromTy = Conv.Bad.getFromType();
12041 QualType ToTy = Conv.Bad.getToType();
12042 SourceRange ToParamRange;
12043
12044 // FIXME: In presence of parameter packs we can't determine parameter range
12045 // reliably, as we don't have access to instantiation.
12046 bool HasParamPack =
12047 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12048 return Parm->isParameterPack();
12049 });
12050 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12051 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12052
12053 if (FromTy == S.Context.OverloadTy) {
12054 assert(FromExpr && "overload set argument came from implicit argument?");
12055 Expr *E = FromExpr->IgnoreParens();
12056 if (isa<UnaryOperator>(Val: E))
12057 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12058 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12059
12060 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12061 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12062 << ToParamRange << ToTy << Name << I + 1;
12063 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12064 return;
12065 }
12066
12067 // Do some hand-waving analysis to see if the non-viability is due
12068 // to a qualifier mismatch.
12069 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12070 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12071 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12072 CToTy = RT->getPointeeType();
12073 else {
12074 // TODO: detect and diagnose the full richness of const mismatches.
12075 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12076 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12077 CFromTy = FromPT->getPointeeType();
12078 CToTy = ToPT->getPointeeType();
12079 }
12080 }
12081
12082 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12083 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12084 Qualifiers FromQs = CFromTy.getQualifiers();
12085 Qualifiers ToQs = CToTy.getQualifiers();
12086
12087 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12088 if (isObjectArgument)
12089 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12090 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12091 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12092 else
12093 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12094 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12095 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12096 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12097 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12098 return;
12099 }
12100
12101 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12102 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12103 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12104 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12105 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12106 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12107 return;
12108 }
12109
12110 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12111 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12112 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12113 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12114 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12115 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12116 return;
12117 }
12118
12119 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12120 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12121 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12122 << FromTy << !!FromQs.getPointerAuth()
12123 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12124 << ToQs.getPointerAuth().getAsString() << I + 1
12125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12126 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12127 return;
12128 }
12129
12130 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12131 assert(CVR && "expected qualifiers mismatch");
12132
12133 if (isObjectArgument) {
12134 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12135 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12136 << FromTy << (CVR - 1);
12137 } else {
12138 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12139 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12140 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12141 }
12142 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12143 return;
12144 }
12145
12146 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12147 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12148 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12149 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12150 << (unsigned)isObjectArgument << I + 1
12151 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12152 << ToParamRange;
12153 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12154 return;
12155 }
12156
12157 // Special diagnostic for failure to convert an initializer list, since
12158 // telling the user that it has type void is not useful.
12159 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12160 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12161 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12162 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12163 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12164 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12165 ? 2
12166 : 0);
12167 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12168 return;
12169 }
12170
12171 // Diagnose references or pointers to incomplete types differently,
12172 // since it's far from impossible that the incompleteness triggered
12173 // the failure.
12174 QualType TempFromTy = FromTy.getNonReferenceType();
12175 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12176 TempFromTy = PTy->getPointeeType();
12177 if (TempFromTy->isIncompleteType()) {
12178 // Emit the generic diagnostic and, optionally, add the hints to it.
12179 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12180 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12181 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12182 << (unsigned)(Cand->Fix.Kind);
12183
12184 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12185 return;
12186 }
12187
12188 // Diagnose base -> derived pointer conversions.
12189 unsigned BaseToDerivedConversion = 0;
12190 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12191 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12192 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12193 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12194 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12195 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12196 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12197 Base: FromPtrTy->getPointeeType()))
12198 BaseToDerivedConversion = 1;
12199 }
12200 } else if (const ObjCObjectPointerType *FromPtrTy
12201 = FromTy->getAs<ObjCObjectPointerType>()) {
12202 if (const ObjCObjectPointerType *ToPtrTy
12203 = ToTy->getAs<ObjCObjectPointerType>())
12204 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12205 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12206 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12207 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12208 FromIface->isSuperClassOf(I: ToIface))
12209 BaseToDerivedConversion = 2;
12210 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12211 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12212 Ctx: S.getASTContext()) &&
12213 !FromTy->isIncompleteType() &&
12214 !ToRefTy->getPointeeType()->isIncompleteType() &&
12215 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12216 BaseToDerivedConversion = 3;
12217 }
12218 }
12219
12220 if (BaseToDerivedConversion) {
12221 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12222 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12223 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12224 << I + 1;
12225 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12226 return;
12227 }
12228
12229 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12230 isa<PointerType>(Val: CToTy)) {
12231 Qualifiers FromQs = CFromTy.getQualifiers();
12232 Qualifiers ToQs = CToTy.getQualifiers();
12233 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12234 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12235 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12236 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12237 << I + 1;
12238 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12239 return;
12240 }
12241 }
12242
12243 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12244 return;
12245
12246 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12247 // although this is almost always an error and we advise against it.
12248 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12249 ToTy == S.Context.getLogicalOperationType()) {
12250 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12251 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12252 << Conv.Bad.FromExpr << ToTy;
12253 return;
12254 }
12255
12256 // Emit the generic diagnostic and, optionally, add the hints to it.
12257 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12258 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12259 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12260 << (unsigned)(Cand->Fix.Kind);
12261
12262 // Check that location of Fn is not in system header.
12263 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12264 // If we can fix the conversion, suggest the FixIts.
12265 for (const FixItHint &HI : Cand->Fix.Hints)
12266 FDiag << HI;
12267 }
12268
12269 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12270
12271 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12272}
12273
12274/// Additional arity mismatch diagnosis specific to a function overload
12275/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12276/// over a candidate in any candidate set.
12277static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12278 unsigned NumArgs, bool IsAddressOf = false) {
12279 assert(Cand->Function && "Candidate is required to be a function.");
12280 FunctionDecl *Fn = Cand->Function;
12281 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12282 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12283
12284 // With invalid overloaded operators, it's possible that we think we
12285 // have an arity mismatch when in fact it looks like we have the
12286 // right number of arguments, because only overloaded operators have
12287 // the weird behavior of overloading member and non-member functions.
12288 // Just don't report anything.
12289 if (Fn->isInvalidDecl() &&
12290 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12291 return true;
12292
12293 if (NumArgs < MinParams) {
12294 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12295 (Cand->FailureKind == ovl_fail_bad_deduction &&
12296 Cand->DeductionFailure.getResult() ==
12297 TemplateDeductionResult::TooFewArguments));
12298 } else {
12299 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12300 (Cand->FailureKind == ovl_fail_bad_deduction &&
12301 Cand->DeductionFailure.getResult() ==
12302 TemplateDeductionResult::TooManyArguments));
12303 }
12304
12305 return false;
12306}
12307
12308/// General arity mismatch diagnosis over a candidate in a candidate set.
12309static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12310 unsigned NumFormalArgs,
12311 bool IsAddressOf = false) {
12312 assert(isa<FunctionDecl>(D) &&
12313 "The templated declaration should at least be a function"
12314 " when diagnosing bad template argument deduction due to too many"
12315 " or too few arguments");
12316
12317 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12318
12319 // TODO: treat calls to a missing default constructor as a special case
12320 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12321 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12322 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12323
12324 // at least / at most / exactly
12325 bool HasExplicitObjectParam =
12326 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12327
12328 unsigned ParamCount =
12329 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12330 unsigned mode, modeCount;
12331
12332 if (NumFormalArgs < MinParams) {
12333 if (MinParams != ParamCount || FnTy->isVariadic() ||
12334 FnTy->isTemplateVariadic())
12335 mode = 0; // "at least"
12336 else
12337 mode = 2; // "exactly"
12338 modeCount = MinParams;
12339 } else {
12340 if (MinParams != ParamCount)
12341 mode = 1; // "at most"
12342 else
12343 mode = 2; // "exactly"
12344 modeCount = ParamCount;
12345 }
12346
12347 std::string Description;
12348 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12349 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12350
12351 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12352 if (modeCount == 1 && !IsAddressOf &&
12353 FirstNonObjectParamIdx < Fn->getNumParams() &&
12354 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12355 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12356 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12357 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12358 << NumFormalArgs << HasExplicitObjectParam
12359 << Fn->getParametersSourceRange();
12360 else
12361 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12362 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12363 << Description << mode << modeCount << NumFormalArgs
12364 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12365
12366 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12367}
12368
12369/// Arity mismatch diagnosis specific to a function overload candidate.
12370static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12371 unsigned NumFormalArgs) {
12372 assert(Cand->Function && "Candidate must be a function");
12373 FunctionDecl *Fn = Cand->Function;
12374 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12375 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12376 IsAddressOf: Cand->TookAddressOfOverload);
12377}
12378
12379static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12380 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12381 return TD;
12382 llvm_unreachable("Unsupported: Getting the described template declaration"
12383 " for bad deduction diagnosis");
12384}
12385
12386/// Diagnose a failed template-argument deduction.
12387static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12388 DeductionFailureInfo &DeductionFailure,
12389 unsigned NumArgs,
12390 bool TakingCandidateAddress) {
12391 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12392 NamedDecl *ParamD;
12393 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12394 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12395 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12396 switch (DeductionFailure.getResult()) {
12397 case TemplateDeductionResult::Success:
12398 llvm_unreachable(
12399 "TemplateDeductionResult::Success while diagnosing bad deduction");
12400 case TemplateDeductionResult::NonDependentConversionFailure:
12401 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12402 "while diagnosing bad deduction");
12403 case TemplateDeductionResult::Invalid:
12404 case TemplateDeductionResult::AlreadyDiagnosed:
12405 return;
12406
12407 case TemplateDeductionResult::Incomplete: {
12408 assert(ParamD && "no parameter found for incomplete deduction result");
12409 S.Diag(Loc: Templated->getLocation(),
12410 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12411 << ParamD->getDeclName();
12412 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12413 return;
12414 }
12415
12416 case TemplateDeductionResult::IncompletePack: {
12417 assert(ParamD && "no parameter found for incomplete deduction result");
12418 S.Diag(Loc: Templated->getLocation(),
12419 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12420 << ParamD->getDeclName()
12421 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12422 << *DeductionFailure.getFirstArg();
12423 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12424 return;
12425 }
12426
12427 case TemplateDeductionResult::Underqualified: {
12428 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12429 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12430
12431 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12432
12433 // Param will have been canonicalized, but it should just be a
12434 // qualified version of ParamD, so move the qualifiers to that.
12435 QualifierCollector Qs;
12436 Qs.strip(type: Param);
12437 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12438 assert(S.Context.hasSameType(Param, NonCanonParam));
12439
12440 // Arg has also been canonicalized, but there's nothing we can do
12441 // about that. It also doesn't matter as much, because it won't
12442 // have any template parameters in it (because deduction isn't
12443 // done on dependent types).
12444 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12445
12446 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12447 << ParamD->getDeclName() << Arg << NonCanonParam;
12448 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12449 return;
12450 }
12451
12452 case TemplateDeductionResult::Inconsistent: {
12453 assert(ParamD && "no parameter found for inconsistent deduction result");
12454 int which = 0;
12455 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12456 which = 0;
12457 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12458 // Deduction might have failed because we deduced arguments of two
12459 // different types for a non-type template parameter.
12460 // FIXME: Use a different TDK value for this.
12461 QualType T1 =
12462 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12463 QualType T2 =
12464 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12465 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12466 S.Diag(Loc: Templated->getLocation(),
12467 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12468 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12469 << *DeductionFailure.getSecondArg() << T2;
12470 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12471 return;
12472 }
12473
12474 which = 1;
12475 } else {
12476 which = 2;
12477 }
12478
12479 // Tweak the diagnostic if the problem is that we deduced packs of
12480 // different arities. We'll print the actual packs anyway in case that
12481 // includes additional useful information.
12482 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12483 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12484 DeductionFailure.getFirstArg()->pack_size() !=
12485 DeductionFailure.getSecondArg()->pack_size()) {
12486 which = 3;
12487 }
12488
12489 S.Diag(Loc: Templated->getLocation(),
12490 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12491 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12492 << *DeductionFailure.getSecondArg();
12493 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12494 return;
12495 }
12496
12497 case TemplateDeductionResult::InvalidExplicitArguments: {
12498 assert(ParamD && "no parameter found for invalid explicit arguments");
12499
12500 auto Diag = S.Diag(Loc: Templated->getLocation(),
12501 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch);
12502 if (ParamD->getDeclName())
12503 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12504 else
12505 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12506 << (getDepthAndIndex(ND: ParamD).second + 1);
12507 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12508 SmallString<128> DiagContent;
12509 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: DiagContent);
12510 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12511 } else {
12512 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12513 }
12514
12515 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12516 return;
12517 }
12518 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12519 // Format the template argument list into the argument string.
12520 SmallString<128> TemplateArgString;
12521 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12522 TemplateArgString = " ";
12523 TemplateArgString += S.getTemplateArgumentBindingsText(
12524 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12525 if (TemplateArgString.size() == 1)
12526 TemplateArgString.clear();
12527 S.Diag(Loc: Templated->getLocation(),
12528 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12529 << TemplateArgString;
12530
12531 S.DiagnoseUnsatisfiedConstraint(
12532 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12533 return;
12534 }
12535 case TemplateDeductionResult::TooManyArguments:
12536 case TemplateDeductionResult::TooFewArguments:
12537 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12538 return;
12539
12540 case TemplateDeductionResult::InstantiationDepth:
12541 S.Diag(Loc: Templated->getLocation(),
12542 DiagID: diag::note_ovl_candidate_instantiation_depth);
12543 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12544 return;
12545
12546 case TemplateDeductionResult::SubstitutionFailure: {
12547 // Format the template argument list into the argument string.
12548 SmallString<128> TemplateArgString;
12549 if (TemplateArgumentList *Args =
12550 DeductionFailure.getTemplateArgumentList()) {
12551 TemplateArgString = " ";
12552 TemplateArgString += S.getTemplateArgumentBindingsText(
12553 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12554 if (TemplateArgString.size() == 1)
12555 TemplateArgString.clear();
12556 }
12557
12558 // If this candidate was disabled by enable_if, say so.
12559 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12560 if (PDiag && PDiag->second.getDiagID() ==
12561 diag::err_typename_nested_not_found_enable_if) {
12562 // FIXME: Use the source range of the condition, and the fully-qualified
12563 // name of the enable_if template. These are both present in PDiag.
12564 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12565 << "'enable_if'" << TemplateArgString;
12566 return;
12567 }
12568
12569 // We found a specific requirement that disabled the enable_if.
12570 if (PDiag && PDiag->second.getDiagID() ==
12571 diag::err_typename_nested_not_found_requirement) {
12572 S.Diag(Loc: Templated->getLocation(),
12573 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12574 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12575 return;
12576 }
12577
12578 // Format the SFINAE diagnostic into the argument string.
12579 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12580 // formatted message in another diagnostic.
12581 SmallString<128> SFINAEArgString;
12582 SourceRange R;
12583 if (PDiag) {
12584 SFINAEArgString = ": ";
12585 R = SourceRange(PDiag->first, PDiag->first);
12586 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12587 }
12588
12589 S.Diag(Loc: Templated->getLocation(),
12590 DiagID: diag::note_ovl_candidate_substitution_failure)
12591 << TemplateArgString << SFINAEArgString << R;
12592 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12593 return;
12594 }
12595
12596 case TemplateDeductionResult::DeducedMismatch:
12597 case TemplateDeductionResult::DeducedMismatchNested: {
12598 // Format the template argument list into the argument string.
12599 SmallString<128> TemplateArgString;
12600 if (TemplateArgumentList *Args =
12601 DeductionFailure.getTemplateArgumentList()) {
12602 TemplateArgString = " ";
12603 TemplateArgString += S.getTemplateArgumentBindingsText(
12604 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12605 if (TemplateArgString.size() == 1)
12606 TemplateArgString.clear();
12607 }
12608
12609 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12610 << (*DeductionFailure.getCallArgIndex() + 1)
12611 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12612 << TemplateArgString
12613 << (DeductionFailure.getResult() ==
12614 TemplateDeductionResult::DeducedMismatchNested);
12615 break;
12616 }
12617
12618 case TemplateDeductionResult::NonDeducedMismatch: {
12619 // FIXME: Provide a source location to indicate what we couldn't match.
12620 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12621 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12622 if (FirstTA.getKind() == TemplateArgument::Template &&
12623 SecondTA.getKind() == TemplateArgument::Template) {
12624 TemplateName FirstTN = FirstTA.getAsTemplate();
12625 TemplateName SecondTN = SecondTA.getAsTemplate();
12626 if (FirstTN.getKind() == TemplateName::Template &&
12627 SecondTN.getKind() == TemplateName::Template) {
12628 if (FirstTN.getAsTemplateDecl()->getName() ==
12629 SecondTN.getAsTemplateDecl()->getName()) {
12630 // FIXME: This fixes a bad diagnostic where both templates are named
12631 // the same. This particular case is a bit difficult since:
12632 // 1) It is passed as a string to the diagnostic printer.
12633 // 2) The diagnostic printer only attempts to find a better
12634 // name for types, not decls.
12635 // Ideally, this should folded into the diagnostic printer.
12636 S.Diag(Loc: Templated->getLocation(),
12637 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12638 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12639 return;
12640 }
12641 }
12642 }
12643
12644 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12645 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12646 return;
12647
12648 // FIXME: For generic lambda parameters, check if the function is a lambda
12649 // call operator, and if so, emit a prettier and more informative
12650 // diagnostic that mentions 'auto' and lambda in addition to
12651 // (or instead of?) the canonical template type parameters.
12652 S.Diag(Loc: Templated->getLocation(),
12653 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12654 << FirstTA << SecondTA;
12655 return;
12656 }
12657 // TODO: diagnose these individually, then kill off
12658 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12659 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12660 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12661 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12662 return;
12663 case TemplateDeductionResult::CUDATargetMismatch:
12664 S.Diag(Loc: Templated->getLocation(),
12665 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12666 return;
12667 }
12668}
12669
12670/// Diagnose a failed template-argument deduction, for function calls.
12671static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12672 unsigned NumArgs,
12673 bool TakingCandidateAddress) {
12674 assert(Cand->Function && "Candidate must be a function");
12675 FunctionDecl *Fn = Cand->Function;
12676 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12677 if (TDK == TemplateDeductionResult::TooFewArguments ||
12678 TDK == TemplateDeductionResult::TooManyArguments) {
12679 if (CheckArityMismatch(S, Cand, NumArgs))
12680 return;
12681 }
12682 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12683 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12684}
12685
12686/// CUDA: diagnose an invalid call across targets.
12687static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12688 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12689 assert(Cand->Function && "Candidate must be a Function.");
12690 FunctionDecl *Callee = Cand->Function;
12691
12692 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12693 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12694
12695 std::string FnDesc;
12696 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12697 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12698 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12699
12700 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12701 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12702 << FnDesc /* Ignored */
12703 << CalleeTarget << CallerTarget;
12704
12705 // This could be an implicit constructor for which we could not infer the
12706 // target due to a collsion. Diagnose that case.
12707 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12708 if (Meth != nullptr && Meth->isImplicit()) {
12709 CXXRecordDecl *ParentClass = Meth->getParent();
12710 CXXSpecialMemberKind CSM;
12711
12712 switch (FnKindPair.first) {
12713 default:
12714 return;
12715 case oc_implicit_default_constructor:
12716 CSM = CXXSpecialMemberKind::DefaultConstructor;
12717 break;
12718 case oc_implicit_copy_constructor:
12719 CSM = CXXSpecialMemberKind::CopyConstructor;
12720 break;
12721 case oc_implicit_move_constructor:
12722 CSM = CXXSpecialMemberKind::MoveConstructor;
12723 break;
12724 case oc_implicit_copy_assignment:
12725 CSM = CXXSpecialMemberKind::CopyAssignment;
12726 break;
12727 case oc_implicit_move_assignment:
12728 CSM = CXXSpecialMemberKind::MoveAssignment;
12729 break;
12730 };
12731
12732 bool ConstRHS = false;
12733 if (Meth->getNumParams()) {
12734 if (const ReferenceType *RT =
12735 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12736 ConstRHS = RT->getPointeeType().isConstQualified();
12737 }
12738 }
12739
12740 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12741 /* ConstRHS */ ConstRHS,
12742 /* Diagnose */ true);
12743 }
12744}
12745
12746static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12747 assert(Cand->Function && "Candidate must be a function");
12748 FunctionDecl *Callee = Cand->Function;
12749 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12750
12751 S.Diag(Loc: Callee->getLocation(),
12752 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12753 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12754}
12755
12756static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12757 assert(Cand->Function && "Candidate must be a function");
12758 FunctionDecl *Fn = Cand->Function;
12759 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12760 assert(ES.isExplicit() && "not an explicit candidate");
12761
12762 unsigned Kind;
12763 switch (Fn->getDeclKind()) {
12764 case Decl::Kind::CXXConstructor:
12765 Kind = 0;
12766 break;
12767 case Decl::Kind::CXXConversion:
12768 Kind = 1;
12769 break;
12770 case Decl::Kind::CXXDeductionGuide:
12771 Kind = Fn->isImplicit() ? 0 : 2;
12772 break;
12773 default:
12774 llvm_unreachable("invalid Decl");
12775 }
12776
12777 // Note the location of the first (in-class) declaration; a redeclaration
12778 // (particularly an out-of-class definition) will typically lack the
12779 // 'explicit' specifier.
12780 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12781 FunctionDecl *First = Fn->getFirstDecl();
12782 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12783 First = Pattern->getFirstDecl();
12784
12785 S.Diag(Loc: First->getLocation(),
12786 DiagID: diag::note_ovl_candidate_explicit)
12787 << Kind << (ES.getExpr() ? 1 : 0)
12788 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12789}
12790
12791static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12792 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12793 if (!DG)
12794 return;
12795 TemplateDecl *OriginTemplate =
12796 DG->getDeclName().getCXXDeductionGuideTemplate();
12797 // We want to always print synthesized deduction guides for type aliases.
12798 // They would retain the explicit bit of the corresponding constructor.
12799 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12800 return;
12801 std::string FunctionProto;
12802 llvm::raw_string_ostream OS(FunctionProto);
12803 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12804 if (!Template) {
12805 // This also could be an instantiation. Find out the primary template.
12806 FunctionDecl *Pattern =
12807 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12808 if (!Pattern) {
12809 // The implicit deduction guide is built on an explicit non-template
12810 // deduction guide. Currently, this might be the case only for type
12811 // aliases.
12812 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12813 // gets merged.
12814 assert(OriginTemplate->isTypeAlias() &&
12815 "Non-template implicit deduction guides are only possible for "
12816 "type aliases");
12817 DG->print(Out&: OS);
12818 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12819 << FunctionProto;
12820 return;
12821 }
12822 Template = Pattern->getDescribedFunctionTemplate();
12823 assert(Template && "Cannot find the associated function template of "
12824 "CXXDeductionGuideDecl?");
12825 }
12826 Template->print(Out&: OS);
12827 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12828 << FunctionProto;
12829}
12830
12831/// Generates a 'note' diagnostic for an overload candidate. We've
12832/// already generated a primary error at the call site.
12833///
12834/// It really does need to be a single diagnostic with its caret
12835/// pointed at the candidate declaration. Yes, this creates some
12836/// major challenges of technical writing. Yes, this makes pointing
12837/// out problems with specific arguments quite awkward. It's still
12838/// better than generating twenty screens of text for every failed
12839/// overload.
12840///
12841/// It would be great to be able to express per-candidate problems
12842/// more richly for those diagnostic clients that cared, but we'd
12843/// still have to be just as careful with the default diagnostics.
12844/// \param CtorDestAS Addr space of object being constructed (for ctor
12845/// candidates only).
12846static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12847 unsigned NumArgs,
12848 bool TakingCandidateAddress,
12849 LangAS CtorDestAS = LangAS::Default) {
12850 assert(Cand->Function && "Candidate must be a function");
12851 FunctionDecl *Fn = Cand->Function;
12852 if (shouldSkipNotingLambdaConversionDecl(Fn))
12853 return;
12854
12855 // There is no physical candidate declaration to point to for OpenCL builtins.
12856 // Except for failed conversions, the notes are identical for each candidate,
12857 // so do not generate such notes.
12858 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12859 Cand->FailureKind != ovl_fail_bad_conversion)
12860 return;
12861
12862 // Skip implicit member functions when trying to resolve
12863 // the address of a an overload set for a function pointer.
12864 if (Cand->TookAddressOfOverload &&
12865 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12866 return;
12867
12868 // Note deleted candidates, but only if they're viable.
12869 if (Cand->Viable) {
12870 if (Fn->isDeleted()) {
12871 std::string FnDesc;
12872 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12873 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12874 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12875
12876 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12877 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12878 << (Fn->isDeleted()
12879 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12880 : 0);
12881 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12882 return;
12883 }
12884
12885 // We don't really have anything else to say about viable candidates.
12886 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12887 return;
12888 }
12889
12890 // If this is a synthesized deduction guide we're deducing against, add a note
12891 // for it. These deduction guides are not explicitly spelled in the source
12892 // code, so simply printing a deduction failure note mentioning synthesized
12893 // template parameters or pointing to the header of the surrounding RecordDecl
12894 // would be confusing.
12895 //
12896 // We prefer adding such notes at the end of the deduction failure because
12897 // duplicate code snippets appearing in the diagnostic would likely become
12898 // noisy.
12899 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12900
12901 switch (Cand->FailureKind) {
12902 case ovl_fail_too_many_arguments:
12903 case ovl_fail_too_few_arguments:
12904 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12905
12906 case ovl_fail_bad_deduction:
12907 return DiagnoseBadDeduction(S, Cand, NumArgs,
12908 TakingCandidateAddress);
12909
12910 case ovl_fail_illegal_constructor: {
12911 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12912 << (Fn->getPrimaryTemplate() ? 1 : 0);
12913 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12914 return;
12915 }
12916
12917 case ovl_fail_object_addrspace_mismatch: {
12918 Qualifiers QualsForPrinting;
12919 QualsForPrinting.setAddressSpace(CtorDestAS);
12920 S.Diag(Loc: Fn->getLocation(),
12921 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12922 << QualsForPrinting;
12923 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12924 return;
12925 }
12926
12927 case ovl_fail_trivial_conversion:
12928 case ovl_fail_bad_final_conversion:
12929 case ovl_fail_final_conversion_not_exact:
12930 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12931
12932 case ovl_fail_bad_conversion: {
12933 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12934 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12935 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12936 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12937
12938 // FIXME: this currently happens when we're called from SemaInit
12939 // when user-conversion overload fails. Figure out how to handle
12940 // those conditions and diagnose them well.
12941 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12942 }
12943
12944 case ovl_fail_bad_target:
12945 return DiagnoseBadTarget(S, Cand);
12946
12947 case ovl_fail_enable_if:
12948 return DiagnoseFailedEnableIfAttr(S, Cand);
12949
12950 case ovl_fail_explicit:
12951 return DiagnoseFailedExplicitSpec(S, Cand);
12952
12953 case ovl_fail_inhctor_slice:
12954 // It's generally not interesting to note copy/move constructors here.
12955 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12956 return;
12957 S.Diag(Loc: Fn->getLocation(),
12958 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12959 << (Fn->getPrimaryTemplate() ? 1 : 0)
12960 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12961 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12962 return;
12963
12964 case ovl_fail_addr_not_available: {
12965 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12966 (void)Available;
12967 assert(!Available);
12968 break;
12969 }
12970 case ovl_non_default_multiversion_function:
12971 // Do nothing, these should simply be ignored.
12972 break;
12973
12974 case ovl_fail_constraints_not_satisfied: {
12975 std::string FnDesc;
12976 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12977 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12978 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12979
12980 S.Diag(Loc: Fn->getLocation(),
12981 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12982 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12983 << FnDesc /* Ignored */;
12984 ConstraintSatisfaction Satisfaction;
12985 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
12986 /*ForOverloadResolution=*/true))
12987 break;
12988 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12989 }
12990 }
12991}
12992
12993static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12994 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12995 return;
12996
12997 // Desugar the type of the surrogate down to a function type,
12998 // retaining as many typedefs as possible while still showing
12999 // the function type (and, therefore, its parameter types).
13000 QualType FnType = Cand->Surrogate->getConversionType();
13001 bool isLValueReference = false;
13002 bool isRValueReference = false;
13003 bool isPointer = false;
13004 if (const LValueReferenceType *FnTypeRef =
13005 FnType->getAs<LValueReferenceType>()) {
13006 FnType = FnTypeRef->getPointeeType();
13007 isLValueReference = true;
13008 } else if (const RValueReferenceType *FnTypeRef =
13009 FnType->getAs<RValueReferenceType>()) {
13010 FnType = FnTypeRef->getPointeeType();
13011 isRValueReference = true;
13012 }
13013 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13014 FnType = FnTypePtr->getPointeeType();
13015 isPointer = true;
13016 }
13017 // Desugar down to a function type.
13018 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13019 // Reconstruct the pointer/reference as appropriate.
13020 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
13021 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13022 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13023
13024 if (!Cand->Viable &&
13025 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13026 S.Diag(Loc: Cand->Surrogate->getLocation(),
13027 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13028 << Cand->Surrogate;
13029 ConstraintSatisfaction Satisfaction;
13030 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13031 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13032 } else {
13033 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13034 << FnType;
13035 }
13036}
13037
13038static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13039 SourceLocation OpLoc,
13040 OverloadCandidate *Cand) {
13041 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13042 std::string TypeStr("operator");
13043 TypeStr += Opc;
13044 TypeStr += "(";
13045 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13046 if (Cand->Conversions.size() == 1) {
13047 TypeStr += ")";
13048 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13049 } else {
13050 TypeStr += ", ";
13051 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13052 TypeStr += ")";
13053 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13054 }
13055}
13056
13057static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13058 OverloadCandidate *Cand) {
13059 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13060 if (ICS.isBad()) break; // all meaningless after first invalid
13061 if (!ICS.isAmbiguous()) continue;
13062
13063 ICS.DiagnoseAmbiguousConversion(
13064 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13065 }
13066}
13067
13068static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13069 if (Cand->Function)
13070 return Cand->Function->getLocation();
13071 if (Cand->IsSurrogate)
13072 return Cand->Surrogate->getLocation();
13073 return SourceLocation();
13074}
13075
13076static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13077 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13078 case TemplateDeductionResult::Success:
13079 case TemplateDeductionResult::NonDependentConversionFailure:
13080 case TemplateDeductionResult::AlreadyDiagnosed:
13081 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13082
13083 case TemplateDeductionResult::Invalid:
13084 case TemplateDeductionResult::Incomplete:
13085 case TemplateDeductionResult::IncompletePack:
13086 return 1;
13087
13088 case TemplateDeductionResult::Underqualified:
13089 case TemplateDeductionResult::Inconsistent:
13090 return 2;
13091
13092 case TemplateDeductionResult::SubstitutionFailure:
13093 case TemplateDeductionResult::DeducedMismatch:
13094 case TemplateDeductionResult::ConstraintsNotSatisfied:
13095 case TemplateDeductionResult::DeducedMismatchNested:
13096 case TemplateDeductionResult::NonDeducedMismatch:
13097 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13098 case TemplateDeductionResult::CUDATargetMismatch:
13099 return 3;
13100
13101 case TemplateDeductionResult::InstantiationDepth:
13102 return 4;
13103
13104 case TemplateDeductionResult::InvalidExplicitArguments:
13105 return 5;
13106
13107 case TemplateDeductionResult::TooManyArguments:
13108 case TemplateDeductionResult::TooFewArguments:
13109 return 6;
13110 }
13111 llvm_unreachable("Unhandled deduction result");
13112}
13113
13114namespace {
13115
13116struct CompareOverloadCandidatesForDisplay {
13117 Sema &S;
13118 SourceLocation Loc;
13119 size_t NumArgs;
13120 OverloadCandidateSet::CandidateSetKind CSK;
13121
13122 CompareOverloadCandidatesForDisplay(
13123 Sema &S, SourceLocation Loc, size_t NArgs,
13124 OverloadCandidateSet::CandidateSetKind CSK)
13125 : S(S), NumArgs(NArgs), CSK(CSK) {}
13126
13127 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13128 // If there are too many or too few arguments, that's the high-order bit we
13129 // want to sort by, even if the immediate failure kind was something else.
13130 if (C->FailureKind == ovl_fail_too_many_arguments ||
13131 C->FailureKind == ovl_fail_too_few_arguments)
13132 return static_cast<OverloadFailureKind>(C->FailureKind);
13133
13134 if (C->Function) {
13135 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13136 return ovl_fail_too_many_arguments;
13137 if (NumArgs < C->Function->getMinRequiredArguments())
13138 return ovl_fail_too_few_arguments;
13139 }
13140
13141 return static_cast<OverloadFailureKind>(C->FailureKind);
13142 }
13143
13144 bool operator()(const OverloadCandidate *L,
13145 const OverloadCandidate *R) {
13146 // Fast-path this check.
13147 if (L == R) return false;
13148
13149 // Order first by viability.
13150 if (L->Viable) {
13151 if (!R->Viable) return true;
13152
13153 if (int Ord = CompareConversions(L: *L, R: *R))
13154 return Ord < 0;
13155 // Use other tie breakers.
13156 } else if (R->Viable)
13157 return false;
13158
13159 assert(L->Viable == R->Viable);
13160
13161 // Criteria by which we can sort non-viable candidates:
13162 if (!L->Viable) {
13163 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13164 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13165
13166 // 1. Arity mismatches come after other candidates.
13167 if (LFailureKind == ovl_fail_too_many_arguments ||
13168 LFailureKind == ovl_fail_too_few_arguments) {
13169 if (RFailureKind == ovl_fail_too_many_arguments ||
13170 RFailureKind == ovl_fail_too_few_arguments) {
13171 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13172 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13173 if (LDist == RDist) {
13174 if (LFailureKind == RFailureKind)
13175 // Sort non-surrogates before surrogates.
13176 return !L->IsSurrogate && R->IsSurrogate;
13177 // Sort candidates requiring fewer parameters than there were
13178 // arguments given after candidates requiring more parameters
13179 // than there were arguments given.
13180 return LFailureKind == ovl_fail_too_many_arguments;
13181 }
13182 return LDist < RDist;
13183 }
13184 return false;
13185 }
13186 if (RFailureKind == ovl_fail_too_many_arguments ||
13187 RFailureKind == ovl_fail_too_few_arguments)
13188 return true;
13189
13190 // 2. Bad conversions come first and are ordered by the number
13191 // of bad conversions and quality of good conversions.
13192 if (LFailureKind == ovl_fail_bad_conversion) {
13193 if (RFailureKind != ovl_fail_bad_conversion)
13194 return true;
13195
13196 // The conversion that can be fixed with a smaller number of changes,
13197 // comes first.
13198 unsigned numLFixes = L->Fix.NumConversionsFixed;
13199 unsigned numRFixes = R->Fix.NumConversionsFixed;
13200 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13201 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13202 if (numLFixes != numRFixes) {
13203 return numLFixes < numRFixes;
13204 }
13205
13206 // If there's any ordering between the defined conversions...
13207 if (int Ord = CompareConversions(L: *L, R: *R))
13208 return Ord < 0;
13209 } else if (RFailureKind == ovl_fail_bad_conversion)
13210 return false;
13211
13212 if (LFailureKind == ovl_fail_bad_deduction) {
13213 if (RFailureKind != ovl_fail_bad_deduction)
13214 return true;
13215
13216 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13217 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13218 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13219 if (LRank != RRank)
13220 return LRank < RRank;
13221 }
13222 } else if (RFailureKind == ovl_fail_bad_deduction)
13223 return false;
13224
13225 // TODO: others?
13226 }
13227
13228 // Sort everything else by location.
13229 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13230 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13231
13232 // Put candidates without locations (e.g. builtins) at the end.
13233 if (LLoc.isValid() && RLoc.isValid())
13234 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13235 if (LLoc.isValid() && !RLoc.isValid())
13236 return true;
13237 if (RLoc.isValid() && !LLoc.isValid())
13238 return false;
13239 assert(!LLoc.isValid() && !RLoc.isValid());
13240 // For builtins and other functions without locations, fallback to the order
13241 // in which they were added into the candidate set.
13242 return L < R;
13243 }
13244
13245private:
13246 struct ConversionSignals {
13247 unsigned KindRank = 0;
13248 ImplicitConversionRank Rank = ICR_Exact_Match;
13249
13250 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13251 ConversionSignals Sig;
13252 Sig.KindRank = Seq.getKindRank();
13253 if (Seq.isStandard())
13254 Sig.Rank = Seq.Standard.getRank();
13255 else if (Seq.isUserDefined())
13256 Sig.Rank = Seq.UserDefined.After.getRank();
13257 // We intend StaticObjectArgumentConversion to compare the same as
13258 // StandardConversion with ICR_ExactMatch rank.
13259 return Sig;
13260 }
13261
13262 static ConversionSignals ForObjectArgument() {
13263 // We intend StaticObjectArgumentConversion to compare the same as
13264 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13265 return {};
13266 }
13267 };
13268
13269 // Returns -1 if conversions in L are considered better.
13270 // 0 if they are considered indistinguishable.
13271 // 1 if conversions in R are better.
13272 int CompareConversions(const OverloadCandidate &L,
13273 const OverloadCandidate &R) {
13274 // We cannot use `isBetterOverloadCandidate` because it is defined
13275 // according to the C++ standard and provides a partial order, but we need
13276 // a total order as this function is used in sort.
13277 assert(L.Conversions.size() == R.Conversions.size());
13278 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13279 auto LS = L.IgnoreObjectArgument && I == 0
13280 ? ConversionSignals::ForObjectArgument()
13281 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13282 auto RS = R.IgnoreObjectArgument
13283 ? ConversionSignals::ForObjectArgument()
13284 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13285 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13286 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13287 ? -1
13288 : 1;
13289 }
13290 // FIXME: find a way to compare templates for being more or less
13291 // specialized that provides a strict weak ordering.
13292 return 0;
13293 }
13294};
13295}
13296
13297/// CompleteNonViableCandidate - Normally, overload resolution only
13298/// computes up to the first bad conversion. Produces the FixIt set if
13299/// possible.
13300static void
13301CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13302 ArrayRef<Expr *> Args,
13303 OverloadCandidateSet::CandidateSetKind CSK) {
13304 assert(!Cand->Viable);
13305
13306 // Don't do anything on failures other than bad conversion.
13307 if (Cand->FailureKind != ovl_fail_bad_conversion)
13308 return;
13309
13310 // We only want the FixIts if all the arguments can be corrected.
13311 bool Unfixable = false;
13312 // Use a implicit copy initialization to check conversion fixes.
13313 Cand->Fix.setConversionChecker(TryCopyInitialization);
13314
13315 // Attempt to fix the bad conversion.
13316 unsigned ConvCount = Cand->Conversions.size();
13317 for (unsigned ConvIdx =
13318 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13319 : 0);
13320 /**/; ++ConvIdx) {
13321 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13322 if (Cand->Conversions[ConvIdx].isInitialized() &&
13323 Cand->Conversions[ConvIdx].isBad()) {
13324 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13325 break;
13326 }
13327 }
13328
13329 // FIXME: this should probably be preserved from the overload
13330 // operation somehow.
13331 bool SuppressUserConversions = false;
13332
13333 unsigned ConvIdx = 0;
13334 unsigned ArgIdx = 0;
13335 ArrayRef<QualType> ParamTypes;
13336 bool Reversed = Cand->isReversed();
13337
13338 if (Cand->IsSurrogate) {
13339 QualType ConvType
13340 = Cand->Surrogate->getConversionType().getNonReferenceType();
13341 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13342 ConvType = ConvPtrType->getPointeeType();
13343 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13344 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13345 ConvIdx = 1;
13346 } else if (Cand->Function) {
13347 ParamTypes =
13348 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13349 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13350 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13351 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13352 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13353 ConvIdx = 1;
13354 if (CSK == OverloadCandidateSet::CSK_Operator &&
13355 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13356 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13357 OO_Subscript)
13358 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13359 ArgIdx = 1;
13360 }
13361 } else {
13362 // Builtin operator.
13363 assert(ConvCount <= 3);
13364 ParamTypes = Cand->BuiltinParamTypes;
13365 }
13366
13367 // Fill in the rest of the conversions.
13368 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13369 ConvIdx != ConvCount && ArgIdx < Args.size();
13370 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13371 if (Cand->Conversions[ConvIdx].isInitialized()) {
13372 // We've already checked this conversion.
13373 } else if (ParamIdx < ParamTypes.size()) {
13374 if (ParamTypes[ParamIdx]->isDependentType())
13375 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13376 Args[ArgIdx]->getType());
13377 else {
13378 Cand->Conversions[ConvIdx] =
13379 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13380 SuppressUserConversions,
13381 /*InOverloadResolution=*/true,
13382 /*AllowObjCWritebackConversion=*/
13383 S.getLangOpts().ObjCAutoRefCount);
13384 // Store the FixIt in the candidate if it exists.
13385 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13386 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13387 }
13388 } else
13389 Cand->Conversions[ConvIdx].setEllipsis();
13390 }
13391}
13392
13393SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13394 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13395 SourceLocation OpLoc,
13396 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13397
13398 InjectNonDeducedTemplateCandidates(S);
13399
13400 // Sort the candidates by viability and position. Sorting directly would
13401 // be prohibitive, so we make a set of pointers and sort those.
13402 SmallVector<OverloadCandidate*, 32> Cands;
13403 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13404 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13405 Cand != LastCand; ++Cand) {
13406 if (!Filter(*Cand))
13407 continue;
13408 switch (OCD) {
13409 case OCD_AllCandidates:
13410 if (!Cand->Viable) {
13411 if (!Cand->Function && !Cand->IsSurrogate) {
13412 // This a non-viable builtin candidate. We do not, in general,
13413 // want to list every possible builtin candidate.
13414 continue;
13415 }
13416 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13417 }
13418 break;
13419
13420 case OCD_ViableCandidates:
13421 if (!Cand->Viable)
13422 continue;
13423 break;
13424
13425 case OCD_AmbiguousCandidates:
13426 if (!Cand->Best)
13427 continue;
13428 break;
13429 }
13430
13431 Cands.push_back(Elt: Cand);
13432 }
13433
13434 llvm::stable_sort(
13435 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13436
13437 return Cands;
13438}
13439
13440bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13441 SourceLocation OpLoc) {
13442 bool DeferHint = false;
13443 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13444 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13445 // host device candidates.
13446 auto WrongSidedCands =
13447 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13448 return (Cand.Viable == false &&
13449 Cand.FailureKind == ovl_fail_bad_target) ||
13450 (Cand.Function &&
13451 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13452 Cand.Function->template hasAttr<CUDADeviceAttr>());
13453 });
13454 DeferHint = !WrongSidedCands.empty();
13455 }
13456 return DeferHint;
13457}
13458
13459/// When overload resolution fails, prints diagnostic messages containing the
13460/// candidates in the candidate set.
13461void OverloadCandidateSet::NoteCandidates(
13462 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13463 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13464 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13465
13466 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13467
13468 {
13469 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13470 S.Diag(Loc: PD.first, PD: PD.second);
13471 }
13472
13473 // In WebAssembly we don't want to emit further diagnostics if a table is
13474 // passed as an argument to a function.
13475 bool NoteCands = true;
13476 for (const Expr *Arg : Args) {
13477 if (Arg->getType()->isWebAssemblyTableType())
13478 NoteCands = false;
13479 }
13480
13481 if (NoteCands)
13482 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13483
13484 if (OCD == OCD_AmbiguousCandidates)
13485 MaybeDiagnoseAmbiguousConstraints(S,
13486 Cands: {Candidates.begin(), Candidates.end()});
13487}
13488
13489void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13490 ArrayRef<OverloadCandidate *> Cands,
13491 StringRef Opc, SourceLocation OpLoc) {
13492 bool ReportedAmbiguousConversions = false;
13493
13494 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13495 unsigned CandsShown = 0;
13496 auto I = Cands.begin(), E = Cands.end();
13497 for (; I != E; ++I) {
13498 OverloadCandidate *Cand = *I;
13499
13500 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13501 ShowOverloads == Ovl_Best) {
13502 break;
13503 }
13504 ++CandsShown;
13505
13506 if (Cand->Function)
13507 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13508 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13509 else if (Cand->IsSurrogate)
13510 NoteSurrogateCandidate(S, Cand);
13511 else {
13512 assert(Cand->Viable &&
13513 "Non-viable built-in candidates are not added to Cands.");
13514 // Generally we only see ambiguities including viable builtin
13515 // operators if overload resolution got screwed up by an
13516 // ambiguous user-defined conversion.
13517 //
13518 // FIXME: It's quite possible for different conversions to see
13519 // different ambiguities, though.
13520 if (!ReportedAmbiguousConversions) {
13521 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13522 ReportedAmbiguousConversions = true;
13523 }
13524
13525 // If this is a viable builtin, print it.
13526 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13527 }
13528 }
13529
13530 // Inform S.Diags that we've shown an overload set with N elements. This may
13531 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13532 S.Diags.overloadCandidatesShown(N: CandsShown);
13533
13534 if (I != E) {
13535 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13536 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13537 }
13538}
13539
13540bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
13541 const Sema &S) const {
13542 if (S.getLangOpts().CUDA) {
13543 auto *Caller = S.getCurFunctionDecl(AllowLambda: true);
13544 // Overloading based on __host__ and __device__ attributes takes
13545 // higher priority, HD functions may favor template candidates even when a
13546 // non-template candidate would be a perfect match.
13547 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13548 Caller->hasAttr<CUDADeviceAttr>())
13549 return false;
13550 }
13551
13552 return
13553 // For user defined conversion we need to check against different
13554 // combination of CV qualifiers and look at any explicit specifier, so
13555 // always deduce template candidates.
13556 Kind != CSK_InitByUserDefinedConversion
13557 // When doing code completion, we want to see all the
13558 // viable candidates.
13559 && Kind != CSK_CodeCompletion;
13560}
13561
13562static SourceLocation
13563GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13564 return Cand->Specialization ? Cand->Specialization->getLocation()
13565 : SourceLocation();
13566}
13567
13568namespace {
13569struct CompareTemplateSpecCandidatesForDisplay {
13570 Sema &S;
13571 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13572
13573 bool operator()(const TemplateSpecCandidate *L,
13574 const TemplateSpecCandidate *R) {
13575 // Fast-path this check.
13576 if (L == R)
13577 return false;
13578
13579 // Assuming that both candidates are not matches...
13580
13581 // Sort by the ranking of deduction failures.
13582 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13583 return RankDeductionFailure(DFI: L->DeductionFailure) <
13584 RankDeductionFailure(DFI: R->DeductionFailure);
13585
13586 // Sort everything else by location.
13587 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13588 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13589
13590 // Put candidates without locations (e.g. builtins) at the end.
13591 if (LLoc.isInvalid())
13592 return false;
13593 if (RLoc.isInvalid())
13594 return true;
13595
13596 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13597 }
13598};
13599}
13600
13601/// Diagnose a template argument deduction failure.
13602/// We are treating these failures as overload failures due to bad
13603/// deductions.
13604void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13605 bool ForTakingAddress) {
13606 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13607 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13608}
13609
13610void TemplateSpecCandidateSet::destroyCandidates() {
13611 for (iterator i = begin(), e = end(); i != e; ++i) {
13612 i->DeductionFailure.Destroy();
13613 }
13614}
13615
13616void TemplateSpecCandidateSet::clear() {
13617 destroyCandidates();
13618 Candidates.clear();
13619}
13620
13621/// NoteCandidates - When no template specialization match is found, prints
13622/// diagnostic messages containing the non-matching specializations that form
13623/// the candidate set.
13624/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13625/// OCD == OCD_AllCandidates and Cand->Viable == false.
13626void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13627 // Sort the candidates by position (assuming no candidate is a match).
13628 // Sorting directly would be prohibitive, so we make a set of pointers
13629 // and sort those.
13630 SmallVector<TemplateSpecCandidate *, 32> Cands;
13631 Cands.reserve(N: size());
13632 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13633 if (Cand->Specialization)
13634 Cands.push_back(Elt: Cand);
13635 // Otherwise, this is a non-matching builtin candidate. We do not,
13636 // in general, want to list every possible builtin candidate.
13637 }
13638
13639 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13640
13641 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13642 // for generalization purposes (?).
13643 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13644
13645 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13646 unsigned CandsShown = 0;
13647 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13648 TemplateSpecCandidate *Cand = *I;
13649
13650 // Set an arbitrary limit on the number of candidates we'll spam
13651 // the user with. FIXME: This limit should depend on details of the
13652 // candidate list.
13653 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13654 break;
13655 ++CandsShown;
13656
13657 assert(Cand->Specialization &&
13658 "Non-matching built-in candidates are not added to Cands.");
13659 Cand->NoteDeductionFailure(S, ForTakingAddress);
13660 }
13661
13662 if (I != E)
13663 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13664}
13665
13666// [PossiblyAFunctionType] --> [Return]
13667// NonFunctionType --> NonFunctionType
13668// R (A) --> R(A)
13669// R (*)(A) --> R (A)
13670// R (&)(A) --> R (A)
13671// R (S::*)(A) --> R (A)
13672QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13673 QualType Ret = PossiblyAFunctionType;
13674 if (const PointerType *ToTypePtr =
13675 PossiblyAFunctionType->getAs<PointerType>())
13676 Ret = ToTypePtr->getPointeeType();
13677 else if (const ReferenceType *ToTypeRef =
13678 PossiblyAFunctionType->getAs<ReferenceType>())
13679 Ret = ToTypeRef->getPointeeType();
13680 else if (const MemberPointerType *MemTypePtr =
13681 PossiblyAFunctionType->getAs<MemberPointerType>())
13682 Ret = MemTypePtr->getPointeeType();
13683 Ret =
13684 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13685 return Ret;
13686}
13687
13688static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13689 bool Complain = true) {
13690 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13691 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13692 return true;
13693
13694 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13695 if (S.getLangOpts().CPlusPlus17 &&
13696 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13697 !S.ResolveExceptionSpec(Loc, FPT))
13698 return true;
13699
13700 return false;
13701}
13702
13703namespace {
13704// A helper class to help with address of function resolution
13705// - allows us to avoid passing around all those ugly parameters
13706class AddressOfFunctionResolver {
13707 Sema& S;
13708 Expr* SourceExpr;
13709 const QualType& TargetType;
13710 QualType TargetFunctionType; // Extracted function type from target type
13711
13712 bool Complain;
13713 //DeclAccessPair& ResultFunctionAccessPair;
13714 ASTContext& Context;
13715
13716 bool TargetTypeIsNonStaticMemberFunction;
13717 bool FoundNonTemplateFunction;
13718 bool StaticMemberFunctionFromBoundPointer;
13719 bool HasComplained;
13720
13721 OverloadExpr::FindResult OvlExprInfo;
13722 OverloadExpr *OvlExpr;
13723 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13724 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13725 TemplateSpecCandidateSet FailedCandidates;
13726
13727public:
13728 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13729 const QualType &TargetType, bool Complain)
13730 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13731 Complain(Complain), Context(S.getASTContext()),
13732 TargetTypeIsNonStaticMemberFunction(
13733 !!TargetType->getAs<MemberPointerType>()),
13734 FoundNonTemplateFunction(false),
13735 StaticMemberFunctionFromBoundPointer(false),
13736 HasComplained(false),
13737 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13738 OvlExpr(OvlExprInfo.Expression),
13739 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13740 ExtractUnqualifiedFunctionTypeFromTargetType();
13741
13742 if (TargetFunctionType->isFunctionType()) {
13743 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13744 if (!UME->isImplicitAccess() &&
13745 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13746 StaticMemberFunctionFromBoundPointer = true;
13747 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13748 DeclAccessPair dap;
13749 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13750 ovl: OvlExpr, Complain: false, Found: &dap)) {
13751 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13752 if (!Method->isStatic()) {
13753 // If the target type is a non-function type and the function found
13754 // is a non-static member function, pretend as if that was the
13755 // target, it's the only possible type to end up with.
13756 TargetTypeIsNonStaticMemberFunction = true;
13757
13758 // And skip adding the function if its not in the proper form.
13759 // We'll diagnose this due to an empty set of functions.
13760 if (!OvlExprInfo.HasFormOfMemberPointer)
13761 return;
13762 }
13763
13764 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13765 }
13766 return;
13767 }
13768
13769 if (OvlExpr->hasExplicitTemplateArgs())
13770 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13771
13772 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13773 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13774 EliminateSuboptimalCudaMatches();
13775
13776 // C++ [over.over]p4:
13777 // If more than one function is selected, [...]
13778 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13779 if (FoundNonTemplateFunction) {
13780 EliminateAllTemplateMatches();
13781 EliminateLessPartialOrderingConstrainedMatches();
13782 } else
13783 EliminateAllExceptMostSpecializedTemplate();
13784 }
13785 }
13786 }
13787
13788 bool hasComplained() const { return HasComplained; }
13789
13790private:
13791 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13792 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13793 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13794 }
13795
13796 /// \return true if A is considered a better overload candidate for the
13797 /// desired type than B.
13798 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13799 // If A doesn't have exactly the correct type, we don't want to classify it
13800 // as "better" than anything else. This way, the user is required to
13801 // disambiguate for us if there are multiple candidates and no exact match.
13802 return candidateHasExactlyCorrectType(FD: A) &&
13803 (!candidateHasExactlyCorrectType(FD: B) ||
13804 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13805 }
13806
13807 /// \return true if we were able to eliminate all but one overload candidate,
13808 /// false otherwise.
13809 bool eliminiateSuboptimalOverloadCandidates() {
13810 // Same algorithm as overload resolution -- one pass to pick the "best",
13811 // another pass to be sure that nothing is better than the best.
13812 auto Best = Matches.begin();
13813 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13814 if (isBetterCandidate(A: I->second, B: Best->second))
13815 Best = I;
13816
13817 const FunctionDecl *BestFn = Best->second;
13818 auto IsBestOrInferiorToBest = [this, BestFn](
13819 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13820 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13821 };
13822
13823 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13824 // option, so we can potentially give the user a better error
13825 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13826 return false;
13827 Matches[0] = *Best;
13828 Matches.resize(N: 1);
13829 return true;
13830 }
13831
13832 bool isTargetTypeAFunction() const {
13833 return TargetFunctionType->isFunctionType();
13834 }
13835
13836 // [ToType] [Return]
13837
13838 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13839 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13840 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13841 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13842 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13843 }
13844
13845 // return true if any matching specializations were found
13846 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13847 const DeclAccessPair& CurAccessFunPair) {
13848 if (CXXMethodDecl *Method
13849 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13850 // Skip non-static function templates when converting to pointer, and
13851 // static when converting to member pointer.
13852 bool CanConvertToFunctionPointer =
13853 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13854 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13855 return false;
13856 }
13857 else if (TargetTypeIsNonStaticMemberFunction)
13858 return false;
13859
13860 // C++ [over.over]p2:
13861 // If the name is a function template, template argument deduction is
13862 // done (14.8.2.2), and if the argument deduction succeeds, the
13863 // resulting template argument list is used to generate a single
13864 // function template specialization, which is added to the set of
13865 // overloaded functions considered.
13866 FunctionDecl *Specialization = nullptr;
13867 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13868 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13869 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13870 Specialization, Info, /*IsAddressOfFunction*/ true);
13871 Result != TemplateDeductionResult::Success) {
13872 // Make a note of the failed deduction for diagnostics.
13873 FailedCandidates.addCandidate()
13874 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13875 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13876 return false;
13877 }
13878
13879 // Template argument deduction ensures that we have an exact match or
13880 // compatible pointer-to-function arguments that would be adjusted by ICS.
13881 // This function template specicalization works.
13882 assert(S.isSameOrCompatibleFunctionType(
13883 Context.getCanonicalType(Specialization->getType()),
13884 Context.getCanonicalType(TargetFunctionType)));
13885
13886 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13887 return false;
13888
13889 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13890 return true;
13891 }
13892
13893 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13894 const DeclAccessPair& CurAccessFunPair) {
13895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13896 // Skip non-static functions when converting to pointer, and static
13897 // when converting to member pointer.
13898 bool CanConvertToFunctionPointer =
13899 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13900 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13901 return false;
13902 }
13903 else if (TargetTypeIsNonStaticMemberFunction)
13904 return false;
13905
13906 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13907 if (S.getLangOpts().CUDA) {
13908 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13909 if (!(Caller && Caller->isImplicit()) &&
13910 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13911 return false;
13912 }
13913 if (FunDecl->isMultiVersion()) {
13914 const auto *TA = FunDecl->getAttr<TargetAttr>();
13915 if (TA && !TA->isDefaultVersion())
13916 return false;
13917 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13918 if (TVA && !TVA->isDefaultVersion())
13919 return false;
13920 }
13921
13922 // If any candidate has a placeholder return type, trigger its deduction
13923 // now.
13924 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13925 Complain)) {
13926 HasComplained |= Complain;
13927 return false;
13928 }
13929
13930 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13931 return false;
13932
13933 // If we're in C, we need to support types that aren't exactly identical.
13934 if (!S.getLangOpts().CPlusPlus ||
13935 candidateHasExactlyCorrectType(FD: FunDecl)) {
13936 Matches.push_back(Elt: std::make_pair(
13937 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13938 FoundNonTemplateFunction = true;
13939 return true;
13940 }
13941 }
13942
13943 return false;
13944 }
13945
13946 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13947 bool Ret = false;
13948
13949 // If the overload expression doesn't have the form of a pointer to
13950 // member, don't try to convert it to a pointer-to-member type.
13951 if (IsInvalidFormOfPointerToMemberFunction())
13952 return false;
13953
13954 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13955 E = OvlExpr->decls_end();
13956 I != E; ++I) {
13957 // Look through any using declarations to find the underlying function.
13958 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13959
13960 // C++ [over.over]p3:
13961 // Non-member functions and static member functions match
13962 // targets of type "pointer-to-function" or "reference-to-function."
13963 // Nonstatic member functions match targets of
13964 // type "pointer-to-member-function."
13965 // Note that according to DR 247, the containing class does not matter.
13966 if (FunctionTemplateDecl *FunctionTemplate
13967 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13968 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13969 Ret = true;
13970 }
13971 // If we have explicit template arguments supplied, skip non-templates.
13972 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13973 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13974 Ret = true;
13975 }
13976 assert(Ret || Matches.empty());
13977 return Ret;
13978 }
13979
13980 void EliminateAllExceptMostSpecializedTemplate() {
13981 // [...] and any given function template specialization F1 is
13982 // eliminated if the set contains a second function template
13983 // specialization whose function template is more specialized
13984 // than the function template of F1 according to the partial
13985 // ordering rules of 14.5.5.2.
13986
13987 // The algorithm specified above is quadratic. We instead use a
13988 // two-pass algorithm (similar to the one used to identify the
13989 // best viable function in an overload set) that identifies the
13990 // best function template (if it exists).
13991
13992 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13993 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13994 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13995
13996 // TODO: It looks like FailedCandidates does not serve much purpose
13997 // here, since the no_viable diagnostic has index 0.
13998 UnresolvedSetIterator Result = S.getMostSpecialized(
13999 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
14000 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
14001 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
14002 << Matches[0].second->getDeclName(),
14003 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
14004 << (unsigned)oc_function << (unsigned)ocs_described_template,
14005 Complain, TargetType: TargetFunctionType);
14006
14007 if (Result != MatchesCopy.end()) {
14008 // Make it the first and only element
14009 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14010 Matches[0].second = cast<FunctionDecl>(Val: *Result);
14011 Matches.resize(N: 1);
14012 } else
14013 HasComplained |= Complain;
14014 }
14015
14016 void EliminateAllTemplateMatches() {
14017 // [...] any function template specializations in the set are
14018 // eliminated if the set also contains a non-template function, [...]
14019 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14020 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14021 ++I;
14022 else {
14023 Matches[I] = Matches[--N];
14024 Matches.resize(N);
14025 }
14026 }
14027 }
14028
14029 void EliminateLessPartialOrderingConstrainedMatches() {
14030 // C++ [over.over]p5:
14031 // [...] Any given non-template function F0 is eliminated if the set
14032 // contains a second non-template function that is more
14033 // partial-ordering-constrained than F0. [...]
14034 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14035 "Call EliminateAllTemplateMatches() first");
14036 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14037 Results.push_back(Elt: Matches[0]);
14038 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14039 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14040 FunctionDecl *F = getMorePartialOrderingConstrained(
14041 S, Fn1: Matches[I].second, Fn2: Results[0].second,
14042 /*IsFn1Reversed=*/false,
14043 /*IsFn2Reversed=*/false);
14044 if (!F) {
14045 Results.push_back(Elt: Matches[I]);
14046 continue;
14047 }
14048 if (F == Matches[I].second) {
14049 Results.clear();
14050 Results.push_back(Elt: Matches[I]);
14051 }
14052 }
14053 std::swap(LHS&: Matches, RHS&: Results);
14054 }
14055
14056 void EliminateSuboptimalCudaMatches() {
14057 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14058 Matches);
14059 }
14060
14061public:
14062 void ComplainNoMatchesFound() const {
14063 assert(Matches.empty());
14064 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14065 << OvlExpr->getName() << TargetFunctionType
14066 << OvlExpr->getSourceRange();
14067 if (FailedCandidates.empty())
14068 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14069 /*TakingAddress=*/true);
14070 else {
14071 // We have some deduction failure messages. Use them to diagnose
14072 // the function templates, and diagnose the non-template candidates
14073 // normally.
14074 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14075 IEnd = OvlExpr->decls_end();
14076 I != IEnd; ++I)
14077 if (FunctionDecl *Fun =
14078 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14079 if (!functionHasPassObjectSizeParams(FD: Fun))
14080 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14081 /*TakingAddress=*/true);
14082 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14083 }
14084 }
14085
14086 bool IsInvalidFormOfPointerToMemberFunction() const {
14087 return TargetTypeIsNonStaticMemberFunction &&
14088 !OvlExprInfo.HasFormOfMemberPointer;
14089 }
14090
14091 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14092 // TODO: Should we condition this on whether any functions might
14093 // have matched, or is it more appropriate to do that in callers?
14094 // TODO: a fixit wouldn't hurt.
14095 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14096 << TargetType << OvlExpr->getSourceRange();
14097 }
14098
14099 bool IsStaticMemberFunctionFromBoundPointer() const {
14100 return StaticMemberFunctionFromBoundPointer;
14101 }
14102
14103 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14104 S.Diag(Loc: OvlExpr->getBeginLoc(),
14105 DiagID: diag::err_invalid_form_pointer_member_function)
14106 << OvlExpr->getSourceRange();
14107 }
14108
14109 void ComplainOfInvalidConversion() const {
14110 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14111 << OvlExpr->getName() << TargetType;
14112 }
14113
14114 void ComplainMultipleMatchesFound() const {
14115 assert(Matches.size() > 1);
14116 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14117 << OvlExpr->getName() << OvlExpr->getSourceRange();
14118 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14119 /*TakingAddress=*/true);
14120 }
14121
14122 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14123
14124 int getNumMatches() const { return Matches.size(); }
14125
14126 FunctionDecl* getMatchingFunctionDecl() const {
14127 if (Matches.size() != 1) return nullptr;
14128 return Matches[0].second;
14129 }
14130
14131 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14132 if (Matches.size() != 1) return nullptr;
14133 return &Matches[0].first;
14134 }
14135};
14136}
14137
14138FunctionDecl *
14139Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14140 QualType TargetType,
14141 bool Complain,
14142 DeclAccessPair &FoundResult,
14143 bool *pHadMultipleCandidates) {
14144 assert(AddressOfExpr->getType() == Context.OverloadTy);
14145
14146 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14147 Complain);
14148 int NumMatches = Resolver.getNumMatches();
14149 FunctionDecl *Fn = nullptr;
14150 bool ShouldComplain = Complain && !Resolver.hasComplained();
14151 if (NumMatches == 0 && ShouldComplain) {
14152 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14153 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14154 else
14155 Resolver.ComplainNoMatchesFound();
14156 }
14157 else if (NumMatches > 1 && ShouldComplain)
14158 Resolver.ComplainMultipleMatchesFound();
14159 else if (NumMatches == 1) {
14160 Fn = Resolver.getMatchingFunctionDecl();
14161 assert(Fn);
14162 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14163 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14164 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14165 if (Complain) {
14166 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14167 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14168 else
14169 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14170 }
14171 }
14172
14173 if (pHadMultipleCandidates)
14174 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14175 return Fn;
14176}
14177
14178FunctionDecl *
14179Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14180 OverloadExpr::FindResult R = OverloadExpr::find(E);
14181 OverloadExpr *Ovl = R.Expression;
14182 bool IsResultAmbiguous = false;
14183 FunctionDecl *Result = nullptr;
14184 DeclAccessPair DAP;
14185 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14186
14187 // Return positive for better, negative for worse, 0 for equal preference.
14188 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14189 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14190 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14191 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14192 };
14193
14194 // Don't use the AddressOfResolver because we're specifically looking for
14195 // cases where we have one overload candidate that lacks
14196 // enable_if/pass_object_size/...
14197 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14198 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14199 if (!FD)
14200 return nullptr;
14201
14202 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14203 continue;
14204
14205 // If we found a better result, update Result.
14206 auto FoundBetter = [&]() {
14207 IsResultAmbiguous = false;
14208 DAP = I.getPair();
14209 Result = FD;
14210 };
14211
14212 // We have more than one result - see if it is more
14213 // partial-ordering-constrained than the previous one.
14214 if (Result) {
14215 // Check CUDA preference first. If the candidates have differennt CUDA
14216 // preference, choose the one with higher CUDA preference. Otherwise,
14217 // choose the one with more constraints.
14218 if (getLangOpts().CUDA) {
14219 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14220 // FD has different preference than Result.
14221 if (PreferenceByCUDA != 0) {
14222 // FD is more preferable than Result.
14223 if (PreferenceByCUDA > 0)
14224 FoundBetter();
14225 continue;
14226 }
14227 }
14228 // FD has the same CUDA preference than Result. Continue to check
14229 // constraints.
14230
14231 // C++ [over.over]p5:
14232 // [...] Any given non-template function F0 is eliminated if the set
14233 // contains a second non-template function that is more
14234 // partial-ordering-constrained than F0 [...]
14235 FunctionDecl *MoreConstrained =
14236 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14237 /*IsFn1Reversed=*/false,
14238 /*IsFn2Reversed=*/false);
14239 if (MoreConstrained != FD) {
14240 if (!MoreConstrained) {
14241 IsResultAmbiguous = true;
14242 AmbiguousDecls.push_back(Elt: FD);
14243 }
14244 continue;
14245 }
14246 // FD is more constrained - replace Result with it.
14247 }
14248 FoundBetter();
14249 }
14250
14251 if (IsResultAmbiguous)
14252 return nullptr;
14253
14254 if (Result) {
14255 // We skipped over some ambiguous declarations which might be ambiguous with
14256 // the selected result.
14257 for (FunctionDecl *Skipped : AmbiguousDecls) {
14258 // If skipped candidate has different CUDA preference than the result,
14259 // there is no ambiguity. Otherwise check whether they have different
14260 // constraints.
14261 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14262 continue;
14263 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14264 return nullptr;
14265 }
14266 Pair = DAP;
14267 }
14268 return Result;
14269}
14270
14271bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14272 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14273 Expr *E = SrcExpr.get();
14274 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14275
14276 DeclAccessPair DAP;
14277 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14278 if (!Found || Found->isCPUDispatchMultiVersion() ||
14279 Found->isCPUSpecificMultiVersion())
14280 return false;
14281
14282 // Emitting multiple diagnostics for a function that is both inaccessible and
14283 // unavailable is consistent with our behavior elsewhere. So, always check
14284 // for both.
14285 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14286 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14287 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14288 if (Res.isInvalid())
14289 return false;
14290 Expr *Fixed = Res.get();
14291 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14292 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14293 else
14294 SrcExpr = Fixed;
14295 return true;
14296}
14297
14298FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14299 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14300 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14301 // C++ [over.over]p1:
14302 // [...] [Note: any redundant set of parentheses surrounding the
14303 // overloaded function name is ignored (5.1). ]
14304 // C++ [over.over]p1:
14305 // [...] The overloaded function name can be preceded by the &
14306 // operator.
14307
14308 // If we didn't actually find any template-ids, we're done.
14309 if (!ovl->hasExplicitTemplateArgs())
14310 return nullptr;
14311
14312 TemplateArgumentListInfo ExplicitTemplateArgs;
14313 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14314
14315 // Look through all of the overloaded functions, searching for one
14316 // whose type matches exactly.
14317 FunctionDecl *Matched = nullptr;
14318 for (UnresolvedSetIterator I = ovl->decls_begin(),
14319 E = ovl->decls_end(); I != E; ++I) {
14320 // C++0x [temp.arg.explicit]p3:
14321 // [...] In contexts where deduction is done and fails, or in contexts
14322 // where deduction is not done, if a template argument list is
14323 // specified and it, along with any default template arguments,
14324 // identifies a single function template specialization, then the
14325 // template-id is an lvalue for the function template specialization.
14326 FunctionTemplateDecl *FunctionTemplate =
14327 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14328 if (!FunctionTemplate)
14329 continue;
14330
14331 // C++ [over.over]p2:
14332 // If the name is a function template, template argument deduction is
14333 // done (14.8.2.2), and if the argument deduction succeeds, the
14334 // resulting template argument list is used to generate a single
14335 // function template specialization, which is added to the set of
14336 // overloaded functions considered.
14337 FunctionDecl *Specialization = nullptr;
14338 TemplateDeductionInfo Info(ovl->getNameLoc());
14339 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14340 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14341 /*IsAddressOfFunction*/ true);
14342 Result != TemplateDeductionResult::Success) {
14343 // Make a note of the failed deduction for diagnostics.
14344 if (FailedTSC)
14345 FailedTSC->addCandidate().set(
14346 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14347 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14348 continue;
14349 }
14350
14351 assert(Specialization && "no specialization and no error?");
14352
14353 // C++ [temp.deduct.call]p6:
14354 // [...] If all successful deductions yield the same deduced A, that
14355 // deduced A is the result of deduction; otherwise, the parameter is
14356 // treated as a non-deduced context.
14357 if (Matched) {
14358 if (ForTypeDeduction &&
14359 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14360 Arg: Specialization->getType()))
14361 continue;
14362 // Multiple matches; we can't resolve to a single declaration.
14363 if (Complain) {
14364 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14365 << ovl->getName();
14366 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14367 }
14368 return nullptr;
14369 }
14370
14371 Matched = Specialization;
14372 if (FoundResult) *FoundResult = I.getPair();
14373 }
14374
14375 if (Matched &&
14376 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14377 return nullptr;
14378
14379 return Matched;
14380}
14381
14382bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14383 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14384 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14385 unsigned DiagIDForComplaining) {
14386 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14387
14388 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14389
14390 DeclAccessPair found;
14391 ExprResult SingleFunctionExpression;
14392 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14393 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14394 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14395 SrcExpr = ExprError();
14396 return true;
14397 }
14398
14399 // It is only correct to resolve to an instance method if we're
14400 // resolving a form that's permitted to be a pointer to member.
14401 // Otherwise we'll end up making a bound member expression, which
14402 // is illegal in all the contexts we resolve like this.
14403 if (!ovl.HasFormOfMemberPointer &&
14404 isa<CXXMethodDecl>(Val: fn) &&
14405 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14406 if (!complain) return false;
14407
14408 Diag(Loc: ovl.Expression->getExprLoc(),
14409 DiagID: diag::err_bound_member_function)
14410 << 0 << ovl.Expression->getSourceRange();
14411
14412 // TODO: I believe we only end up here if there's a mix of
14413 // static and non-static candidates (otherwise the expression
14414 // would have 'bound member' type, not 'overload' type).
14415 // Ideally we would note which candidate was chosen and why
14416 // the static candidates were rejected.
14417 SrcExpr = ExprError();
14418 return true;
14419 }
14420
14421 // Fix the expression to refer to 'fn'.
14422 SingleFunctionExpression =
14423 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14424
14425 // If desired, do function-to-pointer decay.
14426 if (doFunctionPointerConversion) {
14427 SingleFunctionExpression =
14428 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14429 if (SingleFunctionExpression.isInvalid()) {
14430 SrcExpr = ExprError();
14431 return true;
14432 }
14433 }
14434 }
14435
14436 if (!SingleFunctionExpression.isUsable()) {
14437 if (complain) {
14438 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14439 << ovl.Expression->getName()
14440 << DestTypeForComplaining
14441 << OpRangeForComplaining
14442 << ovl.Expression->getQualifierLoc().getSourceRange();
14443 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14444
14445 SrcExpr = ExprError();
14446 return true;
14447 }
14448
14449 return false;
14450 }
14451
14452 SrcExpr = SingleFunctionExpression;
14453 return true;
14454}
14455
14456/// Add a single candidate to the overload set.
14457static void AddOverloadedCallCandidate(Sema &S,
14458 DeclAccessPair FoundDecl,
14459 TemplateArgumentListInfo *ExplicitTemplateArgs,
14460 ArrayRef<Expr *> Args,
14461 OverloadCandidateSet &CandidateSet,
14462 bool PartialOverloading,
14463 bool KnownValid) {
14464 NamedDecl *Callee = FoundDecl.getDecl();
14465 if (isa<UsingShadowDecl>(Val: Callee))
14466 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14467
14468 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14469 if (ExplicitTemplateArgs) {
14470 assert(!KnownValid && "Explicit template arguments?");
14471 return;
14472 }
14473 // Prevent ill-formed function decls to be added as overload candidates.
14474 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14475 return;
14476
14477 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14478 /*SuppressUserConversions=*/false,
14479 PartialOverloading);
14480 return;
14481 }
14482
14483 if (FunctionTemplateDecl *FuncTemplate
14484 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14485 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14486 ExplicitTemplateArgs, Args, CandidateSet,
14487 /*SuppressUserConversions=*/false,
14488 PartialOverloading);
14489 return;
14490 }
14491
14492 assert(!KnownValid && "unhandled case in overloaded call candidate");
14493}
14494
14495void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14496 ArrayRef<Expr *> Args,
14497 OverloadCandidateSet &CandidateSet,
14498 bool PartialOverloading) {
14499
14500#ifndef NDEBUG
14501 // Verify that ArgumentDependentLookup is consistent with the rules
14502 // in C++0x [basic.lookup.argdep]p3:
14503 //
14504 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14505 // and let Y be the lookup set produced by argument dependent
14506 // lookup (defined as follows). If X contains
14507 //
14508 // -- a declaration of a class member, or
14509 //
14510 // -- a block-scope function declaration that is not a
14511 // using-declaration, or
14512 //
14513 // -- a declaration that is neither a function or a function
14514 // template
14515 //
14516 // then Y is empty.
14517
14518 if (ULE->requiresADL()) {
14519 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14520 E = ULE->decls_end(); I != E; ++I) {
14521 assert(!(*I)->getDeclContext()->isRecord());
14522 assert(isa<UsingShadowDecl>(*I) ||
14523 !(*I)->getDeclContext()->isFunctionOrMethod());
14524 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14525 }
14526 }
14527#endif
14528
14529 // It would be nice to avoid this copy.
14530 TemplateArgumentListInfo TABuffer;
14531 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14532 if (ULE->hasExplicitTemplateArgs()) {
14533 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14534 ExplicitTemplateArgs = &TABuffer;
14535 }
14536
14537 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14538 E = ULE->decls_end(); I != E; ++I)
14539 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14540 CandidateSet, PartialOverloading,
14541 /*KnownValid*/ true);
14542
14543 if (ULE->requiresADL())
14544 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14545 Args, ExplicitTemplateArgs,
14546 CandidateSet, PartialOverloading);
14547}
14548
14549void Sema::AddOverloadedCallCandidates(
14550 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14551 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14552 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14553 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14554 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14555}
14556
14557/// Determine whether a declaration with the specified name could be moved into
14558/// a different namespace.
14559static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14560 switch (Name.getCXXOverloadedOperator()) {
14561 case OO_New: case OO_Array_New:
14562 case OO_Delete: case OO_Array_Delete:
14563 return false;
14564
14565 default:
14566 return true;
14567 }
14568}
14569
14570/// Attempt to recover from an ill-formed use of a non-dependent name in a
14571/// template, where the non-dependent name was declared after the template
14572/// was defined. This is common in code written for a compilers which do not
14573/// correctly implement two-stage name lookup.
14574///
14575/// Returns true if a viable candidate was found and a diagnostic was issued.
14576static bool DiagnoseTwoPhaseLookup(
14577 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14578 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14579 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14580 CXXRecordDecl **FoundInClass = nullptr) {
14581 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14582 return false;
14583
14584 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14585 if (DC->isTransparentContext())
14586 continue;
14587
14588 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14589
14590 if (!R.empty()) {
14591 R.suppressDiagnostics();
14592
14593 OverloadCandidateSet Candidates(FnLoc, CSK);
14594 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14595 CandidateSet&: Candidates);
14596
14597 OverloadCandidateSet::iterator Best;
14598 OverloadingResult OR =
14599 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14600
14601 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14602 // We either found non-function declarations or a best viable function
14603 // at class scope. A class-scope lookup result disables ADL. Don't
14604 // look past this, but let the caller know that we found something that
14605 // either is, or might be, usable in this class.
14606 if (FoundInClass) {
14607 *FoundInClass = RD;
14608 if (OR == OR_Success) {
14609 R.clear();
14610 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14611 R.resolveKind();
14612 }
14613 }
14614 return false;
14615 }
14616
14617 if (OR != OR_Success) {
14618 // There wasn't a unique best function or function template.
14619 return false;
14620 }
14621
14622 // Find the namespaces where ADL would have looked, and suggest
14623 // declaring the function there instead.
14624 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14625 Sema::AssociatedClassSet AssociatedClasses;
14626 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14627 AssociatedNamespaces,
14628 AssociatedClasses);
14629 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14630 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14631 DeclContext *Std = SemaRef.getStdNamespace();
14632 for (Sema::AssociatedNamespaceSet::iterator
14633 it = AssociatedNamespaces.begin(),
14634 end = AssociatedNamespaces.end(); it != end; ++it) {
14635 // Never suggest declaring a function within namespace 'std'.
14636 if (Std && Std->Encloses(DC: *it))
14637 continue;
14638
14639 // Never suggest declaring a function within a namespace with a
14640 // reserved name, like __gnu_cxx.
14641 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14642 if (NS &&
14643 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14644 continue;
14645
14646 SuggestedNamespaces.insert(X: *it);
14647 }
14648 }
14649
14650 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14651 << R.getLookupName();
14652 if (SuggestedNamespaces.empty()) {
14653 SemaRef.Diag(Loc: Best->Function->getLocation(),
14654 DiagID: diag::note_not_found_by_two_phase_lookup)
14655 << R.getLookupName() << 0;
14656 } else if (SuggestedNamespaces.size() == 1) {
14657 SemaRef.Diag(Loc: Best->Function->getLocation(),
14658 DiagID: diag::note_not_found_by_two_phase_lookup)
14659 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14660 } else {
14661 // FIXME: It would be useful to list the associated namespaces here,
14662 // but the diagnostics infrastructure doesn't provide a way to produce
14663 // a localized representation of a list of items.
14664 SemaRef.Diag(Loc: Best->Function->getLocation(),
14665 DiagID: diag::note_not_found_by_two_phase_lookup)
14666 << R.getLookupName() << 2;
14667 }
14668
14669 // Try to recover by calling this function.
14670 return true;
14671 }
14672
14673 R.clear();
14674 }
14675
14676 return false;
14677}
14678
14679/// Attempt to recover from ill-formed use of a non-dependent operator in a
14680/// template, where the non-dependent operator was declared after the template
14681/// was defined.
14682///
14683/// Returns true if a viable candidate was found and a diagnostic was issued.
14684static bool
14685DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14686 SourceLocation OpLoc,
14687 ArrayRef<Expr *> Args) {
14688 DeclarationName OpName =
14689 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14690 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14691 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14692 CSK: OverloadCandidateSet::CSK_Operator,
14693 /*ExplicitTemplateArgs=*/nullptr, Args);
14694}
14695
14696namespace {
14697class BuildRecoveryCallExprRAII {
14698 Sema &SemaRef;
14699 Sema::SatisfactionStackResetRAII SatStack;
14700
14701public:
14702 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14703 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14704 SemaRef.IsBuildingRecoveryCallExpr = true;
14705 }
14706
14707 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14708};
14709}
14710
14711/// Attempts to recover from a call where no functions were found.
14712///
14713/// This function will do one of three things:
14714/// * Diagnose, recover, and return a recovery expression.
14715/// * Diagnose, fail to recover, and return ExprError().
14716/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14717/// expected to diagnose as appropriate.
14718static ExprResult
14719BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14720 UnresolvedLookupExpr *ULE,
14721 SourceLocation LParenLoc,
14722 MutableArrayRef<Expr *> Args,
14723 SourceLocation RParenLoc,
14724 bool EmptyLookup, bool AllowTypoCorrection) {
14725 // Do not try to recover if it is already building a recovery call.
14726 // This stops infinite loops for template instantiations like
14727 //
14728 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14729 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14730 if (SemaRef.IsBuildingRecoveryCallExpr)
14731 return ExprResult();
14732 BuildRecoveryCallExprRAII RCE(SemaRef);
14733
14734 CXXScopeSpec SS;
14735 SS.Adopt(Other: ULE->getQualifierLoc());
14736 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14737
14738 TemplateArgumentListInfo TABuffer;
14739 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14740 if (ULE->hasExplicitTemplateArgs()) {
14741 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14742 ExplicitTemplateArgs = &TABuffer;
14743 }
14744
14745 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14746 Sema::LookupOrdinaryName);
14747 CXXRecordDecl *FoundInClass = nullptr;
14748 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14749 CSK: OverloadCandidateSet::CSK_Normal,
14750 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14751 // OK, diagnosed a two-phase lookup issue.
14752 } else if (EmptyLookup) {
14753 // Try to recover from an empty lookup with typo correction.
14754 R.clear();
14755 NoTypoCorrectionCCC NoTypoValidator{};
14756 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14757 ExplicitTemplateArgs != nullptr,
14758 dyn_cast<MemberExpr>(Val: Fn));
14759 CorrectionCandidateCallback &Validator =
14760 AllowTypoCorrection
14761 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14762 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14763 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14764 Args))
14765 return ExprError();
14766 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14767 // We found a usable declaration of the name in a dependent base of some
14768 // enclosing class.
14769 // FIXME: We should also explain why the candidates found by name lookup
14770 // were not viable.
14771 if (SemaRef.DiagnoseDependentMemberLookup(R))
14772 return ExprError();
14773 } else {
14774 // We had viable candidates and couldn't recover; let the caller diagnose
14775 // this.
14776 return ExprResult();
14777 }
14778
14779 // If we get here, we should have issued a diagnostic and formed a recovery
14780 // lookup result.
14781 assert(!R.empty() && "lookup results empty despite recovery");
14782
14783 // If recovery created an ambiguity, just bail out.
14784 if (R.isAmbiguous()) {
14785 R.suppressDiagnostics();
14786 return ExprError();
14787 }
14788
14789 // Build an implicit member call if appropriate. Just drop the
14790 // casts and such from the call, we don't really care.
14791 ExprResult NewFn = ExprError();
14792 if ((*R.begin())->isCXXClassMember())
14793 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14794 TemplateArgs: ExplicitTemplateArgs, S);
14795 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14796 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14797 TemplateArgs: ExplicitTemplateArgs);
14798 else
14799 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14800
14801 if (NewFn.isInvalid())
14802 return ExprError();
14803
14804 // This shouldn't cause an infinite loop because we're giving it
14805 // an expression with viable lookup results, which should never
14806 // end up here.
14807 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14808 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14809 RParenLoc);
14810}
14811
14812bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14813 UnresolvedLookupExpr *ULE,
14814 MultiExprArg Args,
14815 SourceLocation RParenLoc,
14816 OverloadCandidateSet *CandidateSet,
14817 ExprResult *Result) {
14818#ifndef NDEBUG
14819 if (ULE->requiresADL()) {
14820 // To do ADL, we must have found an unqualified name.
14821 assert(!ULE->getQualifier() && "qualified name with ADL");
14822
14823 // We don't perform ADL for implicit declarations of builtins.
14824 // Verify that this was correctly set up.
14825 FunctionDecl *F;
14826 if (ULE->decls_begin() != ULE->decls_end() &&
14827 ULE->decls_begin() + 1 == ULE->decls_end() &&
14828 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14829 F->getBuiltinID() && F->isImplicit())
14830 llvm_unreachable("performing ADL for builtin");
14831
14832 // We don't perform ADL in C.
14833 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14834 }
14835#endif
14836
14837 UnbridgedCastsSet UnbridgedCasts;
14838 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14839 *Result = ExprError();
14840 return true;
14841 }
14842
14843 // Add the functions denoted by the callee to the set of candidate
14844 // functions, including those from argument-dependent lookup.
14845 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14846
14847 if (getLangOpts().MSVCCompat &&
14848 CurContext->isDependentContext() && !isSFINAEContext() &&
14849 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14850
14851 OverloadCandidateSet::iterator Best;
14852 if (CandidateSet->empty() ||
14853 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14854 OR_No_Viable_Function) {
14855 // In Microsoft mode, if we are inside a template class member function
14856 // then create a type dependent CallExpr. The goal is to postpone name
14857 // lookup to instantiation time to be able to search into type dependent
14858 // base classes.
14859 CallExpr *CE =
14860 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14861 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14862 CE->markDependentForPostponedNameLookup();
14863 *Result = CE;
14864 return true;
14865 }
14866 }
14867
14868 if (CandidateSet->empty())
14869 return false;
14870
14871 UnbridgedCasts.restore();
14872 return false;
14873}
14874
14875// Guess at what the return type for an unresolvable overload should be.
14876static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14877 OverloadCandidateSet::iterator *Best) {
14878 std::optional<QualType> Result;
14879 // Adjust Type after seeing a candidate.
14880 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14881 if (!Candidate.Function)
14882 return;
14883 if (Candidate.Function->isInvalidDecl())
14884 return;
14885 QualType T = Candidate.Function->getReturnType();
14886 if (T.isNull())
14887 return;
14888 if (!Result)
14889 Result = T;
14890 else if (Result != T)
14891 Result = QualType();
14892 };
14893
14894 // Look for an unambiguous type from a progressively larger subset.
14895 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14896 //
14897 // First, consider only the best candidate.
14898 if (Best && *Best != CS.end())
14899 ConsiderCandidate(**Best);
14900 // Next, consider only viable candidates.
14901 if (!Result)
14902 for (const auto &C : CS)
14903 if (C.Viable)
14904 ConsiderCandidate(C);
14905 // Finally, consider all candidates.
14906 if (!Result)
14907 for (const auto &C : CS)
14908 ConsiderCandidate(C);
14909
14910 if (!Result)
14911 return QualType();
14912 auto Value = *Result;
14913 if (Value.isNull() || Value->isUndeducedType())
14914 return QualType();
14915 return Value;
14916}
14917
14918/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14919/// the completed call expression. If overload resolution fails, emits
14920/// diagnostics and returns ExprError()
14921static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14922 UnresolvedLookupExpr *ULE,
14923 SourceLocation LParenLoc,
14924 MultiExprArg Args,
14925 SourceLocation RParenLoc,
14926 Expr *ExecConfig,
14927 OverloadCandidateSet *CandidateSet,
14928 OverloadCandidateSet::iterator *Best,
14929 OverloadingResult OverloadResult,
14930 bool AllowTypoCorrection) {
14931 switch (OverloadResult) {
14932 case OR_Success: {
14933 FunctionDecl *FDecl = (*Best)->Function;
14934 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14935 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14936 return ExprError();
14937 ExprResult Res =
14938 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14939 if (Res.isInvalid())
14940 return ExprError();
14941 return SemaRef.BuildResolvedCallExpr(
14942 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14943 /*IsExecConfig=*/false,
14944 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14945 }
14946
14947 case OR_No_Viable_Function: {
14948 if (*Best != CandidateSet->end() &&
14949 CandidateSet->getKind() ==
14950 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14951 if (CXXMethodDecl *M =
14952 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14953 M && M->isImplicitObjectMemberFunction()) {
14954 CandidateSet->NoteCandidates(
14955 PD: PartialDiagnosticAt(
14956 Fn->getBeginLoc(),
14957 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14958 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14959 return ExprError();
14960 }
14961 }
14962
14963 // Try to recover by looking for viable functions which the user might
14964 // have meant to call.
14965 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14966 Args, RParenLoc,
14967 EmptyLookup: CandidateSet->empty(),
14968 AllowTypoCorrection);
14969 if (Recovery.isInvalid() || Recovery.isUsable())
14970 return Recovery;
14971
14972 // If the user passes in a function that we can't take the address of, we
14973 // generally end up emitting really bad error messages. Here, we attempt to
14974 // emit better ones.
14975 for (const Expr *Arg : Args) {
14976 if (!Arg->getType()->isFunctionType())
14977 continue;
14978 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14979 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14980 if (FD &&
14981 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14982 Loc: Arg->getExprLoc()))
14983 return ExprError();
14984 }
14985 }
14986
14987 CandidateSet->NoteCandidates(
14988 PD: PartialDiagnosticAt(
14989 Fn->getBeginLoc(),
14990 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
14991 << ULE->getName() << Fn->getSourceRange()),
14992 S&: SemaRef, OCD: OCD_AllCandidates, Args);
14993 break;
14994 }
14995
14996 case OR_Ambiguous:
14997 CandidateSet->NoteCandidates(
14998 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
14999 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
15000 << ULE->getName() << Fn->getSourceRange()),
15001 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15002 break;
15003
15004 case OR_Deleted: {
15005 FunctionDecl *FDecl = (*Best)->Function;
15006 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
15007 Range: Fn->getSourceRange(), Name: ULE->getName(),
15008 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
15009
15010 // We emitted an error for the unavailable/deleted function call but keep
15011 // the call in the AST.
15012 ExprResult Res =
15013 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15014 if (Res.isInvalid())
15015 return ExprError();
15016 return SemaRef.BuildResolvedCallExpr(
15017 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15018 /*IsExecConfig=*/false,
15019 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15020 }
15021 }
15022
15023 // Overload resolution failed, try to recover.
15024 SmallVector<Expr *, 8> SubExprs = {Fn};
15025 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
15026 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
15027 T: chooseRecoveryType(CS&: *CandidateSet, Best));
15028}
15029
15030static void markUnaddressableCandidatesUnviable(Sema &S,
15031 OverloadCandidateSet &CS) {
15032 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15033 if (I->Viable &&
15034 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
15035 I->Viable = false;
15036 I->FailureKind = ovl_fail_addr_not_available;
15037 }
15038 }
15039}
15040
15041ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
15042 UnresolvedLookupExpr *ULE,
15043 SourceLocation LParenLoc,
15044 MultiExprArg Args,
15045 SourceLocation RParenLoc,
15046 Expr *ExecConfig,
15047 bool AllowTypoCorrection,
15048 bool CalleesAddressIsTaken) {
15049
15050 OverloadCandidateSet::CandidateSetKind CSK =
15051 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15052 : OverloadCandidateSet::CSK_Normal;
15053
15054 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15055 ExprResult result;
15056
15057 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15058 Result: &result))
15059 return result;
15060
15061 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15062 // functions that aren't addressible are considered unviable.
15063 if (CalleesAddressIsTaken)
15064 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15065
15066 OverloadCandidateSet::iterator Best;
15067 OverloadingResult OverloadResult =
15068 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15069
15070 // [C++23][over.call.func]
15071 // if overload resolution selects a non-static member function,
15072 // the call is ill-formed;
15073 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15074 Best != CandidateSet.end()) {
15075 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15076 M && M->isImplicitObjectMemberFunction()) {
15077 OverloadResult = OR_No_Viable_Function;
15078 }
15079 }
15080
15081 // Model the case with a call to a templated function whose definition
15082 // encloses the call and whose return type contains a placeholder type as if
15083 // the UnresolvedLookupExpr was type-dependent.
15084 if (OverloadResult == OR_Success) {
15085 const FunctionDecl *FDecl = Best->Function;
15086 if (LangOpts.CUDA)
15087 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15088 if (FDecl && FDecl->isTemplateInstantiation() &&
15089 FDecl->getReturnType()->isUndeducedType()) {
15090
15091 // Creating dependent CallExpr is not okay if the enclosing context itself
15092 // is not dependent. This situation notably arises if a non-dependent
15093 // member function calls the later-defined overloaded static function.
15094 //
15095 // For example, in
15096 // class A {
15097 // void c() { callee(1); }
15098 // static auto callee(auto x) { }
15099 // };
15100 //
15101 // Here callee(1) is unresolved at the call site, but is not inside a
15102 // dependent context. There will be no further attempt to resolve this
15103 // call if it is made dependent.
15104
15105 if (const auto *TP =
15106 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15107 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15108 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15109 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15110 }
15111 }
15112 }
15113
15114 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15115 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15116 OverloadResult, AllowTypoCorrection);
15117}
15118
15119ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15120 NestedNameSpecifierLoc NNSLoc,
15121 DeclarationNameInfo DNI,
15122 const UnresolvedSetImpl &Fns,
15123 bool PerformADL) {
15124 return UnresolvedLookupExpr::Create(
15125 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15126 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15127}
15128
15129ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15130 CXXConversionDecl *Method,
15131 bool HadMultipleCandidates) {
15132 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15133 // the FoundDecl as it impedes TransformMemberExpr.
15134 // We go a bit further here: if there's no difference in UnderlyingDecl,
15135 // then using FoundDecl vs Method shouldn't make a difference either.
15136 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15137 FoundDecl = Method;
15138 // Convert the expression to match the conversion function's implicit object
15139 // parameter.
15140 ExprResult Exp;
15141 if (Method->isExplicitObjectMemberFunction())
15142 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15143 else
15144 Exp = PerformImplicitObjectArgumentInitialization(
15145 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15146 if (Exp.isInvalid())
15147 return true;
15148
15149 if (Method->getParent()->isLambda() &&
15150 Method->getConversionType()->isBlockPointerType()) {
15151 // This is a lambda conversion to block pointer; check if the argument
15152 // was a LambdaExpr.
15153 Expr *SubE = E;
15154 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15155 if (CE && CE->getCastKind() == CK_NoOp)
15156 SubE = CE->getSubExpr();
15157 SubE = SubE->IgnoreParens();
15158 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15159 SubE = BE->getSubExpr();
15160 if (isa<LambdaExpr>(Val: SubE)) {
15161 // For the conversion to block pointer on a lambda expression, we
15162 // construct a special BlockLiteral instead; this doesn't really make
15163 // a difference in ARC, but outside of ARC the resulting block literal
15164 // follows the normal lifetime rules for block literals instead of being
15165 // autoreleased.
15166 PushExpressionEvaluationContext(
15167 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15168 ExprResult BlockExp = BuildBlockForLambdaConversion(
15169 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15170 PopExpressionEvaluationContext();
15171
15172 // FIXME: This note should be produced by a CodeSynthesisContext.
15173 if (BlockExp.isInvalid())
15174 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15175 return BlockExp;
15176 }
15177 }
15178 CallExpr *CE;
15179 QualType ResultType = Method->getReturnType();
15180 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15181 ResultType = ResultType.getNonLValueExprType(Context);
15182 if (Method->isExplicitObjectMemberFunction()) {
15183 ExprResult FnExpr =
15184 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15185 HadMultipleCandidates, Loc: E->getBeginLoc());
15186 if (FnExpr.isInvalid())
15187 return ExprError();
15188 Expr *ObjectParam = Exp.get();
15189 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15190 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15191 FPFeatures: CurFPFeatureOverrides());
15192 CE->setUsesMemberSyntax(true);
15193 } else {
15194 MemberExpr *ME =
15195 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15196 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15197 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15198 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15199 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15200
15201 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15202 RP: Exp.get()->getEndLoc(),
15203 FPFeatures: CurFPFeatureOverrides());
15204 }
15205
15206 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15207 Proto: Method->getType()->castAs<FunctionProtoType>()))
15208 return ExprError();
15209
15210 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15211}
15212
15213ExprResult
15214Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15215 const UnresolvedSetImpl &Fns,
15216 Expr *Input, bool PerformADL) {
15217 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15218 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15219 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15220 // TODO: provide better source location info.
15221 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15222
15223 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15224 return ExprError();
15225
15226 Expr *Args[2] = { Input, nullptr };
15227 unsigned NumArgs = 1;
15228
15229 // For post-increment and post-decrement, add the implicit '0' as
15230 // the second argument, so that we know this is a post-increment or
15231 // post-decrement.
15232 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15233 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15234 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15235 l: SourceLocation());
15236 NumArgs = 2;
15237 }
15238
15239 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15240
15241 if (Input->isTypeDependent()) {
15242 ExprValueKind VK = ExprValueKind::VK_PRValue;
15243 // [C++26][expr.unary.op][expr.pre.incr]
15244 // The * operator yields an lvalue of type
15245 // The pre/post increment operators yied an lvalue.
15246 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15247 VK = VK_LValue;
15248
15249 if (Fns.empty())
15250 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15251 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15252 FPFeatures: CurFPFeatureOverrides());
15253
15254 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15255 ExprResult Fn = CreateUnresolvedLookupExpr(
15256 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15257 if (Fn.isInvalid())
15258 return ExprError();
15259 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15260 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15261 FPFeatures: CurFPFeatureOverrides());
15262 }
15263
15264 // Build an empty overload set.
15265 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15266
15267 // Add the candidates from the given function set.
15268 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
15269
15270 // Add operator candidates that are member functions.
15271 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15272
15273 // Add candidates from ADL.
15274 if (PerformADL) {
15275 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15276 /*ExplicitTemplateArgs*/nullptr,
15277 CandidateSet);
15278 }
15279
15280 // Add builtin operator candidates.
15281 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15282
15283 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15284
15285 // Perform overload resolution.
15286 OverloadCandidateSet::iterator Best;
15287 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15288 case OR_Success: {
15289 // We found a built-in operator or an overloaded operator.
15290 FunctionDecl *FnDecl = Best->Function;
15291
15292 if (FnDecl) {
15293 Expr *Base = nullptr;
15294 // We matched an overloaded operator. Build a call to that
15295 // operator.
15296
15297 // Convert the arguments.
15298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15299 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15300
15301 ExprResult InputInit;
15302 if (Method->isExplicitObjectMemberFunction())
15303 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15304 else
15305 InputInit = PerformImplicitObjectArgumentInitialization(
15306 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15307 if (InputInit.isInvalid())
15308 return ExprError();
15309 Base = Input = InputInit.get();
15310 } else {
15311 // Convert the arguments.
15312 ExprResult InputInit
15313 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15314 Context,
15315 Parm: FnDecl->getParamDecl(i: 0)),
15316 EqualLoc: SourceLocation(),
15317 Init: Input);
15318 if (InputInit.isInvalid())
15319 return ExprError();
15320 Input = InputInit.get();
15321 }
15322
15323 // Build the actual expression node.
15324 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15325 Base, HadMultipleCandidates,
15326 Loc: OpLoc);
15327 if (FnExpr.isInvalid())
15328 return ExprError();
15329
15330 // Determine the result type.
15331 QualType ResultTy = FnDecl->getReturnType();
15332 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15333 ResultTy = ResultTy.getNonLValueExprType(Context);
15334
15335 Args[0] = Input;
15336 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15337 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15338 FPFeatures: CurFPFeatureOverrides(),
15339 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15340
15341 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15342 return ExprError();
15343
15344 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15345 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15346 return ExprError();
15347 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15348 } else {
15349 // We matched a built-in operator. Convert the arguments, then
15350 // break out so that we will build the appropriate built-in
15351 // operator node.
15352 ExprResult InputRes = PerformImplicitConversion(
15353 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15354 Action: AssignmentAction::Passing,
15355 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15356 if (InputRes.isInvalid())
15357 return ExprError();
15358 Input = InputRes.get();
15359 break;
15360 }
15361 }
15362
15363 case OR_No_Viable_Function:
15364 // This is an erroneous use of an operator which can be overloaded by
15365 // a non-member function. Check for non-member operators which were
15366 // defined too late to be candidates.
15367 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15368 // FIXME: Recover by calling the found function.
15369 return ExprError();
15370
15371 // No viable function; fall through to handling this as a
15372 // built-in operator, which will produce an error message for us.
15373 break;
15374
15375 case OR_Ambiguous:
15376 CandidateSet.NoteCandidates(
15377 PD: PartialDiagnosticAt(OpLoc,
15378 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15379 << UnaryOperator::getOpcodeStr(Op: Opc)
15380 << Input->getType() << Input->getSourceRange()),
15381 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15382 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15383 return ExprError();
15384
15385 case OR_Deleted: {
15386 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15387 // object whose method was called. Later in NoteCandidates size of ArgsArray
15388 // is passed further and it eventually ends up compared to number of
15389 // function candidate parameters which never includes the object parameter,
15390 // so slice ArgsArray to make sure apples are compared to apples.
15391 StringLiteral *Msg = Best->Function->getDeletedMessage();
15392 CandidateSet.NoteCandidates(
15393 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15394 << UnaryOperator::getOpcodeStr(Op: Opc)
15395 << (Msg != nullptr)
15396 << (Msg ? Msg->getString() : StringRef())
15397 << Input->getSourceRange()),
15398 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15399 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15400 return ExprError();
15401 }
15402 }
15403
15404 // Either we found no viable overloaded operator or we matched a
15405 // built-in operator. In either case, fall through to trying to
15406 // build a built-in operation.
15407 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15408}
15409
15410void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15411 OverloadedOperatorKind Op,
15412 const UnresolvedSetImpl &Fns,
15413 ArrayRef<Expr *> Args, bool PerformADL) {
15414 SourceLocation OpLoc = CandidateSet.getLocation();
15415
15416 OverloadedOperatorKind ExtraOp =
15417 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15418 ? getRewrittenOverloadedOperator(Kind: Op)
15419 : OO_None;
15420
15421 // Add the candidates from the given function set. This also adds the
15422 // rewritten candidates using these functions if necessary.
15423 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15424
15425 // As template candidates are not deduced immediately,
15426 // persist the array in the overload set.
15427 ArrayRef<Expr *> ReversedArgs;
15428 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15429 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15430 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15431
15432 // Add operator candidates that are member functions.
15433 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15434 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15435 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15436 PO: OverloadCandidateParamOrder::Reversed);
15437
15438 // In C++20, also add any rewritten member candidates.
15439 if (ExtraOp) {
15440 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15441 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15442 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15443 PO: OverloadCandidateParamOrder::Reversed);
15444 }
15445
15446 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15447 // performed for an assignment operator (nor for operator[] nor operator->,
15448 // which don't get here).
15449 if (Op != OO_Equal && PerformADL) {
15450 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15451 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15452 /*ExplicitTemplateArgs*/ nullptr,
15453 CandidateSet);
15454 if (ExtraOp) {
15455 DeclarationName ExtraOpName =
15456 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15457 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15458 /*ExplicitTemplateArgs*/ nullptr,
15459 CandidateSet);
15460 }
15461 }
15462
15463 // Add builtin operator candidates.
15464 //
15465 // FIXME: We don't add any rewritten candidates here. This is strictly
15466 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15467 // resulting in our selecting a rewritten builtin candidate. For example:
15468 //
15469 // enum class E { e };
15470 // bool operator!=(E, E) requires false;
15471 // bool k = E::e != E::e;
15472 //
15473 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15474 // it seems unreasonable to consider rewritten builtin candidates. A core
15475 // issue has been filed proposing to removed this requirement.
15476 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15477}
15478
15479ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15480 BinaryOperatorKind Opc,
15481 const UnresolvedSetImpl &Fns, Expr *LHS,
15482 Expr *RHS, bool PerformADL,
15483 bool AllowRewrittenCandidates,
15484 FunctionDecl *DefaultedFn) {
15485 Expr *Args[2] = { LHS, RHS };
15486 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15487
15488 if (!getLangOpts().CPlusPlus20)
15489 AllowRewrittenCandidates = false;
15490
15491 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15492
15493 // If either side is type-dependent, create an appropriate dependent
15494 // expression.
15495 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15496 if (Fns.empty()) {
15497 // If there are no functions to store, just build a dependent
15498 // BinaryOperator or CompoundAssignment.
15499 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15500 return CompoundAssignOperator::Create(
15501 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15502 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15503 CompResultType: Context.DependentTy);
15504 return BinaryOperator::Create(
15505 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15506 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15507 }
15508
15509 // FIXME: save results of ADL from here?
15510 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15511 // TODO: provide better source location info in DNLoc component.
15512 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15513 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15514 ExprResult Fn = CreateUnresolvedLookupExpr(
15515 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15516 if (Fn.isInvalid())
15517 return ExprError();
15518 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15519 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15520 FPFeatures: CurFPFeatureOverrides());
15521 }
15522
15523 // If this is the .* operator, which is not overloadable, just
15524 // create a built-in binary operator.
15525 if (Opc == BO_PtrMemD) {
15526 auto CheckPlaceholder = [&](Expr *&Arg) {
15527 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15528 if (Res.isUsable())
15529 Arg = Res.get();
15530 return !Res.isUsable();
15531 };
15532
15533 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15534 // expression that contains placeholders (in either the LHS or RHS).
15535 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15536 return ExprError();
15537 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15538 }
15539
15540 // Always do placeholder-like conversions on the RHS.
15541 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15542 return ExprError();
15543
15544 // Do placeholder-like conversion on the LHS; note that we should
15545 // not get here with a PseudoObject LHS.
15546 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15547 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15548 return ExprError();
15549
15550 // If this is the assignment operator, we only perform overload resolution
15551 // if the left-hand side is a class or enumeration type. This is actually
15552 // a hack. The standard requires that we do overload resolution between the
15553 // various built-in candidates, but as DR507 points out, this can lead to
15554 // problems. So we do it this way, which pretty much follows what GCC does.
15555 // Note that we go the traditional code path for compound assignment forms.
15556 // In HLSL, user-defined structs/classes do not have constructors or
15557 // overloadable assignment operators, so we can take this shortcut too.
15558 const Type *LHSTy = Args[0]->getType().getTypePtr();
15559 if (Opc == BO_Assign &&
15560 (!LHSTy->isOverloadableType() ||
15561 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15562 !LHSTy->getAsCXXRecordDecl()->isHLSLBuiltinRecord())))
15563 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15564
15565 // Build the overload set.
15566 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15567 OverloadCandidateSet::OperatorRewriteInfo(
15568 Op, OpLoc, AllowRewrittenCandidates));
15569 if (DefaultedFn)
15570 CandidateSet.exclude(F: DefaultedFn);
15571 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15572
15573 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15574
15575 // Perform overload resolution.
15576 OverloadCandidateSet::iterator Best;
15577 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15578 case OR_Success: {
15579 // We found a built-in operator or an overloaded operator.
15580 FunctionDecl *FnDecl = Best->Function;
15581
15582 bool IsReversed = Best->isReversed();
15583 if (IsReversed)
15584 std::swap(a&: Args[0], b&: Args[1]);
15585
15586 if (FnDecl) {
15587
15588 if (FnDecl->isInvalidDecl())
15589 return ExprError();
15590
15591 Expr *Base = nullptr;
15592 // We matched an overloaded operator. Build a call to that
15593 // operator.
15594
15595 OverloadedOperatorKind ChosenOp =
15596 FnDecl->getDeclName().getCXXOverloadedOperator();
15597
15598 // C++2a [over.match.oper]p9:
15599 // If a rewritten operator== candidate is selected by overload
15600 // resolution for an operator@, its return type shall be cv bool
15601 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15602 !FnDecl->getReturnType()->isBooleanType()) {
15603 bool IsExtension =
15604 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15605 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15606 : diag::err_ovl_rewrite_equalequal_not_bool)
15607 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15609 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15610 if (!IsExtension)
15611 return ExprError();
15612 }
15613
15614 if (AllowRewrittenCandidates && !IsReversed &&
15615 CandidateSet.getRewriteInfo().isReversible()) {
15616 // We could have reversed this operator, but didn't. Check if some
15617 // reversed form was a viable candidate, and if so, if it had a
15618 // better conversion for either parameter. If so, this call is
15619 // formally ambiguous, and allowing it is an extension.
15620 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15621 for (OverloadCandidate &Cand : CandidateSet) {
15622 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15623 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15624 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15625 if (CompareImplicitConversionSequences(
15626 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15627 ICS2: Best->Conversions[ArgIdx]) ==
15628 ImplicitConversionSequence::Better) {
15629 AmbiguousWith.push_back(Elt: Cand.Function);
15630 break;
15631 }
15632 }
15633 }
15634 }
15635
15636 if (!AmbiguousWith.empty()) {
15637 bool AmbiguousWithSelf =
15638 AmbiguousWith.size() == 1 &&
15639 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15640 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15641 << BinaryOperator::getOpcodeStr(Op: Opc)
15642 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15643 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15644 if (AmbiguousWithSelf) {
15645 Diag(Loc: FnDecl->getLocation(),
15646 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15647 // Mark member== const or provide matching != to disallow reversed
15648 // args. Eg.
15649 // struct S { bool operator==(const S&); };
15650 // S()==S();
15651 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15652 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15653 !MD->isConst() &&
15654 !MD->hasCXXExplicitFunctionObjectParameter() &&
15655 Context.hasSameUnqualifiedType(
15656 T1: MD->getFunctionObjectParameterType(),
15657 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15658 Context.hasSameUnqualifiedType(
15659 T1: MD->getFunctionObjectParameterType(),
15660 T2: Args[0]->getType()) &&
15661 Context.hasSameUnqualifiedType(
15662 T1: MD->getFunctionObjectParameterType(),
15663 T2: Args[1]->getType()))
15664 Diag(Loc: FnDecl->getLocation(),
15665 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15666 } else {
15667 Diag(Loc: FnDecl->getLocation(),
15668 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15669 for (auto *F : AmbiguousWith)
15670 Diag(Loc: F->getLocation(),
15671 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15672 }
15673 }
15674 }
15675
15676 // Check for nonnull = nullable.
15677 // This won't be caught in the arg's initialization: the parameter to
15678 // the assignment operator is not marked nonnull.
15679 if (Op == OO_Equal)
15680 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15681 SrcType: Args[1]->getType(), Loc: OpLoc);
15682
15683 // Convert the arguments.
15684 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15685 // Best->Access is only meaningful for class members.
15686 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15687
15688 ExprResult Arg0, Arg1;
15689 unsigned ParamIdx = 0;
15690 if (Method->isExplicitObjectMemberFunction()) {
15691 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15692 ParamIdx = 1;
15693 } else {
15694 Arg0 = PerformImplicitObjectArgumentInitialization(
15695 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15696 }
15697 Arg1 = PerformCopyInitialization(
15698 Entity: InitializedEntity::InitializeParameter(
15699 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15700 EqualLoc: SourceLocation(), Init: Args[1]);
15701 if (Arg0.isInvalid() || Arg1.isInvalid())
15702 return ExprError();
15703
15704 Base = Args[0] = Arg0.getAs<Expr>();
15705 Args[1] = RHS = Arg1.getAs<Expr>();
15706 } else {
15707 // Convert the arguments.
15708 ExprResult Arg0 = PerformCopyInitialization(
15709 Entity: InitializedEntity::InitializeParameter(Context,
15710 Parm: FnDecl->getParamDecl(i: 0)),
15711 EqualLoc: SourceLocation(), Init: Args[0]);
15712 if (Arg0.isInvalid())
15713 return ExprError();
15714
15715 ExprResult Arg1 =
15716 PerformCopyInitialization(
15717 Entity: InitializedEntity::InitializeParameter(Context,
15718 Parm: FnDecl->getParamDecl(i: 1)),
15719 EqualLoc: SourceLocation(), Init: Args[1]);
15720 if (Arg1.isInvalid())
15721 return ExprError();
15722 Args[0] = LHS = Arg0.getAs<Expr>();
15723 Args[1] = RHS = Arg1.getAs<Expr>();
15724 }
15725
15726 // Build the actual expression node.
15727 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15728 FoundDecl: Best->FoundDecl, Base,
15729 HadMultipleCandidates, Loc: OpLoc);
15730 if (FnExpr.isInvalid())
15731 return ExprError();
15732
15733 // Determine the result type.
15734 QualType ResultTy = FnDecl->getReturnType();
15735 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15736 ResultTy = ResultTy.getNonLValueExprType(Context);
15737
15738 CallExpr *TheCall;
15739 ArrayRef<const Expr *> ArgsArray(Args, 2);
15740 const Expr *ImplicitThis = nullptr;
15741
15742 // We always create a CXXOperatorCallExpr, even for explicit object
15743 // members; CodeGen should take care not to emit the this pointer.
15744 TheCall = CXXOperatorCallExpr::Create(
15745 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15746 FPFeatures: CurFPFeatureOverrides(),
15747 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15748 IsReversed);
15749
15750 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15751 Method && Method->isImplicitObjectMemberFunction()) {
15752 // Cut off the implicit 'this'.
15753 ImplicitThis = ArgsArray[0];
15754 ArgsArray = ArgsArray.slice(N: 1);
15755 }
15756
15757 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15758 FD: FnDecl))
15759 return ExprError();
15760
15761 if (Op == OO_Equal) {
15762 // Check for a self move.
15763 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15764 // lifetime check.
15765 checkAssignmentLifetime(
15766 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15767 Init: Args[1]);
15768 }
15769 if (ImplicitThis) {
15770 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15771 QualType ThisTypeFromDecl = Context.getPointerType(
15772 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15773
15774 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15775 ParamTy: ThisTypeFromDecl);
15776 }
15777
15778 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15779 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15780 CallType: VariadicCallType::DoesNotApply);
15781
15782 ExprResult R = MaybeBindToTemporary(E: TheCall);
15783 if (R.isInvalid())
15784 return ExprError();
15785
15786 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15787 if (R.isInvalid())
15788 return ExprError();
15789
15790 // For a rewritten candidate, we've already reversed the arguments
15791 // if needed. Perform the rest of the rewrite now.
15792 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15793 (Op == OO_Spaceship && IsReversed)) {
15794 if (Op == OO_ExclaimEqual) {
15795 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15796 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15797 } else {
15798 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15799 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15800 Expr *ZeroLiteral =
15801 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15802
15803 Sema::CodeSynthesisContext Ctx;
15804 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15805 Ctx.Entity = FnDecl;
15806 pushCodeSynthesisContext(Ctx);
15807
15808 R = CreateOverloadedBinOp(
15809 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15810 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15811 /*AllowRewrittenCandidates=*/false);
15812
15813 popCodeSynthesisContext();
15814 }
15815 if (R.isInvalid())
15816 return ExprError();
15817 } else {
15818 assert(ChosenOp == Op && "unexpected operator name");
15819 }
15820
15821 // Make a note in the AST if we did any rewriting.
15822 if (Best->RewriteKind != CRK_None)
15823 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15824
15825 return R;
15826 } else {
15827 // We matched a built-in operator. Convert the arguments, then
15828 // break out so that we will build the appropriate built-in
15829 // operator node.
15830 ExprResult ArgsRes0 = PerformImplicitConversion(
15831 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15832 Action: AssignmentAction::Passing,
15833 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15834 if (ArgsRes0.isInvalid())
15835 return ExprError();
15836 Args[0] = ArgsRes0.get();
15837
15838 ExprResult ArgsRes1 = PerformImplicitConversion(
15839 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15840 Action: AssignmentAction::Passing,
15841 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15842 if (ArgsRes1.isInvalid())
15843 return ExprError();
15844 Args[1] = ArgsRes1.get();
15845 break;
15846 }
15847 }
15848
15849 case OR_No_Viable_Function: {
15850 // C++ [over.match.oper]p9:
15851 // If the operator is the operator , [...] and there are no
15852 // viable functions, then the operator is assumed to be the
15853 // built-in operator and interpreted according to clause 5.
15854 if (Opc == BO_Comma)
15855 break;
15856
15857 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15858 // compare result using '==' and '<'.
15859 if (DefaultedFn && Opc == BO_Cmp) {
15860 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15861 RHS: Args[1], DefaultedFn);
15862 if (E.isInvalid() || E.isUsable())
15863 return E;
15864 }
15865
15866 // For class as left operand for assignment or compound assignment
15867 // operator do not fall through to handling in built-in, but report that
15868 // no overloaded assignment operator found
15869 ExprResult Result = ExprError();
15870 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15871 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15872 Args, OpLoc);
15873 DeferDiagsRAII DDR(*this,
15874 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15875 if (Args[0]->getType()->isRecordType() &&
15876 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15877 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15878 << BinaryOperator::getOpcodeStr(Op: Opc)
15879 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15880 if (Args[0]->getType()->isIncompleteType()) {
15881 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15882 << Args[0]->getType()
15883 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15884 }
15885 } else {
15886 // This is an erroneous use of an operator which can be overloaded by
15887 // a non-member function. Check for non-member operators which were
15888 // defined too late to be candidates.
15889 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15890 // FIXME: Recover by calling the found function.
15891 return ExprError();
15892
15893 // No viable function; try to create a built-in operation, which will
15894 // produce an error. Then, show the non-viable candidates.
15895 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15896 }
15897 assert(Result.isInvalid() &&
15898 "C++ binary operator overloading is missing candidates!");
15899 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15900 return Result;
15901 }
15902
15903 case OR_Ambiguous:
15904 CandidateSet.NoteCandidates(
15905 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15906 << BinaryOperator::getOpcodeStr(Op: Opc)
15907 << Args[0]->getType()
15908 << Args[1]->getType()
15909 << Args[0]->getSourceRange()
15910 << Args[1]->getSourceRange()),
15911 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15912 OpLoc);
15913 return ExprError();
15914
15915 case OR_Deleted: {
15916 if (isImplicitlyDeleted(FD: Best->Function)) {
15917 FunctionDecl *DeletedFD = Best->Function;
15918 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15919 if (DFK.isSpecialMember()) {
15920 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15921 << Args[0]->getType() << DFK.asSpecialMember();
15922 } else {
15923 assert(DFK.isComparison());
15924 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15925 << Args[0]->getType() << DeletedFD;
15926 }
15927
15928 // The user probably meant to call this special member. Just
15929 // explain why it's deleted.
15930 NoteDeletedFunction(FD: DeletedFD);
15931 return ExprError();
15932 }
15933
15934 StringLiteral *Msg = Best->Function->getDeletedMessage();
15935 CandidateSet.NoteCandidates(
15936 PD: PartialDiagnosticAt(
15937 OpLoc,
15938 PDiag(DiagID: diag::err_ovl_deleted_oper)
15939 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15940 .getCXXOverloadedOperator())
15941 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15942 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15943 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15944 OpLoc);
15945 return ExprError();
15946 }
15947 }
15948
15949 // We matched a built-in operator; build it.
15950 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15951}
15952
15953ExprResult Sema::BuildSynthesizedThreeWayComparison(
15954 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15955 FunctionDecl *DefaultedFn) {
15956 const ComparisonCategoryInfo *Info =
15957 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15958 // If we're not producing a known comparison category type, we can't
15959 // synthesize a three-way comparison. Let the caller diagnose this.
15960 if (!Info)
15961 return ExprResult((Expr*)nullptr);
15962
15963 // If we ever want to perform this synthesis more generally, we will need to
15964 // apply the temporary materialization conversion to the operands.
15965 assert(LHS->isGLValue() && RHS->isGLValue() &&
15966 "cannot use prvalue expressions more than once");
15967 Expr *OrigLHS = LHS;
15968 Expr *OrigRHS = RHS;
15969
15970 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15971 // each of them multiple times below.
15972 LHS = new (Context)
15973 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15974 LHS->getObjectKind(), LHS);
15975 RHS = new (Context)
15976 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15977 RHS->getObjectKind(), RHS);
15978
15979 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15980 DefaultedFn);
15981 if (Eq.isInvalid())
15982 return ExprError();
15983
15984 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15985 AllowRewrittenCandidates: true, DefaultedFn);
15986 if (Less.isInvalid())
15987 return ExprError();
15988
15989 ExprResult Greater;
15990 if (Info->isPartial()) {
15991 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15992 DefaultedFn);
15993 if (Greater.isInvalid())
15994 return ExprError();
15995 }
15996
15997 // Form the list of comparisons we're going to perform.
15998 struct Comparison {
15999 ExprResult Cmp;
16000 ComparisonCategoryResult Result;
16001 } Comparisons[4] =
16002 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
16003 : ComparisonCategoryResult::Equivalent},
16004 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
16005 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
16006 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
16007 };
16008
16009 int I = Info->isPartial() ? 3 : 2;
16010
16011 // Combine the comparisons with suitable conditional expressions.
16012 ExprResult Result;
16013 for (; I >= 0; --I) {
16014 // Build a reference to the comparison category constant.
16015 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
16016 // FIXME: Missing a constant for a comparison category. Diagnose this?
16017 if (!VI)
16018 return ExprResult((Expr*)nullptr);
16019 ExprResult ThisResult =
16020 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
16021 if (ThisResult.isInvalid())
16022 return ExprError();
16023
16024 // Build a conditional unless this is the final case.
16025 if (Result.get()) {
16026 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
16027 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
16028 if (Result.isInvalid())
16029 return ExprError();
16030 } else {
16031 Result = ThisResult;
16032 }
16033 }
16034
16035 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16036 // bind the OpaqueValueExprs before they're (repeatedly) used.
16037 Expr *SyntacticForm = BinaryOperator::Create(
16038 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
16039 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
16040 FPFeatures: CurFPFeatureOverrides());
16041 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16042 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
16043}
16044
16045static bool PrepareArgumentsForCallToObjectOfClassType(
16046 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16047 MultiExprArg Args, SourceLocation LParenLoc) {
16048
16049 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16050 unsigned NumParams = Proto->getNumParams();
16051 unsigned NumArgsSlots =
16052 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16053 // Build the full argument list for the method call (the implicit object
16054 // parameter is placed at the beginning of the list).
16055 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16056 bool IsError = false;
16057 // Initialize the implicit object parameter.
16058 // Check the argument types.
16059 for (unsigned i = 0; i != NumParams; i++) {
16060 Expr *Arg;
16061 if (i < Args.size()) {
16062 Arg = Args[i];
16063 ExprResult InputInit =
16064 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16065 Context&: S.Context, Parm: Method->getParamDecl(i)),
16066 EqualLoc: SourceLocation(), Init: Arg);
16067 IsError |= InputInit.isInvalid();
16068 Arg = InputInit.getAs<Expr>();
16069 } else {
16070 ExprResult DefArg =
16071 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16072 if (DefArg.isInvalid()) {
16073 IsError = true;
16074 break;
16075 }
16076 Arg = DefArg.getAs<Expr>();
16077 }
16078
16079 MethodArgs.push_back(Elt: Arg);
16080 }
16081 return IsError;
16082}
16083
16084ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16085 SourceLocation RLoc,
16086 Expr *Base,
16087 MultiExprArg ArgExpr) {
16088 SmallVector<Expr *, 2> Args;
16089 Args.push_back(Elt: Base);
16090 for (auto *e : ArgExpr) {
16091 Args.push_back(Elt: e);
16092 }
16093 DeclarationName OpName =
16094 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16095
16096 SourceRange Range = ArgExpr.empty()
16097 ? SourceRange{}
16098 : SourceRange(ArgExpr.front()->getBeginLoc(),
16099 ArgExpr.back()->getEndLoc());
16100
16101 // If either side is type-dependent, create an appropriate dependent
16102 // expression.
16103 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16104
16105 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16106 // CHECKME: no 'operator' keyword?
16107 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16108 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16109 ExprResult Fn = CreateUnresolvedLookupExpr(
16110 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16111 if (Fn.isInvalid())
16112 return ExprError();
16113 // Can't add any actual overloads yet
16114
16115 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16116 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16117 FPFeatures: CurFPFeatureOverrides());
16118 }
16119
16120 // Handle placeholders
16121 UnbridgedCastsSet UnbridgedCasts;
16122 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16123 return ExprError();
16124 }
16125 // Build an empty overload set.
16126 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16127
16128 // Subscript can only be overloaded as a member function.
16129
16130 // Add operator candidates that are member functions.
16131 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16132
16133 // Add builtin operator candidates.
16134 if (Args.size() == 2)
16135 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16136
16137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16138
16139 // Perform overload resolution.
16140 OverloadCandidateSet::iterator Best;
16141 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16142 case OR_Success: {
16143 // We found a built-in operator or an overloaded operator.
16144 FunctionDecl *FnDecl = Best->Function;
16145
16146 if (FnDecl) {
16147 // We matched an overloaded operator. Build a call to that
16148 // operator.
16149
16150 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16151
16152 // Convert the arguments.
16153 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16154 SmallVector<Expr *, 2> MethodArgs;
16155
16156 // Initialize the object parameter.
16157 if (Method->isExplicitObjectMemberFunction()) {
16158 ExprResult Res =
16159 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16160 if (Res.isInvalid())
16161 return ExprError();
16162 Args[0] = Res.get();
16163 ArgExpr = Args;
16164 } else {
16165 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16166 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16167 if (Arg0.isInvalid())
16168 return ExprError();
16169
16170 MethodArgs.push_back(Elt: Arg0.get());
16171 }
16172
16173 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16174 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16175 if (IsError)
16176 return ExprError();
16177
16178 // Build the actual expression node.
16179 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16180 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16181 ExprResult FnExpr = CreateFunctionRefExpr(
16182 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
16183 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
16184 if (FnExpr.isInvalid())
16185 return ExprError();
16186
16187 // Determine the result type
16188 QualType ResultTy = FnDecl->getReturnType();
16189 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16190 ResultTy = ResultTy.getNonLValueExprType(Context);
16191
16192 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16193 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16194 FPFeatures: CurFPFeatureOverrides());
16195
16196 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16197 return ExprError();
16198
16199 if (CheckFunctionCall(FDecl: Method, TheCall,
16200 Proto: Method->getType()->castAs<FunctionProtoType>()))
16201 return ExprError();
16202
16203 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16204 Decl: FnDecl);
16205 } else {
16206 // We matched a built-in operator. Convert the arguments, then
16207 // break out so that we will build the appropriate built-in
16208 // operator node.
16209 ExprResult ArgsRes0 = PerformImplicitConversion(
16210 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16211 Action: AssignmentAction::Passing,
16212 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16213 if (ArgsRes0.isInvalid())
16214 return ExprError();
16215 Args[0] = ArgsRes0.get();
16216
16217 ExprResult ArgsRes1 = PerformImplicitConversion(
16218 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16219 Action: AssignmentAction::Passing,
16220 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16221 if (ArgsRes1.isInvalid())
16222 return ExprError();
16223 Args[1] = ArgsRes1.get();
16224
16225 break;
16226 }
16227 }
16228
16229 case OR_No_Viable_Function: {
16230 PartialDiagnostic PD =
16231 CandidateSet.empty()
16232 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16233 << Args[0]->getType() << /*subscript*/ 0
16234 << Args[0]->getSourceRange() << Range)
16235 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16236 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16237 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16238 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16239 return ExprError();
16240 }
16241
16242 case OR_Ambiguous:
16243 if (Args.size() == 2) {
16244 CandidateSet.NoteCandidates(
16245 PD: PartialDiagnosticAt(
16246 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16247 << "[]" << Args[0]->getType() << Args[1]->getType()
16248 << Args[0]->getSourceRange() << Range),
16249 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16250 } else {
16251 CandidateSet.NoteCandidates(
16252 PD: PartialDiagnosticAt(LLoc,
16253 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16254 << Args[0]->getType()
16255 << Args[0]->getSourceRange() << Range),
16256 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16257 }
16258 return ExprError();
16259
16260 case OR_Deleted: {
16261 StringLiteral *Msg = Best->Function->getDeletedMessage();
16262 CandidateSet.NoteCandidates(
16263 PD: PartialDiagnosticAt(LLoc,
16264 PDiag(DiagID: diag::err_ovl_deleted_oper)
16265 << "[]" << (Msg != nullptr)
16266 << (Msg ? Msg->getString() : StringRef())
16267 << Args[0]->getSourceRange() << Range),
16268 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16269 return ExprError();
16270 }
16271 }
16272
16273 // We matched a built-in operator; build it.
16274 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16275}
16276
16277ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16278 SourceLocation LParenLoc,
16279 MultiExprArg Args,
16280 SourceLocation RParenLoc,
16281 Expr *ExecConfig, bool IsExecConfig,
16282 bool AllowRecovery) {
16283 assert(MemExprE->getType() == Context.BoundMemberTy ||
16284 MemExprE->getType() == Context.OverloadTy);
16285
16286 // Dig out the member expression. This holds both the object
16287 // argument and the member function we're referring to.
16288 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16289
16290 // Determine whether this is a call to a pointer-to-member function.
16291 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16292 assert(op->getType() == Context.BoundMemberTy);
16293 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16294
16295 QualType fnType =
16296 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16297
16298 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16299 QualType resultType = proto->getCallResultType(Context);
16300 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16301
16302 // Check that the object type isn't more qualified than the
16303 // member function we're calling.
16304 Qualifiers funcQuals = proto->getMethodQuals();
16305
16306 QualType objectType = op->getLHS()->getType();
16307 if (op->getOpcode() == BO_PtrMemI)
16308 objectType = objectType->castAs<PointerType>()->getPointeeType();
16309 Qualifiers objectQuals = objectType.getQualifiers();
16310
16311 Qualifiers difference = objectQuals - funcQuals;
16312 difference.removeObjCGCAttr();
16313 difference.removeAddressSpace();
16314 if (difference) {
16315 std::string qualsString = difference.getAsString();
16316 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16317 << fnType.getUnqualifiedType()
16318 << qualsString
16319 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16320 }
16321
16322 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16323 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16324 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16325
16326 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16327 CE: call, FD: nullptr))
16328 return ExprError();
16329
16330 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16331 return ExprError();
16332
16333 if (CheckOtherCall(TheCall: call, Proto: proto))
16334 return ExprError();
16335
16336 return MaybeBindToTemporary(E: call);
16337 }
16338
16339 // We only try to build a recovery expr at this level if we can preserve
16340 // the return type, otherwise we return ExprError() and let the caller
16341 // recover.
16342 auto BuildRecoveryExpr = [&](QualType Type) {
16343 if (!AllowRecovery)
16344 return ExprError();
16345 std::vector<Expr *> SubExprs = {MemExprE};
16346 llvm::append_range(C&: SubExprs, R&: Args);
16347 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16348 T: Type);
16349 };
16350 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16351 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16352 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16353
16354 UnbridgedCastsSet UnbridgedCasts;
16355 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16356 return ExprError();
16357
16358 MemberExpr *MemExpr;
16359 CXXMethodDecl *Method = nullptr;
16360 bool HadMultipleCandidates = false;
16361 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16362 NestedNameSpecifier Qualifier = std::nullopt;
16363 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16364 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16365 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16366 FoundDecl = MemExpr->getFoundDecl();
16367 Qualifier = MemExpr->getQualifier();
16368 UnbridgedCasts.restore();
16369 } else {
16370 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16371 Qualifier = UnresExpr->getQualifier();
16372
16373 QualType ObjectType = UnresExpr->getBaseType();
16374 Expr::Classification ObjectClassification
16375 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16376 : UnresExpr->getBase()->Classify(Ctx&: Context);
16377
16378 // Add overload candidates
16379 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16380 OverloadCandidateSet::CSK_Normal);
16381
16382 // FIXME: avoid copy.
16383 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16384 if (UnresExpr->hasExplicitTemplateArgs()) {
16385 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16386 TemplateArgs = &TemplateArgsBuffer;
16387 }
16388
16389 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16390 E = UnresExpr->decls_end(); I != E; ++I) {
16391
16392 QualType ExplicitObjectType = ObjectType;
16393
16394 NamedDecl *Func = *I;
16395 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16396 if (isa<UsingShadowDecl>(Val: Func))
16397 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16398
16399 bool HasExplicitParameter = false;
16400 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16401 M && M->hasCXXExplicitFunctionObjectParameter())
16402 HasExplicitParameter = true;
16403 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16404 M &&
16405 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16406 HasExplicitParameter = true;
16407
16408 if (HasExplicitParameter)
16409 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16410
16411 // Microsoft supports direct constructor calls.
16412 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16413 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16414 CandidateSet,
16415 /*SuppressUserConversions*/ false);
16416 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16417 // If explicit template arguments were provided, we can't call a
16418 // non-template member function.
16419 if (TemplateArgs)
16420 continue;
16421
16422 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16423 ObjectClassification, Args, CandidateSet,
16424 /*SuppressUserConversions=*/false);
16425 } else {
16426 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16427 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16428 ObjectType: ExplicitObjectType, ObjectClassification,
16429 Args, CandidateSet,
16430 /*SuppressUserConversions=*/false);
16431 }
16432 }
16433
16434 HadMultipleCandidates = (CandidateSet.size() > 1);
16435
16436 DeclarationName DeclName = UnresExpr->getMemberName();
16437
16438 UnbridgedCasts.restore();
16439
16440 OverloadCandidateSet::iterator Best;
16441 bool Succeeded = false;
16442 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16443 Best)) {
16444 case OR_Success:
16445 Method = cast<CXXMethodDecl>(Val: Best->Function);
16446 FoundDecl = Best->FoundDecl;
16447 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16448 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16449 break;
16450 // If FoundDecl is different from Method (such as if one is a template
16451 // and the other a specialization), make sure DiagnoseUseOfDecl is
16452 // called on both.
16453 // FIXME: This would be more comprehensively addressed by modifying
16454 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16455 // being used.
16456 if (Method != FoundDecl.getDecl() &&
16457 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16458 break;
16459 Succeeded = true;
16460 break;
16461
16462 case OR_No_Viable_Function:
16463 CandidateSet.NoteCandidates(
16464 PD: PartialDiagnosticAt(
16465 UnresExpr->getMemberLoc(),
16466 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16467 << DeclName << MemExprE->getSourceRange()),
16468 S&: *this, OCD: OCD_AllCandidates, Args);
16469 break;
16470 case OR_Ambiguous:
16471 CandidateSet.NoteCandidates(
16472 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16473 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16474 << DeclName << MemExprE->getSourceRange()),
16475 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16476 break;
16477 case OR_Deleted:
16478 DiagnoseUseOfDeletedFunction(
16479 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16480 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16481 break;
16482 }
16483 // Overload resolution fails, try to recover.
16484 if (!Succeeded)
16485 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16486
16487 ExprResult Res =
16488 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16489 if (Res.isInvalid())
16490 return ExprError();
16491 MemExprE = Res.get();
16492
16493 // If overload resolution picked a static member
16494 // build a non-member call based on that function.
16495 if (Method->isStatic()) {
16496 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16497 Config: ExecConfig, IsExecConfig);
16498 }
16499
16500 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16501 }
16502
16503 QualType ResultType = Method->getReturnType();
16504 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16505 ResultType = ResultType.getNonLValueExprType(Context);
16506
16507 assert(Method && "Member call to something that isn't a method?");
16508 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16509
16510 CallExpr *TheCall = nullptr;
16511 llvm::SmallVector<Expr *, 8> NewArgs;
16512 if (Method->isExplicitObjectMemberFunction()) {
16513 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16514 NewArgs))
16515 return ExprError();
16516
16517 // Build the actual expression node.
16518 ExprResult FnExpr =
16519 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16520 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16521 if (FnExpr.isInvalid())
16522 return ExprError();
16523
16524 TheCall =
16525 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16526 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16527 TheCall->setUsesMemberSyntax(true);
16528 } else {
16529 // Convert the object argument (for a non-static member function call).
16530 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16531 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16532 if (ObjectArg.isInvalid())
16533 return ExprError();
16534 MemExpr->setBase(ObjectArg.get());
16535 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16536 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16537 MinNumArgs: Proto->getNumParams());
16538 }
16539
16540 // Check for a valid return type.
16541 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16542 CE: TheCall, FD: Method))
16543 return BuildRecoveryExpr(ResultType);
16544
16545 // Convert the rest of the arguments
16546 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16547 RParenLoc))
16548 return BuildRecoveryExpr(ResultType);
16549
16550 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16551
16552 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16553 return ExprError();
16554
16555 // In the case the method to call was not selected by the overloading
16556 // resolution process, we still need to handle the enable_if attribute. Do
16557 // that here, so it will not hide previous -- and more relevant -- errors.
16558 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16559 if (const EnableIfAttr *Attr =
16560 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16561 Diag(Loc: MemE->getMemberLoc(),
16562 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16563 << Method << Method->getSourceRange();
16564 Diag(Loc: Method->getLocation(),
16565 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16566 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16567 return ExprError();
16568 }
16569 }
16570
16571 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16572 TheCall->getDirectCallee()->isPureVirtual()) {
16573 const FunctionDecl *MD = TheCall->getDirectCallee();
16574
16575 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16576 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16577 Diag(Loc: MemExpr->getBeginLoc(),
16578 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16579 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16580 << MD->getParent();
16581
16582 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16583 if (getLangOpts().AppleKext)
16584 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16585 << MD->getParent() << MD->getDeclName();
16586 }
16587 }
16588
16589 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16590 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16591 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16592 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16593 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16594 DtorLoc: MemExpr->getMemberLoc());
16595 }
16596
16597 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16598 Decl: TheCall->getDirectCallee());
16599}
16600
16601ExprResult
16602Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16603 SourceLocation LParenLoc,
16604 MultiExprArg Args,
16605 SourceLocation RParenLoc) {
16606 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16607 return ExprError();
16608 ExprResult Object = Obj;
16609
16610 UnbridgedCastsSet UnbridgedCasts;
16611 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16612 return ExprError();
16613
16614 assert(Object.get()->getType()->isRecordType() &&
16615 "Requires object type argument");
16616
16617 // C++ [over.call.object]p1:
16618 // If the primary-expression E in the function call syntax
16619 // evaluates to a class object of type "cv T", then the set of
16620 // candidate functions includes at least the function call
16621 // operators of T. The function call operators of T are obtained by
16622 // ordinary lookup of the name operator() in the context of
16623 // (E).operator().
16624 OverloadCandidateSet CandidateSet(LParenLoc,
16625 OverloadCandidateSet::CSK_Operator);
16626 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16627
16628 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16629 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16630 return true;
16631
16632 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16633 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16634 LookupQualifiedName(R, LookupCtx: Record);
16635 R.suppressAccessDiagnostics();
16636
16637 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16638 Oper != OperEnd; ++Oper) {
16639 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16640 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16641 /*SuppressUserConversion=*/SuppressUserConversions: false);
16642 }
16643
16644 // When calling a lambda, both the call operator, and
16645 // the conversion operator to function pointer
16646 // are considered. But when constraint checking
16647 // on the call operator fails, it will also fail on the
16648 // conversion operator as the constraints are always the same.
16649 // As the user probably does not intend to perform a surrogate call,
16650 // we filter them out to produce better error diagnostics, ie to avoid
16651 // showing 2 failed overloads instead of one.
16652 bool IgnoreSurrogateFunctions = false;
16653 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16654 const OverloadCandidate &Candidate = *CandidateSet.begin();
16655 if (!Candidate.Viable &&
16656 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16657 IgnoreSurrogateFunctions = true;
16658 }
16659
16660 // C++ [over.call.object]p2:
16661 // In addition, for each (non-explicit in C++0x) conversion function
16662 // declared in T of the form
16663 //
16664 // operator conversion-type-id () cv-qualifier;
16665 //
16666 // where cv-qualifier is the same cv-qualification as, or a
16667 // greater cv-qualification than, cv, and where conversion-type-id
16668 // denotes the type "pointer to function of (P1,...,Pn) returning
16669 // R", or the type "reference to pointer to function of
16670 // (P1,...,Pn) returning R", or the type "reference to function
16671 // of (P1,...,Pn) returning R", a surrogate call function [...]
16672 // is also considered as a candidate function. Similarly,
16673 // surrogate call functions are added to the set of candidate
16674 // functions for each conversion function declared in an
16675 // accessible base class provided the function is not hidden
16676 // within T by another intervening declaration.
16677 const auto &Conversions = Record->getVisibleConversionFunctions();
16678 for (auto I = Conversions.begin(), E = Conversions.end();
16679 !IgnoreSurrogateFunctions && I != E; ++I) {
16680 NamedDecl *D = *I;
16681 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16682 if (isa<UsingShadowDecl>(Val: D))
16683 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16684
16685 // Skip over templated conversion functions; they aren't
16686 // surrogates.
16687 if (isa<FunctionTemplateDecl>(Val: D))
16688 continue;
16689
16690 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16691 if (!Conv->isExplicit()) {
16692 // Strip the reference type (if any) and then the pointer type (if
16693 // any) to get down to what might be a function type.
16694 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16695 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16696 ConvType = ConvPtrType->getPointeeType();
16697
16698 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16699 {
16700 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16701 Object: Object.get(), Args, CandidateSet);
16702 }
16703 }
16704 }
16705
16706 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16707
16708 // Perform overload resolution.
16709 OverloadCandidateSet::iterator Best;
16710 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16711 Best)) {
16712 case OR_Success:
16713 // Overload resolution succeeded; we'll build the appropriate call
16714 // below.
16715 break;
16716
16717 case OR_No_Viable_Function: {
16718 PartialDiagnostic PD =
16719 CandidateSet.empty()
16720 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16721 << Object.get()->getType() << /*call*/ 1
16722 << Object.get()->getSourceRange())
16723 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16724 << Object.get()->getType() << Object.get()->getSourceRange());
16725 CandidateSet.NoteCandidates(
16726 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16727 OCD: OCD_AllCandidates, Args);
16728 break;
16729 }
16730 case OR_Ambiguous:
16731 if (!R.isAmbiguous())
16732 CandidateSet.NoteCandidates(
16733 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16734 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16735 << Object.get()->getType()
16736 << Object.get()->getSourceRange()),
16737 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16738 break;
16739
16740 case OR_Deleted: {
16741 // FIXME: Is this diagnostic here really necessary? It seems that
16742 // 1. we don't have any tests for this diagnostic, and
16743 // 2. we already issue err_deleted_function_use for this later on anyway.
16744 StringLiteral *Msg = Best->Function->getDeletedMessage();
16745 CandidateSet.NoteCandidates(
16746 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16747 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16748 << Object.get()->getType() << (Msg != nullptr)
16749 << (Msg ? Msg->getString() : StringRef())
16750 << Object.get()->getSourceRange()),
16751 S&: *this, OCD: OCD_AllCandidates, Args);
16752 break;
16753 }
16754 }
16755
16756 if (Best == CandidateSet.end())
16757 return true;
16758
16759 UnbridgedCasts.restore();
16760
16761 if (Best->Function == nullptr) {
16762 // Since there is no function declaration, this is one of the
16763 // surrogate candidates. Dig out the conversion function.
16764 CXXConversionDecl *Conv
16765 = cast<CXXConversionDecl>(
16766 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16767
16768 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16769 FoundDecl: Best->FoundDecl);
16770 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16771 return ExprError();
16772 assert(Conv == Best->FoundDecl.getDecl() &&
16773 "Found Decl & conversion-to-functionptr should be same, right?!");
16774 // We selected one of the surrogate functions that converts the
16775 // object parameter to a function pointer. Perform the conversion
16776 // on the object argument, then let BuildCallExpr finish the job.
16777
16778 // Create an implicit member expr to refer to the conversion operator.
16779 // and then call it.
16780 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16781 Method: Conv, HadMultipleCandidates);
16782 if (Call.isInvalid())
16783 return ExprError();
16784 // Record usage of conversion in an implicit cast.
16785 Call = ImplicitCastExpr::Create(
16786 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16787 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16788
16789 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16790 }
16791
16792 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16793
16794 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16795 // that calls this method, using Object for the implicit object
16796 // parameter and passing along the remaining arguments.
16797 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16798
16799 // An error diagnostic has already been printed when parsing the declaration.
16800 if (Method->isInvalidDecl())
16801 return ExprError();
16802
16803 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16804 unsigned NumParams = Proto->getNumParams();
16805
16806 DeclarationNameInfo OpLocInfo(
16807 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16808 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16809 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16810 Base: Obj, HadMultipleCandidates,
16811 Loc: OpLocInfo.getLoc(),
16812 LocInfo: OpLocInfo.getInfo());
16813 if (NewFn.isInvalid())
16814 return true;
16815
16816 SmallVector<Expr *, 8> MethodArgs;
16817 MethodArgs.reserve(N: NumParams + 1);
16818
16819 bool IsError = false;
16820
16821 // Initialize the object parameter.
16822 llvm::SmallVector<Expr *, 8> NewArgs;
16823 if (Method->isExplicitObjectMemberFunction()) {
16824 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16825 } else {
16826 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16827 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16828 if (ObjRes.isInvalid())
16829 IsError = true;
16830 else
16831 Object = ObjRes;
16832 MethodArgs.push_back(Elt: Object.get());
16833 }
16834
16835 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16836 S&: *this, MethodArgs, Method, Args, LParenLoc);
16837
16838 // If this is a variadic call, handle args passed through "...".
16839 if (Proto->isVariadic()) {
16840 // Promote the arguments (C99 6.5.2.2p7).
16841 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16842 ExprResult Arg = DefaultVariadicArgumentPromotion(
16843 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16844 IsError |= Arg.isInvalid();
16845 MethodArgs.push_back(Elt: Arg.get());
16846 }
16847 }
16848
16849 if (IsError)
16850 return true;
16851
16852 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16853
16854 // Once we've built TheCall, all of the expressions are properly owned.
16855 QualType ResultTy = Method->getReturnType();
16856 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16857 ResultTy = ResultTy.getNonLValueExprType(Context);
16858
16859 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16860 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16861 FPFeatures: CurFPFeatureOverrides());
16862
16863 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16864 return true;
16865
16866 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16867 return true;
16868
16869 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16870}
16871
16872ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16873 SourceLocation OpLoc,
16874 bool *NoArrowOperatorFound) {
16875 assert(Base->getType()->isRecordType() &&
16876 "left-hand side must have class type");
16877
16878 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16879 return ExprError();
16880
16881 SourceLocation Loc = Base->getExprLoc();
16882
16883 // C++ [over.ref]p1:
16884 //
16885 // [...] An expression x->m is interpreted as (x.operator->())->m
16886 // for a class object x of type T if T::operator->() exists and if
16887 // the operator is selected as the best match function by the
16888 // overload resolution mechanism (13.3).
16889 DeclarationName OpName =
16890 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16891 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16892
16893 if (RequireCompleteType(Loc, T: Base->getType(),
16894 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16895 return ExprError();
16896
16897 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16898 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16899 R.suppressAccessDiagnostics();
16900
16901 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16902 Oper != OperEnd; ++Oper) {
16903 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16904 Args: {}, CandidateSet,
16905 /*SuppressUserConversion=*/SuppressUserConversions: false);
16906 }
16907
16908 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16909
16910 // Perform overload resolution.
16911 OverloadCandidateSet::iterator Best;
16912 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16913 case OR_Success:
16914 // Overload resolution succeeded; we'll build the call below.
16915 break;
16916
16917 case OR_No_Viable_Function: {
16918 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16919 if (CandidateSet.empty()) {
16920 QualType BaseType = Base->getType();
16921 if (NoArrowOperatorFound) {
16922 // Report this specific error to the caller instead of emitting a
16923 // diagnostic, as requested.
16924 *NoArrowOperatorFound = true;
16925 return ExprError();
16926 }
16927 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16928 << BaseType << Base->getSourceRange();
16929 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16930 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16931 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16932 }
16933 } else
16934 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16935 << "operator->" << Base->getSourceRange();
16936 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16937 return ExprError();
16938 }
16939 case OR_Ambiguous:
16940 if (!R.isAmbiguous())
16941 CandidateSet.NoteCandidates(
16942 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16943 << "->" << Base->getType()
16944 << Base->getSourceRange()),
16945 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16946 return ExprError();
16947
16948 case OR_Deleted: {
16949 StringLiteral *Msg = Best->Function->getDeletedMessage();
16950 CandidateSet.NoteCandidates(
16951 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16952 << "->" << (Msg != nullptr)
16953 << (Msg ? Msg->getString() : StringRef())
16954 << Base->getSourceRange()),
16955 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16956 return ExprError();
16957 }
16958 }
16959
16960 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16961
16962 // Convert the object parameter.
16963 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16964
16965 if (Method->isExplicitObjectMemberFunction()) {
16966 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16967 if (R.isInvalid())
16968 return ExprError();
16969 Base = R.get();
16970 } else {
16971 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16972 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16973 if (BaseResult.isInvalid())
16974 return ExprError();
16975 Base = BaseResult.get();
16976 }
16977
16978 // Build the operator call.
16979 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16980 Base, HadMultipleCandidates, Loc: OpLoc);
16981 if (FnExpr.isInvalid())
16982 return ExprError();
16983
16984 QualType ResultTy = Method->getReturnType();
16985 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16986 ResultTy = ResultTy.getNonLValueExprType(Context);
16987
16988 CallExpr *TheCall =
16989 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16990 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16991
16992 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16993 return ExprError();
16994
16995 if (CheckFunctionCall(FDecl: Method, TheCall,
16996 Proto: Method->getType()->castAs<FunctionProtoType>()))
16997 return ExprError();
16998
16999 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17000}
17001
17002ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
17003 DeclarationNameInfo &SuffixInfo,
17004 ArrayRef<Expr*> Args,
17005 SourceLocation LitEndLoc,
17006 TemplateArgumentListInfo *TemplateArgs) {
17007 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17008
17009 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17010 OverloadCandidateSet::CSK_Normal);
17011 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
17012 ExplicitTemplateArgs: TemplateArgs);
17013
17014 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17015
17016 // Perform overload resolution. This will usually be trivial, but might need
17017 // to perform substitutions for a literal operator template.
17018 OverloadCandidateSet::iterator Best;
17019 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
17020 case OR_Success:
17021 case OR_Deleted:
17022 break;
17023
17024 case OR_No_Viable_Function:
17025 CandidateSet.NoteCandidates(
17026 PD: PartialDiagnosticAt(UDSuffixLoc,
17027 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
17028 << R.getLookupName()),
17029 S&: *this, OCD: OCD_AllCandidates, Args);
17030 return ExprError();
17031
17032 case OR_Ambiguous:
17033 CandidateSet.NoteCandidates(
17034 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
17035 << R.getLookupName()),
17036 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
17037 return ExprError();
17038 }
17039
17040 FunctionDecl *FD = Best->Function;
17041 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
17042 Base: nullptr, HadMultipleCandidates,
17043 Loc: SuffixInfo.getLoc(),
17044 LocInfo: SuffixInfo.getInfo());
17045 if (Fn.isInvalid())
17046 return true;
17047
17048 // Check the argument types. This should almost always be a no-op, except
17049 // that array-to-pointer decay is applied to string literals.
17050 Expr *ConvArgs[2];
17051 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17052 ExprResult InputInit = PerformCopyInitialization(
17053 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17054 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17055 if (InputInit.isInvalid())
17056 return true;
17057 ConvArgs[ArgIdx] = InputInit.get();
17058 }
17059
17060 QualType ResultTy = FD->getReturnType();
17061 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17062 ResultTy = ResultTy.getNonLValueExprType(Context);
17063
17064 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17065 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17066 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17067
17068 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17069 return ExprError();
17070
17071 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17072 return ExprError();
17073
17074 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17075}
17076
17077Sema::ForRangeStatus
17078Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17079 SourceLocation RangeLoc,
17080 const DeclarationNameInfo &NameInfo,
17081 LookupResult &MemberLookup,
17082 OverloadCandidateSet *CandidateSet,
17083 Expr *Range, ExprResult *CallExpr) {
17084 Scope *S = nullptr;
17085
17086 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17087 if (!MemberLookup.empty()) {
17088 ExprResult MemberRef =
17089 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17090 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17091 /*TemplateKWLoc=*/SourceLocation(),
17092 /*FirstQualifierInScope=*/nullptr,
17093 R&: MemberLookup,
17094 /*TemplateArgs=*/nullptr, S);
17095 if (MemberRef.isInvalid()) {
17096 *CallExpr = ExprError();
17097 return FRS_DiagnosticIssued;
17098 }
17099 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17100 if (CallExpr->isInvalid()) {
17101 *CallExpr = ExprError();
17102 return FRS_DiagnosticIssued;
17103 }
17104 } else {
17105 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17106 NNSLoc: NestedNameSpecifierLoc(),
17107 DNI: NameInfo, Fns: UnresolvedSet<0>());
17108 if (FnR.isInvalid())
17109 return FRS_DiagnosticIssued;
17110 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17111
17112 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17113 CandidateSet, Result: CallExpr);
17114 if (CandidateSet->empty() || CandidateSetError) {
17115 *CallExpr = ExprError();
17116 return FRS_NoViableFunction;
17117 }
17118 OverloadCandidateSet::iterator Best;
17119 OverloadingResult OverloadResult =
17120 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17121
17122 if (OverloadResult == OR_No_Viable_Function) {
17123 *CallExpr = ExprError();
17124 return FRS_NoViableFunction;
17125 }
17126 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17127 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17128 OverloadResult,
17129 /*AllowTypoCorrection=*/false);
17130 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17131 *CallExpr = ExprError();
17132 return FRS_DiagnosticIssued;
17133 }
17134 }
17135 return FRS_Success;
17136}
17137
17138ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17139 FunctionDecl *Fn) {
17140 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17141 ExprResult SubExpr =
17142 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17143 if (SubExpr.isInvalid())
17144 return ExprError();
17145 if (SubExpr.get() == PE->getSubExpr())
17146 return PE;
17147
17148 return new (Context)
17149 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17150 }
17151
17152 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17153 ExprResult SubExpr =
17154 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17155 if (SubExpr.isInvalid())
17156 return ExprError();
17157 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17158 SubExpr.get()->getType()) &&
17159 "Implicit cast type cannot be determined from overload");
17160 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17161 if (SubExpr.get() == ICE->getSubExpr())
17162 return ICE;
17163
17164 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17165 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17166 FPO: CurFPFeatureOverrides());
17167 }
17168
17169 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17170 if (!GSE->isResultDependent()) {
17171 ExprResult SubExpr =
17172 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17173 if (SubExpr.isInvalid())
17174 return ExprError();
17175 if (SubExpr.get() == GSE->getResultExpr())
17176 return GSE;
17177
17178 // Replace the resulting type information before rebuilding the generic
17179 // selection expression.
17180 ArrayRef<Expr *> A = GSE->getAssocExprs();
17181 SmallVector<Expr *, 4> AssocExprs(A);
17182 unsigned ResultIdx = GSE->getResultIndex();
17183 AssocExprs[ResultIdx] = SubExpr.get();
17184
17185 if (GSE->isExprPredicate())
17186 return GenericSelectionExpr::Create(
17187 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17188 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17189 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17190 ResultIndex: ResultIdx);
17191 return GenericSelectionExpr::Create(
17192 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17193 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17194 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17195 ResultIndex: ResultIdx);
17196 }
17197 // Rather than fall through to the unreachable, return the original generic
17198 // selection expression.
17199 return GSE;
17200 }
17201
17202 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17203 assert(UnOp->getOpcode() == UO_AddrOf &&
17204 "Can only take the address of an overloaded function");
17205 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17206 if (!Method->isImplicitObjectMemberFunction()) {
17207 // Do nothing: the address of static and
17208 // explicit object member functions is a (non-member) function pointer.
17209 } else {
17210 // Fix the subexpression, which really has to be an
17211 // UnresolvedLookupExpr holding an overloaded member function
17212 // or template.
17213 ExprResult SubExpr =
17214 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17215 if (SubExpr.isInvalid())
17216 return ExprError();
17217 if (SubExpr.get() == UnOp->getSubExpr())
17218 return UnOp;
17219
17220 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17221 Op: SubExpr.get(), MD: Method))
17222 return ExprError();
17223
17224 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17225 "fixed to something other than a decl ref");
17226 NestedNameSpecifier Qualifier =
17227 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17228 assert(Qualifier &&
17229 "fixed to a member ref with no nested name qualifier");
17230
17231 // We have taken the address of a pointer to member
17232 // function. Perform the computation here so that we get the
17233 // appropriate pointer to member type.
17234 QualType MemPtrType = Context.getMemberPointerType(
17235 T: Fn->getType(), Qualifier,
17236 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17237 // Under the MS ABI, lock down the inheritance model now.
17238 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17239 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17240
17241 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17242 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17243 l: UnOp->getOperatorLoc(), CanOverflow: false,
17244 FPFeatures: CurFPFeatureOverrides());
17245 }
17246 }
17247 ExprResult SubExpr =
17248 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17249 if (SubExpr.isInvalid())
17250 return ExprError();
17251 if (SubExpr.get() == UnOp->getSubExpr())
17252 return UnOp;
17253
17254 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17255 InputExpr: SubExpr.get());
17256 }
17257
17258 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17259 if (Found.getAccess() == AS_none) {
17260 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17261 }
17262 // FIXME: avoid copy.
17263 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17264 if (ULE->hasExplicitTemplateArgs()) {
17265 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17266 TemplateArgs = &TemplateArgsBuffer;
17267 }
17268
17269 QualType Type = Fn->getType();
17270 ExprValueKind ValueKind =
17271 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17272 ? VK_LValue
17273 : VK_PRValue;
17274
17275 // FIXME: Duplicated from BuildDeclarationNameExpr.
17276 if (unsigned BID = Fn->getBuiltinID()) {
17277 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17278 Type = Context.BuiltinFnTy;
17279 ValueKind = VK_PRValue;
17280 }
17281 }
17282
17283 DeclRefExpr *DRE = BuildDeclRefExpr(
17284 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17285 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17286 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17287 return DRE;
17288 }
17289
17290 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17291 // FIXME: avoid copy.
17292 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17293 if (MemExpr->hasExplicitTemplateArgs()) {
17294 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17295 TemplateArgs = &TemplateArgsBuffer;
17296 }
17297
17298 Expr *Base;
17299
17300 // If we're filling in a static method where we used to have an
17301 // implicit member access, rewrite to a simple decl ref.
17302 if (MemExpr->isImplicitAccess()) {
17303 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17304 DeclRefExpr *DRE = BuildDeclRefExpr(
17305 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17306 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17307 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17308 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17309 return DRE;
17310 } else {
17311 SourceLocation Loc = MemExpr->getMemberLoc();
17312 if (MemExpr->getQualifier())
17313 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17314 Base =
17315 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17316 }
17317 } else
17318 Base = MemExpr->getBase();
17319
17320 ExprValueKind valueKind;
17321 QualType type;
17322 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17323 valueKind = VK_LValue;
17324 type = Fn->getType();
17325 } else {
17326 valueKind = VK_PRValue;
17327 type = Context.BoundMemberTy;
17328 }
17329
17330 return BuildMemberExpr(
17331 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17332 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17333 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17334 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17335 }
17336
17337 llvm_unreachable("Invalid reference to overloaded function");
17338}
17339
17340ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17341 DeclAccessPair Found,
17342 FunctionDecl *Fn) {
17343 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17344}
17345
17346bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17347 FunctionDecl *Function) {
17348 if (!PartialOverloading || !Function)
17349 return true;
17350 if (Function->isVariadic())
17351 return false;
17352 if (const auto *Proto =
17353 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17354 if (Proto->isTemplateVariadic())
17355 return false;
17356 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17357 if (const auto *Proto =
17358 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17359 if (Proto->isTemplateVariadic())
17360 return false;
17361 return true;
17362}
17363
17364void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17365 DeclarationName Name,
17366 OverloadCandidateSet &CandidateSet,
17367 FunctionDecl *Fn, MultiExprArg Args,
17368 bool IsMember) {
17369 StringLiteral *Msg = Fn->getDeletedMessage();
17370 CandidateSet.NoteCandidates(
17371 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17372 << IsMember << Name << (Msg != nullptr)
17373 << (Msg ? Msg->getString() : StringRef())
17374 << Range),
17375 S&: *this, OCD: OCD_AllCandidates, Args);
17376}
17377