1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTDiagnostic.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/DiagnosticOptions.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaAMDGPU.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
40#include "clang/Sema/TemplateDeduction.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
56using AllowedExplicit = Sema::AllowedExplicit;
57
58static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
59 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
65static ExprResult CreateFunctionRefExpr(
66 Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
67 FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
68 bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo,
69 const TemplateArgumentListInfo *TemplateArgs) {
70 SourceLocation Loc = NameInfo.getLoc();
71
72 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
73 return ExprError();
74 // If FoundDecl is different from Fn (such as if one is a template
75 // and the other a specialization), make sure DiagnoseUseOfDecl is
76 // called on both.
77 // FIXME: This would be more comprehensively addressed by modifying
78 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
79 // being used.
80 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
81 return ExprError();
82 auto *DRE = DeclRefExpr::Create(Context: S.Context, QualifierLoc, TemplateKWLoc, D: Fn,
83 /*RefersToEnclosingVariableOrCapture=*/false,
84 NameInfo, T: Fn->getType(), VK: VK_LValue, FoundD: FoundDecl,
85 TemplateArgs);
86 if (HadMultipleCandidates)
87 DRE->setHadMultipleCandidates(true);
88
89 S.MarkDeclRefReferenced(E: DRE, Base);
90 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
91 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
92 S.ResolveExceptionSpec(Loc, FPT);
93 DRE->setType(Fn->getType());
94 }
95 }
96 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
97 CK: CK_FunctionToPointerDecay);
98}
99
100static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
101 NamedDecl *FoundDecl, const Expr *Base,
102 bool HadMultipleCandidates,
103 const DeclarationNameInfo &NameInfo) {
104 return CreateFunctionRefExpr(S, /*QualifierLoc=*/{}, /*TemplateKWLoc=*/{}, Fn,
105 FoundDecl, Base, HadMultipleCandidates, NameInfo,
106 /*TemplateArgs=*/nullptr);
107}
108
109static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
110 NamedDecl *FoundDecl, const Expr *Base,
111 bool HadMultipleCandidates,
112 SourceLocation Loc) {
113 return CreateFunctionRefExpr(S, Fn, FoundDecl, Base, HadMultipleCandidates,
114 NameInfo: DeclarationNameInfo(Fn->getDeclName(), Loc));
115}
116
117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
118 bool InOverloadResolution,
119 StandardConversionSequence &SCS,
120 bool CStyle,
121 bool AllowObjCWritebackConversion);
122
123static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
124 QualType &ToType,
125 bool InOverloadResolution,
126 StandardConversionSequence &SCS,
127 bool CStyle);
128static OverloadingResult
129IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
130 UserDefinedConversionSequence& User,
131 OverloadCandidateSet& Conversions,
132 AllowedExplicit AllowExplicit,
133 bool AllowObjCConversionOnExplicit);
134
135static ImplicitConversionSequence::CompareKind
136CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
137 const StandardConversionSequence& SCS1,
138 const StandardConversionSequence& SCS2);
139
140static ImplicitConversionSequence::CompareKind
141CompareQualificationConversions(Sema &S,
142 const StandardConversionSequence& SCS1,
143 const StandardConversionSequence& SCS2);
144
145static ImplicitConversionSequence::CompareKind
146CompareOverflowBehaviorConversions(Sema &S,
147 const StandardConversionSequence &SCS1,
148 const StandardConversionSequence &SCS2);
149
150static ImplicitConversionSequence::CompareKind
151CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
152 const StandardConversionSequence& SCS1,
153 const StandardConversionSequence& SCS2);
154
155/// GetConversionRank - Retrieve the implicit conversion rank
156/// corresponding to the given implicit conversion kind.
157ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
158 static const ImplicitConversionRank Rank[] = {
159 ICR_Exact_Match,
160 ICR_Exact_Match,
161 ICR_Exact_Match,
162 ICR_Exact_Match,
163 ICR_Exact_Match,
164 ICR_Exact_Match,
165 ICR_Promotion,
166 ICR_Promotion,
167 ICR_Promotion,
168 ICR_Conversion,
169 ICR_Conversion,
170 ICR_Conversion,
171 ICR_Conversion,
172 ICR_Conversion,
173 ICR_Conversion,
174 ICR_Conversion,
175 ICR_Conversion,
176 ICR_Conversion,
177 ICR_Conversion,
178 ICR_Conversion,
179 ICR_Conversion,
180 ICR_OCL_Scalar_Widening,
181 ICR_Complex_Real_Conversion,
182 ICR_Conversion,
183 ICR_Conversion,
184 ICR_Writeback_Conversion,
185 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
186 // it was omitted by the patch that added
187 // ICK_Zero_Event_Conversion
188 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
189 // it was omitted by the patch that added
190 // ICK_Zero_Queue_Conversion
191 ICR_C_Conversion,
192 ICR_C_Conversion_Extension,
193 ICR_Conversion,
194 ICR_HLSL_Dimension_Reduction,
195 ICR_HLSL_Dimension_Reduction,
196 ICR_Conversion,
197 ICR_HLSL_Scalar_Widening,
198 ICR_HLSL_Scalar_Widening,
199 };
200 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
201 return Rank[(int)Kind];
202}
203
204ImplicitConversionRank
205clang::GetDimensionConversionRank(ImplicitConversionRank Base,
206 ImplicitConversionKind Dimension) {
207 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
208 if (Rank == ICR_HLSL_Scalar_Widening) {
209 if (Base == ICR_Promotion)
210 return ICR_HLSL_Scalar_Widening_Promotion;
211 if (Base == ICR_Conversion)
212 return ICR_HLSL_Scalar_Widening_Conversion;
213 }
214 if (Rank == ICR_HLSL_Dimension_Reduction) {
215 if (Base == ICR_Promotion)
216 return ICR_HLSL_Dimension_Reduction_Promotion;
217 if (Base == ICR_Conversion)
218 return ICR_HLSL_Dimension_Reduction_Conversion;
219 }
220 return Rank;
221}
222
223/// GetImplicitConversionName - Return the name of this kind of
224/// implicit conversion.
225static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
226 static const char *const Name[] = {
227 "No conversion",
228 "Lvalue-to-rvalue",
229 "Array-to-pointer",
230 "Function-to-pointer",
231 "Function pointer conversion",
232 "Qualification",
233 "Integral promotion",
234 "Floating point promotion",
235 "Complex promotion",
236 "Integral conversion",
237 "Floating conversion",
238 "Complex conversion",
239 "Floating-integral conversion",
240 "Pointer conversion",
241 "Pointer-to-member conversion",
242 "Boolean conversion",
243 "Compatible-types conversion",
244 "Derived-to-base conversion",
245 "Vector conversion",
246 "SVE Vector conversion",
247 "RVV Vector conversion",
248 "Vector splat",
249 "Complex-real conversion",
250 "Block Pointer conversion",
251 "Transparent Union Conversion",
252 "Writeback conversion",
253 "OpenCL Zero Event Conversion",
254 "OpenCL Zero Queue Conversion",
255 "C specific type conversion",
256 "Incompatible pointer conversion",
257 "Fixed point conversion",
258 "HLSL vector truncation",
259 "HLSL matrix truncation",
260 "Non-decaying array conversion",
261 "HLSL vector splat",
262 "HLSL matrix splat",
263 };
264 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
265 return Name[Kind];
266}
267
268/// StandardConversionSequence - Set the standard conversion
269/// sequence to the identity conversion.
270void StandardConversionSequence::setAsIdentityConversion() {
271 First = ICK_Identity;
272 Second = ICK_Identity;
273 Dimension = ICK_Identity;
274 Third = ICK_Identity;
275 DeprecatedStringLiteralToCharPtr = false;
276 QualificationIncludesObjCLifetime = false;
277 ReferenceBinding = false;
278 DirectBinding = false;
279 IsLvalueReference = true;
280 BindsToFunctionLvalue = false;
281 BindsToRvalue = false;
282 BindsImplicitObjectArgumentWithoutRefQualifier = false;
283 ObjCLifetimeConversionBinding = false;
284 FromBracedInitList = false;
285 CopyConstructor = nullptr;
286}
287
288/// getRank - Retrieve the rank of this standard conversion sequence
289/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
290/// implicit conversions.
291ImplicitConversionRank StandardConversionSequence::getRank() const {
292 ImplicitConversionRank Rank = ICR_Exact_Match;
293 if (GetConversionRank(Kind: First) > Rank)
294 Rank = GetConversionRank(Kind: First);
295 if (GetConversionRank(Kind: Second) > Rank)
296 Rank = GetConversionRank(Kind: Second);
297 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
298 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
299 if (GetConversionRank(Kind: Third) > Rank)
300 Rank = GetConversionRank(Kind: Third);
301 return Rank;
302}
303
304/// isPointerConversionToBool - Determines whether this conversion is
305/// a conversion of a pointer or pointer-to-member to bool. This is
306/// used as part of the ranking of standard conversion sequences
307/// (C++ 13.3.3.2p4).
308bool StandardConversionSequence::isPointerConversionToBool() const {
309 // Note that FromType has not necessarily been transformed by the
310 // array-to-pointer or function-to-pointer implicit conversions, so
311 // check for their presence as well as checking whether FromType is
312 // a pointer.
313 if (getToType(Idx: 1)->isBooleanType() &&
314 (getFromType()->isPointerType() ||
315 getFromType()->isMemberPointerType() ||
316 getFromType()->isObjCObjectPointerType() ||
317 getFromType()->isBlockPointerType() ||
318 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
319 return true;
320
321 return false;
322}
323
324/// isPointerConversionToVoidPointer - Determines whether this
325/// conversion is a conversion of a pointer to a void pointer. This is
326/// used as part of the ranking of standard conversion sequences (C++
327/// 13.3.3.2p4).
328bool
329StandardConversionSequence::
330isPointerConversionToVoidPointer(ASTContext& Context) const {
331 QualType FromType = getFromType();
332 QualType ToType = getToType(Idx: 1);
333
334 // Note that FromType has not necessarily been transformed by the
335 // array-to-pointer implicit conversion, so check for its presence
336 // and redo the conversion to get a pointer.
337 if (First == ICK_Array_To_Pointer)
338 FromType = Context.getArrayDecayedType(T: FromType);
339
340 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
341 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
342 return ToPtrType->getPointeeType()->isVoidType();
343
344 return false;
345}
346
347/// Skip any implicit casts which could be either part of a narrowing conversion
348/// or after one in an implicit conversion.
349static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
350 const Expr *Converted) {
351 // We can have cleanups wrapping the converted expression; these need to be
352 // preserved so that destructors run if necessary.
353 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
354 Expr *Inner =
355 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
356 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
357 objects: EWC->getObjects());
358 }
359
360 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
361 switch (ICE->getCastKind()) {
362 case CK_NoOp:
363 case CK_IntegralCast:
364 case CK_IntegralToBoolean:
365 case CK_IntegralToFloating:
366 case CK_BooleanToSignedIntegral:
367 case CK_FloatingToIntegral:
368 case CK_FloatingToBoolean:
369 case CK_FloatingCast:
370 Converted = ICE->getSubExpr();
371 continue;
372
373 default:
374 return Converted;
375 }
376 }
377
378 return Converted;
379}
380
381/// Check if this standard conversion sequence represents a narrowing
382/// conversion, according to C++11 [dcl.init.list]p7.
383///
384/// \param Ctx The AST context.
385/// \param Converted The result of applying this standard conversion sequence.
386/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
387/// value of the expression prior to the narrowing conversion.
388/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
389/// type of the expression prior to the narrowing conversion.
390/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
391/// from floating point types to integral types should be ignored.
392/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
393/// to conform MSVC compiler behavior.
394NarrowingKind StandardConversionSequence::getNarrowingKind(
395 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
396 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
397 bool AllowRelaxedEval) const {
398 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
399 "narrowing check outside C++");
400
401 // C++11 [dcl.init.list]p7:
402 // A narrowing conversion is an implicit conversion ...
403 QualType FromType = getToType(Idx: 0);
404 QualType ToType = getToType(Idx: 1);
405
406 // A conversion to an enumeration type is narrowing if the conversion to
407 // the underlying type is narrowing. This only arises for expressions of
408 // the form 'Enum{init}'.
409 if (const auto *ED = ToType->getAsEnumDecl())
410 ToType = ED->getIntegerType();
411
412 switch (Second) {
413 // 'bool' is an integral type; dispatch to the right place to handle it.
414 case ICK_Boolean_Conversion:
415 if (FromType->isRealFloatingType())
416 goto FloatingIntegralConversion;
417 if (FromType->isIntegralOrUnscopedEnumerationType())
418 goto IntegralConversion;
419 // -- from a pointer type or pointer-to-member type to bool, or
420 return NK_Type_Narrowing;
421
422 // -- from a floating-point type to an integer type, or
423 //
424 // -- from an integer type or unscoped enumeration type to a floating-point
425 // type, except where the source is a constant expression and the actual
426 // value after conversion will fit into the target type and will produce
427 // the original value when converted back to the original type, or
428 case ICK_Floating_Integral:
429 FloatingIntegralConversion:
430 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
431 return NK_Type_Narrowing;
432 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
433 ToType->isRealFloatingType()) {
434 if (IgnoreFloatToIntegralConversion)
435 return NK_Not_Narrowing;
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
437 assert(Initializer && "Unknown conversion expression");
438
439 // If it's value-dependent, we can't tell whether it's narrowing.
440 if (Initializer->isValueDependent())
441 return NK_Dependent_Narrowing;
442
443 if (std::optional<llvm::APSInt> IntConstantValue =
444 Initializer->getIntegerConstantExpr(Ctx)) {
445 // Convert the integer to the floating type.
446 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
447 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
448 RM: llvm::APFloat::rmNearestTiesToEven);
449 // And back.
450 llvm::APSInt ConvertedValue = *IntConstantValue;
451 bool ignored;
452 llvm::APFloat::opStatus Status = Result.convertToInteger(
453 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
454 // If the converted-back integer has unspecified value, or if the
455 // resulting value is different, this was a narrowing conversion.
456 if (Status == llvm::APFloat::opInvalidOp ||
457 *IntConstantValue != ConvertedValue) {
458 ConstantValue = APValue(*IntConstantValue);
459 ConstantType = Initializer->getType();
460 return NK_Constant_Narrowing;
461 }
462 } else {
463 // Variables are always narrowings.
464 return NK_Variable_Narrowing;
465 }
466 }
467 return NK_Not_Narrowing;
468
469 // -- from long double to double or float, or from double to float, except
470 // where the source is a constant expression and the actual value after
471 // conversion is within the range of values that can be represented (even
472 // if it cannot be represented exactly), or
473 case ICK_Floating_Conversion:
474 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
475 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
476 // FromType is larger than ToType.
477 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
478
479 // If it's value-dependent, we can't tell whether it's narrowing.
480 if (Initializer->isValueDependent())
481 return NK_Dependent_Narrowing;
482
483 Expr::EvalResult R;
484 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
485 ((Ctx.getLangOpts().CPlusPlus &&
486 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue,
487 AllowRelaxedEval)))) {
488 // Constant!
489 if (Ctx.getLangOpts().C23)
490 ConstantValue = R.Val;
491 assert(ConstantValue.isFloat());
492 llvm::APFloat FloatVal = ConstantValue.getFloat();
493 // Convert the source value into the target type.
494 bool ignored;
495 llvm::APFloat Converted = FloatVal;
496 llvm::APFloat::opStatus ConvertStatus =
497 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
498 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
499 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
500 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
501 if (Ctx.getLangOpts().C23) {
502 if (FloatVal.isNaN() && Converted.isNaN() &&
503 !FloatVal.isSignaling() && !Converted.isSignaling()) {
504 // Quiet NaNs are considered the same value, regardless of
505 // payloads.
506 return NK_Not_Narrowing;
507 }
508 // For normal values, check exact equality.
509 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
510 ConstantType = Initializer->getType();
511 return NK_Constant_Narrowing;
512 }
513 } else {
514 // If there was no overflow, the source value is within the range of
515 // values that can be represented.
516 if (ConvertStatus & llvm::APFloat::opOverflow) {
517 ConstantType = Initializer->getType();
518 return NK_Constant_Narrowing;
519 }
520 }
521 } else {
522 return NK_Variable_Narrowing;
523 }
524 }
525 return NK_Not_Narrowing;
526
527 // -- from an integer type or unscoped enumeration type to an integer type
528 // that cannot represent all the values of the original type, except where
529 // (CWG2627) -- the source is a bit-field whose width w is less than that
530 // of its type (or, for an enumeration type, its underlying type) and the
531 // target type can represent all the values of a hypothetical extended
532 // integer type with width w and with the same signedness as the original
533 // type or
534 // -- the source is a constant expression and the actual value after
535 // conversion will fit into the target type and will produce the original
536 // value when converted back to the original type.
537 case ICK_Integral_Conversion:
538 IntegralConversion: {
539 assert(FromType->isIntegralOrUnscopedEnumerationType());
540 assert(ToType->isIntegralOrUnscopedEnumerationType());
541 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
542 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
543 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
544 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
545
546 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
547 bool ToSigned, unsigned ToWidth) {
548 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
549 !(FromSigned && !ToSigned);
550 };
551
552 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
553 return NK_Not_Narrowing;
554
555 // Not all values of FromType can be represented in ToType.
556 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
557
558 bool DependentBitField = false;
559 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
560 if (BitField->getBitWidth()->isValueDependent())
561 DependentBitField = true;
562 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
563 BitFieldWidth < FromWidth) {
564 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
565 return NK_Not_Narrowing;
566
567 // The initializer will be truncated to the bit-field width
568 FromWidth = BitFieldWidth;
569 }
570 }
571
572 // If it's value-dependent, we can't tell whether it's narrowing.
573 if (Initializer->isValueDependent())
574 return NK_Dependent_Narrowing;
575
576 std::optional<llvm::APSInt> OptInitializerValue =
577 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
578 if (!OptInitializerValue) {
579 // If the bit-field width was dependent, it might end up being small
580 // enough to fit in the target type (unless the target type is unsigned
581 // and the source type is signed, in which case it will never fit)
582 if (DependentBitField && !(FromSigned && !ToSigned))
583 return NK_Dependent_Narrowing;
584
585 // Otherwise, such a conversion is always narrowing
586 return NK_Variable_Narrowing;
587 }
588 llvm::APSInt &InitializerValue = *OptInitializerValue;
589 bool Narrowing = false;
590 if (FromWidth < ToWidth) {
591 // Negative -> unsigned is narrowing. Otherwise, more bits is never
592 // narrowing.
593 if (InitializerValue.isSigned() && InitializerValue.isNegative())
594 Narrowing = true;
595 } else {
596 // Add a bit to the InitializerValue so we don't have to worry about
597 // signed vs. unsigned comparisons.
598 InitializerValue =
599 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
600 // Convert the initializer to and from the target width and signed-ness.
601 llvm::APSInt ConvertedValue = InitializerValue;
602 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
603 ConvertedValue.setIsSigned(ToSigned);
604 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
605 ConvertedValue.setIsSigned(InitializerValue.isSigned());
606 // If the result is different, this was a narrowing conversion.
607 if (ConvertedValue != InitializerValue)
608 Narrowing = true;
609 }
610 if (Narrowing) {
611 ConstantType = Initializer->getType();
612 ConstantValue = APValue(InitializerValue);
613 return NK_Constant_Narrowing;
614 }
615
616 return NK_Not_Narrowing;
617 }
618 case ICK_Complex_Real:
619 if (FromType->isComplexType() && !ToType->isComplexType())
620 return NK_Type_Narrowing;
621 return NK_Not_Narrowing;
622
623 case ICK_Floating_Promotion:
624 if (Ctx.getLangOpts().C23) {
625 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
626 Expr::EvalResult R;
627 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
628 ConstantValue = R.Val;
629 assert(ConstantValue.isFloat());
630 llvm::APFloat FloatVal = ConstantValue.getFloat();
631 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
632 // value, the unqualified versions of the type of the initializer and
633 // the corresponding real type of the object declared shall be
634 // compatible.
635 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
636 ConstantType = Initializer->getType();
637 return NK_Constant_Narrowing;
638 }
639 }
640 }
641 return NK_Not_Narrowing;
642 default:
643 // Other kinds of conversions are not narrowings.
644 return NK_Not_Narrowing;
645 }
646}
647
648/// dump - Print this standard conversion sequence to standard
649/// error. Useful for debugging overloading issues.
650LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
651 raw_ostream &OS = llvm::errs();
652 bool PrintedSomething = false;
653 if (First != ICK_Identity) {
654 OS << GetImplicitConversionName(Kind: First);
655 PrintedSomething = true;
656 }
657
658 if (Second != ICK_Identity) {
659 if (PrintedSomething) {
660 OS << " -> ";
661 }
662 OS << GetImplicitConversionName(Kind: Second);
663
664 if (CopyConstructor) {
665 OS << " (by copy constructor)";
666 } else if (DirectBinding) {
667 OS << " (direct reference binding)";
668 } else if (ReferenceBinding) {
669 OS << " (reference binding)";
670 }
671 PrintedSomething = true;
672 }
673
674 if (Third != ICK_Identity) {
675 if (PrintedSomething) {
676 OS << " -> ";
677 }
678 OS << GetImplicitConversionName(Kind: Third);
679 PrintedSomething = true;
680 }
681
682 if (!PrintedSomething) {
683 OS << "No conversions required";
684 }
685}
686
687/// dump - Print this user-defined conversion sequence to standard
688/// error. Useful for debugging overloading issues.
689void UserDefinedConversionSequence::dump() const {
690 raw_ostream &OS = llvm::errs();
691 if (Before.First || Before.Second || Before.Third) {
692 Before.dump();
693 OS << " -> ";
694 }
695 if (ConversionFunction)
696 OS << '\'' << *ConversionFunction << '\'';
697 else
698 OS << "aggregate initialization";
699 if (After.First || After.Second || After.Third) {
700 OS << " -> ";
701 After.dump();
702 }
703}
704
705/// dump - Print this implicit conversion sequence to standard
706/// error. Useful for debugging overloading issues.
707void ImplicitConversionSequence::dump() const {
708 raw_ostream &OS = llvm::errs();
709 if (hasInitializerListContainerType())
710 OS << "Worst list element conversion: ";
711 switch (ConversionKind) {
712 case StandardConversion:
713 OS << "Standard conversion: ";
714 Standard.dump();
715 break;
716 case UserDefinedConversion:
717 OS << "User-defined conversion: ";
718 UserDefined.dump();
719 break;
720 case EllipsisConversion:
721 OS << "Ellipsis conversion";
722 break;
723 case AmbiguousConversion:
724 OS << "Ambiguous conversion";
725 break;
726 case BadConversion:
727 OS << "Bad conversion";
728 break;
729 }
730
731 OS << "\n";
732}
733
734void AmbiguousConversionSequence::construct() {
735 new (&conversions()) ConversionSet();
736}
737
738void AmbiguousConversionSequence::destruct() {
739 conversions().~ConversionSet();
740}
741
742void
743AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
744 FromTypePtr = O.FromTypePtr;
745 ToTypePtr = O.ToTypePtr;
746 new (&conversions()) ConversionSet(O.conversions());
747}
748
749namespace {
750 // Structure used by DeductionFailureInfo to store
751 // template argument information.
752 struct DFIArguments {
753 TemplateArgument FirstArg;
754 TemplateArgument SecondArg;
755 };
756 // Structure used by DeductionFailureInfo to store
757 // template parameter and template argument information.
758 struct DFIParamWithArguments : DFIArguments {
759 TemplateParameter Param;
760 };
761 // Structure used by DeductionFailureInfo to store template argument
762 // information and the index of the problematic call argument.
763 struct DFIDeducedMismatchArgs : DFIArguments {
764 TemplateArgumentList *TemplateArgs;
765 unsigned CallArgIndex;
766 };
767 // Structure used by DeductionFailureInfo to store information about
768 // unsatisfied constraints.
769 struct CNSInfo {
770 TemplateArgumentList *TemplateArgs;
771 ConstraintSatisfaction Satisfaction;
772 };
773}
774
775/// Convert from Sema's representation of template deduction information
776/// to the form used in overload-candidate information.
777DeductionFailureInfo
778clang::MakeDeductionFailureInfo(ASTContext &Context,
779 TemplateDeductionResult TDK,
780 TemplateDeductionInfo &Info) {
781 DeductionFailureInfo Result;
782 Result.Result = static_cast<unsigned>(TDK);
783 Result.HasDiagnostic = false;
784 switch (TDK) {
785 case TemplateDeductionResult::Invalid:
786 case TemplateDeductionResult::InstantiationDepth:
787 case TemplateDeductionResult::TooManyArguments:
788 case TemplateDeductionResult::TooFewArguments:
789 case TemplateDeductionResult::MiscellaneousDeductionFailure:
790 case TemplateDeductionResult::CUDATargetMismatch:
791 Result.Data = nullptr;
792 break;
793
794 case TemplateDeductionResult::Incomplete:
795 Result.Data = Info.Param.getOpaqueValue();
796 break;
797 case TemplateDeductionResult::InvalidExplicitArguments:
798 Result.Data = Info.Param.getOpaqueValue();
799 if (Info.hasSFINAEDiagnostic()) {
800 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
801 SourceLocation(), PartialDiagnostic::NullDiagnostic());
802 Info.takeSFINAEDiagnostic(PD&: *Diag);
803 Result.HasDiagnostic = true;
804 }
805 break;
806
807 case TemplateDeductionResult::DeducedMismatch:
808 case TemplateDeductionResult::DeducedMismatchNested: {
809 // FIXME: Should allocate from normal heap so that we can free this later.
810 auto *Saved = new (Context) DFIDeducedMismatchArgs;
811 Saved->FirstArg = Info.FirstArg;
812 Saved->SecondArg = Info.SecondArg;
813 Saved->TemplateArgs = Info.takeSugared();
814 Saved->CallArgIndex = Info.CallArgIndex;
815 Result.Data = Saved;
816 break;
817 }
818
819 case TemplateDeductionResult::NonDeducedMismatch: {
820 // FIXME: Should allocate from normal heap so that we can free this later.
821 DFIArguments *Saved = new (Context) DFIArguments;
822 Saved->FirstArg = Info.FirstArg;
823 Saved->SecondArg = Info.SecondArg;
824 Result.Data = Saved;
825 break;
826 }
827
828 case TemplateDeductionResult::IncompletePack:
829 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
830 case TemplateDeductionResult::Inconsistent:
831 case TemplateDeductionResult::Underqualified: {
832 // FIXME: Should allocate from normal heap so that we can free this later.
833 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
834 Saved->Param = Info.Param;
835 Saved->FirstArg = Info.FirstArg;
836 Saved->SecondArg = Info.SecondArg;
837 Result.Data = Saved;
838 break;
839 }
840
841 case TemplateDeductionResult::SubstitutionFailure:
842 Result.Data = Info.takeSugared();
843 if (Info.hasSFINAEDiagnostic()) {
844 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
845 SourceLocation(), PartialDiagnostic::NullDiagnostic());
846 Info.takeSFINAEDiagnostic(PD&: *Diag);
847 Result.HasDiagnostic = true;
848 }
849 break;
850
851 case TemplateDeductionResult::ConstraintsNotSatisfied: {
852 CNSInfo *Saved = new (Context) CNSInfo;
853 Saved->TemplateArgs = Info.takeSugared();
854 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
855 Result.Data = Saved;
856 break;
857 }
858
859 case TemplateDeductionResult::Success:
860 case TemplateDeductionResult::NonDependentConversionFailure:
861 case TemplateDeductionResult::AlreadyDiagnosed:
862 llvm_unreachable("not a deduction failure");
863 }
864
865 return Result;
866}
867
868void DeductionFailureInfo::Destroy() {
869 switch (static_cast<TemplateDeductionResult>(Result)) {
870 case TemplateDeductionResult::Success:
871 case TemplateDeductionResult::Invalid:
872 case TemplateDeductionResult::InstantiationDepth:
873 case TemplateDeductionResult::Incomplete:
874 case TemplateDeductionResult::TooManyArguments:
875 case TemplateDeductionResult::TooFewArguments:
876 case TemplateDeductionResult::CUDATargetMismatch:
877 case TemplateDeductionResult::NonDependentConversionFailure:
878 break;
879
880 case TemplateDeductionResult::IncompletePack:
881 case TemplateDeductionResult::Inconsistent:
882 case TemplateDeductionResult::Underqualified:
883 case TemplateDeductionResult::DeducedMismatch:
884 case TemplateDeductionResult::DeducedMismatchNested:
885 case TemplateDeductionResult::NonDeducedMismatch:
886 // FIXME: Destroy the data?
887 Data = nullptr;
888 break;
889
890 case TemplateDeductionResult::InvalidExplicitArguments:
891 case TemplateDeductionResult::SubstitutionFailure:
892 // FIXME: Destroy the template argument list?
893 Data = nullptr;
894 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
895 Diag->~PartialDiagnosticAt();
896 HasDiagnostic = false;
897 }
898 break;
899
900 case TemplateDeductionResult::ConstraintsNotSatisfied:
901 // FIXME: Destroy the template argument list?
902 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
903 Data = nullptr;
904 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
905 Diag->~PartialDiagnosticAt();
906 HasDiagnostic = false;
907 }
908 break;
909
910 // Unhandled
911 case TemplateDeductionResult::MiscellaneousDeductionFailure:
912 case TemplateDeductionResult::AlreadyDiagnosed:
913 break;
914 }
915}
916
917PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
918 if (HasDiagnostic)
919 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
920 return nullptr;
921}
922
923TemplateParameter DeductionFailureInfo::getTemplateParameter() {
924 switch (static_cast<TemplateDeductionResult>(Result)) {
925 case TemplateDeductionResult::Success:
926 case TemplateDeductionResult::Invalid:
927 case TemplateDeductionResult::InstantiationDepth:
928 case TemplateDeductionResult::TooManyArguments:
929 case TemplateDeductionResult::TooFewArguments:
930 case TemplateDeductionResult::SubstitutionFailure:
931 case TemplateDeductionResult::DeducedMismatch:
932 case TemplateDeductionResult::DeducedMismatchNested:
933 case TemplateDeductionResult::NonDeducedMismatch:
934 case TemplateDeductionResult::CUDATargetMismatch:
935 case TemplateDeductionResult::NonDependentConversionFailure:
936 case TemplateDeductionResult::ConstraintsNotSatisfied:
937 return TemplateParameter();
938
939 case TemplateDeductionResult::Incomplete:
940 case TemplateDeductionResult::InvalidExplicitArguments:
941 return TemplateParameter::getFromOpaqueValue(VP: Data);
942
943 case TemplateDeductionResult::IncompletePack:
944 case TemplateDeductionResult::Inconsistent:
945 case TemplateDeductionResult::Underqualified:
946 return static_cast<DFIParamWithArguments*>(Data)->Param;
947
948 // Unhandled
949 case TemplateDeductionResult::MiscellaneousDeductionFailure:
950 case TemplateDeductionResult::AlreadyDiagnosed:
951 break;
952 }
953
954 return TemplateParameter();
955}
956
957TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
958 switch (static_cast<TemplateDeductionResult>(Result)) {
959 case TemplateDeductionResult::Success:
960 case TemplateDeductionResult::Invalid:
961 case TemplateDeductionResult::InstantiationDepth:
962 case TemplateDeductionResult::TooManyArguments:
963 case TemplateDeductionResult::TooFewArguments:
964 case TemplateDeductionResult::Incomplete:
965 case TemplateDeductionResult::IncompletePack:
966 case TemplateDeductionResult::InvalidExplicitArguments:
967 case TemplateDeductionResult::Inconsistent:
968 case TemplateDeductionResult::Underqualified:
969 case TemplateDeductionResult::NonDeducedMismatch:
970 case TemplateDeductionResult::CUDATargetMismatch:
971 case TemplateDeductionResult::NonDependentConversionFailure:
972 return nullptr;
973
974 case TemplateDeductionResult::DeducedMismatch:
975 case TemplateDeductionResult::DeducedMismatchNested:
976 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
977
978 case TemplateDeductionResult::SubstitutionFailure:
979 return static_cast<TemplateArgumentList*>(Data);
980
981 case TemplateDeductionResult::ConstraintsNotSatisfied:
982 return static_cast<CNSInfo*>(Data)->TemplateArgs;
983
984 // Unhandled
985 case TemplateDeductionResult::MiscellaneousDeductionFailure:
986 case TemplateDeductionResult::AlreadyDiagnosed:
987 break;
988 }
989
990 return nullptr;
991}
992
993const TemplateArgument *DeductionFailureInfo::getFirstArg() {
994 switch (static_cast<TemplateDeductionResult>(Result)) {
995 case TemplateDeductionResult::Success:
996 case TemplateDeductionResult::Invalid:
997 case TemplateDeductionResult::InstantiationDepth:
998 case TemplateDeductionResult::Incomplete:
999 case TemplateDeductionResult::TooManyArguments:
1000 case TemplateDeductionResult::TooFewArguments:
1001 case TemplateDeductionResult::InvalidExplicitArguments:
1002 case TemplateDeductionResult::SubstitutionFailure:
1003 case TemplateDeductionResult::CUDATargetMismatch:
1004 case TemplateDeductionResult::NonDependentConversionFailure:
1005 case TemplateDeductionResult::ConstraintsNotSatisfied:
1006 return nullptr;
1007
1008 case TemplateDeductionResult::IncompletePack:
1009 case TemplateDeductionResult::Inconsistent:
1010 case TemplateDeductionResult::Underqualified:
1011 case TemplateDeductionResult::DeducedMismatch:
1012 case TemplateDeductionResult::DeducedMismatchNested:
1013 case TemplateDeductionResult::NonDeducedMismatch:
1014 return &static_cast<DFIArguments*>(Data)->FirstArg;
1015
1016 // Unhandled
1017 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1018 case TemplateDeductionResult::AlreadyDiagnosed:
1019 break;
1020 }
1021
1022 return nullptr;
1023}
1024
1025const TemplateArgument *DeductionFailureInfo::getSecondArg() {
1026 switch (static_cast<TemplateDeductionResult>(Result)) {
1027 case TemplateDeductionResult::Success:
1028 case TemplateDeductionResult::Invalid:
1029 case TemplateDeductionResult::InstantiationDepth:
1030 case TemplateDeductionResult::Incomplete:
1031 case TemplateDeductionResult::IncompletePack:
1032 case TemplateDeductionResult::TooManyArguments:
1033 case TemplateDeductionResult::TooFewArguments:
1034 case TemplateDeductionResult::InvalidExplicitArguments:
1035 case TemplateDeductionResult::SubstitutionFailure:
1036 case TemplateDeductionResult::CUDATargetMismatch:
1037 case TemplateDeductionResult::NonDependentConversionFailure:
1038 case TemplateDeductionResult::ConstraintsNotSatisfied:
1039 return nullptr;
1040
1041 case TemplateDeductionResult::Inconsistent:
1042 case TemplateDeductionResult::Underqualified:
1043 case TemplateDeductionResult::DeducedMismatch:
1044 case TemplateDeductionResult::DeducedMismatchNested:
1045 case TemplateDeductionResult::NonDeducedMismatch:
1046 return &static_cast<DFIArguments*>(Data)->SecondArg;
1047
1048 // Unhandled
1049 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1050 case TemplateDeductionResult::AlreadyDiagnosed:
1051 break;
1052 }
1053
1054 return nullptr;
1055}
1056
1057UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1058 switch (static_cast<TemplateDeductionResult>(Result)) {
1059 case TemplateDeductionResult::DeducedMismatch:
1060 case TemplateDeductionResult::DeducedMismatchNested:
1061 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1062
1063 default:
1064 return std::nullopt;
1065 }
1066}
1067
1068static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1069 const FunctionDecl *Y) {
1070 if (!X || !Y)
1071 return false;
1072 if (X->getNumParams() != Y->getNumParams())
1073 return false;
1074 // FIXME: when do rewritten comparison operators
1075 // with explicit object parameters correspond?
1076 // https://cplusplus.github.io/CWG/issues/2797.html
1077 for (unsigned I = 0; I < X->getNumParams(); ++I)
1078 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1079 T2: Y->getParamDecl(i: I)->getType()))
1080 return false;
1081 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1082 auto *FTY = Y->getDescribedFunctionTemplate();
1083 if (!FTY)
1084 return false;
1085 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1086 Y: FTY->getTemplateParameters()))
1087 return false;
1088 }
1089 return true;
1090}
1091
1092static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1093 Expr *FirstOperand, FunctionDecl *EqFD) {
1094 assert(EqFD->getOverloadedOperator() ==
1095 OverloadedOperatorKind::OO_EqualEqual);
1096 // C++2a [over.match.oper]p4:
1097 // A non-template function or function template F named operator== is a
1098 // rewrite target with first operand o unless a search for the name operator!=
1099 // in the scope S from the instantiation context of the operator expression
1100 // finds a function or function template that would correspond
1101 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1102 // scope of the class type of o if F is a class member, and the namespace
1103 // scope of which F is a member otherwise. A function template specialization
1104 // named operator== is a rewrite target if its function template is a rewrite
1105 // target.
1106 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1107 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1108 if (isa<CXXMethodDecl>(Val: EqFD)) {
1109 // If F is a class member, search scope is class type of first operand.
1110 QualType RHS = FirstOperand->getType();
1111 auto *RHSRec = RHS->getAsCXXRecordDecl();
1112 if (!RHSRec)
1113 return true;
1114 LookupResult Members(S, NotEqOp, OpLoc,
1115 Sema::LookupNameKind::LookupMemberName);
1116 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1117 Members.suppressAccessDiagnostics();
1118 for (NamedDecl *Op : Members)
1119 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1120 return false;
1121 return true;
1122 }
1123 // Otherwise the search scope is the namespace scope of which F is a member.
1124 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1125 auto *NotEqFD = Op->getAsFunction();
1126 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1127 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1128 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1129 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1130 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1131 return false;
1132 }
1133 return true;
1134}
1135
1136bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1137 OverloadedOperatorKind Op) const {
1138 if (!AllowRewrittenCandidates)
1139 return false;
1140 return Op == OO_EqualEqual || Op == OO_Spaceship;
1141}
1142
1143bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1144 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1145 auto Op = FD->getOverloadedOperator();
1146 if (!allowsReversed(Op))
1147 return false;
1148 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1149 assert(OriginalArgs.size() == 2);
1150 if (!shouldAddReversedEqEq(
1151 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1152 return false;
1153 }
1154 // Don't bother adding a reversed candidate that can never be a better
1155 // match than the non-reversed version.
1156 return FD->getNumNonObjectParams() != 2 ||
1157 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1158 T2: FD->getParamDecl(i: 1)->getType()) ||
1159 FD->hasAttr<EnableIfAttr>();
1160}
1161
1162void OverloadCandidateSet::destroyCandidates() {
1163 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1164 for (auto &C : i->Conversions)
1165 C.~ImplicitConversionSequence();
1166 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1167 i->DeductionFailure.Destroy();
1168 }
1169}
1170
1171void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1172 destroyCandidates();
1173 SlabAllocator.Reset();
1174 NumInlineBytesUsed = 0;
1175 Candidates.clear();
1176 Functions.clear();
1177 Kind = CSK;
1178 FirstDeferredCandidate = nullptr;
1179 DeferredCandidatesCount = 0;
1180 HasDeferredTemplateConstructors = false;
1181 ResolutionByPerfectCandidateIsDisabled = false;
1182}
1183
1184namespace {
1185 class UnbridgedCastsSet {
1186 struct Entry {
1187 Expr **Addr;
1188 Expr *Saved;
1189 };
1190 SmallVector<Entry, 2> Entries;
1191
1192 public:
1193 void save(Sema &S, Expr *&E) {
1194 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1195 Entry entry = { .Addr: &E, .Saved: E };
1196 Entries.push_back(Elt: entry);
1197 E = S.ObjC().stripARCUnbridgedCast(e: E);
1198 }
1199
1200 void restore() {
1201 for (SmallVectorImpl<Entry>::iterator
1202 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1203 *i->Addr = i->Saved;
1204 }
1205 };
1206}
1207
1208/// checkPlaceholderForOverload - Do any interesting placeholder-like
1209/// preprocessing on the given expression.
1210///
1211/// \param unbridgedCasts a collection to which to add unbridged casts;
1212/// without this, they will be immediately diagnosed as errors
1213///
1214/// Return true on unrecoverable error.
1215static bool
1216checkPlaceholderForOverload(Sema &S, Expr *&E,
1217 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1218 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1219 // We can't handle overloaded expressions here because overload
1220 // resolution might reasonably tweak them.
1221 if (placeholder->getKind() == BuiltinType::Overload) return false;
1222
1223 // If the context potentially accepts unbridged ARC casts, strip
1224 // the unbridged cast and add it to the collection for later restoration.
1225 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1226 unbridgedCasts) {
1227 unbridgedCasts->save(S, E);
1228 return false;
1229 }
1230
1231 // Go ahead and check everything else.
1232 ExprResult result = S.CheckPlaceholderExpr(E);
1233 if (result.isInvalid())
1234 return true;
1235
1236 E = result.get();
1237 return false;
1238 }
1239
1240 // Nothing to do.
1241 return false;
1242}
1243
1244/// checkArgPlaceholdersForOverload - Check a set of call operands for
1245/// placeholders.
1246static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1247 UnbridgedCastsSet &unbridged) {
1248 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1249 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1250 return true;
1251
1252 return false;
1253}
1254
1255OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1256 const LookupResult &Old, NamedDecl *&Match,
1257 bool NewIsUsingDecl) {
1258 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1259 I != E; ++I) {
1260 NamedDecl *OldD = *I;
1261
1262 bool OldIsUsingDecl = false;
1263 if (isa<UsingShadowDecl>(Val: OldD)) {
1264 OldIsUsingDecl = true;
1265
1266 // We can always introduce two using declarations into the same
1267 // context, even if they have identical signatures.
1268 if (NewIsUsingDecl) continue;
1269
1270 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1271 }
1272
1273 // A using-declaration does not conflict with another declaration
1274 // if one of them is hidden.
1275 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1276 continue;
1277
1278 // If either declaration was introduced by a using declaration,
1279 // we'll need to use slightly different rules for matching.
1280 // Essentially, these rules are the normal rules, except that
1281 // function templates hide function templates with different
1282 // return types or template parameter lists.
1283 bool UseMemberUsingDeclRules =
1284 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1285 !New->getFriendObjectKind();
1286
1287 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1288 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1289 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1290 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1291 continue;
1292 }
1293
1294 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1295 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1296 continue;
1297
1298 Match = *I;
1299 return OverloadKind::Match;
1300 }
1301
1302 // Builtins that have custom typechecking or have a reference should
1303 // not be overloadable or redeclarable.
1304 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1305 Match = *I;
1306 return OverloadKind::NonFunction;
1307 }
1308 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1309 // We can overload with these, which can show up when doing
1310 // redeclaration checks for UsingDecls.
1311 assert(Old.getLookupKind() == LookupUsingDeclName);
1312 } else if (isa<TagDecl>(Val: OldD)) {
1313 // We can always overload with tags by hiding them.
1314 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1315 // Optimistically assume that an unresolved using decl will
1316 // overload; if it doesn't, we'll have to diagnose during
1317 // template instantiation.
1318 //
1319 // Exception: if the scope is dependent and this is not a class
1320 // member, the using declaration can only introduce an enumerator.
1321 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1322 Match = *I;
1323 return OverloadKind::NonFunction;
1324 }
1325 } else {
1326 // (C++ 13p1):
1327 // Only function declarations can be overloaded; object and type
1328 // declarations cannot be overloaded.
1329 Match = *I;
1330 return OverloadKind::NonFunction;
1331 }
1332 }
1333
1334 // C++ [temp.friend]p1:
1335 // For a friend function declaration that is not a template declaration:
1336 // -- if the name of the friend is a qualified or unqualified template-id,
1337 // [...], otherwise
1338 // -- if the name of the friend is a qualified-id and a matching
1339 // non-template function is found in the specified class or namespace,
1340 // the friend declaration refers to that function, otherwise,
1341 // -- if the name of the friend is a qualified-id and a matching function
1342 // template is found in the specified class or namespace, the friend
1343 // declaration refers to the deduced specialization of that function
1344 // template, otherwise
1345 // -- the name shall be an unqualified-id [...]
1346 // If we get here for a qualified friend declaration, we've just reached the
1347 // third bullet. If the type of the friend is dependent, skip this lookup
1348 // until instantiation.
1349 if (New->getFriendObjectKind() && New->getQualifier() &&
1350 !New->getDescribedFunctionTemplate() &&
1351 !New->getDependentSpecializationInfo() &&
1352 !New->getType()->isDependentType()) {
1353 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1354 TemplateSpecResult.addAllDecls(Other: Old);
1355 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1356 /*QualifiedFriend*/true)) {
1357 New->setInvalidDecl();
1358 return OverloadKind::Overload;
1359 }
1360
1361 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1362 return OverloadKind::Match;
1363 }
1364
1365 return OverloadKind::Overload;
1366}
1367
1368template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1369 assert(D && "function decl should not be null");
1370 if (auto *A = D->getAttr<AttrT>())
1371 return !A->isImplicit();
1372 return false;
1373}
1374
1375static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1376 FunctionDecl *Old,
1377 bool UseMemberUsingDeclRules,
1378 bool ConsiderCudaAttrs,
1379 bool UseOverrideRules = false) {
1380 // C++ [basic.start.main]p2: This function shall not be overloaded.
1381 if (New->isMain())
1382 return false;
1383
1384 // MSVCRT user defined entry points cannot be overloaded.
1385 if (New->isMSVCRTEntryPoint())
1386 return false;
1387
1388 NamedDecl *OldDecl = Old;
1389 NamedDecl *NewDecl = New;
1390 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1391 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1392
1393 // C++ [temp.fct]p2:
1394 // A function template can be overloaded with other function templates
1395 // and with normal (non-template) functions.
1396 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1397 return true;
1398
1399 // Is the function New an overload of the function Old?
1400 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1401 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1402
1403 // Compare the signatures (C++ 1.3.10) of the two functions to
1404 // determine whether they are overloads. If we find any mismatch
1405 // in the signature, they are overloads.
1406
1407 // If either of these functions is a K&R-style function (no
1408 // prototype), then we consider them to have matching signatures.
1409 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1410 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1411 return false;
1412
1413 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1414 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1415
1416 // The signature of a function includes the types of its
1417 // parameters (C++ 1.3.10), which includes the presence or absence
1418 // of the ellipsis; see C++ DR 357).
1419 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1420 return true;
1421
1422 // For member-like friends, the enclosing class is part of the signature.
1423 if ((New->isMemberLikeConstrainedFriend() ||
1424 Old->isMemberLikeConstrainedFriend()) &&
1425 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1426 return true;
1427
1428 // Compare the parameter lists.
1429 // This can only be done once we have establish that friend functions
1430 // inhabit the same context, otherwise we might tried to instantiate
1431 // references to non-instantiated entities during constraint substitution.
1432 // GH78101.
1433 if (NewTemplate) {
1434 OldDecl = OldTemplate;
1435 NewDecl = NewTemplate;
1436 // C++ [temp.over.link]p4:
1437 // The signature of a function template consists of its function
1438 // signature, its return type and its template parameter list. The names
1439 // of the template parameters are significant only for establishing the
1440 // relationship between the template parameters and the rest of the
1441 // signature.
1442 //
1443 // We check the return type and template parameter lists for function
1444 // templates first; the remaining checks follow.
1445 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1446 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1447 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1448 bool SameReturnType = SemaRef.Context.hasSameType(
1449 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1450 // FIXME(GH58571): Match template parameter list even for non-constrained
1451 // template heads. This currently ensures that the code prior to C++20 is
1452 // not newly broken.
1453 bool ConstraintsInTemplateHead =
1454 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1455 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1456 // C++ [namespace.udecl]p11:
1457 // The set of declarations named by a using-declarator that inhabits a
1458 // class C does not include member functions and member function
1459 // templates of a base class that "correspond" to (and thus would
1460 // conflict with) a declaration of a function or function template in
1461 // C.
1462 // Comparing return types is not required for the "correspond" check to
1463 // decide whether a member introduced by a shadow declaration is hidden.
1464 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1465 !SameTemplateParameterList)
1466 return true;
1467 if (!UseMemberUsingDeclRules &&
1468 (!SameTemplateParameterList || !SameReturnType))
1469 return true;
1470 }
1471
1472 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1473 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1474
1475 int OldParamsOffset = 0;
1476 int NewParamsOffset = 0;
1477
1478 // When determining if a method is an overload from a base class, act as if
1479 // the implicit object parameter are of the same type.
1480
1481 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1482 if (M->isExplicitObjectMemberFunction()) {
1483 auto ThisType = M->getFunctionObjectParameterReferenceType();
1484 if (ThisType.isConstQualified())
1485 Q.removeConst();
1486 return Q;
1487 }
1488
1489 // We do not allow overloading based off of '__restrict'.
1490 Q.removeRestrict();
1491
1492 // We may not have applied the implicit const for a constexpr member
1493 // function yet (because we haven't yet resolved whether this is a static
1494 // or non-static member function). Add it now, on the assumption that this
1495 // is a redeclaration of OldMethod.
1496 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1497 (M->isConstexpr() || M->isConsteval()) &&
1498 !isa<CXXConstructorDecl>(Val: NewMethod))
1499 Q.addConst();
1500 return Q;
1501 };
1502
1503 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1504 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1505 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1506
1507 if (OldMethod->isExplicitObjectMemberFunction()) {
1508 BS.Quals.removeVolatile();
1509 DS.Quals.removeVolatile();
1510 }
1511
1512 return BS.Quals == DS.Quals;
1513 };
1514
1515 auto CompareType = [&](QualType Base, QualType D) {
1516 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1517 auto DS = D.getNonReferenceType().getCanonicalType().split();
1518
1519 if (!AreQualifiersEqual(BS, DS))
1520 return false;
1521
1522 if (OldMethod->isImplicitObjectMemberFunction() &&
1523 OldMethod->getParent() != NewMethod->getParent()) {
1524 CanQualType ParentType =
1525 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1526 if (ParentType.getTypePtr() != BS.Ty)
1527 return false;
1528 BS.Ty = DS.Ty;
1529 }
1530
1531 // FIXME: should we ignore some type attributes here?
1532 if (BS.Ty != DS.Ty)
1533 return false;
1534
1535 if (Base->isLValueReferenceType())
1536 return D->isLValueReferenceType();
1537 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1538 };
1539
1540 // If the function is a class member, its signature includes the
1541 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1542 auto DiagnoseInconsistentRefQualifiers = [&]() {
1543 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1544 return false;
1545 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1546 return false;
1547 if (OldMethod->isExplicitObjectMemberFunction() ||
1548 NewMethod->isExplicitObjectMemberFunction())
1549 return false;
1550 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1551 NewMethod->getRefQualifier() == RQ_None)) {
1552 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1553 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1554 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1555 return true;
1556 }
1557 return false;
1558 };
1559
1560 // We look at the parameters first, as it is the common case.
1561 // However we should not emit diagnostic before checking
1562 // the overloads do not differ by constraints or other discriminant.
1563 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1564 bool HaveInconsistentQualifiers = false;
1565
1566 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1567 OldParamsOffset++;
1568 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1569 NewParamsOffset++;
1570
1571 if (OldType->getNumParams() - OldParamsOffset !=
1572 NewType->getNumParams() - NewParamsOffset ||
1573 !SemaRef.FunctionParamTypesAreEqual(
1574 Old: {OldType->param_type_begin() + OldParamsOffset,
1575 OldType->param_type_end()},
1576 New: {NewType->param_type_begin() + NewParamsOffset,
1577 NewType->param_type_end()},
1578 ArgPos: nullptr)) {
1579 return true;
1580 }
1581
1582 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1583 !NewMethod->isStatic()) {
1584 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1585 const CXXMethodDecl *New) {
1586 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1587 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1588
1589 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1590 return F->getRefQualifier() == RQ_None &&
1591 !F->isExplicitObjectMemberFunction();
1592 };
1593
1594 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1595 CompareType(OldObjectType.getNonReferenceType(),
1596 NewObjectType.getNonReferenceType()))
1597 return true;
1598 return CompareType(OldObjectType, NewObjectType);
1599 }(OldMethod, NewMethod);
1600
1601 if (!HaveCorrespondingObjectParameters) {
1602 ShouldDiagnoseInconsistentRefQualifiers = true;
1603 // CWG2554
1604 // and, if at least one is an explicit object member function, ignoring
1605 // object parameters
1606 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1607 !OldMethod->isExplicitObjectMemberFunction()))
1608 HaveInconsistentQualifiers = true;
1609 }
1610 }
1611
1612 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1613 NewMethod->isImplicitObjectMemberFunction())
1614 ShouldDiagnoseInconsistentRefQualifiers = true;
1615
1616 if (!UseOverrideRules &&
1617 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1618 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1619 OldRC = Old->getTrailingRequiresClause();
1620 if (!NewRC != !OldRC)
1621 return true;
1622 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1623 return true;
1624 if (NewRC &&
1625 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1626 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1627 return true;
1628 }
1629
1630 // Though pass_object_size is placed on parameters and takes an argument, we
1631 // consider it to be a function-level modifier for the sake of function
1632 // identity. Either the function has one or more parameters with
1633 // pass_object_size or it doesn't.
1634 if (functionHasPassObjectSizeParams(FD: New) !=
1635 functionHasPassObjectSizeParams(FD: Old))
1636 return true;
1637
1638 // enable_if attributes are an order-sensitive part of the signature.
1639 for (specific_attr_iterator<EnableIfAttr>
1640 NewI = New->specific_attr_begin<EnableIfAttr>(),
1641 NewE = New->specific_attr_end<EnableIfAttr>(),
1642 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1643 OldE = Old->specific_attr_end<EnableIfAttr>();
1644 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1645 if (NewI == NewE || OldI == OldE)
1646 return true;
1647 llvm::FoldingSetNodeID NewID, OldID;
1648 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1649 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1650 if (NewID != OldID)
1651 return true;
1652 }
1653
1654 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1655 DiagnoseInconsistentRefQualifiers()) ||
1656 HaveInconsistentQualifiers)
1657 return true;
1658
1659 // At this point, it is known that the two functions have the same signature.
1660 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1661 // Don't allow overloading of destructors. (In theory we could, but it
1662 // would be a giant change to clang.)
1663 if (!isa<CXXDestructorDecl>(Val: New)) {
1664 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1665 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1666 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1667 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1668 "Unexpected invalid target.");
1669
1670 // Allow overloading of functions with same signature and different CUDA
1671 // target attributes.
1672 if (NewTarget != OldTarget) {
1673 // Special case: non-constexpr function is allowed to override
1674 // constexpr virtual function
1675 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1676 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1677 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1678 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1679 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1680 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1681 return false;
1682 }
1683 return true;
1684 }
1685 }
1686 }
1687 }
1688
1689 // The signatures match; this is not an overload.
1690 return false;
1691}
1692
1693bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1694 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1695 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1696 ConsiderCudaAttrs);
1697}
1698
1699bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1700 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1701 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1702 /*UseMemberUsingDeclRules=*/false,
1703 /*ConsiderCudaAttrs=*/true,
1704 /*UseOverrideRules=*/true);
1705}
1706
1707/// Tries a user-defined conversion from From to ToType.
1708///
1709/// Produces an implicit conversion sequence for when a standard conversion
1710/// is not an option. See TryImplicitConversion for more information.
1711static ImplicitConversionSequence
1712TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1713 bool SuppressUserConversions,
1714 AllowedExplicit AllowExplicit,
1715 bool InOverloadResolution,
1716 bool CStyle,
1717 bool AllowObjCWritebackConversion,
1718 bool AllowObjCConversionOnExplicit) {
1719 ImplicitConversionSequence ICS;
1720
1721 if (SuppressUserConversions) {
1722 // We're not in the case above, so there is no conversion that
1723 // we can perform.
1724 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1725 return ICS;
1726 }
1727
1728 // Attempt user-defined conversion.
1729 OverloadCandidateSet Conversions(From->getExprLoc(),
1730 OverloadCandidateSet::CSK_Normal);
1731 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1732 Conversions, AllowExplicit,
1733 AllowObjCConversionOnExplicit)) {
1734 case OR_Success:
1735 case OR_Deleted:
1736 ICS.setUserDefined();
1737 // C++ [over.ics.user]p4:
1738 // A conversion of an expression of class type to the same class
1739 // type is given Exact Match rank, and a conversion of an
1740 // expression of class type to a base class of that type is
1741 // given Conversion rank, in spite of the fact that a copy
1742 // constructor (i.e., a user-defined conversion function) is
1743 // called for those cases.
1744 if (CXXConstructorDecl *Constructor
1745 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1746 QualType FromType;
1747 SourceLocation FromLoc;
1748 // C++11 [over.ics.list]p6, per DR2137:
1749 // C++17 [over.ics.list]p6:
1750 // If C is not an initializer-list constructor and the initializer list
1751 // has a single element of type cv U, where U is X or a class derived
1752 // from X, the implicit conversion sequence has Exact Match rank if U is
1753 // X, or Conversion rank if U is derived from X.
1754 bool FromListInit = false;
1755 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1756 InitList && InitList->getNumInits() == 1 &&
1757 !S.isInitListConstructor(Ctor: Constructor)) {
1758 const Expr *SingleInit = InitList->getInit(Init: 0);
1759 FromType = SingleInit->getType();
1760 FromLoc = SingleInit->getBeginLoc();
1761 FromListInit = true;
1762 } else {
1763 FromType = From->getType();
1764 FromLoc = From->getBeginLoc();
1765 }
1766 QualType FromCanon =
1767 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1768 QualType ToCanon
1769 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1770 if ((FromCanon == ToCanon ||
1771 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1772 // Turn this into a "standard" conversion sequence, so that it
1773 // gets ranked with standard conversion sequences.
1774 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1775 ICS.setStandard();
1776 ICS.Standard.setAsIdentityConversion();
1777 ICS.Standard.setFromType(FromType);
1778 ICS.Standard.setAllToTypes(ToType);
1779 ICS.Standard.FromBracedInitList = FromListInit;
1780 ICS.Standard.CopyConstructor = Constructor;
1781 ICS.Standard.FoundCopyConstructor = Found;
1782 if (ToCanon != FromCanon)
1783 ICS.Standard.Second = ICK_Derived_To_Base;
1784 }
1785 }
1786 break;
1787
1788 case OR_Ambiguous:
1789 ICS.setAmbiguous();
1790 ICS.Ambiguous.setFromType(From->getType());
1791 ICS.Ambiguous.setToType(ToType);
1792 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1793 Cand != Conversions.end(); ++Cand)
1794 if (Cand->Best)
1795 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1796 break;
1797
1798 // Fall through.
1799 case OR_No_Viable_Function:
1800 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1801 break;
1802 }
1803
1804 return ICS;
1805}
1806
1807/// TryImplicitConversion - Attempt to perform an implicit conversion
1808/// from the given expression (Expr) to the given type (ToType). This
1809/// function returns an implicit conversion sequence that can be used
1810/// to perform the initialization. Given
1811///
1812/// void f(float f);
1813/// void g(int i) { f(i); }
1814///
1815/// this routine would produce an implicit conversion sequence to
1816/// describe the initialization of f from i, which will be a standard
1817/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1818/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1819//
1820/// Note that this routine only determines how the conversion can be
1821/// performed; it does not actually perform the conversion. As such,
1822/// it will not produce any diagnostics if no conversion is available,
1823/// but will instead return an implicit conversion sequence of kind
1824/// "BadConversion".
1825///
1826/// If @p SuppressUserConversions, then user-defined conversions are
1827/// not permitted.
1828/// If @p AllowExplicit, then explicit user-defined conversions are
1829/// permitted.
1830///
1831/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1832/// writeback conversion, which allows __autoreleasing id* parameters to
1833/// be initialized with __strong id* or __weak id* arguments.
1834static ImplicitConversionSequence
1835TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1836 bool SuppressUserConversions,
1837 AllowedExplicit AllowExplicit,
1838 bool InOverloadResolution,
1839 bool CStyle,
1840 bool AllowObjCWritebackConversion,
1841 bool AllowObjCConversionOnExplicit) {
1842 ImplicitConversionSequence ICS;
1843 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1844 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1845 ICS.setStandard();
1846 return ICS;
1847 }
1848
1849 if (!S.getLangOpts().CPlusPlus) {
1850 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1851 return ICS;
1852 }
1853
1854 // C++ [over.ics.user]p4:
1855 // A conversion of an expression of class type to the same class
1856 // type is given Exact Match rank, and a conversion of an
1857 // expression of class type to a base class of that type is
1858 // given Conversion rank, in spite of the fact that a copy/move
1859 // constructor (i.e., a user-defined conversion function) is
1860 // called for those cases.
1861 QualType FromType = From->getType();
1862 if (ToType->isRecordType() &&
1863 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1864 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1865 ICS.setStandard();
1866 ICS.Standard.setAsIdentityConversion();
1867 ICS.Standard.setFromType(FromType);
1868 ICS.Standard.setAllToTypes(ToType);
1869
1870 // We don't actually check at this point whether there is a valid
1871 // copy/move constructor, since overloading just assumes that it
1872 // exists. When we actually perform initialization, we'll find the
1873 // appropriate constructor to copy the returned object, if needed.
1874 ICS.Standard.CopyConstructor = nullptr;
1875
1876 // In HLSL, a conversion of an expression of class type to the same class
1877 // type needs implicit LvaluetoRvalue conversion.
1878 if (S.getLangOpts().HLSL)
1879 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
1880
1881 // Determine whether this is considered a derived-to-base conversion.
1882 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1883 ICS.Standard.Second = ICK_Derived_To_Base;
1884
1885 return ICS;
1886 }
1887
1888 if (S.getLangOpts().HLSL) {
1889 // Handle conversion of the HLSL resource types.
1890 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1891 if (FromTy->isHLSLAttributedResourceType()) {
1892 // Attributed resource types can convert to other attributed
1893 // resource types with the same attributes and contained types,
1894 // or to __hlsl_resource_t without any attributes.
1895 bool CanConvert = false;
1896 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1897 if (ToTy->isHLSLAttributedResourceType()) {
1898 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1899 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1900 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1901 T2: FromResType->getWrappedType()) &&
1902 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1903 T2: FromResType->getContainedType()) &&
1904 ToResType->getAttrs() == FromResType->getAttrs())
1905 CanConvert = true;
1906 } else if (ToTy->isHLSLResourceType()) {
1907 CanConvert = true;
1908 }
1909 if (CanConvert) {
1910 ICS.setStandard();
1911 ICS.Standard.setAsIdentityConversion();
1912 ICS.Standard.setFromType(FromType);
1913 ICS.Standard.setAllToTypes(ToType);
1914 return ICS;
1915 }
1916 }
1917 }
1918
1919 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1920 AllowExplicit, InOverloadResolution, CStyle,
1921 AllowObjCWritebackConversion,
1922 AllowObjCConversionOnExplicit);
1923}
1924
1925ImplicitConversionSequence
1926Sema::TryImplicitConversion(Expr *From, QualType ToType,
1927 bool SuppressUserConversions,
1928 AllowedExplicit AllowExplicit,
1929 bool InOverloadResolution,
1930 bool CStyle,
1931 bool AllowObjCWritebackConversion) {
1932 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1933 AllowExplicit, InOverloadResolution, CStyle,
1934 AllowObjCWritebackConversion,
1935 /*AllowObjCConversionOnExplicit=*/false);
1936}
1937
1938ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1939 AssignmentAction Action,
1940 bool AllowExplicit) {
1941 if (checkPlaceholderForOverload(S&: *this, E&: From))
1942 return ExprError();
1943
1944 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1945 bool AllowObjCWritebackConversion =
1946 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1947 Action == AssignmentAction::Sending);
1948 if (getLangOpts().ObjC)
1949 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1950 SrcType: From->getType(), SrcExpr&: From);
1951 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1952 S&: *this, From, ToType,
1953 /*SuppressUserConversions=*/false,
1954 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1955 /*InOverloadResolution=*/false,
1956 /*CStyle=*/false, AllowObjCWritebackConversion,
1957 /*AllowObjCConversionOnExplicit=*/false);
1958 return PerformImplicitConversion(From, ToType, ICS, Action);
1959}
1960
1961bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1962 QualType &ResultTy) const {
1963 bool Changed = IsFunctionConversion(FromType, ToType);
1964 if (Changed)
1965 ResultTy = ToType;
1966 return Changed;
1967}
1968
1969bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1970 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1971 return false;
1972
1973 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1974 // or F(t noexcept) -> F(t)
1975 // where F adds one of the following at most once:
1976 // - a pointer
1977 // - a member pointer
1978 // - a block pointer
1979 // Changes here need matching changes in FindCompositePointerType.
1980 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1981 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1982 Type::TypeClass TyClass = CanTo->getTypeClass();
1983 if (TyClass != CanFrom->getTypeClass()) return false;
1984 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1985 if (TyClass == Type::Pointer) {
1986 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1987 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1988 } else if (TyClass == Type::BlockPointer) {
1989 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1990 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1991 } else if (TyClass == Type::MemberPointer) {
1992 auto ToMPT = CanTo.castAs<MemberPointerType>();
1993 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1994 // A function pointer conversion cannot change the class of the function.
1995 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1996 D2: FromMPT->getMostRecentCXXRecordDecl()))
1997 return false;
1998 CanTo = ToMPT->getPointeeType();
1999 CanFrom = FromMPT->getPointeeType();
2000 } else {
2001 return false;
2002 }
2003
2004 TyClass = CanTo->getTypeClass();
2005 if (TyClass != CanFrom->getTypeClass()) return false;
2006 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
2007 return false;
2008 }
2009
2010 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
2011 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
2012
2013 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
2014 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
2015
2016 bool Changed = false;
2017
2018 // Drop 'noreturn' if not present in target type.
2019 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
2020 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
2021 Changed = true;
2022 }
2023
2024 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
2025 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
2026
2027 if (FromFPT && ToFPT) {
2028 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2029 QualType NewTy = Context.getFunctionType(
2030 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
2031 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2032 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
2033 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
2034 FromFn = FromFPT;
2035 Changed = true;
2036 }
2037 }
2038
2039 // Drop 'noexcept' if not present in target type.
2040 if (FromFPT && ToFPT) {
2041 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2042 FromFn = cast<FunctionType>(
2043 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
2044 ESI: EST_None)
2045 .getTypePtr());
2046 Changed = true;
2047 }
2048
2049 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2050 // only if the ExtParameterInfo lists of the two function prototypes can be
2051 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2052 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2053 bool CanUseToFPT, CanUseFromFPT;
2054 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2055 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2056 CanUseToFPT && !CanUseFromFPT) {
2057 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2058 ExtInfo.ExtParameterInfos =
2059 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2060 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2061 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2062 FromFn = QT->getAs<FunctionType>();
2063 Changed = true;
2064 }
2065
2066 if (Context.hasAnyFunctionEffects()) {
2067 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2068
2069 // Transparently add/drop effects; here we are concerned with
2070 // language rules/canonicalization. Adding/dropping effects is a warning.
2071 const auto FromFX = FromFPT->getFunctionEffects();
2072 const auto ToFX = ToFPT->getFunctionEffects();
2073 if (FromFX != ToFX) {
2074 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2075 ExtInfo.FunctionEffects = ToFX;
2076 QualType QT = Context.getFunctionType(
2077 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2078 FromFn = QT->getAs<FunctionType>();
2079 Changed = true;
2080 }
2081 }
2082 }
2083
2084 if (!Changed)
2085 return false;
2086
2087 assert(QualType(FromFn, 0).isCanonical());
2088 if (QualType(FromFn, 0) != CanTo) return false;
2089
2090 return true;
2091}
2092
2093/// Determine whether the conversion from FromType to ToType is a valid
2094/// floating point conversion.
2095///
2096static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2097 QualType ToType) {
2098 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2099 return false;
2100 // FIXME: disable conversions between long double, __ibm128 and __float128
2101 // if their representation is different until there is back end support
2102 // We of course allow this conversion if long double is really double.
2103
2104 // Conversions between bfloat16 and float16 are currently not supported.
2105 if ((FromType->isBFloat16Type() &&
2106 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2107 (ToType->isBFloat16Type() &&
2108 (FromType->isFloat16Type() || FromType->isHalfType())))
2109 return false;
2110
2111 // Conversions between IEEE-quad and IBM-extended semantics are not
2112 // permitted.
2113 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2114 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2115 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2116 &ToSem == &llvm::APFloat::IEEEquad()) ||
2117 (&FromSem == &llvm::APFloat::IEEEquad() &&
2118 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2119 return false;
2120 return true;
2121}
2122
2123static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2124 QualType ToType,
2125 ImplicitConversionKind &ICK,
2126 Expr *From) {
2127 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2128 return true;
2129
2130 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2131 ICK = ICK_Floating_Promotion;
2132 return true;
2133 }
2134
2135 if (IsFloatingPointConversion(S, FromType, ToType)) {
2136 ICK = ICK_Floating_Conversion;
2137 return true;
2138 }
2139
2140 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2141 ICK = ICK_Boolean_Conversion;
2142 return true;
2143 }
2144
2145 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2146 (FromType->isIntegralOrUnscopedEnumerationType() &&
2147 ToType->isRealFloatingType())) {
2148 ICK = ICK_Floating_Integral;
2149 return true;
2150 }
2151
2152 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2153 ICK = ICK_Integral_Promotion;
2154 return true;
2155 }
2156
2157 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2158 ToType->isIntegralType(Ctx: S.Context)) {
2159 ICK = ICK_Integral_Conversion;
2160 return true;
2161 }
2162
2163 return false;
2164}
2165
2166/// Determine whether the conversion from FromType to ToType is a valid
2167/// matrix conversion.
2168///
2169/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2170/// conversion.
2171static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2172 ImplicitConversionKind &ICK,
2173 ImplicitConversionKind &ElConv, Expr *From,
2174 bool InOverloadResolution, bool CStyle) {
2175 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2176 if (!S.getLangOpts().HLSL)
2177 return false;
2178
2179 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2180 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2181
2182 // If both arguments are matrix, handle possible matrix truncation and
2183 // element conversion.
2184 if (ToMatrixType && FromMatrixType) {
2185 unsigned FromCols = FromMatrixType->getNumColumns();
2186 unsigned ToCols = ToMatrixType->getNumColumns();
2187 if (FromCols < ToCols)
2188 return false;
2189
2190 unsigned FromRows = FromMatrixType->getNumRows();
2191 unsigned ToRows = ToMatrixType->getNumRows();
2192 if (FromRows < ToRows)
2193 return false;
2194
2195 if (FromRows == ToRows && FromCols == ToCols)
2196 ElConv = ICK_Identity;
2197 else
2198 ElConv = ICK_HLSL_Matrix_Truncation;
2199
2200 QualType FromElTy = FromMatrixType->getElementType();
2201 QualType ToElTy = ToMatrixType->getElementType();
2202 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2203 return true;
2204 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2205 }
2206
2207 // Matrix splat from any arithmetic type to a matrix.
2208 if (ToMatrixType && FromType->isArithmeticType()) {
2209 ElConv = ICK_HLSL_Matrix_Splat;
2210 QualType ToElTy = ToMatrixType->getElementType();
2211 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2212 }
2213 if (FromMatrixType && !ToMatrixType) {
2214 ElConv = ICK_HLSL_Matrix_Truncation;
2215 QualType FromElTy = FromMatrixType->getElementType();
2216 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2217 return true;
2218 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2219 }
2220
2221 return false;
2222}
2223
2224/// Determine whether the conversion from FromType to ToType is a valid
2225/// vector conversion.
2226///
2227/// \param ICK Will be set to the vector conversion kind, if this is a vector
2228/// conversion.
2229static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2230 ImplicitConversionKind &ICK,
2231 ImplicitConversionKind &ElConv, Expr *From,
2232 bool InOverloadResolution, bool CStyle) {
2233 // We need at least one of these types to be a vector type to have a vector
2234 // conversion.
2235 if (!ToType->isVectorType() && !FromType->isVectorType())
2236 return false;
2237
2238 // Identical types require no conversions.
2239 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2240 return false;
2241
2242 // HLSL allows implicit truncation of vector types.
2243 if (S.getLangOpts().HLSL) {
2244 auto *ToExtType = ToType->getAs<ExtVectorType>();
2245 auto *FromExtType = FromType->getAs<ExtVectorType>();
2246
2247 // If both arguments are vectors, handle possible vector truncation and
2248 // element conversion.
2249 if (ToExtType && FromExtType) {
2250 unsigned FromElts = FromExtType->getNumElements();
2251 unsigned ToElts = ToExtType->getNumElements();
2252 if (FromElts < ToElts)
2253 return false;
2254 if (FromElts == ToElts)
2255 ElConv = ICK_Identity;
2256 else
2257 ElConv = ICK_HLSL_Vector_Truncation;
2258
2259 QualType FromElTy = FromExtType->getElementType();
2260 QualType ToElTy = ToExtType->getElementType();
2261 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2262 return true;
2263 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2264 }
2265 if (FromExtType && !ToExtType) {
2266 ElConv = ICK_HLSL_Vector_Truncation;
2267 QualType FromElTy = FromExtType->getElementType();
2268 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2269 return true;
2270 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2271 }
2272 // Fallthrough for the case where ToType is a vector and FromType is not.
2273 }
2274
2275 // There are no conversions between extended vector types, only identity.
2276 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2277 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2278 // Implicit conversions require the same number of elements.
2279 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2280 return false;
2281
2282 // Permit implicit conversions from integral values to boolean vectors.
2283 if (ToType->isExtVectorBoolType() &&
2284 FromExtType->getElementType()->isIntegerType()) {
2285 ICK = ICK_Boolean_Conversion;
2286 return true;
2287 }
2288 // There are no other conversions between extended vector types.
2289 return false;
2290 }
2291
2292 // Vector splat from any arithmetic type to a vector.
2293 if (FromType->isArithmeticType()) {
2294 if (S.getLangOpts().HLSL) {
2295 ElConv = ICK_HLSL_Vector_Splat;
2296 QualType ToElTy = ToExtType->getElementType();
2297 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2298 From);
2299 }
2300 ICK = ICK_Vector_Splat;
2301 return true;
2302 }
2303 }
2304
2305 if (ToType->isSVESizelessBuiltinType() ||
2306 FromType->isSVESizelessBuiltinType())
2307 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2308 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2309 ICK = ICK_SVE_Vector_Conversion;
2310 return true;
2311 }
2312
2313 if (ToType->isRVVSizelessBuiltinType() ||
2314 FromType->isRVVSizelessBuiltinType())
2315 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2316 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2317 ICK = ICK_RVV_Vector_Conversion;
2318 return true;
2319 }
2320
2321 // We can perform the conversion between vector types in the following cases:
2322 // 1)vector types are equivalent AltiVec and GCC vector types
2323 // 2)lax vector conversions are permitted and the vector types are of the
2324 // same size
2325 // 3)the destination type does not have the ARM MVE strict-polymorphism
2326 // attribute, which inhibits lax vector conversion for overload resolution
2327 // only
2328 if (ToType->isVectorType() && FromType->isVectorType()) {
2329 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2330 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2331 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2332 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2333 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2334 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2335 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2336 !InOverloadResolution && !CStyle) {
2337 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2338 << FromType << ToType;
2339 }
2340 ICK = ICK_Vector_Conversion;
2341 return true;
2342 }
2343 }
2344
2345 return false;
2346}
2347
2348static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2349 bool InOverloadResolution,
2350 StandardConversionSequence &SCS,
2351 bool CStyle);
2352
2353static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2354 QualType ToType,
2355 bool InOverloadResolution,
2356 StandardConversionSequence &SCS,
2357 bool CStyle);
2358
2359/// IsStandardConversion - Determines whether there is a standard
2360/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2361/// expression From to the type ToType. Standard conversion sequences
2362/// only consider non-class types; for conversions that involve class
2363/// types, use TryImplicitConversion. If a conversion exists, SCS will
2364/// contain the standard conversion sequence required to perform this
2365/// conversion and this routine will return true. Otherwise, this
2366/// routine will return false and the value of SCS is unspecified.
2367static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2368 bool InOverloadResolution,
2369 StandardConversionSequence &SCS,
2370 bool CStyle,
2371 bool AllowObjCWritebackConversion) {
2372 QualType FromType = From->getType();
2373
2374 // Standard conversions (C++ [conv])
2375 SCS.setAsIdentityConversion();
2376 SCS.IncompatibleObjC = false;
2377 SCS.setFromType(FromType);
2378 SCS.CopyConstructor = nullptr;
2379
2380 // There are no standard conversions for class types in C++, so
2381 // abort early. When overloading in C, however, we do permit them.
2382 if (S.getLangOpts().CPlusPlus &&
2383 (FromType->isRecordType() || ToType->isRecordType()))
2384 return false;
2385
2386 // The first conversion can be an lvalue-to-rvalue conversion,
2387 // array-to-pointer conversion, or function-to-pointer conversion
2388 // (C++ 4p1).
2389
2390 if (FromType == S.Context.OverloadTy) {
2391 DeclAccessPair AccessPair;
2392 if (FunctionDecl *Fn
2393 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2394 Found&: AccessPair)) {
2395 // We were able to resolve the address of the overloaded function,
2396 // so we can convert to the type of that function.
2397 FromType = Fn->getType();
2398 SCS.setFromType(FromType);
2399
2400 // we can sometimes resolve &foo<int> regardless of ToType, so check
2401 // if the type matches (identity) or we are converting to bool
2402 if (!S.Context.hasSameUnqualifiedType(
2403 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2404 // if the function type matches except for [[noreturn]], it's ok
2405 if (!S.IsFunctionConversion(FromType,
2406 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2407 // otherwise, only a boolean conversion is standard
2408 if (!ToType->isBooleanType())
2409 return false;
2410 }
2411
2412 // Check if the "from" expression is taking the address of an overloaded
2413 // function and recompute the FromType accordingly. Take advantage of the
2414 // fact that non-static member functions *must* have such an address-of
2415 // expression.
2416 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2417 if (Method && !Method->isStatic() &&
2418 !Method->isExplicitObjectMemberFunction()) {
2419 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2420 "Non-unary operator on non-static member address");
2421 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2422 == UO_AddrOf &&
2423 "Non-address-of operator on non-static member address");
2424 FromType = S.Context.getMemberPointerType(
2425 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2426 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2427 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2428 UO_AddrOf &&
2429 "Non-address-of operator for overloaded function expression");
2430 FromType = S.Context.getPointerType(T: FromType);
2431 }
2432 } else {
2433 return false;
2434 }
2435 }
2436
2437 bool argIsLValue = From->isGLValue();
2438 // To handle conversion from ArrayParameterType to ConstantArrayType
2439 // this block must be above the one below because Array parameters
2440 // do not decay and when handling HLSLOutArgExprs and
2441 // the From expression is an LValue.
2442 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2443 ToType->isConstantArrayType()) {
2444 // HLSL constant array parameters do not decay, so if the argument is a
2445 // constant array and the parameter is an ArrayParameterType we have special
2446 // handling here.
2447 if (ToType->isArrayParameterType()) {
2448 FromType = S.Context.getArrayParameterType(Ty: FromType);
2449 } else if (FromType->isArrayParameterType()) {
2450 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2451 FromType = APT->getConstantArrayType(Ctx: S.Context);
2452 }
2453
2454 SCS.First = ICK_HLSL_Array_RValue;
2455
2456 // Don't consider qualifiers, which include things like address spaces
2457 if (FromType.getCanonicalType().getUnqualifiedType() !=
2458 ToType.getCanonicalType().getUnqualifiedType())
2459 return false;
2460
2461 SCS.setAllToTypes(ToType);
2462 return true;
2463 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2464 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2465 // Lvalue-to-rvalue conversion (C++11 4.1):
2466 // A glvalue (3.10) of a non-function, non-array type T can
2467 // be converted to a prvalue.
2468
2469 SCS.First = ICK_Lvalue_To_Rvalue;
2470
2471 // C11 6.3.2.1p2:
2472 // ... if the lvalue has atomic type, the value has the non-atomic version
2473 // of the type of the lvalue ...
2474 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2475 FromType = Atomic->getValueType();
2476
2477 // If T is a non-class type, the type of the rvalue is the
2478 // cv-unqualified version of T. Otherwise, the type of the rvalue
2479 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2480 // just strip the qualifiers because they don't matter.
2481 FromType = FromType.getUnqualifiedType();
2482 } else if (FromType->isArrayType()) {
2483 // Array-to-pointer conversion (C++ 4.2)
2484 SCS.First = ICK_Array_To_Pointer;
2485
2486 // An lvalue or rvalue of type "array of N T" or "array of unknown
2487 // bound of T" can be converted to an rvalue of type "pointer to
2488 // T" (C++ 4.2p1).
2489 FromType = S.Context.getArrayDecayedType(T: FromType);
2490
2491 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2492 // This conversion is deprecated in C++03 (D.4)
2493 SCS.DeprecatedStringLiteralToCharPtr = true;
2494
2495 // For the purpose of ranking in overload resolution
2496 // (13.3.3.1.1), this conversion is considered an
2497 // array-to-pointer conversion followed by a qualification
2498 // conversion (4.4). (C++ 4.2p2)
2499 SCS.Second = ICK_Identity;
2500 SCS.Third = ICK_Qualification;
2501 SCS.QualificationIncludesObjCLifetime = false;
2502 SCS.setAllToTypes(FromType);
2503 return true;
2504 }
2505 } else if (FromType->isFunctionType() && argIsLValue) {
2506 // Function-to-pointer conversion (C++ 4.3).
2507 SCS.First = ICK_Function_To_Pointer;
2508
2509 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2510 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2511 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2512 return false;
2513
2514 // An lvalue of function type T can be converted to an rvalue of
2515 // type "pointer to T." The result is a pointer to the
2516 // function. (C++ 4.3p1).
2517 FromType = S.Context.getPointerType(T: FromType);
2518 } else {
2519 // We don't require any conversions for the first step.
2520 SCS.First = ICK_Identity;
2521 }
2522 SCS.setToType(Idx: 0, T: FromType);
2523
2524 // The second conversion can be an integral promotion, floating
2525 // point promotion, integral conversion, floating point conversion,
2526 // floating-integral conversion, pointer conversion,
2527 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2528 // For overloading in C, this can also be a "compatible-type"
2529 // conversion.
2530 bool IncompatibleObjC = false;
2531 ImplicitConversionKind SecondICK = ICK_Identity;
2532 ImplicitConversionKind DimensionICK = ICK_Identity;
2533 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2534 // The unqualified versions of the types are the same: there's no
2535 // conversion to do.
2536 SCS.Second = ICK_Identity;
2537 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2538 // Integral promotion (C++ 4.5).
2539 SCS.Second = ICK_Integral_Promotion;
2540 FromType = ToType.getUnqualifiedType();
2541 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2542 // Floating point promotion (C++ 4.6).
2543 SCS.Second = ICK_Floating_Promotion;
2544 FromType = ToType.getUnqualifiedType();
2545 } else if (S.IsComplexPromotion(FromType, ToType)) {
2546 // Complex promotion (Clang extension)
2547 SCS.Second = ICK_Complex_Promotion;
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2550 // OverflowBehaviorType promotions
2551 SCS.Second = ICK_Integral_Promotion;
2552 FromType = ToType.getUnqualifiedType();
2553 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2554 // OverflowBehaviorType conversions
2555 SCS.Second = ICK_Integral_Conversion;
2556 FromType = ToType.getUnqualifiedType();
2557 } else if (ToType->isBooleanType() &&
2558 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2559 FromType->isBlockPointerType() ||
2560 FromType->isMemberPointerType())) {
2561 // Boolean conversions (C++ 4.12).
2562 SCS.Second = ICK_Boolean_Conversion;
2563 FromType = S.Context.BoolTy;
2564 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2565 ToType->isIntegralType(Ctx: S.Context)) {
2566 // Integral conversions (C++ 4.7).
2567 SCS.Second = ICK_Integral_Conversion;
2568 FromType = ToType.getUnqualifiedType();
2569 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2570 // Complex conversions (C99 6.3.1.6)
2571 SCS.Second = ICK_Complex_Conversion;
2572 FromType = ToType.getUnqualifiedType();
2573 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2574 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2575 // Complex-real conversions (C99 6.3.1.7)
2576 SCS.Second = ICK_Complex_Real;
2577 FromType = ToType.getUnqualifiedType();
2578 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2579 // Floating point conversions (C++ 4.8).
2580 SCS.Second = ICK_Floating_Conversion;
2581 FromType = ToType.getUnqualifiedType();
2582 } else if ((FromType->isRealFloatingType() &&
2583 ToType->isIntegralType(Ctx: S.Context)) ||
2584 (FromType->isIntegralOrUnscopedEnumerationType() &&
2585 ToType->isRealFloatingType())) {
2586
2587 // Floating-integral conversions (C++ 4.9).
2588 SCS.Second = ICK_Floating_Integral;
2589 FromType = ToType.getUnqualifiedType();
2590 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2591 SCS.Second = ICK_Block_Pointer_Conversion;
2592 } else if (AllowObjCWritebackConversion &&
2593 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2594 SCS.Second = ICK_Writeback_Conversion;
2595 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2596 ConvertedType&: FromType, IncompatibleObjC)) {
2597 // Pointer conversions (C++ 4.10).
2598 SCS.Second = ICK_Pointer_Conversion;
2599 SCS.IncompatibleObjC = IncompatibleObjC;
2600 FromType = FromType.getUnqualifiedType();
2601 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2602 InOverloadResolution, ConvertedType&: FromType)) {
2603 // Pointer to member conversions (4.11).
2604 SCS.Second = ICK_Pointer_Member;
2605 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2606 From, InOverloadResolution, CStyle)) {
2607 SCS.Second = SecondICK;
2608 SCS.Dimension = DimensionICK;
2609 FromType = ToType.getUnqualifiedType();
2610 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2611 From, InOverloadResolution, CStyle)) {
2612 SCS.Second = SecondICK;
2613 SCS.Dimension = DimensionICK;
2614 FromType = ToType.getUnqualifiedType();
2615 } else if (!S.getLangOpts().CPlusPlus &&
2616 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2617 // Compatible conversions (Clang extension for C function overloading)
2618 SCS.Second = ICK_Compatible_Conversion;
2619 FromType = ToType.getUnqualifiedType();
2620 } else if (IsTransparentUnionStandardConversion(
2621 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2622 SCS.Second = ICK_TransparentUnionConversion;
2623 FromType = ToType;
2624 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2625 CStyle)) {
2626 // tryAtomicConversion has updated the standard conversion sequence
2627 // appropriately.
2628 return true;
2629 } else if (tryOverflowBehaviorTypeConversion(
2630 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2631 return true;
2632 } else if (ToType->isEventT() &&
2633 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2634 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2635 SCS.Second = ICK_Zero_Event_Conversion;
2636 FromType = ToType;
2637 } else if (ToType->isQueueT() &&
2638 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2639 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2640 SCS.Second = ICK_Zero_Queue_Conversion;
2641 FromType = ToType;
2642 } else if (ToType->isSamplerT() &&
2643 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2644 SCS.Second = ICK_Compatible_Conversion;
2645 FromType = ToType;
2646 } else if ((ToType->isFixedPointType() &&
2647 FromType->isConvertibleToFixedPointType()) ||
2648 (FromType->isFixedPointType() &&
2649 ToType->isConvertibleToFixedPointType())) {
2650 SCS.Second = ICK_Fixed_Point_Conversion;
2651 FromType = ToType;
2652 } else {
2653 // No second conversion required.
2654 SCS.Second = ICK_Identity;
2655 }
2656 SCS.setToType(Idx: 1, T: FromType);
2657
2658 // The third conversion can be a function pointer conversion or a
2659 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2660 bool ObjCLifetimeConversion;
2661 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2662 // Function pointer conversions (removing 'noexcept') including removal of
2663 // 'noreturn' (Clang extension).
2664 SCS.Third = ICK_Function_Conversion;
2665 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2666 ObjCLifetimeConversion)) {
2667 SCS.Third = ICK_Qualification;
2668 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2669 FromType = ToType;
2670 } else {
2671 // No conversion required
2672 SCS.Third = ICK_Identity;
2673 }
2674
2675 // C++ [over.best.ics]p6:
2676 // [...] Any difference in top-level cv-qualification is
2677 // subsumed by the initialization itself and does not constitute
2678 // a conversion. [...]
2679 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2680 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2681 if (CanonFrom.getLocalUnqualifiedType()
2682 == CanonTo.getLocalUnqualifiedType() &&
2683 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2684 FromType = ToType;
2685 CanonFrom = CanonTo;
2686 }
2687
2688 SCS.setToType(Idx: 2, T: FromType);
2689
2690 if (CanonFrom == CanonTo)
2691 return true;
2692
2693 // If we have not converted the argument type to the parameter type,
2694 // this is a bad conversion sequence, unless we're resolving an overload in C.
2695 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2696 return false;
2697
2698 ExprResult ER = ExprResult{From};
2699 AssignConvertType Conv =
2700 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2701 /*Diagnose=*/false,
2702 /*DiagnoseCFAudited=*/false,
2703 /*ConvertRHS=*/false);
2704 ImplicitConversionKind SecondConv;
2705 switch (Conv) {
2706 case AssignConvertType::Compatible:
2707 case AssignConvertType::
2708 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2709 SecondConv = ICK_C_Only_Conversion;
2710 break;
2711 // For our purposes, discarding qualifiers is just as bad as using an
2712 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2713 // qualifiers, as well.
2714 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2715 case AssignConvertType::IncompatiblePointer:
2716 case AssignConvertType::IncompatiblePointerSign:
2717 SecondConv = ICK_Incompatible_Pointer_Conversion;
2718 break;
2719 default:
2720 return false;
2721 }
2722
2723 // First can only be an lvalue conversion, so we pretend that this was the
2724 // second conversion. First should already be valid from earlier in the
2725 // function.
2726 SCS.Second = SecondConv;
2727 SCS.setToType(Idx: 1, T: ToType);
2728
2729 // Third is Identity, because Second should rank us worse than any other
2730 // conversion. This could also be ICK_Qualification, but it's simpler to just
2731 // lump everything in with the second conversion, and we don't gain anything
2732 // from making this ICK_Qualification.
2733 SCS.Third = ICK_Identity;
2734 SCS.setToType(Idx: 2, T: ToType);
2735 return true;
2736}
2737
2738static bool
2739IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2740 QualType &ToType,
2741 bool InOverloadResolution,
2742 StandardConversionSequence &SCS,
2743 bool CStyle) {
2744
2745 const RecordType *UT = ToType->getAsUnionType();
2746 if (!UT)
2747 return false;
2748 // The field to initialize within the transparent union.
2749 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2750 if (!UD->hasAttr<TransparentUnionAttr>())
2751 return false;
2752 // It's compatible if the expression matches any of the fields.
2753 for (const auto *it : UD->fields()) {
2754 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2755 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2756 ToType = it->getType();
2757 return true;
2758 }
2759 }
2760 return false;
2761}
2762
2763bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2764 const BuiltinType *To = ToType->getAs<BuiltinType>();
2765 // All integers are built-in.
2766 if (!To) {
2767 return false;
2768 }
2769
2770 // An rvalue of type char, signed char, unsigned char, short int, or
2771 // unsigned short int can be converted to an rvalue of type int if
2772 // int can represent all the values of the source type; otherwise,
2773 // the source rvalue can be converted to an rvalue of type unsigned
2774 // int (C++ 4.5p1).
2775 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2776 !FromType->isEnumeralType()) {
2777 if ( // We can promote any signed, promotable integer type to an int
2778 (FromType->isSignedIntegerType() ||
2779 // We can promote any unsigned integer type whose size is
2780 // less than int to an int.
2781 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2782 return To->getKind() == BuiltinType::Int;
2783 }
2784
2785 return To->getKind() == BuiltinType::UInt;
2786 }
2787
2788 // C++11 [conv.prom]p3:
2789 // A prvalue of an unscoped enumeration type whose underlying type is not
2790 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2791 // following types that can represent all the values of the enumeration
2792 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2793 // unsigned int, long int, unsigned long int, long long int, or unsigned
2794 // long long int. If none of the types in that list can represent all the
2795 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2796 // type can be converted to an rvalue a prvalue of the extended integer type
2797 // with lowest integer conversion rank (4.13) greater than the rank of long
2798 // long in which all the values of the enumeration can be represented. If
2799 // there are two such extended types, the signed one is chosen.
2800 // C++11 [conv.prom]p4:
2801 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2802 // can be converted to a prvalue of its underlying type. Moreover, if
2803 // integral promotion can be applied to its underlying type, a prvalue of an
2804 // unscoped enumeration type whose underlying type is fixed can also be
2805 // converted to a prvalue of the promoted underlying type.
2806 if (const auto *FromED = FromType->getAsEnumDecl()) {
2807 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2808 // provided for a scoped enumeration.
2809 if (FromED->isScoped())
2810 return false;
2811
2812 // We can perform an integral promotion to the underlying type of the enum,
2813 // even if that's not the promoted type. Note that the check for promoting
2814 // the underlying type is based on the type alone, and does not consider
2815 // the bitfield-ness of the actual source expression.
2816 if (FromED->isFixed()) {
2817 QualType Underlying = FromED->getIntegerType();
2818 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2819 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2820 }
2821
2822 // We have already pre-calculated the promotion type, so this is trivial.
2823 if (ToType->isIntegerType() &&
2824 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2825 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2826
2827 // C++ [conv.prom]p5:
2828 // If the bit-field has an enumerated type, it is treated as any other
2829 // value of that type for promotion purposes.
2830 //
2831 // ... so do not fall through into the bit-field checks below in C++.
2832 if (getLangOpts().CPlusPlus)
2833 return false;
2834 }
2835
2836 // C++0x [conv.prom]p2:
2837 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2838 // to an rvalue a prvalue of the first of the following types that can
2839 // represent all the values of its underlying type: int, unsigned int,
2840 // long int, unsigned long int, long long int, or unsigned long long int.
2841 // If none of the types in that list can represent all the values of its
2842 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2843 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2844 // type.
2845 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2846 ToType->isIntegerType()) {
2847 // Determine whether the type we're converting from is signed or
2848 // unsigned.
2849 bool FromIsSigned = FromType->isSignedIntegerType();
2850 uint64_t FromSize = Context.getTypeSize(T: FromType);
2851
2852 // The types we'll try to promote to, in the appropriate
2853 // order. Try each of these types.
2854 QualType PromoteTypes[6] = {
2855 Context.IntTy, Context.UnsignedIntTy,
2856 Context.LongTy, Context.UnsignedLongTy ,
2857 Context.LongLongTy, Context.UnsignedLongLongTy
2858 };
2859 for (int Idx = 0; Idx < 6; ++Idx) {
2860 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2861 if (FromSize < ToSize ||
2862 (FromSize == ToSize &&
2863 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2864 // We found the type that we can promote to. If this is the
2865 // type we wanted, we have a promotion. Otherwise, no
2866 // promotion.
2867 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2868 }
2869 }
2870 }
2871
2872 // An rvalue for an integral bit-field (9.6) can be converted to an
2873 // rvalue of type int if int can represent all the values of the
2874 // bit-field; otherwise, it can be converted to unsigned int if
2875 // unsigned int can represent all the values of the bit-field. If
2876 // the bit-field is larger yet, no integral promotion applies to
2877 // it. If the bit-field has an enumerated type, it is treated as any
2878 // other value of that type for promotion purposes (C++ 4.5p3).
2879 // FIXME: We should delay checking of bit-fields until we actually perform the
2880 // conversion.
2881 //
2882 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2883 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2884 // bit-fields and those whose underlying type is larger than int) for GCC
2885 // compatibility.
2886 if (From) {
2887 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2888 std::optional<llvm::APSInt> BitWidth;
2889 if (FromType->isIntegralType(Ctx: Context) &&
2890 (BitWidth =
2891 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2892 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2893 ToSize = Context.getTypeSize(T: ToType);
2894
2895 // Are we promoting to an int from a bitfield that fits in an int?
2896 if (*BitWidth < ToSize ||
2897 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2898 return To->getKind() == BuiltinType::Int;
2899 }
2900
2901 // Are we promoting to an unsigned int from an unsigned bitfield
2902 // that fits into an unsigned int?
2903 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2904 return To->getKind() == BuiltinType::UInt;
2905 }
2906
2907 return false;
2908 }
2909 }
2910 }
2911
2912 // An rvalue of type bool can be converted to an rvalue of type int,
2913 // with false becoming zero and true becoming one (C++ 4.5p4).
2914 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2915 return true;
2916 }
2917
2918 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2919 // integral type.
2920 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2921 ToType->isIntegerType())
2922 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2923
2924 return false;
2925}
2926
2927bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2928 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2929 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2930 /// An rvalue of type float can be converted to an rvalue of type
2931 /// double. (C++ 4.6p1).
2932 if (FromBuiltin->getKind() == BuiltinType::Float &&
2933 ToBuiltin->getKind() == BuiltinType::Double)
2934 return true;
2935
2936 // C99 6.3.1.5p1:
2937 // When a float is promoted to double or long double, or a
2938 // double is promoted to long double [...].
2939 if (!getLangOpts().CPlusPlus &&
2940 (FromBuiltin->getKind() == BuiltinType::Float ||
2941 FromBuiltin->getKind() == BuiltinType::Double) &&
2942 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2943 ToBuiltin->getKind() == BuiltinType::Float128 ||
2944 ToBuiltin->getKind() == BuiltinType::Ibm128))
2945 return true;
2946
2947 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2948 // or not native half types are enabled.
2949 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2950 (ToBuiltin->getKind() == BuiltinType::Float ||
2951 ToBuiltin->getKind() == BuiltinType::Double))
2952 return true;
2953
2954 // Half can be promoted to float.
2955 if (!getLangOpts().NativeHalfType &&
2956 FromBuiltin->getKind() == BuiltinType::Half &&
2957 ToBuiltin->getKind() == BuiltinType::Float)
2958 return true;
2959 }
2960
2961 return false;
2962}
2963
2964bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2965 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2966 if (!FromComplex)
2967 return false;
2968
2969 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2970 if (!ToComplex)
2971 return false;
2972
2973 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2974 ToType: ToComplex->getElementType()) ||
2975 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2976 ToType: ToComplex->getElementType());
2977}
2978
2979bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
2980 if (!getLangOpts().OverflowBehaviorTypes)
2981 return false;
2982
2983 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2984 return false;
2985
2986 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2987}
2988
2989bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
2990 QualType ToType) {
2991 if (!getLangOpts().OverflowBehaviorTypes)
2992 return false;
2993
2994 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2995 if (ToType->isBooleanType())
2996 return false;
2997 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2998 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2999 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
3000 if (ToED->isScoped())
3001 return false;
3002 }
3003 return true;
3004 }
3005
3006 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3007 return true;
3008
3009 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3010 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
3011
3012 return false;
3013}
3014
3015/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
3016/// the pointer type FromPtr to a pointer to type ToPointee, with the
3017/// same type qualifiers as FromPtr has on its pointee type. ToType,
3018/// if non-empty, will be a pointer to ToType that may or may not have
3019/// the right set of qualifiers on its pointee.
3020///
3021static QualType
3022BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
3023 QualType ToPointee, QualType ToType,
3024 ASTContext &Context,
3025 bool StripObjCLifetime = false) {
3026 assert((FromPtr->getTypeClass() == Type::Pointer ||
3027 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3028 "Invalid similarly-qualified pointer type");
3029
3030 /// Conversions to 'id' subsume cv-qualifier conversions.
3031 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3032 return ToType.getUnqualifiedType();
3033
3034 QualType CanonFromPointee
3035 = Context.getCanonicalType(T: FromPtr->getPointeeType());
3036 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
3037 Qualifiers Quals = CanonFromPointee.getQualifiers();
3038
3039 if (StripObjCLifetime)
3040 Quals.removeObjCLifetime();
3041
3042 // Exact qualifier match -> return the pointer type we're converting to.
3043 if (CanonToPointee.getLocalQualifiers() == Quals) {
3044 // ToType is exactly what we need. Return it.
3045 if (!ToType.isNull())
3046 return ToType.getUnqualifiedType();
3047
3048 // Build a pointer to ToPointee. It has the right qualifiers
3049 // already.
3050 if (isa<ObjCObjectPointerType>(Val: ToType))
3051 return Context.getObjCObjectPointerType(OIT: ToPointee);
3052 return Context.getPointerType(T: ToPointee);
3053 }
3054
3055 // Just build a canonical type that has the right qualifiers.
3056 QualType QualifiedCanonToPointee
3057 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3058
3059 if (isa<ObjCObjectPointerType>(Val: ToType))
3060 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3061 return Context.getPointerType(T: QualifiedCanonToPointee);
3062}
3063
3064static bool isNullPointerConstantForConversion(Expr *Expr,
3065 bool InOverloadResolution,
3066 ASTContext &Context) {
3067 // Handle value-dependent integral null pointer constants correctly.
3068 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3069 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3070 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3071 return !InOverloadResolution;
3072
3073 return Expr->isNullPointerConstant(Ctx&: Context,
3074 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3075 : Expr::NPC_ValueDependentIsNull);
3076}
3077
3078bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3079 bool InOverloadResolution,
3080 QualType& ConvertedType,
3081 bool &IncompatibleObjC) {
3082 IncompatibleObjC = false;
3083 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3084 IncompatibleObjC))
3085 return true;
3086
3087 // Conversion from a null pointer constant to any Objective-C pointer type.
3088 if (ToType->isObjCObjectPointerType() &&
3089 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3090 ConvertedType = ToType;
3091 return true;
3092 }
3093
3094 // Blocks: Block pointers can be converted to void*.
3095 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3096 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3097 ConvertedType = ToType;
3098 return true;
3099 }
3100 // Blocks: A null pointer constant can be converted to a block
3101 // pointer type.
3102 if (ToType->isBlockPointerType() &&
3103 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3104 ConvertedType = ToType;
3105 return true;
3106 }
3107
3108 // If the left-hand-side is nullptr_t, the right side can be a null
3109 // pointer constant.
3110 if (ToType->isNullPtrType() &&
3111 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3112 ConvertedType = ToType;
3113 return true;
3114 }
3115
3116 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3117 if (!ToTypePtr)
3118 return false;
3119
3120 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3121 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3122 ConvertedType = ToType;
3123 return true;
3124 }
3125
3126 // Beyond this point, both types need to be pointers
3127 // , including objective-c pointers.
3128 QualType ToPointeeType = ToTypePtr->getPointeeType();
3129 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3130 !getLangOpts().ObjCAutoRefCount) {
3131 ConvertedType = BuildSimilarlyQualifiedPointerType(
3132 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3133 Context);
3134 return true;
3135 }
3136 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3137 if (!FromTypePtr)
3138 return false;
3139
3140 QualType FromPointeeType = FromTypePtr->getPointeeType();
3141
3142 // If the unqualified pointee types are the same, this can't be a
3143 // pointer conversion, so don't do all of the work below.
3144 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3145 return false;
3146
3147 // An rvalue of type "pointer to cv T," where T is an object type,
3148 // can be converted to an rvalue of type "pointer to cv void" (C++
3149 // 4.10p2).
3150 if (FromPointeeType->isIncompleteOrObjectType() &&
3151 ToPointeeType->isVoidType()) {
3152 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3153 ToPointee: ToPointeeType,
3154 ToType, Context,
3155 /*StripObjCLifetime=*/true);
3156 return true;
3157 }
3158
3159 // MSVC allows implicit function to void* type conversion.
3160 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3161 ToPointeeType->isVoidType()) {
3162 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3163 ToPointee: ToPointeeType,
3164 ToType, Context);
3165 return true;
3166 }
3167
3168 // When we're overloading in C, we allow a special kind of pointer
3169 // conversion for compatible-but-not-identical pointee types.
3170 if (!getLangOpts().CPlusPlus &&
3171 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3172 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3173 ToPointee: ToPointeeType,
3174 ToType, Context);
3175 return true;
3176 }
3177
3178 // C++ [conv.ptr]p3:
3179 //
3180 // An rvalue of type "pointer to cv D," where D is a class type,
3181 // can be converted to an rvalue of type "pointer to cv B," where
3182 // B is a base class (clause 10) of D. If B is an inaccessible
3183 // (clause 11) or ambiguous (10.2) base class of D, a program that
3184 // necessitates this conversion is ill-formed. The result of the
3185 // conversion is a pointer to the base class sub-object of the
3186 // derived class object. The null pointer value is converted to
3187 // the null pointer value of the destination type.
3188 //
3189 // Note that we do not check for ambiguity or inaccessibility
3190 // here. That is handled by CheckPointerConversion.
3191 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3192 ToPointeeType->isRecordType() &&
3193 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3194 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3196 ToPointee: ToPointeeType,
3197 ToType, Context);
3198 return true;
3199 }
3200
3201 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3202 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3203 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3204 ToPointee: ToPointeeType,
3205 ToType, Context);
3206 return true;
3207 }
3208
3209 return false;
3210}
3211
3212/// Adopt the given qualifiers for the given type.
3213static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3214 Qualifiers TQs = T.getQualifiers();
3215
3216 // Check whether qualifiers already match.
3217 if (TQs == Qs)
3218 return T;
3219
3220 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3221 return Context.getQualifiedType(T, Qs);
3222
3223 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3224}
3225
3226bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3227 QualType& ConvertedType,
3228 bool &IncompatibleObjC) {
3229 if (!getLangOpts().ObjC)
3230 return false;
3231
3232 // The set of qualifiers on the type we're converting from.
3233 Qualifiers FromQualifiers = FromType.getQualifiers();
3234
3235 // First, we handle all conversions on ObjC object pointer types.
3236 const ObjCObjectPointerType* ToObjCPtr =
3237 ToType->getAs<ObjCObjectPointerType>();
3238 const ObjCObjectPointerType *FromObjCPtr =
3239 FromType->getAs<ObjCObjectPointerType>();
3240
3241 if (ToObjCPtr && FromObjCPtr) {
3242 // If the pointee types are the same (ignoring qualifications),
3243 // then this is not a pointer conversion.
3244 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3245 T2: FromObjCPtr->getPointeeType()))
3246 return false;
3247
3248 // Conversion between Objective-C pointers.
3249 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3250 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3251 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3252 if (getLangOpts().CPlusPlus && LHS && RHS &&
3253 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3254 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3255 return false;
3256 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3257 ToPointee: ToObjCPtr->getPointeeType(),
3258 ToType, Context);
3259 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3260 return true;
3261 }
3262
3263 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3264 // Okay: this is some kind of implicit downcast of Objective-C
3265 // interfaces, which is permitted. However, we're going to
3266 // complain about it.
3267 IncompatibleObjC = true;
3268 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3269 ToPointee: ToObjCPtr->getPointeeType(),
3270 ToType, Context);
3271 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3272 return true;
3273 }
3274 }
3275 // Beyond this point, both types need to be C pointers or block pointers.
3276 QualType ToPointeeType;
3277 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3278 ToPointeeType = ToCPtr->getPointeeType();
3279 else if (const BlockPointerType *ToBlockPtr =
3280 ToType->getAs<BlockPointerType>()) {
3281 // Objective C++: We're able to convert from a pointer to any object
3282 // to a block pointer type.
3283 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3284 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3285 return true;
3286 }
3287 ToPointeeType = ToBlockPtr->getPointeeType();
3288 }
3289 else if (FromType->getAs<BlockPointerType>() &&
3290 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3291 // Objective C++: We're able to convert from a block pointer type to a
3292 // pointer to any object.
3293 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3294 return true;
3295 }
3296 else
3297 return false;
3298
3299 QualType FromPointeeType;
3300 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3301 FromPointeeType = FromCPtr->getPointeeType();
3302 else if (const BlockPointerType *FromBlockPtr =
3303 FromType->getAs<BlockPointerType>())
3304 FromPointeeType = FromBlockPtr->getPointeeType();
3305 else
3306 return false;
3307
3308 // If we have pointers to pointers, recursively check whether this
3309 // is an Objective-C conversion.
3310 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3311 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3312 IncompatibleObjC)) {
3313 // We always complain about this conversion.
3314 IncompatibleObjC = true;
3315 ConvertedType = Context.getPointerType(T: ConvertedType);
3316 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3317 return true;
3318 }
3319 // Allow conversion of pointee being objective-c pointer to another one;
3320 // as in I* to id.
3321 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3322 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3323 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3324 IncompatibleObjC)) {
3325
3326 ConvertedType = Context.getPointerType(T: ConvertedType);
3327 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3328 return true;
3329 }
3330
3331 // If we have pointers to functions or blocks, check whether the only
3332 // differences in the argument and result types are in Objective-C
3333 // pointer conversions. If so, we permit the conversion (but
3334 // complain about it).
3335 const FunctionProtoType *FromFunctionType
3336 = FromPointeeType->getAs<FunctionProtoType>();
3337 const FunctionProtoType *ToFunctionType
3338 = ToPointeeType->getAs<FunctionProtoType>();
3339 if (FromFunctionType && ToFunctionType) {
3340 // If the function types are exactly the same, this isn't an
3341 // Objective-C pointer conversion.
3342 if (Context.getCanonicalType(T: FromPointeeType)
3343 == Context.getCanonicalType(T: ToPointeeType))
3344 return false;
3345
3346 // Perform the quick checks that will tell us whether these
3347 // function types are obviously different.
3348 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3349 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3350 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3351 return false;
3352
3353 bool HasObjCConversion = false;
3354 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3355 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3356 // Okay, the types match exactly. Nothing to do.
3357 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3358 ToType: ToFunctionType->getReturnType(),
3359 ConvertedType, IncompatibleObjC)) {
3360 // Okay, we have an Objective-C pointer conversion.
3361 HasObjCConversion = true;
3362 } else {
3363 // Function types are too different. Abort.
3364 return false;
3365 }
3366
3367 // Check argument types.
3368 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3369 ArgIdx != NumArgs; ++ArgIdx) {
3370 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3371 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3372 if (Context.getCanonicalType(T: FromArgType)
3373 == Context.getCanonicalType(T: ToArgType)) {
3374 // Okay, the types match exactly. Nothing to do.
3375 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3376 ConvertedType, IncompatibleObjC)) {
3377 // Okay, we have an Objective-C pointer conversion.
3378 HasObjCConversion = true;
3379 } else {
3380 // Argument types are too different. Abort.
3381 return false;
3382 }
3383 }
3384
3385 if (HasObjCConversion) {
3386 // We had an Objective-C conversion. Allow this pointer
3387 // conversion, but complain about it.
3388 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3389 IncompatibleObjC = true;
3390 return true;
3391 }
3392 }
3393
3394 return false;
3395}
3396
3397bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3398 QualType& ConvertedType) {
3399 QualType ToPointeeType;
3400 if (const BlockPointerType *ToBlockPtr =
3401 ToType->getAs<BlockPointerType>())
3402 ToPointeeType = ToBlockPtr->getPointeeType();
3403 else
3404 return false;
3405
3406 QualType FromPointeeType;
3407 if (const BlockPointerType *FromBlockPtr =
3408 FromType->getAs<BlockPointerType>())
3409 FromPointeeType = FromBlockPtr->getPointeeType();
3410 else
3411 return false;
3412 // We have pointer to blocks, check whether the only
3413 // differences in the argument and result types are in Objective-C
3414 // pointer conversions. If so, we permit the conversion.
3415
3416 const FunctionProtoType *FromFunctionType
3417 = FromPointeeType->getAs<FunctionProtoType>();
3418 const FunctionProtoType *ToFunctionType
3419 = ToPointeeType->getAs<FunctionProtoType>();
3420
3421 if (!FromFunctionType || !ToFunctionType)
3422 return false;
3423
3424 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3425 return true;
3426
3427 // Perform the quick checks that will tell us whether these
3428 // function types are obviously different.
3429 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3430 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3431 return false;
3432
3433 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3434 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3435 if (FromEInfo != ToEInfo)
3436 return false;
3437
3438 bool IncompatibleObjC = false;
3439 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3440 T2: ToFunctionType->getReturnType())) {
3441 // Okay, the types match exactly. Nothing to do.
3442 } else {
3443 QualType RHS = FromFunctionType->getReturnType();
3444 QualType LHS = ToFunctionType->getReturnType();
3445 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3446 !RHS.hasQualifiers() && LHS.hasQualifiers())
3447 LHS = LHS.getUnqualifiedType();
3448
3449 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3450 // OK exact match.
3451 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3452 ConvertedType, IncompatibleObjC)) {
3453 if (IncompatibleObjC)
3454 return false;
3455 // Okay, we have an Objective-C pointer conversion.
3456 }
3457 else
3458 return false;
3459 }
3460
3461 // Check argument types.
3462 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3463 ArgIdx != NumArgs; ++ArgIdx) {
3464 IncompatibleObjC = false;
3465 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3466 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3467 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3468 // Okay, the types match exactly. Nothing to do.
3469 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3470 ConvertedType, IncompatibleObjC)) {
3471 if (IncompatibleObjC)
3472 return false;
3473 // Okay, we have an Objective-C pointer conversion.
3474 } else
3475 // Argument types are too different. Abort.
3476 return false;
3477 }
3478
3479 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3480 bool CanUseToFPT, CanUseFromFPT;
3481 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3482 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3483 NewParamInfos))
3484 return false;
3485
3486 ConvertedType = ToType;
3487 return true;
3488}
3489
3490enum {
3491 ft_default,
3492 ft_different_class,
3493 ft_parameter_arity,
3494 ft_parameter_mismatch,
3495 ft_return_type,
3496 ft_qualifer_mismatch,
3497 ft_noexcept
3498};
3499
3500/// Attempts to get the FunctionProtoType from a Type. Handles
3501/// MemberFunctionPointers properly.
3502static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3503 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3504 return FPT;
3505
3506 if (auto *MPT = FromType->getAs<MemberPointerType>())
3507 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3508
3509 return nullptr;
3510}
3511
3512void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3513 QualType FromType, QualType ToType) {
3514 // If either type is not valid, include no extra info.
3515 if (FromType.isNull() || ToType.isNull()) {
3516 PDiag << ft_default;
3517 return;
3518 }
3519
3520 // Get the function type from the pointers.
3521 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3522 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3523 *ToMember = ToType->castAs<MemberPointerType>();
3524 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3525 D2: ToMember->getMostRecentCXXRecordDecl())) {
3526 PDiag << ft_different_class;
3527 if (ToMember->isSugared())
3528 PDiag << Context.getCanonicalTagType(
3529 TD: ToMember->getMostRecentCXXRecordDecl());
3530 else
3531 PDiag << ToMember->getQualifier();
3532 if (FromMember->isSugared())
3533 PDiag << Context.getCanonicalTagType(
3534 TD: FromMember->getMostRecentCXXRecordDecl());
3535 else
3536 PDiag << FromMember->getQualifier();
3537 return;
3538 }
3539 FromType = FromMember->getPointeeType();
3540 ToType = ToMember->getPointeeType();
3541 }
3542
3543 if (FromType->isPointerType())
3544 FromType = FromType->getPointeeType();
3545 if (ToType->isPointerType())
3546 ToType = ToType->getPointeeType();
3547
3548 // Remove references.
3549 FromType = FromType.getNonReferenceType();
3550 ToType = ToType.getNonReferenceType();
3551
3552 // Don't print extra info for non-specialized template functions.
3553 if (FromType->isInstantiationDependentType() &&
3554 !FromType->getAs<TemplateSpecializationType>()) {
3555 PDiag << ft_default;
3556 return;
3557 }
3558
3559 // No extra info for same types.
3560 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3561 PDiag << ft_default;
3562 return;
3563 }
3564
3565 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3566 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3567
3568 // Both types need to be function types.
3569 if (!FromFunction || !ToFunction) {
3570 PDiag << ft_default;
3571 return;
3572 }
3573
3574 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3575 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3576 << FromFunction->getNumParams();
3577 return;
3578 }
3579
3580 // Handle different parameter types.
3581 unsigned ArgPos;
3582 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3583 PDiag << ft_parameter_mismatch << ArgPos + 1
3584 << ToFunction->getParamType(i: ArgPos)
3585 << FromFunction->getParamType(i: ArgPos);
3586 return;
3587 }
3588
3589 // Handle different return type.
3590 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3591 T2: ToFunction->getReturnType())) {
3592 PDiag << ft_return_type << ToFunction->getReturnType()
3593 << FromFunction->getReturnType();
3594 return;
3595 }
3596
3597 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3598 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3599 << FromFunction->getMethodQuals();
3600 return;
3601 }
3602
3603 // Handle exception specification differences on canonical type (in C++17
3604 // onwards).
3605 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3606 ->isNothrow() !=
3607 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3608 ->isNothrow()) {
3609 PDiag << ft_noexcept;
3610 return;
3611 }
3612
3613 // Unable to find a difference, so add no extra info.
3614 PDiag << ft_default;
3615}
3616
3617bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3618 ArrayRef<QualType> New, unsigned *ArgPos,
3619 bool Reversed) {
3620 assert(llvm::size(Old) == llvm::size(New) &&
3621 "Can't compare parameters of functions with different number of "
3622 "parameters!");
3623
3624 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3625 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3626 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3627
3628 // Ignore address spaces in pointee type. This is to disallow overloading
3629 // on __ptr32/__ptr64 address spaces.
3630 QualType OldType =
3631 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3632 QualType NewType =
3633 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3634
3635 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3636 if (ArgPos)
3637 *ArgPos = Idx;
3638 return false;
3639 }
3640 }
3641 return true;
3642}
3643
3644bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3645 const FunctionProtoType *NewType,
3646 unsigned *ArgPos, bool Reversed) {
3647 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3648 New: NewType->param_types(), ArgPos, Reversed);
3649}
3650
3651bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3652 const FunctionDecl *NewFunction,
3653 unsigned *ArgPos,
3654 bool Reversed) {
3655
3656 if (OldFunction->getNumNonObjectParams() !=
3657 NewFunction->getNumNonObjectParams())
3658 return false;
3659
3660 unsigned OldIgnore =
3661 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3662 unsigned NewIgnore =
3663 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3664
3665 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3666 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3667
3668 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3669 New: NewPT->param_types().slice(N: NewIgnore),
3670 ArgPos, Reversed);
3671}
3672
3673bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3674 CastKind &Kind,
3675 CXXCastPath& BasePath,
3676 bool IgnoreBaseAccess,
3677 bool Diagnose) {
3678 QualType FromType = From->getType();
3679 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3680
3681 Kind = CK_BitCast;
3682
3683 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3684 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3685 Expr::NPCK_ZeroExpression) {
3686 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3687 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3688 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3689 << ToType << From->getSourceRange());
3690 else if (!isUnevaluatedContext())
3691 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3692 << ToType << From->getSourceRange();
3693 }
3694 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3695 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3696 QualType FromPointeeType = FromPtrType->getPointeeType(),
3697 ToPointeeType = ToPtrType->getPointeeType();
3698
3699 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3700 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3701 // We must have a derived-to-base conversion. Check an
3702 // ambiguous or inaccessible conversion.
3703 unsigned InaccessibleID = 0;
3704 unsigned AmbiguousID = 0;
3705 if (Diagnose) {
3706 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3707 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3708 }
3709 if (CheckDerivedToBaseConversion(
3710 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3711 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3712 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3713 return true;
3714
3715 // The conversion was successful.
3716 Kind = CK_DerivedToBase;
3717 }
3718
3719 if (Diagnose && !IsCStyleOrFunctionalCast &&
3720 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3721 assert(getLangOpts().MSVCCompat &&
3722 "this should only be possible with MSVCCompat!");
3723 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3724 << From->getSourceRange();
3725 }
3726 }
3727 } else if (const ObjCObjectPointerType *ToPtrType =
3728 ToType->getAs<ObjCObjectPointerType>()) {
3729 if (const ObjCObjectPointerType *FromPtrType =
3730 FromType->getAs<ObjCObjectPointerType>()) {
3731 // Objective-C++ conversions are always okay.
3732 // FIXME: We should have a different class of conversions for the
3733 // Objective-C++ implicit conversions.
3734 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3735 return false;
3736 } else if (FromType->isBlockPointerType()) {
3737 Kind = CK_BlockPointerToObjCPointerCast;
3738 } else {
3739 Kind = CK_CPointerToObjCPointerCast;
3740 }
3741 } else if (ToType->isBlockPointerType()) {
3742 if (!FromType->isBlockPointerType())
3743 Kind = CK_AnyPointerToBlockPointerCast;
3744 }
3745
3746 // We shouldn't fall into this case unless it's valid for other
3747 // reasons.
3748 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3749 Kind = CK_NullToPointer;
3750
3751 return false;
3752}
3753
3754bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3755 QualType ToType,
3756 bool InOverloadResolution,
3757 QualType &ConvertedType) {
3758 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3759 if (!ToTypePtr)
3760 return false;
3761
3762 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3763 if (From->isNullPointerConstant(Ctx&: Context,
3764 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3765 : Expr::NPC_ValueDependentIsNull)) {
3766 ConvertedType = ToType;
3767 return true;
3768 }
3769
3770 // Otherwise, both types have to be member pointers.
3771 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3772 if (!FromTypePtr)
3773 return false;
3774
3775 // A pointer to member of B can be converted to a pointer to member of D,
3776 // where D is derived from B (C++ 4.11p2).
3777 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3778 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3779
3780 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3781 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3782 ConvertedType = Context.getMemberPointerType(
3783 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3784 return true;
3785 }
3786
3787 return false;
3788}
3789
3790Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3791 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3792 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3793 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3794 // Lock down the inheritance model right now in MS ABI, whether or not the
3795 // pointee types are the same.
3796 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3797 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3798 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3799 }
3800
3801 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3802 if (!FromPtrType) {
3803 // This must be a null pointer to member pointer conversion
3804 Kind = CK_NullToMemberPointer;
3805 return MemberPointerConversionResult::Success;
3806 }
3807
3808 // T == T, modulo cv
3809 if (Direction == MemberPointerConversionDirection::Upcast &&
3810 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3811 T2: ToPtrType->getPointeeType()))
3812 return MemberPointerConversionResult::DifferentPointee;
3813
3814 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3815 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3816
3817 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3818 const CXXRecordDecl *Cls) {
3819 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3820 PD << Qual;
3821 else
3822 PD << Context.getCanonicalTagType(TD: Cls);
3823 };
3824 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3825 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3826 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3827 return PD;
3828 };
3829
3830 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3831 if (Direction == MemberPointerConversionDirection::Upcast)
3832 std::swap(a&: Base, b&: Derived);
3833
3834 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3835 /*DetectVirtual=*/true);
3836 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3837 return MemberPointerConversionResult::NotDerived;
3838
3839 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3840 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3841 PD << int(Direction);
3842 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3843 Diag(Loc: CheckLoc, PD);
3844 return MemberPointerConversionResult::Ambiguous;
3845 }
3846
3847 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3848 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3849 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3850 Diag(Loc: CheckLoc, PD);
3851 return MemberPointerConversionResult::Virtual;
3852 }
3853
3854 // Must be a base to derived member conversion.
3855 BuildBasePathArray(Paths, BasePath);
3856 Kind = Direction == MemberPointerConversionDirection::Upcast
3857 ? CK_DerivedToBaseMemberPointer
3858 : CK_BaseToDerivedMemberPointer;
3859
3860 if (!IgnoreBaseAccess)
3861 switch (CheckBaseClassAccess(
3862 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3863 DiagID: Direction == MemberPointerConversionDirection::Upcast
3864 ? diag::err_upcast_to_inaccessible_base
3865 : diag::err_downcast_from_inaccessible_base,
3866 SetupPDiag: [&](PartialDiagnostic &PD) {
3867 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3868 DerivedQual = ToPtrType->getQualifier();
3869 if (Direction == MemberPointerConversionDirection::Upcast)
3870 std::swap(a&: BaseQual, b&: DerivedQual);
3871 DiagCls(PD, DerivedQual, Derived);
3872 DiagCls(PD, BaseQual, Base);
3873 })) {
3874 case Sema::AR_accessible:
3875 case Sema::AR_delayed:
3876 case Sema::AR_dependent:
3877 // Optimistically assume that the delayed and dependent cases
3878 // will work out.
3879 break;
3880
3881 case Sema::AR_inaccessible:
3882 return MemberPointerConversionResult::Inaccessible;
3883 }
3884
3885 return MemberPointerConversionResult::Success;
3886}
3887
3888/// Determine whether the lifetime conversion between the two given
3889/// qualifiers sets is nontrivial.
3890static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3891 Qualifiers ToQuals) {
3892 // Converting anything to const __unsafe_unretained is trivial.
3893 if (ToQuals.hasConst() &&
3894 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3895 return false;
3896
3897 return true;
3898}
3899
3900/// Perform a single iteration of the loop for checking if a qualification
3901/// conversion is valid.
3902///
3903/// Specifically, check whether any change between the qualifiers of \p
3904/// FromType and \p ToType is permissible, given knowledge about whether every
3905/// outer layer is const-qualified.
3906static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3907 bool CStyle, bool IsTopLevel,
3908 bool &PreviousToQualsIncludeConst,
3909 bool &ObjCLifetimeConversion,
3910 const ASTContext &Ctx) {
3911 Qualifiers FromQuals = FromType.getQualifiers();
3912 Qualifiers ToQuals = ToType.getQualifiers();
3913
3914 // Ignore __unaligned qualifier.
3915 FromQuals.removeUnaligned();
3916
3917 // Objective-C ARC:
3918 // Check Objective-C lifetime conversions.
3919 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3920 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3921 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3922 ObjCLifetimeConversion = true;
3923 FromQuals.removeObjCLifetime();
3924 ToQuals.removeObjCLifetime();
3925 } else {
3926 // Qualification conversions cannot cast between different
3927 // Objective-C lifetime qualifiers.
3928 return false;
3929 }
3930 }
3931
3932 // Allow addition/removal of GC attributes but not changing GC attributes.
3933 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3934 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3935 FromQuals.removeObjCGCAttr();
3936 ToQuals.removeObjCGCAttr();
3937 }
3938
3939 // __ptrauth qualifiers must match exactly.
3940 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3941 return false;
3942
3943 // -- for every j > 0, if const is in cv 1,j then const is in cv
3944 // 2,j, and similarly for volatile.
3945 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3946 return false;
3947
3948 // If address spaces mismatch:
3949 // - in top level it is only valid to convert to addr space that is a
3950 // superset in all cases apart from C-style casts where we allow
3951 // conversions between overlapping address spaces.
3952 // - in non-top levels it is not a valid conversion.
3953 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3954 (!IsTopLevel ||
3955 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3956 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3957 return false;
3958
3959 // -- if the cv 1,j and cv 2,j are different, then const is in
3960 // every cv for 0 < k < j.
3961 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3962 !PreviousToQualsIncludeConst)
3963 return false;
3964
3965 // The following wording is from C++20, where the result of the conversion
3966 // is T3, not T2.
3967 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3968 // "array of unknown bound of"
3969 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3970 return false;
3971
3972 // -- if the resulting P3,i is different from P1,i [...], then const is
3973 // added to every cv 3_k for 0 < k < i.
3974 if (!CStyle && FromType->isConstantArrayType() &&
3975 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3976 return false;
3977
3978 // Keep track of whether all prior cv-qualifiers in the "to" type
3979 // include const.
3980 PreviousToQualsIncludeConst =
3981 PreviousToQualsIncludeConst && ToQuals.hasConst();
3982 return true;
3983}
3984
3985bool
3986Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3987 bool CStyle, bool &ObjCLifetimeConversion) {
3988 FromType = Context.getCanonicalType(T: FromType);
3989 ToType = Context.getCanonicalType(T: ToType);
3990 ObjCLifetimeConversion = false;
3991
3992 // If FromType and ToType are the same type, this is not a
3993 // qualification conversion.
3994 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3995 return false;
3996
3997 // (C++ 4.4p4):
3998 // A conversion can add cv-qualifiers at levels other than the first
3999 // in multi-level pointers, subject to the following rules: [...]
4000 bool PreviousToQualsIncludeConst = true;
4001 bool UnwrappedAnyPointer = false;
4002 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
4003 if (!isQualificationConversionStep(FromType, ToType, CStyle,
4004 IsTopLevel: !UnwrappedAnyPointer,
4005 PreviousToQualsIncludeConst,
4006 ObjCLifetimeConversion, Ctx: getASTContext()))
4007 return false;
4008 UnwrappedAnyPointer = true;
4009 }
4010
4011 // We are left with FromType and ToType being the pointee types
4012 // after unwrapping the original FromType and ToType the same number
4013 // of times. If we unwrapped any pointers, and if FromType and
4014 // ToType have the same unqualified type (since we checked
4015 // qualifiers above), then this is a qualification conversion.
4016 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
4017}
4018
4019/// - Determine whether this is a conversion from a scalar type to an
4020/// atomic type.
4021///
4022/// If successful, updates \c SCS's second and third steps in the conversion
4023/// sequence to finish the conversion.
4024static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4025 bool InOverloadResolution,
4026 StandardConversionSequence &SCS,
4027 bool CStyle) {
4028 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4029 if (!ToAtomic)
4030 return false;
4031
4032 StandardConversionSequence InnerSCS;
4033 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
4034 InOverloadResolution, SCS&: InnerSCS,
4035 CStyle, /*AllowObjCWritebackConversion=*/false))
4036 return false;
4037
4038 SCS.Second = InnerSCS.Second;
4039 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4040 SCS.Third = InnerSCS.Third;
4041 SCS.QualificationIncludesObjCLifetime
4042 = InnerSCS.QualificationIncludesObjCLifetime;
4043 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4044 return true;
4045}
4046
4047static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
4048 QualType ToType,
4049 bool InOverloadResolution,
4050 StandardConversionSequence &SCS,
4051 bool CStyle) {
4052 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4053 if (!ToOBT)
4054 return false;
4055
4056 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4057 QualType FromType = From->getType();
4058 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4059 return false;
4060
4061 StandardConversionSequence InnerSCS;
4062 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4063 InOverloadResolution, SCS&: InnerSCS, CStyle,
4064 /*AllowObjCWritebackConversion=*/false))
4065 return false;
4066
4067 SCS.Second = InnerSCS.Second;
4068 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4069 SCS.Third = InnerSCS.Third;
4070 SCS.QualificationIncludesObjCLifetime =
4071 InnerSCS.QualificationIncludesObjCLifetime;
4072 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4073 return true;
4074}
4075
4076static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4077 CXXConstructorDecl *Constructor,
4078 QualType Type) {
4079 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4080 if (CtorType->getNumParams() > 0) {
4081 QualType FirstArg = CtorType->getParamType(i: 0);
4082 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4083 return true;
4084 }
4085 return false;
4086}
4087
4088static OverloadingResult
4089IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4090 CXXRecordDecl *To,
4091 UserDefinedConversionSequence &User,
4092 OverloadCandidateSet &CandidateSet,
4093 bool AllowExplicit) {
4094 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4095 for (auto *D : S.LookupConstructors(Class: To)) {
4096 auto Info = getConstructorInfo(ND: D);
4097 if (!Info)
4098 continue;
4099
4100 bool Usable = !Info.Constructor->isInvalidDecl() &&
4101 S.isInitListConstructor(Ctor: Info.Constructor);
4102 if (Usable) {
4103 bool SuppressUserConversions = false;
4104 if (Info.ConstructorTmpl)
4105 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4106 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4107 CandidateSet, SuppressUserConversions,
4108 /*PartialOverloading*/ false,
4109 AllowExplicit);
4110 else
4111 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4112 CandidateSet, SuppressUserConversions,
4113 /*PartialOverloading*/ false, AllowExplicit);
4114 }
4115 }
4116
4117 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4118
4119 OverloadCandidateSet::iterator Best;
4120 switch (auto Result =
4121 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4122 case OR_Deleted:
4123 case OR_Success: {
4124 // Record the standard conversion we used and the conversion function.
4125 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4126 QualType ThisType = Constructor->getFunctionObjectParameterType();
4127 // Initializer lists don't have conversions as such.
4128 User.Before.setAsIdentityConversion();
4129 User.HadMultipleCandidates = HadMultipleCandidates;
4130 User.ConversionFunction = Constructor;
4131 User.FoundConversionFunction = Best->FoundDecl;
4132 User.After.setAsIdentityConversion();
4133 User.After.setFromType(ThisType);
4134 User.After.setAllToTypes(ToType);
4135 return Result;
4136 }
4137
4138 case OR_No_Viable_Function:
4139 return OR_No_Viable_Function;
4140 case OR_Ambiguous:
4141 return OR_Ambiguous;
4142 }
4143
4144 llvm_unreachable("Invalid OverloadResult!");
4145}
4146
4147/// Determines whether there is a user-defined conversion sequence
4148/// (C++ [over.ics.user]) that converts expression From to the type
4149/// ToType. If such a conversion exists, User will contain the
4150/// user-defined conversion sequence that performs such a conversion
4151/// and this routine will return true. Otherwise, this routine returns
4152/// false and User is unspecified.
4153///
4154/// \param AllowExplicit true if the conversion should consider C++0x
4155/// "explicit" conversion functions as well as non-explicit conversion
4156/// functions (C++0x [class.conv.fct]p2).
4157///
4158/// \param AllowObjCConversionOnExplicit true if the conversion should
4159/// allow an extra Objective-C pointer conversion on uses of explicit
4160/// constructors. Requires \c AllowExplicit to also be set.
4161static OverloadingResult
4162IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4163 UserDefinedConversionSequence &User,
4164 OverloadCandidateSet &CandidateSet,
4165 AllowedExplicit AllowExplicit,
4166 bool AllowObjCConversionOnExplicit) {
4167 assert(AllowExplicit != AllowedExplicit::None ||
4168 !AllowObjCConversionOnExplicit);
4169 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4170
4171 // Whether we will only visit constructors.
4172 bool ConstructorsOnly = false;
4173
4174 // If the type we are conversion to is a class type, enumerate its
4175 // constructors.
4176 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4177 // C++ [over.match.ctor]p1:
4178 // When objects of class type are direct-initialized (8.5), or
4179 // copy-initialized from an expression of the same or a
4180 // derived class type (8.5), overload resolution selects the
4181 // constructor. [...] For copy-initialization, the candidate
4182 // functions are all the converting constructors (12.3.1) of
4183 // that class. The argument list is the expression-list within
4184 // the parentheses of the initializer.
4185 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4186 (From->getType()->isRecordType() &&
4187 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4188 ConstructorsOnly = true;
4189
4190 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4191 // We're not going to find any constructors.
4192 } else if (auto *ToRecordDecl =
4193 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4194 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4195
4196 Expr **Args = &From;
4197 unsigned NumArgs = 1;
4198 bool ListInitializing = false;
4199 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4200 // But first, see if there is an init-list-constructor that will work.
4201 OverloadingResult Result = IsInitializerListConstructorConversion(
4202 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4203 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4204 if (Result != OR_No_Viable_Function)
4205 return Result;
4206 // Never mind.
4207 CandidateSet.clear(
4208 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4209
4210 // If we're list-initializing, we pass the individual elements as
4211 // arguments, not the entire list.
4212 Args = InitList->getInits();
4213 NumArgs = InitList->getNumInits();
4214 ListInitializing = true;
4215 }
4216
4217 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4218 auto Info = getConstructorInfo(ND: D);
4219 if (!Info)
4220 continue;
4221
4222 bool Usable = !Info.Constructor->isInvalidDecl();
4223 if (!ListInitializing)
4224 Usable = Usable && Info.Constructor->isConvertingConstructor(
4225 /*AllowExplicit*/ true);
4226 if (Usable) {
4227 bool SuppressUserConversions = !ConstructorsOnly;
4228 // C++20 [over.best.ics.general]/4.5:
4229 // if the target is the first parameter of a constructor [of class
4230 // X] and the constructor [...] is a candidate by [...] the second
4231 // phase of [over.match.list] when the initializer list has exactly
4232 // one element that is itself an initializer list, [...] and the
4233 // conversion is to X or reference to cv X, user-defined conversion
4234 // sequences are not considered.
4235 if (SuppressUserConversions && ListInitializing) {
4236 SuppressUserConversions =
4237 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4238 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4239 Type: ToType);
4240 }
4241 if (Info.ConstructorTmpl)
4242 S.AddTemplateOverloadCandidate(
4243 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4244 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4245 CandidateSet, SuppressUserConversions,
4246 /*PartialOverloading*/ false,
4247 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4248 else
4249 // Allow one user-defined conversion when user specifies a
4250 // From->ToType conversion via an static cast (c-style, etc).
4251 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4252 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4253 SuppressUserConversions,
4254 /*PartialOverloading*/ false,
4255 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4256 }
4257 }
4258 }
4259 }
4260
4261 // Enumerate conversion functions, if we're allowed to.
4262 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4263 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4264 // No conversion functions from incomplete types.
4265 } else if (const RecordType *FromRecordType =
4266 From->getType()->getAsCanonical<RecordType>()) {
4267 if (auto *FromRecordDecl =
4268 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4269 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4270 // Add all of the conversion functions as candidates.
4271 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4272 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4273 DeclAccessPair FoundDecl = I.getPair();
4274 NamedDecl *D = FoundDecl.getDecl();
4275 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4276 if (isa<UsingShadowDecl>(Val: D))
4277 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4278
4279 CXXConversionDecl *Conv;
4280 FunctionTemplateDecl *ConvTemplate;
4281 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4282 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4283 else
4284 Conv = cast<CXXConversionDecl>(Val: D);
4285
4286 if (ConvTemplate)
4287 S.AddTemplateConversionCandidate(
4288 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4289 CandidateSet, AllowObjCConversionOnExplicit,
4290 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4291 else
4292 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4293 CandidateSet, AllowObjCConversionOnExplicit,
4294 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4295 }
4296 }
4297 }
4298
4299 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4300
4301 OverloadCandidateSet::iterator Best;
4302 switch (auto Result =
4303 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4304 case OR_Success:
4305 case OR_Deleted:
4306 // Record the standard conversion we used and the conversion function.
4307 if (CXXConstructorDecl *Constructor
4308 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4309 // C++ [over.ics.user]p1:
4310 // If the user-defined conversion is specified by a
4311 // constructor (12.3.1), the initial standard conversion
4312 // sequence converts the source type to the type required by
4313 // the argument of the constructor.
4314 //
4315 if (isa<InitListExpr>(Val: From)) {
4316 // Initializer lists don't have conversions as such.
4317 User.Before.setAsIdentityConversion();
4318 User.Before.FromBracedInitList = true;
4319 } else {
4320 if (Best->Conversions[0].isEllipsis())
4321 User.EllipsisConversion = true;
4322 else {
4323 User.Before = Best->Conversions[0].Standard;
4324 User.EllipsisConversion = false;
4325 }
4326 }
4327 User.HadMultipleCandidates = HadMultipleCandidates;
4328 User.ConversionFunction = Constructor;
4329 User.FoundConversionFunction = Best->FoundDecl;
4330 User.After.setAsIdentityConversion();
4331 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4332 User.After.setAllToTypes(ToType);
4333 return Result;
4334 }
4335 if (CXXConversionDecl *Conversion
4336 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4337
4338 assert(Best->HasFinalConversion);
4339
4340 // C++ [over.ics.user]p1:
4341 //
4342 // [...] If the user-defined conversion is specified by a
4343 // conversion function (12.3.2), the initial standard
4344 // conversion sequence converts the source type to the
4345 // implicit object parameter of the conversion function.
4346 User.Before = Best->Conversions[0].Standard;
4347 User.HadMultipleCandidates = HadMultipleCandidates;
4348 User.ConversionFunction = Conversion;
4349 User.FoundConversionFunction = Best->FoundDecl;
4350 User.EllipsisConversion = false;
4351
4352 // C++ [over.ics.user]p2:
4353 // The second standard conversion sequence converts the
4354 // result of the user-defined conversion to the target type
4355 // for the sequence. Since an implicit conversion sequence
4356 // is an initialization, the special rules for
4357 // initialization by user-defined conversion apply when
4358 // selecting the best user-defined conversion for a
4359 // user-defined conversion sequence (see 13.3.3 and
4360 // 13.3.3.1).
4361 User.After = Best->FinalConversion;
4362 return Result;
4363 }
4364 llvm_unreachable("Not a constructor or conversion function?");
4365
4366 case OR_No_Viable_Function:
4367 return OR_No_Viable_Function;
4368
4369 case OR_Ambiguous:
4370 return OR_Ambiguous;
4371 }
4372
4373 llvm_unreachable("Invalid OverloadResult!");
4374}
4375
4376bool
4377Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4378 ImplicitConversionSequence ICS;
4379 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4380 OverloadCandidateSet::CSK_Normal);
4381 OverloadingResult OvResult =
4382 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4383 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4384
4385 if (!(OvResult == OR_Ambiguous ||
4386 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4387 return false;
4388
4389 auto Cands = CandidateSet.CompleteCandidates(
4390 S&: *this,
4391 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4392 Args: From);
4393 if (OvResult == OR_Ambiguous)
4394 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4395 << From->getType() << ToType << From->getSourceRange();
4396 else { // OR_No_Viable_Function && !CandidateSet.empty()
4397 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4398 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4399 Args: From->getType(), Args: From->getSourceRange()))
4400 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4401 << false << From->getType() << From->getSourceRange() << ToType;
4402 }
4403
4404 CandidateSet.NoteCandidates(
4405 S&: *this, Args: From, Cands);
4406 return true;
4407}
4408
4409// Helper for compareConversionFunctions that gets the FunctionType that the
4410// conversion-operator return value 'points' to, or nullptr.
4411static const FunctionType *
4412getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4413 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4414 const PointerType *RetPtrTy =
4415 ConvFuncTy->getReturnType()->getAs<PointerType>();
4416
4417 if (!RetPtrTy)
4418 return nullptr;
4419
4420 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4421}
4422
4423/// Compare the user-defined conversion functions or constructors
4424/// of two user-defined conversion sequences to determine whether any ordering
4425/// is possible.
4426static ImplicitConversionSequence::CompareKind
4427compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4428 FunctionDecl *Function2) {
4429 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4430 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4431 if (!Conv1 || !Conv2)
4432 return ImplicitConversionSequence::Indistinguishable;
4433
4434 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4435 return ImplicitConversionSequence::Indistinguishable;
4436
4437 // Objective-C++:
4438 // If both conversion functions are implicitly-declared conversions from
4439 // a lambda closure type to a function pointer and a block pointer,
4440 // respectively, always prefer the conversion to a function pointer,
4441 // because the function pointer is more lightweight and is more likely
4442 // to keep code working.
4443 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4444 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4445 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4446 if (Block1 != Block2)
4447 return Block1 ? ImplicitConversionSequence::Worse
4448 : ImplicitConversionSequence::Better;
4449 }
4450
4451 // In order to support multiple calling conventions for the lambda conversion
4452 // operator (such as when the free and member function calling convention is
4453 // different), prefer the 'free' mechanism, followed by the calling-convention
4454 // of operator(). The latter is in place to support the MSVC-like solution of
4455 // defining ALL of the possible conversions in regards to calling-convention.
4456 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4457 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4458
4459 if (Conv1FuncRet && Conv2FuncRet &&
4460 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4461 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4462 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4463
4464 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4465 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4466
4467 CallingConv CallOpCC =
4468 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4469 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4470 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4471 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4472 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4473
4474 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4475 for (CallingConv CC : PrefOrder) {
4476 if (Conv1CC == CC)
4477 return ImplicitConversionSequence::Better;
4478 if (Conv2CC == CC)
4479 return ImplicitConversionSequence::Worse;
4480 }
4481 }
4482
4483 return ImplicitConversionSequence::Indistinguishable;
4484}
4485
4486static bool hasDeprecatedStringLiteralToCharPtrConversion(
4487 const ImplicitConversionSequence &ICS) {
4488 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4489 (ICS.isUserDefined() &&
4490 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4491}
4492
4493/// CompareImplicitConversionSequences - Compare two implicit
4494/// conversion sequences to determine whether one is better than the
4495/// other or if they are indistinguishable (C++ 13.3.3.2).
4496static ImplicitConversionSequence::CompareKind
4497CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4498 const ImplicitConversionSequence& ICS1,
4499 const ImplicitConversionSequence& ICS2)
4500{
4501 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4502 // conversion sequences (as defined in 13.3.3.1)
4503 // -- a standard conversion sequence (13.3.3.1.1) is a better
4504 // conversion sequence than a user-defined conversion sequence or
4505 // an ellipsis conversion sequence, and
4506 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4507 // conversion sequence than an ellipsis conversion sequence
4508 // (13.3.3.1.3).
4509 //
4510 // C++0x [over.best.ics]p10:
4511 // For the purpose of ranking implicit conversion sequences as
4512 // described in 13.3.3.2, the ambiguous conversion sequence is
4513 // treated as a user-defined sequence that is indistinguishable
4514 // from any other user-defined conversion sequence.
4515
4516 // String literal to 'char *' conversion has been deprecated in C++03. It has
4517 // been removed from C++11. We still accept this conversion, if it happens at
4518 // the best viable function. Otherwise, this conversion is considered worse
4519 // than ellipsis conversion. Consider this as an extension; this is not in the
4520 // standard. For example:
4521 //
4522 // int &f(...); // #1
4523 // void f(char*); // #2
4524 // void g() { int &r = f("foo"); }
4525 //
4526 // In C++03, we pick #2 as the best viable function.
4527 // In C++11, we pick #1 as the best viable function, because ellipsis
4528 // conversion is better than string-literal to char* conversion (since there
4529 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4530 // convert arguments, #2 would be the best viable function in C++11.
4531 // If the best viable function has this conversion, a warning will be issued
4532 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4533
4534 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4535 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4536 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4537 // Ill-formedness must not differ
4538 ICS1.isBad() == ICS2.isBad())
4539 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4540 ? ImplicitConversionSequence::Worse
4541 : ImplicitConversionSequence::Better;
4542
4543 if (ICS1.getKindRank() < ICS2.getKindRank())
4544 return ImplicitConversionSequence::Better;
4545 if (ICS2.getKindRank() < ICS1.getKindRank())
4546 return ImplicitConversionSequence::Worse;
4547
4548 // The following checks require both conversion sequences to be of
4549 // the same kind.
4550 if (ICS1.getKind() != ICS2.getKind())
4551 return ImplicitConversionSequence::Indistinguishable;
4552
4553 ImplicitConversionSequence::CompareKind Result =
4554 ImplicitConversionSequence::Indistinguishable;
4555
4556 // Two implicit conversion sequences of the same form are
4557 // indistinguishable conversion sequences unless one of the
4558 // following rules apply: (C++ 13.3.3.2p3):
4559
4560 // List-initialization sequence L1 is a better conversion sequence than
4561 // list-initialization sequence L2 if:
4562 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4563 // if not that,
4564 // — L1 and L2 convert to arrays of the same element type, and either the
4565 // number of elements n_1 initialized by L1 is less than the number of
4566 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4567 // an array of unknown bound and L1 does not,
4568 // even if one of the other rules in this paragraph would otherwise apply.
4569 if (!ICS1.isBad()) {
4570 bool StdInit1 = false, StdInit2 = false;
4571 if (ICS1.hasInitializerListContainerType())
4572 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4573 Element: nullptr);
4574 if (ICS2.hasInitializerListContainerType())
4575 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4576 Element: nullptr);
4577 if (StdInit1 != StdInit2)
4578 return StdInit1 ? ImplicitConversionSequence::Better
4579 : ImplicitConversionSequence::Worse;
4580
4581 if (ICS1.hasInitializerListContainerType() &&
4582 ICS2.hasInitializerListContainerType())
4583 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4584 T: ICS1.getInitializerListContainerType()))
4585 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4586 T: ICS2.getInitializerListContainerType())) {
4587 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4588 T2: CAT2->getElementType())) {
4589 // Both to arrays of the same element type
4590 if (CAT1->getSize() != CAT2->getSize())
4591 // Different sized, the smaller wins
4592 return CAT1->getSize().ult(RHS: CAT2->getSize())
4593 ? ImplicitConversionSequence::Better
4594 : ImplicitConversionSequence::Worse;
4595 if (ICS1.isInitializerListOfIncompleteArray() !=
4596 ICS2.isInitializerListOfIncompleteArray())
4597 // One is incomplete, it loses
4598 return ICS2.isInitializerListOfIncompleteArray()
4599 ? ImplicitConversionSequence::Better
4600 : ImplicitConversionSequence::Worse;
4601 }
4602 }
4603 }
4604
4605 if (ICS1.isStandard())
4606 // Standard conversion sequence S1 is a better conversion sequence than
4607 // standard conversion sequence S2 if [...]
4608 Result = CompareStandardConversionSequences(S, Loc,
4609 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4610 else if (ICS1.isUserDefined()) {
4611 // With lazy template loading, it is possible to find non-canonical
4612 // FunctionDecls, depending on when redecl chains are completed. Make sure
4613 // to compare the canonical decls of conversion functions. This avoids
4614 // ambiguity problems for templated conversion operators.
4615 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4616 if (ConvFunc1)
4617 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4618 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4619 if (ConvFunc2)
4620 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4621 // User-defined conversion sequence U1 is a better conversion
4622 // sequence than another user-defined conversion sequence U2 if
4623 // they contain the same user-defined conversion function or
4624 // constructor and if the second standard conversion sequence of
4625 // U1 is better than the second standard conversion sequence of
4626 // U2 (C++ 13.3.3.2p3).
4627 if (ConvFunc1 == ConvFunc2)
4628 Result = CompareStandardConversionSequences(S, Loc,
4629 SCS1: ICS1.UserDefined.After,
4630 SCS2: ICS2.UserDefined.After);
4631 else
4632 Result = compareConversionFunctions(S,
4633 Function1: ICS1.UserDefined.ConversionFunction,
4634 Function2: ICS2.UserDefined.ConversionFunction);
4635 }
4636
4637 return Result;
4638}
4639
4640// Per 13.3.3.2p3, compare the given standard conversion sequences to
4641// determine if one is a proper subset of the other.
4642static ImplicitConversionSequence::CompareKind
4643compareStandardConversionSubsets(ASTContext &Context,
4644 const StandardConversionSequence& SCS1,
4645 const StandardConversionSequence& SCS2) {
4646 ImplicitConversionSequence::CompareKind Result
4647 = ImplicitConversionSequence::Indistinguishable;
4648
4649 // the identity conversion sequence is considered to be a subsequence of
4650 // any non-identity conversion sequence
4651 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4652 return ImplicitConversionSequence::Better;
4653 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4654 return ImplicitConversionSequence::Worse;
4655
4656 if (SCS1.Second != SCS2.Second) {
4657 if (SCS1.Second == ICK_Identity)
4658 Result = ImplicitConversionSequence::Better;
4659 else if (SCS2.Second == ICK_Identity)
4660 Result = ImplicitConversionSequence::Worse;
4661 else
4662 return ImplicitConversionSequence::Indistinguishable;
4663 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4664 return ImplicitConversionSequence::Indistinguishable;
4665
4666 if (SCS1.Third == SCS2.Third) {
4667 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4668 : ImplicitConversionSequence::Indistinguishable;
4669 }
4670
4671 if (SCS1.Third == ICK_Identity)
4672 return Result == ImplicitConversionSequence::Worse
4673 ? ImplicitConversionSequence::Indistinguishable
4674 : ImplicitConversionSequence::Better;
4675
4676 if (SCS2.Third == ICK_Identity)
4677 return Result == ImplicitConversionSequence::Better
4678 ? ImplicitConversionSequence::Indistinguishable
4679 : ImplicitConversionSequence::Worse;
4680
4681 return ImplicitConversionSequence::Indistinguishable;
4682}
4683
4684/// Determine whether one of the given reference bindings is better
4685/// than the other based on what kind of bindings they are.
4686static bool
4687isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4688 const StandardConversionSequence &SCS2) {
4689 // C++0x [over.ics.rank]p3b4:
4690 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4691 // implicit object parameter of a non-static member function declared
4692 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4693 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4694 // lvalue reference to a function lvalue and S2 binds an rvalue
4695 // reference*.
4696 //
4697 // FIXME: Rvalue references. We're going rogue with the above edits,
4698 // because the semantics in the current C++0x working paper (N3225 at the
4699 // time of this writing) break the standard definition of std::forward
4700 // and std::reference_wrapper when dealing with references to functions.
4701 // Proposed wording changes submitted to CWG for consideration.
4702 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4703 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4704 return false;
4705
4706 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4707 SCS2.IsLvalueReference) ||
4708 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4709 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4710}
4711
4712enum class FixedEnumPromotion {
4713 None,
4714 ToUnderlyingType,
4715 ToPromotedUnderlyingType
4716};
4717
4718/// Returns kind of fixed enum promotion the \a SCS uses.
4719static FixedEnumPromotion
4720getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4721
4722 if (SCS.Second != ICK_Integral_Promotion)
4723 return FixedEnumPromotion::None;
4724
4725 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4726 if (!Enum)
4727 return FixedEnumPromotion::None;
4728
4729 if (!Enum->isFixed())
4730 return FixedEnumPromotion::None;
4731
4732 QualType UnderlyingType = Enum->getIntegerType();
4733 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4734 return FixedEnumPromotion::ToUnderlyingType;
4735
4736 return FixedEnumPromotion::ToPromotedUnderlyingType;
4737}
4738
4739/// CompareStandardConversionSequences - Compare two standard
4740/// conversion sequences to determine whether one is better than the
4741/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4742static ImplicitConversionSequence::CompareKind
4743CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4744 const StandardConversionSequence& SCS1,
4745 const StandardConversionSequence& SCS2)
4746{
4747 // Standard conversion sequence S1 is a better conversion sequence
4748 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4749
4750 // -- S1 is a proper subsequence of S2 (comparing the conversion
4751 // sequences in the canonical form defined by 13.3.3.1.1,
4752 // excluding any Lvalue Transformation; the identity conversion
4753 // sequence is considered to be a subsequence of any
4754 // non-identity conversion sequence) or, if not that,
4755 if (ImplicitConversionSequence::CompareKind CK
4756 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4757 return CK;
4758
4759 // -- the rank of S1 is better than the rank of S2 (by the rules
4760 // defined below), or, if not that,
4761 ImplicitConversionRank Rank1 = SCS1.getRank();
4762 ImplicitConversionRank Rank2 = SCS2.getRank();
4763 if (Rank1 < Rank2)
4764 return ImplicitConversionSequence::Better;
4765 else if (Rank2 < Rank1)
4766 return ImplicitConversionSequence::Worse;
4767
4768 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4769 // are indistinguishable unless one of the following rules
4770 // applies:
4771
4772 // A conversion that is not a conversion of a pointer, or
4773 // pointer to member, to bool is better than another conversion
4774 // that is such a conversion.
4775 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4776 return SCS2.isPointerConversionToBool()
4777 ? ImplicitConversionSequence::Better
4778 : ImplicitConversionSequence::Worse;
4779
4780 // C++14 [over.ics.rank]p4b2:
4781 // This is retroactively applied to C++11 by CWG 1601.
4782 //
4783 // A conversion that promotes an enumeration whose underlying type is fixed
4784 // to its underlying type is better than one that promotes to the promoted
4785 // underlying type, if the two are different.
4786 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4787 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4788 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4789 FEP1 != FEP2)
4790 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4791 ? ImplicitConversionSequence::Better
4792 : ImplicitConversionSequence::Worse;
4793
4794 // C++ [over.ics.rank]p4b2:
4795 //
4796 // If class B is derived directly or indirectly from class A,
4797 // conversion of B* to A* is better than conversion of B* to
4798 // void*, and conversion of A* to void* is better than conversion
4799 // of B* to void*.
4800 bool SCS1ConvertsToVoid
4801 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4802 bool SCS2ConvertsToVoid
4803 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4804 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4805 // Exactly one of the conversion sequences is a conversion to
4806 // a void pointer; it's the worse conversion.
4807 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4808 : ImplicitConversionSequence::Worse;
4809 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4810 // Neither conversion sequence converts to a void pointer; compare
4811 // their derived-to-base conversions.
4812 if (ImplicitConversionSequence::CompareKind DerivedCK
4813 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4814 return DerivedCK;
4815 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4816 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4817 // Both conversion sequences are conversions to void
4818 // pointers. Compare the source types to determine if there's an
4819 // inheritance relationship in their sources.
4820 QualType FromType1 = SCS1.getFromType();
4821 QualType FromType2 = SCS2.getFromType();
4822
4823 // Adjust the types we're converting from via the array-to-pointer
4824 // conversion, if we need to.
4825 if (SCS1.First == ICK_Array_To_Pointer)
4826 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4827 if (SCS2.First == ICK_Array_To_Pointer)
4828 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4829
4830 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4831 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4832
4833 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4834 return ImplicitConversionSequence::Better;
4835 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4836 return ImplicitConversionSequence::Worse;
4837
4838 // Objective-C++: If one interface is more specific than the
4839 // other, it is the better one.
4840 const ObjCObjectPointerType* FromObjCPtr1
4841 = FromType1->getAs<ObjCObjectPointerType>();
4842 const ObjCObjectPointerType* FromObjCPtr2
4843 = FromType2->getAs<ObjCObjectPointerType>();
4844 if (FromObjCPtr1 && FromObjCPtr2) {
4845 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4846 RHSOPT: FromObjCPtr2);
4847 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4848 RHSOPT: FromObjCPtr1);
4849 if (AssignLeft != AssignRight) {
4850 return AssignLeft? ImplicitConversionSequence::Better
4851 : ImplicitConversionSequence::Worse;
4852 }
4853 }
4854 }
4855
4856 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4857 // Check for a better reference binding based on the kind of bindings.
4858 if (isBetterReferenceBindingKind(SCS1, SCS2))
4859 return ImplicitConversionSequence::Better;
4860 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4861 return ImplicitConversionSequence::Worse;
4862 }
4863
4864 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4865 // bullet 3).
4866 if (ImplicitConversionSequence::CompareKind QualCK
4867 = CompareQualificationConversions(S, SCS1, SCS2))
4868 return QualCK;
4869
4870 if (ImplicitConversionSequence::CompareKind ObtCK =
4871 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4872 return ObtCK;
4873
4874 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4875 // C++ [over.ics.rank]p3b4:
4876 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4877 // which the references refer are the same type except for
4878 // top-level cv-qualifiers, and the type to which the reference
4879 // initialized by S2 refers is more cv-qualified than the type
4880 // to which the reference initialized by S1 refers.
4881 QualType T1 = SCS1.getToType(Idx: 2);
4882 QualType T2 = SCS2.getToType(Idx: 2);
4883 T1 = S.Context.getCanonicalType(T: T1);
4884 T2 = S.Context.getCanonicalType(T: T2);
4885 Qualifiers T1Quals, T2Quals;
4886 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4887 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4888 if (UnqualT1 == UnqualT2) {
4889 // Objective-C++ ARC: If the references refer to objects with different
4890 // lifetimes, prefer bindings that don't change lifetime.
4891 if (SCS1.ObjCLifetimeConversionBinding !=
4892 SCS2.ObjCLifetimeConversionBinding) {
4893 return SCS1.ObjCLifetimeConversionBinding
4894 ? ImplicitConversionSequence::Worse
4895 : ImplicitConversionSequence::Better;
4896 }
4897
4898 // If the type is an array type, promote the element qualifiers to the
4899 // type for comparison.
4900 if (isa<ArrayType>(Val: T1) && T1Quals)
4901 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4902 if (isa<ArrayType>(Val: T2) && T2Quals)
4903 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4904 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4905 return ImplicitConversionSequence::Better;
4906 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4907 return ImplicitConversionSequence::Worse;
4908 }
4909 }
4910
4911 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4912 // floating-to-integral conversion if the integral conversion
4913 // is between types of the same size.
4914 // For example:
4915 // void f(float);
4916 // void f(int);
4917 // int main {
4918 // long a;
4919 // f(a);
4920 // }
4921 // Here, MSVC will call f(int) instead of generating a compile error
4922 // as clang will do in standard mode.
4923 if (S.getLangOpts().MSVCCompat &&
4924 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4925 SCS1.Second == ICK_Integral_Conversion &&
4926 SCS2.Second == ICK_Floating_Integral &&
4927 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4928 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4929 return ImplicitConversionSequence::Better;
4930
4931 // Prefer a compatible vector conversion over a lax vector conversion
4932 // For example:
4933 //
4934 // typedef float __v4sf __attribute__((__vector_size__(16)));
4935 // void f(vector float);
4936 // void f(vector signed int);
4937 // int main() {
4938 // __v4sf a;
4939 // f(a);
4940 // }
4941 // Here, we'd like to choose f(vector float) and not
4942 // report an ambiguous call error
4943 if (SCS1.Second == ICK_Vector_Conversion &&
4944 SCS2.Second == ICK_Vector_Conversion) {
4945 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4946 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4947 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4948 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4949
4950 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4951 return SCS1IsCompatibleVectorConversion
4952 ? ImplicitConversionSequence::Better
4953 : ImplicitConversionSequence::Worse;
4954 }
4955
4956 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4957 SCS2.Second == ICK_SVE_Vector_Conversion) {
4958 bool SCS1IsCompatibleSVEVectorConversion =
4959 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4960 bool SCS2IsCompatibleSVEVectorConversion =
4961 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4962
4963 if (SCS1IsCompatibleSVEVectorConversion !=
4964 SCS2IsCompatibleSVEVectorConversion)
4965 return SCS1IsCompatibleSVEVectorConversion
4966 ? ImplicitConversionSequence::Better
4967 : ImplicitConversionSequence::Worse;
4968 }
4969
4970 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4971 SCS2.Second == ICK_RVV_Vector_Conversion) {
4972 bool SCS1IsCompatibleRVVVectorConversion =
4973 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4974 bool SCS2IsCompatibleRVVVectorConversion =
4975 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4976
4977 if (SCS1IsCompatibleRVVVectorConversion !=
4978 SCS2IsCompatibleRVVVectorConversion)
4979 return SCS1IsCompatibleRVVVectorConversion
4980 ? ImplicitConversionSequence::Better
4981 : ImplicitConversionSequence::Worse;
4982 }
4983 return ImplicitConversionSequence::Indistinguishable;
4984}
4985
4986/// CompareOverflowBehaviorConversions - Compares two standard conversion
4987/// sequences to determine whether they can be ranked based on their
4988/// OverflowBehaviorType's underlying type.
4989static ImplicitConversionSequence::CompareKind
4990CompareOverflowBehaviorConversions(Sema &S,
4991 const StandardConversionSequence &SCS1,
4992 const StandardConversionSequence &SCS2) {
4993
4994 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4995 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4996 return ImplicitConversionSequence::Better;
4997
4998 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4999 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
5000 return ImplicitConversionSequence::Worse;
5001
5002 return ImplicitConversionSequence::Indistinguishable;
5003}
5004
5005/// CompareQualificationConversions - Compares two standard conversion
5006/// sequences to determine whether they can be ranked based on their
5007/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
5008static ImplicitConversionSequence::CompareKind
5009CompareQualificationConversions(Sema &S,
5010 const StandardConversionSequence& SCS1,
5011 const StandardConversionSequence& SCS2) {
5012 // C++ [over.ics.rank]p3:
5013 // -- S1 and S2 differ only in their qualification conversion and
5014 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
5015 // [C++98]
5016 // [...] and the cv-qualification signature of type T1 is a proper subset
5017 // of the cv-qualification signature of type T2, and S1 is not the
5018 // deprecated string literal array-to-pointer conversion (4.2).
5019 // [C++2a]
5020 // [...] where T1 can be converted to T2 by a qualification conversion.
5021 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5022 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5023 return ImplicitConversionSequence::Indistinguishable;
5024
5025 // FIXME: the example in the standard doesn't use a qualification
5026 // conversion (!)
5027 QualType T1 = SCS1.getToType(Idx: 2);
5028 QualType T2 = SCS2.getToType(Idx: 2);
5029 T1 = S.Context.getCanonicalType(T: T1);
5030 T2 = S.Context.getCanonicalType(T: T2);
5031 assert(!T1->isReferenceType() && !T2->isReferenceType());
5032 Qualifiers T1Quals, T2Quals;
5033 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5034 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5035
5036 // If the types are the same, we won't learn anything by unwrapping
5037 // them.
5038 if (UnqualT1 == UnqualT2)
5039 return ImplicitConversionSequence::Indistinguishable;
5040
5041 // Don't ever prefer a standard conversion sequence that uses the deprecated
5042 // string literal array to pointer conversion.
5043 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5044 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5045
5046 // Objective-C++ ARC:
5047 // Prefer qualification conversions not involving a change in lifetime
5048 // to qualification conversions that do change lifetime.
5049 if (SCS1.QualificationIncludesObjCLifetime &&
5050 !SCS2.QualificationIncludesObjCLifetime)
5051 CanPick1 = false;
5052 if (SCS2.QualificationIncludesObjCLifetime &&
5053 !SCS1.QualificationIncludesObjCLifetime)
5054 CanPick2 = false;
5055
5056 bool ObjCLifetimeConversion;
5057 if (CanPick1 &&
5058 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5059 CanPick1 = false;
5060 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5061 // directions, so we can't short-cut this second check in general.
5062 if (CanPick2 &&
5063 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5064 CanPick2 = false;
5065
5066 if (CanPick1 != CanPick2)
5067 return CanPick1 ? ImplicitConversionSequence::Better
5068 : ImplicitConversionSequence::Worse;
5069 return ImplicitConversionSequence::Indistinguishable;
5070}
5071
5072/// CompareDerivedToBaseConversions - Compares two standard conversion
5073/// sequences to determine whether they can be ranked based on their
5074/// various kinds of derived-to-base conversions (C++
5075/// [over.ics.rank]p4b3). As part of these checks, we also look at
5076/// conversions between Objective-C interface types.
5077static ImplicitConversionSequence::CompareKind
5078CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5079 const StandardConversionSequence& SCS1,
5080 const StandardConversionSequence& SCS2) {
5081 QualType FromType1 = SCS1.getFromType();
5082 QualType ToType1 = SCS1.getToType(Idx: 1);
5083 QualType FromType2 = SCS2.getFromType();
5084 QualType ToType2 = SCS2.getToType(Idx: 1);
5085
5086 // Adjust the types we're converting from via the array-to-pointer
5087 // conversion, if we need to.
5088 if (SCS1.First == ICK_Array_To_Pointer)
5089 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5090 if (SCS2.First == ICK_Array_To_Pointer)
5091 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5092
5093 // Canonicalize all of the types.
5094 FromType1 = S.Context.getCanonicalType(T: FromType1);
5095 ToType1 = S.Context.getCanonicalType(T: ToType1);
5096 FromType2 = S.Context.getCanonicalType(T: FromType2);
5097 ToType2 = S.Context.getCanonicalType(T: ToType2);
5098
5099 // C++ [over.ics.rank]p4b3:
5100 //
5101 // If class B is derived directly or indirectly from class A and
5102 // class C is derived directly or indirectly from B,
5103 //
5104 // Compare based on pointer conversions.
5105 if (SCS1.Second == ICK_Pointer_Conversion &&
5106 SCS2.Second == ICK_Pointer_Conversion &&
5107 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5108 FromType1->isPointerType() && FromType2->isPointerType() &&
5109 ToType1->isPointerType() && ToType2->isPointerType()) {
5110 QualType FromPointee1 =
5111 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5112 QualType ToPointee1 =
5113 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5114 QualType FromPointee2 =
5115 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5116 QualType ToPointee2 =
5117 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5118
5119 // -- conversion of C* to B* is better than conversion of C* to A*,
5120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5121 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5122 return ImplicitConversionSequence::Better;
5123 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5124 return ImplicitConversionSequence::Worse;
5125 }
5126
5127 // -- conversion of B* to A* is better than conversion of C* to A*,
5128 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5129 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5130 return ImplicitConversionSequence::Better;
5131 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5132 return ImplicitConversionSequence::Worse;
5133 }
5134 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5135 SCS2.Second == ICK_Pointer_Conversion) {
5136 const ObjCObjectPointerType *FromPtr1
5137 = FromType1->getAs<ObjCObjectPointerType>();
5138 const ObjCObjectPointerType *FromPtr2
5139 = FromType2->getAs<ObjCObjectPointerType>();
5140 const ObjCObjectPointerType *ToPtr1
5141 = ToType1->getAs<ObjCObjectPointerType>();
5142 const ObjCObjectPointerType *ToPtr2
5143 = ToType2->getAs<ObjCObjectPointerType>();
5144
5145 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5146 // Apply the same conversion ranking rules for Objective-C pointer types
5147 // that we do for C++ pointers to class types. However, we employ the
5148 // Objective-C pseudo-subtyping relationship used for assignment of
5149 // Objective-C pointer types.
5150 bool FromAssignLeft
5151 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5152 bool FromAssignRight
5153 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5154 bool ToAssignLeft
5155 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5156 bool ToAssignRight
5157 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5158
5159 // A conversion to an a non-id object pointer type or qualified 'id'
5160 // type is better than a conversion to 'id'.
5161 if (ToPtr1->isObjCIdType() &&
5162 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5163 return ImplicitConversionSequence::Worse;
5164 if (ToPtr2->isObjCIdType() &&
5165 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5166 return ImplicitConversionSequence::Better;
5167
5168 // A conversion to a non-id object pointer type is better than a
5169 // conversion to a qualified 'id' type
5170 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5171 return ImplicitConversionSequence::Worse;
5172 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5173 return ImplicitConversionSequence::Better;
5174
5175 // A conversion to an a non-Class object pointer type or qualified 'Class'
5176 // type is better than a conversion to 'Class'.
5177 if (ToPtr1->isObjCClassType() &&
5178 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5179 return ImplicitConversionSequence::Worse;
5180 if (ToPtr2->isObjCClassType() &&
5181 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5182 return ImplicitConversionSequence::Better;
5183
5184 // A conversion to a non-Class object pointer type is better than a
5185 // conversion to a qualified 'Class' type.
5186 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5187 return ImplicitConversionSequence::Worse;
5188 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5189 return ImplicitConversionSequence::Better;
5190
5191 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5192 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5193 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5194 (ToAssignLeft != ToAssignRight)) {
5195 if (FromPtr1->isSpecialized()) {
5196 // "conversion of B<A> * to B * is better than conversion of B * to
5197 // C *.
5198 bool IsFirstSame =
5199 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5200 bool IsSecondSame =
5201 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5202 if (IsFirstSame) {
5203 if (!IsSecondSame)
5204 return ImplicitConversionSequence::Better;
5205 } else if (IsSecondSame)
5206 return ImplicitConversionSequence::Worse;
5207 }
5208 return ToAssignLeft? ImplicitConversionSequence::Worse
5209 : ImplicitConversionSequence::Better;
5210 }
5211
5212 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5213 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5214 (FromAssignLeft != FromAssignRight))
5215 return FromAssignLeft? ImplicitConversionSequence::Better
5216 : ImplicitConversionSequence::Worse;
5217 }
5218 }
5219
5220 // Ranking of member-pointer types.
5221 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5222 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5223 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5224 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5225 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5226 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5227 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5228 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5229 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5230 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5231 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5232 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5233 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5234 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5235 return ImplicitConversionSequence::Worse;
5236 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5237 return ImplicitConversionSequence::Better;
5238 }
5239 // conversion of B::* to C::* is better than conversion of A::* to C::*
5240 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5241 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5242 return ImplicitConversionSequence::Better;
5243 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5244 return ImplicitConversionSequence::Worse;
5245 }
5246 }
5247
5248 if (SCS1.Second == ICK_Derived_To_Base) {
5249 // -- conversion of C to B is better than conversion of C to A,
5250 // -- binding of an expression of type C to a reference of type
5251 // B& is better than binding an expression of type C to a
5252 // reference of type A&,
5253 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5254 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5255 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5256 return ImplicitConversionSequence::Better;
5257 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5258 return ImplicitConversionSequence::Worse;
5259 }
5260
5261 // -- conversion of B to A is better than conversion of C to A.
5262 // -- binding of an expression of type B to a reference of type
5263 // A& is better than binding an expression of type C to a
5264 // reference of type A&,
5265 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5266 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5267 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5268 return ImplicitConversionSequence::Better;
5269 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5270 return ImplicitConversionSequence::Worse;
5271 }
5272 }
5273
5274 return ImplicitConversionSequence::Indistinguishable;
5275}
5276
5277static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5278 if (!T.getQualifiers().hasUnaligned())
5279 return T;
5280
5281 Qualifiers Q;
5282 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5283 Q.removeUnaligned();
5284 return Ctx.getQualifiedType(T, Qs: Q);
5285}
5286
5287Sema::ReferenceCompareResult
5288Sema::CompareReferenceRelationship(SourceLocation Loc,
5289 QualType OrigT1, QualType OrigT2,
5290 ReferenceConversions *ConvOut) {
5291 assert(!OrigT1->isReferenceType() &&
5292 "T1 must be the pointee type of the reference type");
5293 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5294
5295 QualType T1 = Context.getCanonicalType(T: OrigT1);
5296 QualType T2 = Context.getCanonicalType(T: OrigT2);
5297 Qualifiers T1Quals, T2Quals;
5298 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5299 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5300
5301 ReferenceConversions ConvTmp;
5302 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5303 Conv = ReferenceConversions();
5304
5305 // C++2a [dcl.init.ref]p4:
5306 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5307 // reference-related to "cv2 T2" if T1 is similar to T2, or
5308 // T1 is a base class of T2.
5309 // "cv1 T1" is reference-compatible with "cv2 T2" if
5310 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5311 // "pointer to cv1 T1" via a standard conversion sequence.
5312
5313 // Check for standard conversions we can apply to pointers: derived-to-base
5314 // conversions, ObjC pointer conversions, and function pointer conversions.
5315 // (Qualification conversions are checked last.)
5316 if (UnqualT1 == UnqualT2) {
5317 // Nothing to do.
5318 } else if (isCompleteType(Loc, T: OrigT2) &&
5319 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5320 Conv |= ReferenceConversions::DerivedToBase;
5321 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5322 UnqualT2->isObjCObjectOrInterfaceType() &&
5323 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5324 Conv |= ReferenceConversions::ObjC;
5325 else if (UnqualT2->isFunctionType() &&
5326 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5327 Conv |= ReferenceConversions::Function;
5328 // No need to check qualifiers; function types don't have them.
5329 return Ref_Compatible;
5330 }
5331 bool ConvertedReferent = Conv != 0;
5332
5333 // We can have a qualification conversion. Compute whether the types are
5334 // similar at the same time.
5335 bool PreviousToQualsIncludeConst = true;
5336 bool TopLevel = true;
5337 do {
5338 if (T1 == T2)
5339 break;
5340
5341 // We will need a qualification conversion.
5342 Conv |= ReferenceConversions::Qualification;
5343
5344 // Track whether we performed a qualification conversion anywhere other
5345 // than the top level. This matters for ranking reference bindings in
5346 // overload resolution.
5347 if (!TopLevel)
5348 Conv |= ReferenceConversions::NestedQualification;
5349
5350 // MS compiler ignores __unaligned qualifier for references; do the same.
5351 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5352 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5353
5354 // If we find a qualifier mismatch, the types are not reference-compatible,
5355 // but are still be reference-related if they're similar.
5356 bool ObjCLifetimeConversion = false;
5357 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5358 PreviousToQualsIncludeConst,
5359 ObjCLifetimeConversion, Ctx: getASTContext()))
5360 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5361 ? Ref_Related
5362 : Ref_Incompatible;
5363
5364 // FIXME: Should we track this for any level other than the first?
5365 if (ObjCLifetimeConversion)
5366 Conv |= ReferenceConversions::ObjCLifetime;
5367
5368 TopLevel = false;
5369 } while (Context.UnwrapSimilarTypes(T1, T2));
5370
5371 // At this point, if the types are reference-related, we must either have the
5372 // same inner type (ignoring qualifiers), or must have already worked out how
5373 // to convert the referent.
5374 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5375 ? Ref_Compatible
5376 : Ref_Incompatible;
5377}
5378
5379/// Look for a user-defined conversion to a value reference-compatible
5380/// with DeclType. Return true if something definite is found.
5381static bool
5382FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5383 QualType DeclType, SourceLocation DeclLoc,
5384 Expr *Init, QualType T2, bool AllowRvalues,
5385 bool AllowExplicit) {
5386 assert(T2->isRecordType() && "Can only find conversions of record types.");
5387 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5388 OverloadCandidateSet CandidateSet(
5389 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5390 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5391 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5392 NamedDecl *D = *I;
5393 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5394 if (isa<UsingShadowDecl>(Val: D))
5395 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5396
5397 FunctionTemplateDecl *ConvTemplate
5398 = dyn_cast<FunctionTemplateDecl>(Val: D);
5399 CXXConversionDecl *Conv;
5400 if (ConvTemplate)
5401 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5402 else
5403 Conv = cast<CXXConversionDecl>(Val: D);
5404
5405 if (AllowRvalues) {
5406 // If we are initializing an rvalue reference, don't permit conversion
5407 // functions that return lvalues.
5408 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5409 const ReferenceType *RefType
5410 = Conv->getConversionType()->getAs<LValueReferenceType>();
5411 if (RefType && !RefType->getPointeeType()->isFunctionType())
5412 continue;
5413 }
5414
5415 if (!ConvTemplate &&
5416 S.CompareReferenceRelationship(
5417 Loc: DeclLoc,
5418 OrigT1: Conv->getConversionType()
5419 .getNonReferenceType()
5420 .getUnqualifiedType(),
5421 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5422 Sema::Ref_Incompatible)
5423 continue;
5424 } else {
5425 // If the conversion function doesn't return a reference type,
5426 // it can't be considered for this conversion. An rvalue reference
5427 // is only acceptable if its referencee is a function type.
5428
5429 const ReferenceType *RefType =
5430 Conv->getConversionType()->getAs<ReferenceType>();
5431 if (!RefType ||
5432 (!RefType->isLValueReferenceType() &&
5433 !RefType->getPointeeType()->isFunctionType()))
5434 continue;
5435 }
5436
5437 if (ConvTemplate)
5438 S.AddTemplateConversionCandidate(
5439 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5440 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5441 else
5442 S.AddConversionCandidate(
5443 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5444 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5445 }
5446
5447 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5448
5449 OverloadCandidateSet::iterator Best;
5450 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5451 case OR_Success:
5452
5453 assert(Best->HasFinalConversion);
5454
5455 // C++ [over.ics.ref]p1:
5456 //
5457 // [...] If the parameter binds directly to the result of
5458 // applying a conversion function to the argument
5459 // expression, the implicit conversion sequence is a
5460 // user-defined conversion sequence (13.3.3.1.2), with the
5461 // second standard conversion sequence either an identity
5462 // conversion or, if the conversion function returns an
5463 // entity of a type that is a derived class of the parameter
5464 // type, a derived-to-base Conversion.
5465 if (!Best->FinalConversion.DirectBinding)
5466 return false;
5467
5468 ICS.setUserDefined();
5469 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5470 ICS.UserDefined.After = Best->FinalConversion;
5471 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5472 ICS.UserDefined.ConversionFunction = Best->Function;
5473 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5474 ICS.UserDefined.EllipsisConversion = false;
5475 assert(ICS.UserDefined.After.ReferenceBinding &&
5476 ICS.UserDefined.After.DirectBinding &&
5477 "Expected a direct reference binding!");
5478 return true;
5479
5480 case OR_Ambiguous:
5481 ICS.setAmbiguous();
5482 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5483 Cand != CandidateSet.end(); ++Cand)
5484 if (Cand->Best)
5485 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5486 return true;
5487
5488 case OR_No_Viable_Function:
5489 case OR_Deleted:
5490 // There was no suitable conversion, or we found a deleted
5491 // conversion; continue with other checks.
5492 return false;
5493 }
5494
5495 llvm_unreachable("Invalid OverloadResult!");
5496}
5497
5498/// Compute an implicit conversion sequence for reference
5499/// initialization.
5500static ImplicitConversionSequence
5501TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5502 SourceLocation DeclLoc,
5503 bool SuppressUserConversions,
5504 bool AllowExplicit) {
5505 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5506
5507 // Most paths end in a failed conversion.
5508 ImplicitConversionSequence ICS;
5509 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5510
5511 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5512 QualType T2 = Init->getType();
5513
5514 // If the initializer is the address of an overloaded function, try
5515 // to resolve the overloaded function. If all goes well, T2 is the
5516 // type of the resulting function.
5517 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5518 DeclAccessPair Found;
5519 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5520 Complain: false, Found))
5521 T2 = Fn->getType();
5522 }
5523
5524 // Compute some basic properties of the types and the initializer.
5525 bool isRValRef = DeclType->isRValueReferenceType();
5526 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5527
5528 Sema::ReferenceConversions RefConv;
5529 Sema::ReferenceCompareResult RefRelationship =
5530 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5531
5532 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5533 ICS.setStandard();
5534 ICS.Standard.First = ICK_Identity;
5535 // FIXME: A reference binding can be a function conversion too. We should
5536 // consider that when ordering reference-to-function bindings.
5537 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5538 ? ICK_Derived_To_Base
5539 : (RefConv & Sema::ReferenceConversions::ObjC)
5540 ? ICK_Compatible_Conversion
5541 : ICK_Identity;
5542 ICS.Standard.Dimension = ICK_Identity;
5543 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5544 // a reference binding that performs a non-top-level qualification
5545 // conversion as a qualification conversion, not as an identity conversion.
5546 ICS.Standard.Third = (RefConv &
5547 Sema::ReferenceConversions::NestedQualification)
5548 ? ICK_Qualification
5549 : ICK_Identity;
5550 ICS.Standard.setFromType(T2);
5551 ICS.Standard.setToType(Idx: 0, T: T2);
5552 ICS.Standard.setToType(Idx: 1, T: T1);
5553 ICS.Standard.setToType(Idx: 2, T: T1);
5554 ICS.Standard.ReferenceBinding = true;
5555 ICS.Standard.DirectBinding = BindsDirectly;
5556 ICS.Standard.IsLvalueReference = !isRValRef;
5557 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5558 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5559 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5560 ICS.Standard.ObjCLifetimeConversionBinding =
5561 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5562 ICS.Standard.FromBracedInitList = false;
5563 ICS.Standard.CopyConstructor = nullptr;
5564 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5565 };
5566
5567 // C++0x [dcl.init.ref]p5:
5568 // A reference to type "cv1 T1" is initialized by an expression
5569 // of type "cv2 T2" as follows:
5570
5571 // -- If reference is an lvalue reference and the initializer expression
5572 if (!isRValRef) {
5573 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5574 // reference-compatible with "cv2 T2," or
5575 //
5576 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5577 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5578 // C++ [over.ics.ref]p1:
5579 // When a parameter of reference type binds directly (8.5.3)
5580 // to an argument expression, the implicit conversion sequence
5581 // is the identity conversion, unless the argument expression
5582 // has a type that is a derived class of the parameter type,
5583 // in which case the implicit conversion sequence is a
5584 // derived-to-base Conversion (13.3.3.1).
5585 SetAsReferenceBinding(/*BindsDirectly=*/true);
5586
5587 // Nothing more to do: the inaccessibility/ambiguity check for
5588 // derived-to-base conversions is suppressed when we're
5589 // computing the implicit conversion sequence (C++
5590 // [over.best.ics]p2).
5591 return ICS;
5592 }
5593
5594 // -- has a class type (i.e., T2 is a class type), where T1 is
5595 // not reference-related to T2, and can be implicitly
5596 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5597 // is reference-compatible with "cv3 T3" 92) (this
5598 // conversion is selected by enumerating the applicable
5599 // conversion functions (13.3.1.6) and choosing the best
5600 // one through overload resolution (13.3)),
5601 if (!SuppressUserConversions && T2->isRecordType() &&
5602 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5603 RefRelationship == Sema::Ref_Incompatible) {
5604 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5605 Init, T2, /*AllowRvalues=*/false,
5606 AllowExplicit))
5607 return ICS;
5608 }
5609 }
5610
5611 // -- Otherwise, the reference shall be an lvalue reference to a
5612 // non-volatile const type (i.e., cv1 shall be const), or the reference
5613 // shall be an rvalue reference.
5614 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5615 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5616 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5617 return ICS;
5618 }
5619
5620 // -- If the initializer expression
5621 //
5622 // -- is an xvalue, class prvalue, array prvalue or function
5623 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5624 if (RefRelationship == Sema::Ref_Compatible &&
5625 (InitCategory.isXValue() ||
5626 (InitCategory.isPRValue() &&
5627 (T2->isRecordType() || T2->isArrayType())) ||
5628 (InitCategory.isLValue() && T2->isFunctionType()))) {
5629 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5630 // binding unless we're binding to a class prvalue.
5631 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5632 // allow the use of rvalue references in C++98/03 for the benefit of
5633 // standard library implementors; therefore, we need the xvalue check here.
5634 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5635 !(InitCategory.isPRValue() || T2->isRecordType()));
5636 return ICS;
5637 }
5638
5639 // -- has a class type (i.e., T2 is a class type), where T1 is not
5640 // reference-related to T2, and can be implicitly converted to
5641 // an xvalue, class prvalue, or function lvalue of type
5642 // "cv3 T3", where "cv1 T1" is reference-compatible with
5643 // "cv3 T3",
5644 //
5645 // then the reference is bound to the value of the initializer
5646 // expression in the first case and to the result of the conversion
5647 // in the second case (or, in either case, to an appropriate base
5648 // class subobject).
5649 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5650 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5651 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5652 Init, T2, /*AllowRvalues=*/true,
5653 AllowExplicit)) {
5654 // In the second case, if the reference is an rvalue reference
5655 // and the second standard conversion sequence of the
5656 // user-defined conversion sequence includes an lvalue-to-rvalue
5657 // conversion, the program is ill-formed.
5658 if (ICS.isUserDefined() && isRValRef &&
5659 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5660 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5661
5662 return ICS;
5663 }
5664
5665 // A temporary of function type cannot be created; don't even try.
5666 if (T1->isFunctionType())
5667 return ICS;
5668
5669 // -- Otherwise, a temporary of type "cv1 T1" is created and
5670 // initialized from the initializer expression using the
5671 // rules for a non-reference copy initialization (8.5). The
5672 // reference is then bound to the temporary. If T1 is
5673 // reference-related to T2, cv1 must be the same
5674 // cv-qualification as, or greater cv-qualification than,
5675 // cv2; otherwise, the program is ill-formed.
5676 if (RefRelationship == Sema::Ref_Related) {
5677 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5678 // we would be reference-compatible or reference-compatible with
5679 // added qualification. But that wasn't the case, so the reference
5680 // initialization fails.
5681 //
5682 // Note that we only want to check address spaces and cvr-qualifiers here.
5683 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5684 Qualifiers T1Quals = T1.getQualifiers();
5685 Qualifiers T2Quals = T2.getQualifiers();
5686 T1Quals.removeObjCGCAttr();
5687 T1Quals.removeObjCLifetime();
5688 T2Quals.removeObjCGCAttr();
5689 T2Quals.removeObjCLifetime();
5690 // MS compiler ignores __unaligned qualifier for references; do the same.
5691 T1Quals.removeUnaligned();
5692 T2Quals.removeUnaligned();
5693 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5694 return ICS;
5695 }
5696
5697 // If at least one of the types is a class type, the types are not
5698 // related, and we aren't allowed any user conversions, the
5699 // reference binding fails. This case is important for breaking
5700 // recursion, since TryImplicitConversion below will attempt to
5701 // create a temporary through the use of a copy constructor.
5702 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5703 (T1->isRecordType() || T2->isRecordType()))
5704 return ICS;
5705
5706 // If T1 is reference-related to T2 and the reference is an rvalue
5707 // reference, the initializer expression shall not be an lvalue.
5708 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5709 Init->Classify(Ctx&: S.Context).isLValue()) {
5710 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5711 return ICS;
5712 }
5713
5714 // C++ [over.ics.ref]p2:
5715 // When a parameter of reference type is not bound directly to
5716 // an argument expression, the conversion sequence is the one
5717 // required to convert the argument expression to the
5718 // underlying type of the reference according to
5719 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5720 // to copy-initializing a temporary of the underlying type with
5721 // the argument expression. Any difference in top-level
5722 // cv-qualification is subsumed by the initialization itself
5723 // and does not constitute a conversion.
5724 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5725 AllowExplicit: AllowedExplicit::None,
5726 /*InOverloadResolution=*/false,
5727 /*CStyle=*/false,
5728 /*AllowObjCWritebackConversion=*/false,
5729 /*AllowObjCConversionOnExplicit=*/false);
5730
5731 // Of course, that's still a reference binding.
5732 if (ICS.isStandard()) {
5733 ICS.Standard.ReferenceBinding = true;
5734 ICS.Standard.IsLvalueReference = !isRValRef;
5735 ICS.Standard.BindsToFunctionLvalue = false;
5736 ICS.Standard.BindsToRvalue = true;
5737 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5738 ICS.Standard.ObjCLifetimeConversionBinding = false;
5739 } else if (ICS.isUserDefined()) {
5740 const ReferenceType *LValRefType =
5741 ICS.UserDefined.ConversionFunction->getReturnType()
5742 ->getAs<LValueReferenceType>();
5743
5744 // C++ [over.ics.ref]p3:
5745 // Except for an implicit object parameter, for which see 13.3.1, a
5746 // standard conversion sequence cannot be formed if it requires [...]
5747 // binding an rvalue reference to an lvalue other than a function
5748 // lvalue.
5749 // Note that the function case is not possible here.
5750 if (isRValRef && LValRefType) {
5751 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5752 return ICS;
5753 }
5754
5755 ICS.UserDefined.After.ReferenceBinding = true;
5756 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5757 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5758 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5759 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5760 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5761 ICS.UserDefined.After.FromBracedInitList = false;
5762 }
5763
5764 return ICS;
5765}
5766
5767static ImplicitConversionSequence
5768TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5769 bool SuppressUserConversions,
5770 bool InOverloadResolution,
5771 bool AllowObjCWritebackConversion,
5772 bool AllowExplicit = false);
5773
5774/// TryListConversion - Try to copy-initialize a value of type ToType from the
5775/// initializer list From.
5776static ImplicitConversionSequence
5777TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5778 bool SuppressUserConversions,
5779 bool InOverloadResolution,
5780 bool AllowObjCWritebackConversion) {
5781 // C++11 [over.ics.list]p1:
5782 // When an argument is an initializer list, it is not an expression and
5783 // special rules apply for converting it to a parameter type.
5784
5785 ImplicitConversionSequence Result;
5786 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5787
5788 // We need a complete type for what follows. With one C++20 exception,
5789 // incomplete types can never be initialized from init lists.
5790 QualType InitTy = ToType;
5791 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5792 if (AT && S.getLangOpts().CPlusPlus20)
5793 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5794 // C++20 allows list initialization of an incomplete array type.
5795 InitTy = IAT->getElementType();
5796 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5797 return Result;
5798
5799 // C++20 [over.ics.list]/2:
5800 // If the initializer list is a designated-initializer-list, a conversion
5801 // is only possible if the parameter has an aggregate type
5802 //
5803 // FIXME: The exception for reference initialization here is not part of the
5804 // language rules, but follow other compilers in adding it as a tentative DR
5805 // resolution.
5806 bool IsDesignatedInit = From->hasDesignatedInit();
5807 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5808 IsDesignatedInit)
5809 return Result;
5810
5811 // Per DR1467 and DR2137:
5812 // If the parameter type is an aggregate class X and the initializer list
5813 // has a single element of type cv U, where U is X or a class derived from
5814 // X, the implicit conversion sequence is the one required to convert the
5815 // element to the parameter type.
5816 //
5817 // Otherwise, if the parameter type is a character array [... ]
5818 // and the initializer list has a single element that is an
5819 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5820 // implicit conversion sequence is the identity conversion.
5821 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5822 if (ToType->isRecordType() && ToType->isAggregateType()) {
5823 QualType InitType = From->getInit(Init: 0)->getType();
5824 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5825 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5826 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5827 SuppressUserConversions,
5828 InOverloadResolution,
5829 AllowObjCWritebackConversion);
5830 }
5831
5832 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5833 InitializedEntity Entity =
5834 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5835 /*Consumed=*/false);
5836 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5837 Result.setStandard();
5838 Result.Standard.setAsIdentityConversion();
5839 Result.Standard.setFromType(ToType);
5840 Result.Standard.setAllToTypes(ToType);
5841 return Result;
5842 }
5843 }
5844 }
5845
5846 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5847 // C++11 [over.ics.list]p2:
5848 // If the parameter type is std::initializer_list<X> or "array of X" and
5849 // all the elements can be implicitly converted to X, the implicit
5850 // conversion sequence is the worst conversion necessary to convert an
5851 // element of the list to X.
5852 //
5853 // C++14 [over.ics.list]p3:
5854 // Otherwise, if the parameter type is "array of N X", if the initializer
5855 // list has exactly N elements or if it has fewer than N elements and X is
5856 // default-constructible, and if all the elements of the initializer list
5857 // can be implicitly converted to X, the implicit conversion sequence is
5858 // the worst conversion necessary to convert an element of the list to X.
5859 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5860 unsigned e = From->getNumInits();
5861 ImplicitConversionSequence DfltElt;
5862 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5863 ToType: QualType());
5864 QualType ContTy = ToType;
5865 bool IsUnbounded = false;
5866 if (AT) {
5867 InitTy = AT->getElementType();
5868 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5869 if (CT->getSize().ult(RHS: e)) {
5870 // Too many inits, fatally bad
5871 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5872 ToType);
5873 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5874 return Result;
5875 }
5876 if (CT->getSize().ugt(RHS: e)) {
5877 // Need an init from empty {}, is there one?
5878 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5879 From->getEndLoc(), /*isExplicit=*/false);
5880 EmptyList.setType(S.Context.VoidTy);
5881 DfltElt = TryListConversion(
5882 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5883 InOverloadResolution, AllowObjCWritebackConversion);
5884 if (DfltElt.isBad()) {
5885 // No {} init, fatally bad
5886 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5887 ToType);
5888 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5889 return Result;
5890 }
5891 }
5892 } else {
5893 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5894 IsUnbounded = true;
5895 if (!e) {
5896 // Cannot convert to zero-sized.
5897 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5898 ToType);
5899 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5900 return Result;
5901 }
5902 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5903 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5904 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5905 }
5906 }
5907
5908 Result.setStandard();
5909 Result.Standard.setAsIdentityConversion();
5910 Result.Standard.setFromType(InitTy);
5911 Result.Standard.setAllToTypes(InitTy);
5912 for (unsigned i = 0; i < e; ++i) {
5913 Expr *Init = From->getInit(Init: i);
5914 ImplicitConversionSequence ICS = TryCopyInitialization(
5915 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5916 AllowObjCWritebackConversion);
5917
5918 // Keep the worse conversion seen so far.
5919 // FIXME: Sequences are not totally ordered, so 'worse' can be
5920 // ambiguous. CWG has been informed.
5921 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5922 ICS2: Result) ==
5923 ImplicitConversionSequence::Worse) {
5924 Result = ICS;
5925 // Bail as soon as we find something unconvertible.
5926 if (Result.isBad()) {
5927 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5928 return Result;
5929 }
5930 }
5931 }
5932
5933 // If we needed any implicit {} initialization, compare that now.
5934 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5935 // has been informed that this might not be the best thing.
5936 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5937 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5938 ImplicitConversionSequence::Worse)
5939 Result = DfltElt;
5940 // Record the type being initialized so that we may compare sequences
5941 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5942 return Result;
5943 }
5944
5945 // C++14 [over.ics.list]p4:
5946 // C++11 [over.ics.list]p3:
5947 // Otherwise, if the parameter is a non-aggregate class X and overload
5948 // resolution chooses a single best constructor [...] the implicit
5949 // conversion sequence is a user-defined conversion sequence. If multiple
5950 // constructors are viable but none is better than the others, the
5951 // implicit conversion sequence is a user-defined conversion sequence.
5952 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5953 // This function can deal with initializer lists.
5954 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5955 AllowExplicit: AllowedExplicit::None,
5956 InOverloadResolution, /*CStyle=*/false,
5957 AllowObjCWritebackConversion,
5958 /*AllowObjCConversionOnExplicit=*/false);
5959 }
5960
5961 // C++14 [over.ics.list]p5:
5962 // C++11 [over.ics.list]p4:
5963 // Otherwise, if the parameter has an aggregate type which can be
5964 // initialized from the initializer list [...] the implicit conversion
5965 // sequence is a user-defined conversion sequence.
5966 if (ToType->isAggregateType()) {
5967 // Type is an aggregate, argument is an init list. At this point it comes
5968 // down to checking whether the initialization works.
5969 // FIXME: Find out whether this parameter is consumed or not.
5970 InitializedEntity Entity =
5971 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5972 /*Consumed=*/false);
5973 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5974 From)) {
5975 Result.setUserDefined();
5976 Result.UserDefined.Before.setAsIdentityConversion();
5977 // Initializer lists don't have a type.
5978 Result.UserDefined.Before.setFromType(QualType());
5979 Result.UserDefined.Before.setAllToTypes(QualType());
5980
5981 Result.UserDefined.After.setAsIdentityConversion();
5982 Result.UserDefined.After.setFromType(ToType);
5983 Result.UserDefined.After.setAllToTypes(ToType);
5984 Result.UserDefined.ConversionFunction = nullptr;
5985 }
5986 return Result;
5987 }
5988
5989 // C++14 [over.ics.list]p6:
5990 // C++11 [over.ics.list]p5:
5991 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5992 if (ToType->isReferenceType()) {
5993 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5994 // mention initializer lists in any way. So we go by what list-
5995 // initialization would do and try to extrapolate from that.
5996
5997 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5998
5999 // If the initializer list has a single element that is reference-related
6000 // to the parameter type, we initialize the reference from that.
6001 if (From->getNumInits() == 1 && !IsDesignatedInit) {
6002 Expr *Init = From->getInit(Init: 0);
6003
6004 QualType T2 = Init->getType();
6005
6006 // If the initializer is the address of an overloaded function, try
6007 // to resolve the overloaded function. If all goes well, T2 is the
6008 // type of the resulting function.
6009 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
6010 DeclAccessPair Found;
6011 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
6012 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
6013 T2 = Fn->getType();
6014 }
6015
6016 // Compute some basic properties of the types and the initializer.
6017 Sema::ReferenceCompareResult RefRelationship =
6018 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
6019
6020 if (RefRelationship >= Sema::Ref_Related) {
6021 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
6022 SuppressUserConversions,
6023 /*AllowExplicit=*/false);
6024 }
6025 }
6026
6027 // Otherwise, we bind the reference to a temporary created from the
6028 // initializer list.
6029 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
6030 InOverloadResolution,
6031 AllowObjCWritebackConversion);
6032 if (Result.isFailure())
6033 return Result;
6034 assert(!Result.isEllipsis() &&
6035 "Sub-initialization cannot result in ellipsis conversion.");
6036
6037 // Can we even bind to a temporary?
6038 if (ToType->isRValueReferenceType() ||
6039 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6040 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6041 Result.UserDefined.After;
6042 SCS.ReferenceBinding = true;
6043 SCS.IsLvalueReference = ToType->isLValueReferenceType();
6044 SCS.BindsToRvalue = true;
6045 SCS.BindsToFunctionLvalue = false;
6046 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
6047 SCS.ObjCLifetimeConversionBinding = false;
6048 SCS.FromBracedInitList = false;
6049
6050 } else
6051 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6052 FromExpr: From, ToType);
6053 return Result;
6054 }
6055
6056 // C++14 [over.ics.list]p7:
6057 // C++11 [over.ics.list]p6:
6058 // Otherwise, if the parameter type is not a class:
6059 if (!ToType->isRecordType()) {
6060 // - if the initializer list has one element that is not itself an
6061 // initializer list, the implicit conversion sequence is the one
6062 // required to convert the element to the parameter type.
6063 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6064 // single integer.
6065 unsigned NumInits = From->getNumInits();
6066 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6067 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6068 Result = TryCopyInitialization(
6069 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6070 InOverloadResolution, AllowObjCWritebackConversion);
6071 if (Result.isStandard())
6072 Result.Standard.FromBracedInitList = true;
6073 }
6074 // - if the initializer list has no elements, the implicit conversion
6075 // sequence is the identity conversion.
6076 else if (NumInits == 0) {
6077 Result.setStandard();
6078 Result.Standard.setAsIdentityConversion();
6079 Result.Standard.setFromType(ToType);
6080 Result.Standard.setAllToTypes(ToType);
6081 }
6082 return Result;
6083 }
6084
6085 // C++14 [over.ics.list]p8:
6086 // C++11 [over.ics.list]p7:
6087 // In all cases other than those enumerated above, no conversion is possible
6088 return Result;
6089}
6090
6091/// TryCopyInitialization - Try to copy-initialize a value of type
6092/// ToType from the expression From. Return the implicit conversion
6093/// sequence required to pass this argument, which may be a bad
6094/// conversion sequence (meaning that the argument cannot be passed to
6095/// a parameter of this type). If @p SuppressUserConversions, then we
6096/// do not permit any user-defined conversion sequences.
6097static ImplicitConversionSequence
6098TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6099 bool SuppressUserConversions,
6100 bool InOverloadResolution,
6101 bool AllowObjCWritebackConversion,
6102 bool AllowExplicit) {
6103 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6104 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6105 InOverloadResolution,AllowObjCWritebackConversion);
6106
6107 if (ToType->isReferenceType())
6108 return TryReferenceInit(S, Init: From, DeclType: ToType,
6109 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6110 SuppressUserConversions, AllowExplicit);
6111
6112 return TryImplicitConversion(S, From, ToType,
6113 SuppressUserConversions,
6114 AllowExplicit: AllowedExplicit::None,
6115 InOverloadResolution,
6116 /*CStyle=*/false,
6117 AllowObjCWritebackConversion,
6118 /*AllowObjCConversionOnExplicit=*/false);
6119}
6120
6121static bool TryCopyInitialization(const CanQualType FromQTy,
6122 const CanQualType ToQTy,
6123 Sema &S,
6124 SourceLocation Loc,
6125 ExprValueKind FromVK) {
6126 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6127 ImplicitConversionSequence ICS =
6128 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6129
6130 return !ICS.isBad();
6131}
6132
6133/// TryObjectArgumentInitialization - Try to initialize the object
6134/// parameter of the given member function (@c Method) from the
6135/// expression @p From.
6136static ImplicitConversionSequence TryObjectArgumentInitialization(
6137 Sema &S, SourceLocation Loc, QualType FromType,
6138 Expr::Classification FromClassification, CXXMethodDecl *Method,
6139 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6140 QualType ExplicitParameterType = QualType(),
6141 bool SuppressUserConversion = false) {
6142
6143 // We need to have an object of class type.
6144 if (const auto *PT = FromType->getAs<PointerType>()) {
6145 FromType = PT->getPointeeType();
6146
6147 // When we had a pointer, it's implicitly dereferenced, so we
6148 // better have an lvalue.
6149 assert(FromClassification.isLValue());
6150 }
6151
6152 auto ValueKindFromClassification = [](Expr::Classification C) {
6153 if (C.isPRValue())
6154 return clang::VK_PRValue;
6155 if (C.isXValue())
6156 return VK_XValue;
6157 return clang::VK_LValue;
6158 };
6159
6160 if (Method->isExplicitObjectMemberFunction()) {
6161 if (ExplicitParameterType.isNull())
6162 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6163 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6164 ValueKindFromClassification(FromClassification));
6165 ImplicitConversionSequence ICS = TryCopyInitialization(
6166 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6167 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6168 if (ICS.isBad())
6169 ICS.Bad.FromExpr = nullptr;
6170 return ICS;
6171 }
6172
6173 assert(FromType->isRecordType());
6174
6175 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6176 // C++98 [class.dtor]p2:
6177 // A destructor can be invoked for a const, volatile or const volatile
6178 // object.
6179 // C++98 [over.match.funcs]p4:
6180 // For static member functions, the implicit object parameter is considered
6181 // to match any object (since if the function is selected, the object is
6182 // discarded).
6183 Qualifiers Quals = Method->getMethodQualifiers();
6184 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6185 Quals.addConst();
6186 Quals.addVolatile();
6187 }
6188
6189 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6190
6191 // Set up the conversion sequence as a "bad" conversion, to allow us
6192 // to exit early.
6193 ImplicitConversionSequence ICS;
6194
6195 // C++0x [over.match.funcs]p4:
6196 // For non-static member functions, the type of the implicit object
6197 // parameter is
6198 //
6199 // - "lvalue reference to cv X" for functions declared without a
6200 // ref-qualifier or with the & ref-qualifier
6201 // - "rvalue reference to cv X" for functions declared with the &&
6202 // ref-qualifier
6203 //
6204 // where X is the class of which the function is a member and cv is the
6205 // cv-qualification on the member function declaration.
6206 //
6207 // However, when finding an implicit conversion sequence for the argument, we
6208 // are not allowed to perform user-defined conversions
6209 // (C++ [over.match.funcs]p5). We perform a simplified version of
6210 // reference binding here, that allows class rvalues to bind to
6211 // non-constant references.
6212
6213 // First check the qualifiers.
6214 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6215 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6216 if (ImplicitParamType.getCVRQualifiers() !=
6217 FromTypeCanon.getLocalCVRQualifiers() &&
6218 !ImplicitParamType.isAtLeastAsQualifiedAs(
6219 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6220 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6221 FromType, ToType: ImplicitParamType);
6222 return ICS;
6223 }
6224
6225 if (FromTypeCanon.hasAddressSpace()) {
6226 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6227 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6228 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6229 Ctx: S.getASTContext())) {
6230 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6231 FromType, ToType: ImplicitParamType);
6232 return ICS;
6233 }
6234 }
6235
6236 // Check that we have either the same type or a derived type. It
6237 // affects the conversion rank.
6238 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6239 ImplicitConversionKind SecondKind;
6240 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6241 SecondKind = ICK_Identity;
6242 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6243 SecondKind = ICK_Derived_To_Base;
6244 } else if (!Method->isExplicitObjectMemberFunction()) {
6245 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6246 FromType, ToType: ImplicitParamType);
6247 return ICS;
6248 }
6249
6250 // Check the ref-qualifier.
6251 switch (Method->getRefQualifier()) {
6252 case RQ_None:
6253 // Do nothing; we don't care about lvalueness or rvalueness.
6254 break;
6255
6256 case RQ_LValue:
6257 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6258 // non-const lvalue reference cannot bind to an rvalue
6259 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6260 ToType: ImplicitParamType);
6261 return ICS;
6262 }
6263 break;
6264
6265 case RQ_RValue:
6266 if (!FromClassification.isRValue()) {
6267 // rvalue reference cannot bind to an lvalue
6268 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6269 ToType: ImplicitParamType);
6270 return ICS;
6271 }
6272 break;
6273 }
6274
6275 // Success. Mark this as a reference binding.
6276 ICS.setStandard();
6277 ICS.Standard.setAsIdentityConversion();
6278 ICS.Standard.Second = SecondKind;
6279 ICS.Standard.setFromType(FromType);
6280 ICS.Standard.setAllToTypes(ImplicitParamType);
6281 ICS.Standard.ReferenceBinding = true;
6282 ICS.Standard.DirectBinding = true;
6283 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6284 ICS.Standard.BindsToFunctionLvalue = false;
6285 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6286 ICS.Standard.FromBracedInitList = false;
6287 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6288 = (Method->getRefQualifier() == RQ_None);
6289 return ICS;
6290}
6291
6292/// PerformObjectArgumentInitialization - Perform initialization of
6293/// the implicit object parameter for the given Method with the given
6294/// expression.
6295ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6296 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6297 CXXMethodDecl *Method) {
6298 QualType FromRecordType, DestType;
6299 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6300
6301 if (getLangOpts().HLSL &&
6302 From->getType().getAddressSpace() == LangAS::hlsl_constant) {
6303 QualType CastType = From->getType().getLocalUnqualifiedType().withConst();
6304 From = ImplicitCastExpr::Create(Context, T: CastType, Kind: CK_LValueToRValue, Operand: From,
6305 /*BasePath=*/nullptr, Cat: VK_PRValue,
6306 FPO: FPOptionsOverride());
6307 }
6308
6309 Expr::Classification FromClassification;
6310 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6311 FromRecordType = PT->getPointeeType();
6312 DestType = Method->getThisType();
6313 FromClassification = Expr::Classification::makeSimpleLValue();
6314 } else {
6315 FromRecordType = From->getType();
6316 DestType = ImplicitParamRecordType;
6317 FromClassification = From->Classify(Ctx&: Context);
6318
6319 // CWG2813 [expr.call]p6:
6320 // If the function is an implicit object member function, the object
6321 // expression of the class member access shall be a glvalue [...]
6322 if (From->isPRValue()) {
6323 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6324 BoundToLvalueReference: Method->getRefQualifier() !=
6325 RefQualifierKind::RQ_RValue);
6326 }
6327 }
6328
6329 // Note that we always use the true parent context when performing
6330 // the actual argument initialization.
6331 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6332 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6333 ActingContext: Method->getParent());
6334 if (ICS.isBad()) {
6335 switch (ICS.Bad.Kind) {
6336 case BadConversionSequence::bad_qualifiers: {
6337 Qualifiers FromQs = FromRecordType.getQualifiers();
6338 Qualifiers ToQs = DestType.getQualifiers();
6339 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6340 if (CVR) {
6341 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6342 << Method->getDeclName() << FromRecordType << (CVR - 1)
6343 << From->getSourceRange();
6344 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6345 << Method->getDeclName();
6346 return ExprError();
6347 }
6348 break;
6349 }
6350
6351 case BadConversionSequence::lvalue_ref_to_rvalue:
6352 case BadConversionSequence::rvalue_ref_to_lvalue: {
6353 bool IsRValueQualified =
6354 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6355 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6356 << Method->getDeclName() << FromClassification.isRValue()
6357 << IsRValueQualified;
6358 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6359 << Method->getDeclName();
6360 return ExprError();
6361 }
6362
6363 case BadConversionSequence::no_conversion:
6364 case BadConversionSequence::unrelated_class:
6365 break;
6366
6367 case BadConversionSequence::too_few_initializers:
6368 case BadConversionSequence::too_many_initializers:
6369 llvm_unreachable("Lists are not objects");
6370 }
6371
6372 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6373 << ImplicitParamRecordType << FromRecordType
6374 << From->getSourceRange();
6375 }
6376
6377 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6378 ExprResult FromRes =
6379 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6380 if (FromRes.isInvalid())
6381 return ExprError();
6382 From = FromRes.get();
6383 }
6384
6385 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6386 CastKind CK;
6387 QualType PteeTy = DestType->getPointeeType();
6388 LangAS DestAS =
6389 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6390 if (FromRecordType.getAddressSpace() != DestAS)
6391 CK = CK_AddressSpaceConversion;
6392 else
6393 CK = CK_NoOp;
6394 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6395 }
6396 return From;
6397}
6398
6399/// TryContextuallyConvertToBool - Attempt to contextually convert the
6400/// expression From to bool (C++0x [conv]p3).
6401static ImplicitConversionSequence
6402TryContextuallyConvertToBool(Sema &S, Expr *From) {
6403 // C++ [dcl.init]/17.8:
6404 // - Otherwise, if the initialization is direct-initialization, the source
6405 // type is std::nullptr_t, and the destination type is bool, the initial
6406 // value of the object being initialized is false.
6407 if (From->getType()->isNullPtrType())
6408 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6409 DestType: S.Context.BoolTy,
6410 NeedLValToRVal: From->isGLValue());
6411
6412 // All other direct-initialization of bool is equivalent to an implicit
6413 // conversion to bool in which explicit conversions are permitted.
6414 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6415 /*SuppressUserConversions=*/false,
6416 AllowExplicit: AllowedExplicit::Conversions,
6417 /*InOverloadResolution=*/false,
6418 /*CStyle=*/false,
6419 /*AllowObjCWritebackConversion=*/false,
6420 /*AllowObjCConversionOnExplicit=*/false);
6421}
6422
6423ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6424 if (checkPlaceholderForOverload(S&: *this, E&: From))
6425 return ExprError();
6426 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6427 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6428
6429 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6430 if (!ICS.isBad())
6431 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6432 Action: AssignmentAction::Converting);
6433 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6434 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6435 << From->getType() << From->getSourceRange();
6436 return ExprError();
6437}
6438
6439/// Check that the specified conversion is permitted in a converted constant
6440/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6441/// is acceptable.
6442static bool CheckConvertedConstantConversions(Sema &S,
6443 StandardConversionSequence &SCS) {
6444 // Since we know that the target type is an integral or unscoped enumeration
6445 // type, most conversion kinds are impossible. All possible First and Third
6446 // conversions are fine.
6447 switch (SCS.Second) {
6448 case ICK_Identity:
6449 case ICK_Integral_Promotion:
6450 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6451 case ICK_Zero_Queue_Conversion:
6452 return true;
6453
6454 case ICK_Boolean_Conversion:
6455 // Conversion from an integral or unscoped enumeration type to bool is
6456 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6457 // conversion, so we allow it in a converted constant expression.
6458 //
6459 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6460 // a lot of popular code. We should at least add a warning for this
6461 // (non-conforming) extension.
6462 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6463 SCS.getToType(Idx: 2)->isBooleanType();
6464
6465 case ICK_Pointer_Conversion:
6466 case ICK_Pointer_Member:
6467 // C++1z: null pointer conversions and null member pointer conversions are
6468 // only permitted if the source type is std::nullptr_t.
6469 return SCS.getFromType()->isNullPtrType();
6470
6471 case ICK_Floating_Promotion:
6472 case ICK_Complex_Promotion:
6473 case ICK_Floating_Conversion:
6474 case ICK_Complex_Conversion:
6475 case ICK_Floating_Integral:
6476 case ICK_Compatible_Conversion:
6477 case ICK_Derived_To_Base:
6478 case ICK_Vector_Conversion:
6479 case ICK_SVE_Vector_Conversion:
6480 case ICK_RVV_Vector_Conversion:
6481 case ICK_HLSL_Vector_Splat:
6482 case ICK_HLSL_Matrix_Splat:
6483 case ICK_Vector_Splat:
6484 case ICK_Complex_Real:
6485 case ICK_Block_Pointer_Conversion:
6486 case ICK_TransparentUnionConversion:
6487 case ICK_Writeback_Conversion:
6488 case ICK_Zero_Event_Conversion:
6489 case ICK_C_Only_Conversion:
6490 case ICK_Incompatible_Pointer_Conversion:
6491 case ICK_Fixed_Point_Conversion:
6492 case ICK_HLSL_Vector_Truncation:
6493 case ICK_HLSL_Matrix_Truncation:
6494 return false;
6495
6496 case ICK_Lvalue_To_Rvalue:
6497 case ICK_Array_To_Pointer:
6498 case ICK_Function_To_Pointer:
6499 case ICK_HLSL_Array_RValue:
6500 llvm_unreachable("found a first conversion kind in Second");
6501
6502 case ICK_Function_Conversion:
6503 case ICK_Qualification:
6504 llvm_unreachable("found a third conversion kind in Second");
6505
6506 case ICK_Num_Conversion_Kinds:
6507 break;
6508 }
6509
6510 llvm_unreachable("unknown conversion kind");
6511}
6512
6513/// BuildConvertedConstantExpression - Check that the expression From is a
6514/// converted constant expression of type T, perform the conversion but
6515/// does not evaluate the expression
6516static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6517 QualType T, CCEKind CCE,
6518 NamedDecl *Dest,
6519 APValue &PreNarrowingValue) {
6520 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6521 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool ||
6522 CCE == CCEKind::PackIndex);
6523 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6524 "converted constant expression outside C++11 or TTP matching");
6525
6526 if (checkPlaceholderForOverload(S, E&: From))
6527 return ExprError();
6528
6529 if (From->containsErrors()) {
6530 if (S.Context.hasSameType(T1: From->getType(), T2: T))
6531 return From;
6532
6533 // The expression already has errors, so the correct cast kind can't be
6534 // determined. Use RecoveryExpr to keep the expected type T and mark the
6535 // result as invalid, preventing further cascading errors.
6536 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6537 T);
6538 }
6539
6540 // C++1z [expr.const]p3:
6541 // A converted constant expression of type T is an expression,
6542 // implicitly converted to type T, where the converted
6543 // expression is a constant expression and the implicit conversion
6544 // sequence contains only [... list of conversions ...].
6545 ImplicitConversionSequence ICS =
6546 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6547 ? TryContextuallyConvertToBool(S, From)
6548 : TryCopyInitialization(S, From, ToType: T,
6549 /*SuppressUserConversions=*/false,
6550 /*InOverloadResolution=*/false,
6551 /*AllowObjCWritebackConversion=*/false,
6552 /*AllowExplicit=*/false);
6553 StandardConversionSequence *SCS = nullptr;
6554 switch (ICS.getKind()) {
6555 case ImplicitConversionSequence::StandardConversion:
6556 SCS = &ICS.Standard;
6557 break;
6558 case ImplicitConversionSequence::UserDefinedConversion:
6559 if (T->isRecordType())
6560 SCS = &ICS.UserDefined.Before;
6561 else
6562 SCS = &ICS.UserDefined.After;
6563 break;
6564 case ImplicitConversionSequence::AmbiguousConversion:
6565 case ImplicitConversionSequence::BadConversion:
6566 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6567 return S.Diag(Loc: From->getBeginLoc(),
6568 DiagID: diag::err_typecheck_converted_constant_expression)
6569 << From->getType() << From->getSourceRange() << T;
6570 return ExprError();
6571
6572 case ImplicitConversionSequence::EllipsisConversion:
6573 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6574 llvm_unreachable("bad conversion in converted constant expression");
6575 }
6576
6577 // Check that we would only use permitted conversions.
6578 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6579 return S.Diag(Loc: From->getBeginLoc(),
6580 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6581 << From->getType() << From->getSourceRange() << T;
6582 }
6583 // [...] and where the reference binding (if any) binds directly.
6584 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6585 return S.Diag(Loc: From->getBeginLoc(),
6586 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6587 << From->getType() << From->getSourceRange() << T;
6588 }
6589 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6590 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6591 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6592 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6593 // case explicitly.
6594 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6595 return S.Diag(Loc: From->getBeginLoc(),
6596 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6597 << From->getSourceRange();
6598 }
6599
6600 // Usually we can simply apply the ImplicitConversionSequence we formed
6601 // earlier, but that's not guaranteed to work when initializing an object of
6602 // class type.
6603 ExprResult Result;
6604 bool IsTemplateArgument =
6605 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6606 if (T->isRecordType()) {
6607 assert(IsTemplateArgument &&
6608 "unexpected class type converted constant expr");
6609 Result = S.PerformCopyInitialization(
6610 Entity: InitializedEntity::InitializeTemplateParameter(
6611 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6612 EqualLoc: SourceLocation(), Init: From);
6613 } else {
6614 Result =
6615 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6616 }
6617 if (Result.isInvalid())
6618 return Result;
6619
6620 // C++2a [intro.execution]p5:
6621 // A full-expression is [...] a constant-expression [...]
6622 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6623 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6624 IsTemplateArgument);
6625 if (Result.isInvalid())
6626 return Result;
6627
6628 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6629
6630 // Check for a narrowing implicit conversion.
6631 bool ReturnPreNarrowingValue = false;
6632 QualType PreNarrowingType;
6633 switch (SCS->getNarrowingKind(
6634 Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue, ConstantType&: PreNarrowingType,
6635 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6636 case NK_Variable_Narrowing:
6637 // Implicit conversion to a narrower type, and the value is not a constant
6638 // expression. We'll diagnose this in a moment.
6639 case NK_Not_Narrowing:
6640 break;
6641
6642 case NK_Constant_Narrowing:
6643 if (CCE == CCEKind::ArrayBound &&
6644 PreNarrowingType->isIntegralOrEnumerationType() &&
6645 PreNarrowingValue.isInt()) {
6646 // Don't diagnose array bound narrowing here; we produce more precise
6647 // errors by allowing the un-narrowed value through.
6648 ReturnPreNarrowingValue = true;
6649 break;
6650 }
6651 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6652 << CCE << /*Constant*/ 1
6653 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6654 // If this is an SFINAE Context, treat the result as invalid so it stops
6655 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6656 // FIXME: Should do this whenever the above diagnostic is an error, but
6657 // without further changes this would degrade some other diagnostics.
6658 if (S.isSFINAEContext())
6659 return ExprError();
6660 break;
6661
6662 case NK_Dependent_Narrowing:
6663 // Implicit conversion to a narrower type, but the expression is
6664 // value-dependent so we can't tell whether it's actually narrowing.
6665 // For matching the parameters of a TTP, the conversion is ill-formed
6666 // if it may narrow.
6667 if (CCE != CCEKind::TempArgStrict)
6668 break;
6669 [[fallthrough]];
6670 case NK_Type_Narrowing:
6671 // FIXME: It would be better to diagnose that the expression is not a
6672 // constant expression.
6673 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6674 << CCE << /*Constant*/ 0 << From->getType() << T;
6675 if (S.isSFINAEContext())
6676 return ExprError();
6677 break;
6678 }
6679 if (!ReturnPreNarrowingValue)
6680 PreNarrowingValue = {};
6681
6682 return Result;
6683}
6684
6685/// CheckConvertedConstantExpression - Check that the expression From is a
6686/// converted constant expression of type T, perform the conversion and produce
6687/// the converted expression, per C++11 [expr.const]p3.
6688static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6689 QualType T, APValue &Value,
6690 CCEKind CCE, bool RequireInt,
6691 NamedDecl *Dest) {
6692
6693 APValue PreNarrowingValue;
6694 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6695 PreNarrowingValue);
6696 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6697 Value = APValue();
6698 return Result;
6699 }
6700 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6701 RequireInt, PreNarrowingValue);
6702}
6703
6704ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6705 CCEKind CCE,
6706 NamedDecl *Dest) {
6707 APValue PreNarrowingValue;
6708 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6709 PreNarrowingValue);
6710}
6711
6712ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6713 APValue &Value, CCEKind CCE,
6714 NamedDecl *Dest) {
6715 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6716 Dest);
6717}
6718
6719ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6720 llvm::APSInt &Value,
6721 CCEKind CCE) {
6722 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6723
6724 APValue V;
6725 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6726 /*Dest=*/nullptr);
6727 if (!R.isInvalid() && !R.get()->isValueDependent())
6728 Value = V.getInt();
6729 return R;
6730}
6731
6732ExprResult
6733Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6734 CCEKind CCE, bool RequireInt,
6735 const APValue &PreNarrowingValue) {
6736
6737 ExprResult Result = E;
6738 // Check the expression is a constant expression.
6739 SmallVector<PartialDiagnosticAt, 8> Notes;
6740 SmallVector<PartialDiagnosticAt> MSWarning;
6741 Expr::EvalResult Eval;
6742 Eval.Diag = &Notes;
6743 Eval.ExtendedDiag = &MSWarning;
6744
6745 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6746
6747 ConstantExprKind Kind;
6748 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6749 Kind = ConstantExprKind::ClassTemplateArgument;
6750 else if (CCE == CCEKind::TemplateArg)
6751 Kind = ConstantExprKind::NonClassTemplateArgument;
6752 else
6753 Kind = ConstantExprKind::Normal;
6754
6755 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6756 (RequireInt && !Eval.Val.isInt())) {
6757 // The expression can't be folded, so we can't keep it at this position in
6758 // the AST.
6759 Result = ExprError();
6760 } else {
6761 Value = Eval.Val;
6762 // For -fms-compatibility mode we relax some requirements
6763 // for constant folding in non-SFINAE contexts
6764 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6765 if (Notes.empty() && !CantFold) {
6766 for (auto &Info : MSWarning)
6767 Diag(Loc: Info.first, PD: Info.second);
6768 // It's a constant expression.
6769 Expr *E = Result.get();
6770 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6771 // We expect a ConstantExpr to have a value associated with it
6772 // by this point.
6773 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6774 "ConstantExpr has no value associated with it");
6775 (void)CE;
6776 } else {
6777 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6778 }
6779 if (!PreNarrowingValue.isAbsent())
6780 Value = std::move(PreNarrowingValue);
6781 return E;
6782 }
6783 }
6784
6785 // It's not a constant expression. Produce an appropriate diagnostic.
6786 if (Notes.size() == 1 &&
6787 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6788 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6789 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6790 diag::note_constexpr_invalid_template_arg) {
6791 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6792 for (unsigned I = 0; I < Notes.size(); ++I)
6793 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6794 } else {
6795 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6796 << CCE << E->getSourceRange();
6797 for (unsigned I = 0; I < Notes.size(); ++I)
6798 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6799 }
6800 return ExprError();
6801}
6802
6803/// dropPointerConversions - If the given standard conversion sequence
6804/// involves any pointer conversions, remove them. This may change
6805/// the result type of the conversion sequence.
6806static void dropPointerConversion(StandardConversionSequence &SCS) {
6807 if (SCS.Second == ICK_Pointer_Conversion) {
6808 SCS.Second = ICK_Identity;
6809 SCS.Dimension = ICK_Identity;
6810 SCS.Third = ICK_Identity;
6811 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6812 }
6813}
6814
6815/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6816/// convert the expression From to an Objective-C pointer type.
6817static ImplicitConversionSequence
6818TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6819 // Do an implicit conversion to 'id'.
6820 QualType Ty = S.Context.getObjCIdType();
6821 ImplicitConversionSequence ICS
6822 = TryImplicitConversion(S, From, ToType: Ty,
6823 // FIXME: Are these flags correct?
6824 /*SuppressUserConversions=*/false,
6825 AllowExplicit: AllowedExplicit::Conversions,
6826 /*InOverloadResolution=*/false,
6827 /*CStyle=*/false,
6828 /*AllowObjCWritebackConversion=*/false,
6829 /*AllowObjCConversionOnExplicit=*/true);
6830
6831 // Strip off any final conversions to 'id'.
6832 switch (ICS.getKind()) {
6833 case ImplicitConversionSequence::BadConversion:
6834 case ImplicitConversionSequence::AmbiguousConversion:
6835 case ImplicitConversionSequence::EllipsisConversion:
6836 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6837 break;
6838
6839 case ImplicitConversionSequence::UserDefinedConversion:
6840 dropPointerConversion(SCS&: ICS.UserDefined.After);
6841 break;
6842
6843 case ImplicitConversionSequence::StandardConversion:
6844 dropPointerConversion(SCS&: ICS.Standard);
6845 break;
6846 }
6847
6848 return ICS;
6849}
6850
6851ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6852 if (checkPlaceholderForOverload(S&: *this, E&: From))
6853 return ExprError();
6854
6855 QualType Ty = Context.getObjCIdType();
6856 ImplicitConversionSequence ICS =
6857 TryContextuallyConvertToObjCPointer(S&: *this, From);
6858 if (!ICS.isBad())
6859 return PerformImplicitConversion(From, ToType: Ty, ICS,
6860 Action: AssignmentAction::Converting);
6861 return ExprResult();
6862}
6863
6864static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6865 const Expr *Base = nullptr;
6866 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6867 "expected a member expression");
6868
6869 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6870 M && !M->isImplicitAccess())
6871 Base = M->getBase();
6872 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6873 M && !M->isImplicitAccess())
6874 Base = M->getBase();
6875
6876 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6877
6878 if (T->isPointerType())
6879 T = T->getPointeeType();
6880
6881 return T;
6882}
6883
6884static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6885 const FunctionDecl *Fun) {
6886 QualType ObjType = Obj->getType();
6887 if (ObjType->isPointerType()) {
6888 ObjType = ObjType->getPointeeType();
6889 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6890 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6891 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6892 }
6893 return Obj;
6894}
6895
6896ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6897 FunctionDecl *Fun) {
6898 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6899 return S.PerformCopyInitialization(
6900 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6901 EqualLoc: Obj->getExprLoc(), Init: Obj);
6902}
6903
6904static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6905 Expr *Object, MultiExprArg &Args,
6906 SmallVectorImpl<Expr *> &NewArgs) {
6907 assert(Method->isExplicitObjectMemberFunction() &&
6908 "Method is not an explicit member function");
6909 assert(NewArgs.empty() && "NewArgs should be empty");
6910
6911 NewArgs.reserve(N: Args.size() + 1);
6912 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6913 NewArgs.push_back(Elt: This);
6914 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6915 Args = NewArgs;
6916 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6917 Method, CallLoc: Object->getBeginLoc());
6918}
6919
6920/// Determine whether the provided type is an integral type, or an enumeration
6921/// type of a permitted flavor.
6922bool Sema::ICEConvertDiagnoser::match(QualType T) {
6923 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6924 : T->isIntegralOrUnscopedEnumerationType();
6925}
6926
6927static ExprResult
6928diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6929 Sema::ContextualImplicitConverter &Converter,
6930 QualType T, UnresolvedSetImpl &ViableConversions) {
6931
6932 if (Converter.Suppress)
6933 return ExprError();
6934
6935 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6936 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6937 CXXConversionDecl *Conv =
6938 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6939 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6940 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6941 }
6942 return From;
6943}
6944
6945static bool
6946diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6947 Sema::ContextualImplicitConverter &Converter,
6948 QualType T, bool HadMultipleCandidates,
6949 UnresolvedSetImpl &ExplicitConversions) {
6950 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6951 DeclAccessPair Found = ExplicitConversions[0];
6952 CXXConversionDecl *Conversion =
6953 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6954
6955 // The user probably meant to invoke the given explicit
6956 // conversion; use it.
6957 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6958 std::string TypeStr;
6959 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6960
6961 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6962 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6963 Code: "static_cast<" + TypeStr + ">(")
6964 << FixItHint::CreateInsertion(
6965 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6966 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6967
6968 // If we aren't in a SFINAE context, build a call to the
6969 // explicit conversion function.
6970 if (SemaRef.isSFINAEContext())
6971 return true;
6972
6973 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6974 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6975 HadMultipleCandidates);
6976 if (Result.isInvalid())
6977 return true;
6978
6979 // Replace the conversion with a RecoveryExpr, so we don't try to
6980 // instantiate it later, but can further diagnose here.
6981 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6982 SubExprs: From, T: Result.get()->getType());
6983 if (Result.isInvalid())
6984 return true;
6985 From = Result.get();
6986 }
6987 return false;
6988}
6989
6990static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6991 Sema::ContextualImplicitConverter &Converter,
6992 QualType T, bool HadMultipleCandidates,
6993 DeclAccessPair &Found) {
6994 CXXConversionDecl *Conversion =
6995 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6996 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6997
6998 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6999 if (!Converter.SuppressConversion) {
7000 if (SemaRef.isSFINAEContext())
7001 return true;
7002
7003 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
7004 << From->getSourceRange();
7005 }
7006
7007 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
7008 HadMultipleCandidates);
7009 if (Result.isInvalid())
7010 return true;
7011 // Record usage of conversion in an implicit cast.
7012 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
7013 Kind: CK_UserDefinedConversion, Operand: Result.get(),
7014 BasePath: nullptr, Cat: Result.get()->getValueKind(),
7015 FPO: SemaRef.CurFPFeatureOverrides());
7016 return false;
7017}
7018
7019static ExprResult finishContextualImplicitConversion(
7020 Sema &SemaRef, SourceLocation Loc, Expr *From,
7021 Sema::ContextualImplicitConverter &Converter) {
7022 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
7023 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
7024 << From->getSourceRange();
7025
7026 return SemaRef.DefaultLvalueConversion(E: From);
7027}
7028
7029static void
7030collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
7031 UnresolvedSetImpl &ViableConversions,
7032 OverloadCandidateSet &CandidateSet) {
7033 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7034 NamedDecl *D = FoundDecl.getDecl();
7035 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
7036 if (isa<UsingShadowDecl>(Val: D))
7037 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
7038
7039 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
7040 SemaRef.AddTemplateConversionCandidate(
7041 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7042 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7043 continue;
7044 }
7045 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
7046 SemaRef.AddConversionCandidate(
7047 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7048 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7049 }
7050}
7051
7052/// Attempt to convert the given expression to a type which is accepted
7053/// by the given converter.
7054///
7055/// This routine will attempt to convert an expression of class type to a
7056/// type accepted by the specified converter. In C++11 and before, the class
7057/// must have a single non-explicit conversion function converting to a matching
7058/// type. In C++1y, there can be multiple such conversion functions, but only
7059/// one target type.
7060///
7061/// \param Loc The source location of the construct that requires the
7062/// conversion.
7063///
7064/// \param From The expression we're converting from.
7065///
7066/// \param Converter Used to control and diagnose the conversion process.
7067///
7068/// \returns The expression, converted to an integral or enumeration type if
7069/// successful.
7070ExprResult Sema::PerformContextualImplicitConversion(
7071 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7072 // We can't perform any more checking for type-dependent expressions.
7073 if (From->isTypeDependent())
7074 return From;
7075
7076 // Process placeholders immediately.
7077 if (From->hasPlaceholderType()) {
7078 ExprResult result = CheckPlaceholderExpr(E: From);
7079 if (result.isInvalid())
7080 return result;
7081 From = result.get();
7082 }
7083
7084 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7085 ExprResult Converted = DefaultLvalueConversion(E: From);
7086 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7087 From = Converted.isUsable() ? Converted.get() : nullptr;
7088 // If the expression already has a matching type, we're golden.
7089 if (Converter.match(T))
7090 return Converted;
7091
7092 // FIXME: Check for missing '()' if T is a function type?
7093
7094 // We can only perform contextual implicit conversions on objects of class
7095 // type.
7096 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7097 if (!RecordTy || !getLangOpts().CPlusPlus) {
7098 if (!Converter.Suppress)
7099 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7100 return From;
7101 }
7102
7103 // We must have a complete class type.
7104 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7105 ContextualImplicitConverter &Converter;
7106 Expr *From;
7107
7108 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7109 : Converter(Converter), From(From) {}
7110
7111 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7112 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7113 }
7114 } IncompleteDiagnoser(Converter, From);
7115
7116 if (Converter.Suppress ? !isCompleteType(Loc, T)
7117 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7118 return From;
7119
7120 // Look for a conversion to an integral or enumeration type.
7121 UnresolvedSet<4>
7122 ViableConversions; // These are *potentially* viable in C++1y.
7123 UnresolvedSet<4> ExplicitConversions;
7124 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7125 ->getDefinitionOrSelf()
7126 ->getVisibleConversionFunctions();
7127
7128 bool HadMultipleCandidates =
7129 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7130
7131 // To check that there is only one target type, in C++1y:
7132 QualType ToType;
7133 bool HasUniqueTargetType = true;
7134
7135 // Collect explicit or viable (potentially in C++1y) conversions.
7136 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7137 NamedDecl *D = (*I)->getUnderlyingDecl();
7138 CXXConversionDecl *Conversion;
7139 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7140 if (ConvTemplate) {
7141 if (getLangOpts().CPlusPlus14)
7142 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7143 else
7144 continue; // C++11 does not consider conversion operator templates(?).
7145 } else
7146 Conversion = cast<CXXConversionDecl>(Val: D);
7147
7148 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7149 "Conversion operator templates are considered potentially "
7150 "viable in C++1y");
7151
7152 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7153 if (Converter.match(T: CurToType) || ConvTemplate) {
7154
7155 if (Conversion->isExplicit()) {
7156 // FIXME: For C++1y, do we need this restriction?
7157 // cf. diagnoseNoViableConversion()
7158 if (!ConvTemplate)
7159 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7160 } else {
7161 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7162 if (ToType.isNull())
7163 ToType = CurToType.getUnqualifiedType();
7164 else if (HasUniqueTargetType &&
7165 (CurToType.getUnqualifiedType() != ToType))
7166 HasUniqueTargetType = false;
7167 }
7168 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7169 }
7170 }
7171 }
7172
7173 if (getLangOpts().CPlusPlus14) {
7174 // C++1y [conv]p6:
7175 // ... An expression e of class type E appearing in such a context
7176 // is said to be contextually implicitly converted to a specified
7177 // type T and is well-formed if and only if e can be implicitly
7178 // converted to a type T that is determined as follows: E is searched
7179 // for conversion functions whose return type is cv T or reference to
7180 // cv T such that T is allowed by the context. There shall be
7181 // exactly one such T.
7182
7183 // If no unique T is found:
7184 if (ToType.isNull()) {
7185 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7186 HadMultipleCandidates,
7187 ExplicitConversions))
7188 return ExprError();
7189 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7190 }
7191
7192 // If more than one unique Ts are found:
7193 if (!HasUniqueTargetType)
7194 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7195 ViableConversions);
7196
7197 // If one unique T is found:
7198 // First, build a candidate set from the previously recorded
7199 // potentially viable conversions.
7200 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7201 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7202 CandidateSet);
7203
7204 // Then, perform overload resolution over the candidate set.
7205 OverloadCandidateSet::iterator Best;
7206 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7207 case OR_Success: {
7208 // Apply this conversion.
7209 DeclAccessPair Found =
7210 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7211 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7212 HadMultipleCandidates, Found))
7213 return ExprError();
7214 break;
7215 }
7216 case OR_Ambiguous:
7217 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7218 ViableConversions);
7219 case OR_No_Viable_Function:
7220 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7221 HadMultipleCandidates,
7222 ExplicitConversions))
7223 return ExprError();
7224 [[fallthrough]];
7225 case OR_Deleted:
7226 // We'll complain below about a non-integral condition type.
7227 break;
7228 }
7229 } else {
7230 switch (ViableConversions.size()) {
7231 case 0: {
7232 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7233 HadMultipleCandidates,
7234 ExplicitConversions))
7235 return ExprError();
7236
7237 // We'll complain below about a non-integral condition type.
7238 break;
7239 }
7240 case 1: {
7241 // Apply this conversion.
7242 DeclAccessPair Found = ViableConversions[0];
7243 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7244 HadMultipleCandidates, Found))
7245 return ExprError();
7246 break;
7247 }
7248 default:
7249 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7250 ViableConversions);
7251 }
7252 }
7253
7254 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7255}
7256
7257/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7258/// an acceptable non-member overloaded operator for a call whose
7259/// arguments have types T1 (and, if non-empty, T2). This routine
7260/// implements the check in C++ [over.match.oper]p3b2 concerning
7261/// enumeration types.
7262static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7263 FunctionDecl *Fn,
7264 ArrayRef<Expr *> Args) {
7265 QualType T1 = Args[0]->getType();
7266 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7267
7268 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7269 return true;
7270
7271 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7272 return true;
7273
7274 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7275 if (Proto->getNumParams() < 1)
7276 return false;
7277
7278 if (T1->isEnumeralType()) {
7279 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7280 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7281 return true;
7282 }
7283
7284 if (Proto->getNumParams() < 2)
7285 return false;
7286
7287 if (!T2.isNull() && T2->isEnumeralType()) {
7288 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7289 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7290 return true;
7291 }
7292
7293 return false;
7294}
7295
7296static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7297 if (FD->isTargetMultiVersionDefault())
7298 return false;
7299
7300 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7301 return FD->isTargetMultiVersion();
7302
7303 if (!FD->isMultiVersion())
7304 return false;
7305
7306 // Among multiple target versions consider either the default,
7307 // or the first non-default in the absence of default version.
7308 unsigned SeenAt = 0;
7309 unsigned I = 0;
7310 bool HasDefault = false;
7311 FD->getASTContext().forEachMultiversionedFunctionVersion(
7312 FD, Pred: [&](const FunctionDecl *CurFD) {
7313 if (FD == CurFD)
7314 SeenAt = I;
7315 else if (CurFD->isTargetMultiVersionDefault())
7316 HasDefault = true;
7317 ++I;
7318 });
7319 return HasDefault || SeenAt != 0;
7320}
7321
7322void Sema::AddOverloadCandidate(
7323 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7324 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7325 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7326 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7327 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7328 bool StrictPackMatch) {
7329 const FunctionProtoType *Proto
7330 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7331 assert(Proto && "Functions without a prototype cannot be overloaded");
7332 assert(!Function->getDescribedFunctionTemplate() &&
7333 "Use AddTemplateOverloadCandidate for function templates");
7334
7335 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7336 if (!isa<CXXConstructorDecl>(Val: Method)) {
7337 // If we get here, it's because we're calling a member function
7338 // that is named without a member access expression (e.g.,
7339 // "this->f") that was either written explicitly or created
7340 // implicitly. This can happen with a qualified call to a member
7341 // function, e.g., X::f(). We use an empty type for the implied
7342 // object argument (C++ [over.call.func]p3), and the acting context
7343 // is irrelevant.
7344 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7345 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7346 CandidateSet, SuppressUserConversions,
7347 PartialOverloading, EarlyConversions, PO,
7348 StrictPackMatch);
7349 return;
7350 }
7351 // We treat a constructor like a non-member function, since its object
7352 // argument doesn't participate in overload resolution.
7353 }
7354
7355 if (!CandidateSet.isNewCandidate(F: Function, PO))
7356 return;
7357
7358 // C++11 [class.copy]p11: [DR1402]
7359 // A defaulted move constructor that is defined as deleted is ignored by
7360 // overload resolution.
7361 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7362 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7363 Constructor->isMoveConstructor())
7364 return;
7365
7366 // Overload resolution is always an unevaluated context.
7367 EnterExpressionEvaluationContext Unevaluated(
7368 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7369
7370 // C++ [over.match.oper]p3:
7371 // if no operand has a class type, only those non-member functions in the
7372 // lookup set that have a first parameter of type T1 or "reference to
7373 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7374 // is a right operand) a second parameter of type T2 or "reference to
7375 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7376 // candidate functions.
7377 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7378 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7379 return;
7380
7381 // Add this candidate
7382 OverloadCandidate &Candidate =
7383 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7384 Candidate.FoundDecl = FoundDecl;
7385 Candidate.Function = Function;
7386 Candidate.Viable = true;
7387 Candidate.RewriteKind =
7388 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7389 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7390 Candidate.ExplicitCallArguments = Args.size();
7391 Candidate.StrictPackMatch = StrictPackMatch;
7392
7393 // Explicit functions are not actually candidates at all if we're not
7394 // allowing them in this context, but keep them around so we can point
7395 // to them in diagnostics.
7396 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7397 Candidate.Viable = false;
7398 Candidate.FailureKind = ovl_fail_explicit;
7399 return;
7400 }
7401
7402 // Functions with internal linkage are only viable in the same module unit.
7403 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7404 /// FIXME: Currently, the semantics of linkage in clang is slightly
7405 /// different from the semantics in C++ spec. In C++ spec, only names
7406 /// have linkage. So that all entities of the same should share one
7407 /// linkage. But in clang, different entities of the same could have
7408 /// different linkage.
7409 const NamedDecl *ND = Function;
7410 bool IsImplicitlyInstantiated = false;
7411 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7412 ND = SpecInfo->getTemplate();
7413 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7414 TSK_ImplicitInstantiation;
7415 }
7416
7417 /// Don't remove inline functions with internal linkage from the overload
7418 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7419 /// However:
7420 /// - Inline functions with internal linkage are a common pattern in
7421 /// headers to avoid ODR issues.
7422 /// - The global module is meant to be a transition mechanism for C and C++
7423 /// headers, and the current rules as written work against that goal.
7424 const bool IsInlineFunctionInGMF =
7425 Function->isFromGlobalModule() &&
7426 (IsImplicitlyInstantiated || Function->isInlined());
7427
7428 // Don't exclude internal-linkage entities from the current TU's global
7429 // module fragment.
7430 const Module *CurrentModule = getCurrentModule();
7431 const bool IsCurrentUnitGMFDecl =
7432 Function->isFromGlobalModule() && CurrentModule &&
7433 Function->getOwningModule()->getTopLevelModule() ==
7434 CurrentModule->getTopLevelModule();
7435
7436 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7437 !IsCurrentUnitGMFDecl) {
7438 Candidate.Viable = false;
7439 Candidate.FailureKind = ovl_fail_module_mismatched;
7440 return;
7441 }
7442 }
7443
7444 if (isNonViableMultiVersionOverload(FD: Function)) {
7445 Candidate.Viable = false;
7446 Candidate.FailureKind = ovl_non_default_multiversion_function;
7447 return;
7448 }
7449
7450 if (Constructor) {
7451 // C++ [class.copy]p3:
7452 // A member function template is never instantiated to perform the copy
7453 // of a class object to an object of its class type.
7454 CanQualType ClassType =
7455 Context.getCanonicalTagType(TD: Constructor->getParent());
7456 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7457 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7458 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7459 Base: ClassType))) {
7460 Candidate.Viable = false;
7461 Candidate.FailureKind = ovl_fail_illegal_constructor;
7462 return;
7463 }
7464
7465 // C++ [over.match.funcs]p8: (proposed DR resolution)
7466 // A constructor inherited from class type C that has a first parameter
7467 // of type "reference to P" (including such a constructor instantiated
7468 // from a template) is excluded from the set of candidate functions when
7469 // constructing an object of type cv D if the argument list has exactly
7470 // one argument and D is reference-related to P and P is reference-related
7471 // to C.
7472 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7473 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7474 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7475 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7476 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7477 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7478 SourceLocation Loc = Args.front()->getExprLoc();
7479 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7480 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7481 Candidate.Viable = false;
7482 Candidate.FailureKind = ovl_fail_inhctor_slice;
7483 return;
7484 }
7485 }
7486
7487 // Check that the constructor is capable of constructing an object in the
7488 // destination address space.
7489 if (!Qualifiers::isAddressSpaceSupersetOf(
7490 A: Constructor->getMethodQualifiers().getAddressSpace(),
7491 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7492 Candidate.Viable = false;
7493 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7494 }
7495 }
7496
7497 unsigned NumParams = Proto->getNumParams();
7498
7499 // (C++ 13.3.2p2): A candidate function having fewer than m
7500 // parameters is viable only if it has an ellipsis in its parameter
7501 // list (8.3.5).
7502 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7503 !Proto->isVariadic() &&
7504 shouldEnforceArgLimit(PartialOverloading, Function)) {
7505 Candidate.Viable = false;
7506 Candidate.FailureKind = ovl_fail_too_many_arguments;
7507 return;
7508 }
7509
7510 // (C++ 13.3.2p2): A candidate function having more than m parameters
7511 // is viable only if the (m+1)st parameter has a default argument
7512 // (8.3.6). For the purposes of overload resolution, the
7513 // parameter list is truncated on the right, so that there are
7514 // exactly m parameters.
7515 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7516 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7517 !PartialOverloading) {
7518 // Not enough arguments.
7519 Candidate.Viable = false;
7520 Candidate.FailureKind = ovl_fail_too_few_arguments;
7521 return;
7522 }
7523
7524 // (CUDA B.1): Check for invalid calls between targets.
7525 if (getLangOpts().CUDA) {
7526 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7527 // Skip the check for callers that are implicit members, because in this
7528 // case we may not yet know what the member's target is; the target is
7529 // inferred for the member automatically, based on the bases and fields of
7530 // the class.
7531 if (!(Caller && Caller->isImplicit()) &&
7532 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7533 Candidate.Viable = false;
7534 Candidate.FailureKind = ovl_fail_bad_target;
7535 return;
7536 }
7537 }
7538
7539 if (Function->getTrailingRequiresClause()) {
7540 ConstraintSatisfaction Satisfaction;
7541 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7542 /*ForOverloadResolution*/ true) ||
7543 !Satisfaction.IsSatisfied) {
7544 Candidate.Viable = false;
7545 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7546 return;
7547 }
7548 }
7549
7550 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7551 // Determine the implicit conversion sequences for each of the
7552 // arguments.
7553 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7554 unsigned ConvIdx =
7555 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7556 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7557 // We already formed a conversion sequence for this parameter during
7558 // template argument deduction.
7559 } else if (ArgIdx < NumParams) {
7560 // (C++ 13.3.2p3): for F to be a viable function, there shall
7561 // exist for each argument an implicit conversion sequence
7562 // (13.3.3.1) that converts that argument to the corresponding
7563 // parameter of F.
7564 QualType ParamType = Proto->getParamType(i: ArgIdx);
7565 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7566 if (ParamABI == ParameterABI::HLSLOut ||
7567 ParamABI == ParameterABI::HLSLInOut) {
7568 ParamType = ParamType.getNonReferenceType();
7569 if (ParamABI == ParameterABI::HLSLInOut &&
7570 Args[ArgIdx]->getType().getAddressSpace() ==
7571 LangAS::hlsl_groupshared)
7572 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7573 }
7574 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7575 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7576 /*InOverloadResolution=*/true,
7577 /*AllowObjCWritebackConversion=*/
7578 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7579 if (Candidate.Conversions[ConvIdx].isBad()) {
7580 Candidate.Viable = false;
7581 Candidate.FailureKind = ovl_fail_bad_conversion;
7582 return;
7583 }
7584 } else {
7585 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7586 // argument for which there is no corresponding parameter is
7587 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7588 Candidate.Conversions[ConvIdx].setEllipsis();
7589 }
7590 }
7591
7592 if (EnableIfAttr *FailedAttr =
7593 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7594 Candidate.Viable = false;
7595 Candidate.FailureKind = ovl_fail_enable_if;
7596 Candidate.DeductionFailure.Data = FailedAttr;
7597 return;
7598 }
7599}
7600
7601ObjCMethodDecl *
7602Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7603 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7604 if (Methods.size() <= 1)
7605 return nullptr;
7606
7607 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7608 bool Match = true;
7609 ObjCMethodDecl *Method = Methods[b];
7610 unsigned NumNamedArgs = Sel.getNumArgs();
7611 // Method might have more arguments than selector indicates. This is due
7612 // to addition of c-style arguments in method.
7613 if (Method->param_size() > NumNamedArgs)
7614 NumNamedArgs = Method->param_size();
7615 if (Args.size() < NumNamedArgs)
7616 continue;
7617
7618 for (unsigned i = 0; i < NumNamedArgs; i++) {
7619 // We can't do any type-checking on a type-dependent argument.
7620 if (Args[i]->isTypeDependent()) {
7621 Match = false;
7622 break;
7623 }
7624
7625 ParmVarDecl *param = Method->parameters()[i];
7626 Expr *argExpr = Args[i];
7627 assert(argExpr && "SelectBestMethod(): missing expression");
7628
7629 // Strip the unbridged-cast placeholder expression off unless it's
7630 // a consumed argument.
7631 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7632 !param->hasAttr<CFConsumedAttr>())
7633 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7634
7635 // If the parameter is __unknown_anytype, move on to the next method.
7636 if (param->getType() == Context.UnknownAnyTy) {
7637 Match = false;
7638 break;
7639 }
7640
7641 ImplicitConversionSequence ConversionState
7642 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7643 /*SuppressUserConversions*/false,
7644 /*InOverloadResolution=*/true,
7645 /*AllowObjCWritebackConversion=*/
7646 getLangOpts().ObjCAutoRefCount,
7647 /*AllowExplicit*/false);
7648 // This function looks for a reasonably-exact match, so we consider
7649 // incompatible pointer conversions to be a failure here.
7650 if (ConversionState.isBad() ||
7651 (ConversionState.isStandard() &&
7652 ConversionState.Standard.Second ==
7653 ICK_Incompatible_Pointer_Conversion)) {
7654 Match = false;
7655 break;
7656 }
7657 }
7658 // Promote additional arguments to variadic methods.
7659 if (Match && Method->isVariadic()) {
7660 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7661 if (Args[i]->isTypeDependent()) {
7662 Match = false;
7663 break;
7664 }
7665 ExprResult Arg = DefaultVariadicArgumentPromotion(
7666 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7667 if (Arg.isInvalid()) {
7668 Match = false;
7669 break;
7670 }
7671 }
7672 } else {
7673 // Check for extra arguments to non-variadic methods.
7674 if (Args.size() != NumNamedArgs)
7675 Match = false;
7676 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7677 // Special case when selectors have no argument. In this case, select
7678 // one with the most general result type of 'id'.
7679 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7680 QualType ReturnT = Methods[b]->getReturnType();
7681 if (ReturnT->isObjCIdType())
7682 return Methods[b];
7683 }
7684 }
7685 }
7686
7687 if (Match)
7688 return Method;
7689 }
7690 return nullptr;
7691}
7692
7693static bool convertArgsForAvailabilityChecks(
7694 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7695 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7696 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7697 if (ThisArg) {
7698 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7699 assert(!isa<CXXConstructorDecl>(Method) &&
7700 "Shouldn't have `this` for ctors!");
7701 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7702 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7703 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7704 if (R.isInvalid())
7705 return false;
7706 ConvertedThis = R.get();
7707 } else {
7708 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7709 (void)MD;
7710 assert((MissingImplicitThis || MD->isStatic() ||
7711 isa<CXXConstructorDecl>(MD)) &&
7712 "Expected `this` for non-ctor instance methods");
7713 }
7714 ConvertedThis = nullptr;
7715 }
7716
7717 // Ignore any variadic arguments. Converting them is pointless, since the
7718 // user can't refer to them in the function condition.
7719 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7720
7721 // Convert the arguments.
7722 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7723 ExprResult R;
7724 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7725 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7726 EqualLoc: SourceLocation(), Init: Args[I]);
7727
7728 if (R.isInvalid())
7729 return false;
7730
7731 ConvertedArgs.push_back(Elt: R.get());
7732 }
7733
7734 if (Trap.hasErrorOccurred())
7735 return false;
7736
7737 // Push default arguments if needed.
7738 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7739 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7740 ParmVarDecl *P = Function->getParamDecl(i);
7741 if (!P->hasDefaultArg())
7742 return false;
7743 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7744 if (R.isInvalid())
7745 return false;
7746 ConvertedArgs.push_back(Elt: R.get());
7747 }
7748
7749 if (Trap.hasErrorOccurred())
7750 return false;
7751 }
7752 return true;
7753}
7754
7755EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7756 SourceLocation CallLoc,
7757 ArrayRef<Expr *> Args,
7758 bool MissingImplicitThis) {
7759 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7760 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7761 return nullptr;
7762
7763 SFINAETrap Trap(*this);
7764 // Perform the access checking immediately so any access diagnostics are
7765 // caught by the SFINAE trap.
7766 llvm::scope_exit UndelayDiags(
7767 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7768 DelayedDiagnostics.popUndelayed(state: CurrentState);
7769 });
7770 SmallVector<Expr *, 16> ConvertedArgs;
7771 // FIXME: We should look into making enable_if late-parsed.
7772 Expr *DiscardedThis;
7773 if (!convertArgsForAvailabilityChecks(
7774 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7775 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7776 return *EnableIfAttrs.begin();
7777
7778 for (auto *EIA : EnableIfAttrs) {
7779 APValue Result;
7780 // FIXME: This doesn't consider value-dependent cases, because doing so is
7781 // very difficult. Ideally, we should handle them more gracefully.
7782 if (EIA->getCond()->isValueDependent() ||
7783 !EIA->getCond()->EvaluateWithSubstitution(
7784 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7785 return EIA;
7786
7787 if (!Result.isInt() || !Result.getInt().getBoolValue())
7788 return EIA;
7789 }
7790 return nullptr;
7791}
7792
7793template <typename CheckFn>
7794static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7795 bool ArgDependent, SourceLocation Loc,
7796 CheckFn &&IsSuccessful) {
7797 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7798 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7799 if (ArgDependent == DIA->getArgDependent())
7800 Attrs.push_back(Elt: DIA);
7801 }
7802
7803 // Common case: No diagnose_if attributes, so we can quit early.
7804 if (Attrs.empty())
7805 return false;
7806
7807 auto WarningBegin = std::stable_partition(
7808 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7809 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7810 DIA->getWarningGroup().empty();
7811 });
7812
7813 // Note that diagnose_if attributes are late-parsed, so they appear in the
7814 // correct order (unlike enable_if attributes).
7815 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7816 IsSuccessful);
7817 if (ErrAttr != WarningBegin) {
7818 const DiagnoseIfAttr *DIA = *ErrAttr;
7819 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7820 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7821 << DIA->getParent() << DIA->getCond()->getSourceRange();
7822 return true;
7823 }
7824
7825 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7826 switch (Sev) {
7827 case DiagnoseIfAttr::DS_warning:
7828 return diag::Severity::Warning;
7829 case DiagnoseIfAttr::DS_error:
7830 return diag::Severity::Error;
7831 }
7832 llvm_unreachable("Fully covered switch above!");
7833 };
7834
7835 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7836 if (IsSuccessful(DIA)) {
7837 if (DIA->getWarningGroup().empty() &&
7838 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7839 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7840 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7841 << DIA->getParent() << DIA->getCond()->getSourceRange();
7842 } else {
7843 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7844 DIA->getWarningGroup());
7845 assert(DiagGroup);
7846 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7847 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7848 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7849 S.Diag(Loc, DiagID) << DIA->getMessage();
7850 }
7851 }
7852
7853 return false;
7854}
7855
7856bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7857 const Expr *ThisArg,
7858 ArrayRef<const Expr *> Args,
7859 SourceLocation Loc) {
7860 return diagnoseDiagnoseIfAttrsWith(
7861 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7862 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7863 APValue Result;
7864 // It's sane to use the same Args for any redecl of this function, since
7865 // EvaluateWithSubstitution only cares about the position of each
7866 // argument in the arg list, not the ParmVarDecl* it maps to.
7867 if (!DIA->getCond()->EvaluateWithSubstitution(
7868 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7869 return false;
7870 return Result.isInt() && Result.getInt().getBoolValue();
7871 });
7872}
7873
7874bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7875 SourceLocation Loc) {
7876 return diagnoseDiagnoseIfAttrsWith(
7877 S&: *this, ND, /*ArgDependent=*/false, Loc,
7878 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7879 bool Result;
7880 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7881 Result;
7882 });
7883}
7884
7885void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7886 ArrayRef<Expr *> Args,
7887 OverloadCandidateSet &CandidateSet,
7888 TemplateArgumentListInfo *ExplicitTemplateArgs,
7889 bool SuppressUserConversions,
7890 bool PartialOverloading,
7891 bool FirstArgumentIsBase) {
7892 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7893 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7894 ArrayRef<Expr *> FunctionArgs = Args;
7895
7896 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7897 FunctionDecl *FD =
7898 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7899
7900 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7901 QualType ObjectType;
7902 Expr::Classification ObjectClassification;
7903 if (Args.size() > 0) {
7904 if (Expr *E = Args[0]) {
7905 // Use the explicit base to restrict the lookup:
7906 ObjectType = E->getType();
7907 // Pointers in the object arguments are implicitly dereferenced, so we
7908 // always classify them as l-values.
7909 if (!ObjectType.isNull() && ObjectType->isPointerType())
7910 ObjectClassification = Expr::Classification::makeSimpleLValue();
7911 else
7912 ObjectClassification = E->Classify(Ctx&: Context);
7913 } // .. else there is an implicit base.
7914 FunctionArgs = Args.slice(N: 1);
7915 }
7916 if (FunTmpl) {
7917 AddMethodTemplateCandidate(
7918 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7919 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7920 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7921 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7922 PartialOverloading);
7923 } else {
7924 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7925 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7926 ObjectClassification, Args: FunctionArgs, CandidateSet,
7927 SuppressUserConversions, PartialOverloading);
7928 }
7929 } else {
7930 // This branch handles both standalone functions and static methods.
7931
7932 // Slice the first argument (which is the base) when we access
7933 // static method as non-static.
7934 if (Args.size() > 0 &&
7935 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7936 !isa<CXXConstructorDecl>(Val: FD)))) {
7937 assert(cast<CXXMethodDecl>(FD)->isStatic());
7938 FunctionArgs = Args.slice(N: 1);
7939 }
7940 if (FunTmpl) {
7941 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7942 ExplicitTemplateArgs, Args: FunctionArgs,
7943 CandidateSet, SuppressUserConversions,
7944 PartialOverloading);
7945 } else {
7946 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7947 SuppressUserConversions, PartialOverloading);
7948 }
7949 }
7950 }
7951}
7952
7953void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7954 Expr::Classification ObjectClassification,
7955 ArrayRef<Expr *> Args,
7956 OverloadCandidateSet &CandidateSet,
7957 bool SuppressUserConversions,
7958 OverloadCandidateParamOrder PO) {
7959 NamedDecl *Decl = FoundDecl.getDecl();
7960 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7961
7962 if (isa<UsingShadowDecl>(Val: Decl))
7963 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7964
7965 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7966 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7967 "Expected a member function template");
7968 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7969 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7970 ObjectClassification, Args, CandidateSet,
7971 SuppressUserConversions, PartialOverloading: false, PO);
7972 } else {
7973 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7974 ObjectType, ObjectClassification, Args, CandidateSet,
7975 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7976 }
7977}
7978
7979void Sema::AddMethodCandidate(
7980 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7981 CXXRecordDecl *ActingContext, QualType ObjectType,
7982 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7983 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7984 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7985 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7986 const FunctionProtoType *Proto
7987 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7988 assert(Proto && "Methods without a prototype cannot be overloaded");
7989 assert(!isa<CXXConstructorDecl>(Method) &&
7990 "Use AddOverloadCandidate for constructors");
7991
7992 if (!CandidateSet.isNewCandidate(F: Method, PO))
7993 return;
7994
7995 // C++11 [class.copy]p23: [DR1402]
7996 // A defaulted move assignment operator that is defined as deleted is
7997 // ignored by overload resolution.
7998 if (Method->isDefaulted() && Method->isDeleted() &&
7999 Method->isMoveAssignmentOperator())
8000 return;
8001
8002 // Overload resolution is always an unevaluated context.
8003 EnterExpressionEvaluationContext Unevaluated(
8004 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8005
8006 bool IgnoreExplicitObject =
8007 (Method->isExplicitObjectMemberFunction() &&
8008 CandidateSet.getKind() ==
8009 OverloadCandidateSet::CSK_AddressOfOverloadSet);
8010 bool ImplicitObjectMethodTreatedAsStatic =
8011 CandidateSet.getKind() ==
8012 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
8013 Method->isImplicitObjectMemberFunction();
8014
8015 unsigned ExplicitOffset =
8016 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8017
8018 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8019 int(ImplicitObjectMethodTreatedAsStatic);
8020
8021 unsigned ExtraArgs =
8022 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
8023 ? 0
8024 : 1;
8025
8026 // Add this candidate
8027 OverloadCandidate &Candidate =
8028 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
8029 Candidate.FoundDecl = FoundDecl;
8030 Candidate.Function = Method;
8031 Candidate.RewriteKind =
8032 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
8033 Candidate.TookAddressOfOverload =
8034 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8035 Candidate.ExplicitCallArguments = Args.size();
8036 Candidate.StrictPackMatch = StrictPackMatch;
8037
8038 // (C++ 13.3.2p2): A candidate function having fewer than m
8039 // parameters is viable only if it has an ellipsis in its parameter
8040 // list (8.3.5).
8041 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
8042 !Proto->isVariadic() &&
8043 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
8044 Candidate.Viable = false;
8045 Candidate.FailureKind = ovl_fail_too_many_arguments;
8046 return;
8047 }
8048
8049 // (C++ 13.3.2p2): A candidate function having more than m parameters
8050 // is viable only if the (m+1)st parameter has a default argument
8051 // (8.3.6). For the purposes of overload resolution, the
8052 // parameter list is truncated on the right, so that there are
8053 // exactly m parameters.
8054 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8055 ExplicitOffset +
8056 int(ImplicitObjectMethodTreatedAsStatic);
8057
8058 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8059 // Not enough arguments.
8060 Candidate.Viable = false;
8061 Candidate.FailureKind = ovl_fail_too_few_arguments;
8062 return;
8063 }
8064
8065 Candidate.Viable = true;
8066
8067 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8068 if (!IgnoreExplicitObject) {
8069 if (ObjectType.isNull())
8070 Candidate.IgnoreObjectArgument = true;
8071 else if (Method->isStatic()) {
8072 // [over.best.ics.general]p8
8073 // When the parameter is the implicit object parameter of a static member
8074 // function, the implicit conversion sequence is a standard conversion
8075 // sequence that is neither better nor worse than any other standard
8076 // conversion sequence.
8077 //
8078 // This is a rule that was introduced in C++23 to support static lambdas.
8079 // We apply it retroactively because we want to support static lambdas as
8080 // an extension and it doesn't hurt previous code.
8081 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8082 } else {
8083 // Determine the implicit conversion sequence for the object
8084 // parameter.
8085 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8086 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8087 Method, ActingContext, /*InOverloadResolution=*/true);
8088 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8089 Candidate.Viable = false;
8090 Candidate.FailureKind = ovl_fail_bad_conversion;
8091 return;
8092 }
8093 }
8094 }
8095
8096 // (CUDA B.1): Check for invalid calls between targets.
8097 if (getLangOpts().CUDA)
8098 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8099 Callee: Method)) {
8100 Candidate.Viable = false;
8101 Candidate.FailureKind = ovl_fail_bad_target;
8102 return;
8103 }
8104
8105 if (Method->getTrailingRequiresClause()) {
8106 ConstraintSatisfaction Satisfaction;
8107 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8108 /*ForOverloadResolution*/ true) ||
8109 !Satisfaction.IsSatisfied) {
8110 Candidate.Viable = false;
8111 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8112 return;
8113 }
8114 }
8115
8116 // Determine the implicit conversion sequences for each of the
8117 // arguments.
8118 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8119 unsigned ConvIdx =
8120 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8121 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8122 // We already formed a conversion sequence for this parameter during
8123 // template argument deduction.
8124 } else if (ArgIdx < NumParams) {
8125 // (C++ 13.3.2p3): for F to be a viable function, there shall
8126 // exist for each argument an implicit conversion sequence
8127 // (13.3.3.1) that converts that argument to the corresponding
8128 // parameter of F.
8129 QualType ParamType;
8130 if (ImplicitObjectMethodTreatedAsStatic) {
8131 ParamType = ArgIdx == 0
8132 ? Method->getFunctionObjectParameterReferenceType()
8133 : Proto->getParamType(i: ArgIdx - 1);
8134 } else {
8135 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8136 }
8137 Candidate.Conversions[ConvIdx]
8138 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8139 SuppressUserConversions,
8140 /*InOverloadResolution=*/true,
8141 /*AllowObjCWritebackConversion=*/
8142 getLangOpts().ObjCAutoRefCount);
8143 if (Candidate.Conversions[ConvIdx].isBad()) {
8144 Candidate.Viable = false;
8145 Candidate.FailureKind = ovl_fail_bad_conversion;
8146 return;
8147 }
8148 } else {
8149 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8150 // argument for which there is no corresponding parameter is
8151 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8152 Candidate.Conversions[ConvIdx].setEllipsis();
8153 }
8154 }
8155
8156 if (EnableIfAttr *FailedAttr =
8157 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8158 Candidate.Viable = false;
8159 Candidate.FailureKind = ovl_fail_enable_if;
8160 Candidate.DeductionFailure.Data = FailedAttr;
8161 return;
8162 }
8163
8164 if (isNonViableMultiVersionOverload(FD: Method)) {
8165 Candidate.Viable = false;
8166 Candidate.FailureKind = ovl_non_default_multiversion_function;
8167 }
8168}
8169
8170static void AddMethodTemplateCandidateImmediately(
8171 Sema &S, OverloadCandidateSet &CandidateSet,
8172 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8173 CXXRecordDecl *ActingContext,
8174 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8175 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8176 bool SuppressUserConversions, bool PartialOverloading,
8177 OverloadCandidateParamOrder PO) {
8178
8179 // C++ [over.match.funcs]p7:
8180 // In each case where a candidate is a function template, candidate
8181 // function template specializations are generated using template argument
8182 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8183 // candidate functions in the usual way.113) A given name can refer to one
8184 // or more function templates and also to a set of overloaded non-template
8185 // functions. In such a case, the candidate functions generated from each
8186 // function template are combined with the set of non-template candidate
8187 // functions.
8188 TemplateDeductionInfo Info(CandidateSet.getLocation());
8189 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8190 FunctionDecl *Specialization = nullptr;
8191 ConversionSequenceList Conversions;
8192 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8193 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8194 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8195 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8196 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8197 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8198 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8199 bool OnlyInitializeNonUserDefinedConversions) {
8200 return S.CheckNonDependentConversions(
8201 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8202 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8203 SuppressUserConversions,
8204 OnlyInitializeNonUserDefinedConversions),
8205 ActingContext, ObjectType, ObjectClassification, PO);
8206 });
8207 Result != TemplateDeductionResult::Success) {
8208 OverloadCandidate &Candidate =
8209 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8210 Candidate.FoundDecl = FoundDecl;
8211 Candidate.Function = Method;
8212 Candidate.Viable = false;
8213 Candidate.RewriteKind =
8214 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8215 Candidate.IsSurrogate = false;
8216 Candidate.TookAddressOfOverload =
8217 CandidateSet.getKind() ==
8218 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8219
8220 Candidate.IgnoreObjectArgument =
8221 Method->isStatic() ||
8222 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8223 Candidate.ExplicitCallArguments = Args.size();
8224 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8225 Candidate.FailureKind = ovl_fail_bad_conversion;
8226 else {
8227 Candidate.FailureKind = ovl_fail_bad_deduction;
8228 Candidate.DeductionFailure =
8229 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8230 }
8231 return;
8232 }
8233
8234 // Add the function template specialization produced by template argument
8235 // deduction as a candidate.
8236 assert(Specialization && "Missing member function template specialization?");
8237 assert(isa<CXXMethodDecl>(Specialization) &&
8238 "Specialization is not a member function?");
8239 S.AddMethodCandidate(
8240 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8241 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8242 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8243}
8244
8245void Sema::AddMethodTemplateCandidate(
8246 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8247 CXXRecordDecl *ActingContext,
8248 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8249 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8250 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8251 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8252 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8253 return;
8254
8255 if (ExplicitTemplateArgs ||
8256 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this)) {
8257 AddMethodTemplateCandidateImmediately(
8258 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8259 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8260 SuppressUserConversions, PartialOverloading, PO);
8261 return;
8262 }
8263
8264 CandidateSet.AddDeferredMethodTemplateCandidate(
8265 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8266 Args, SuppressUserConversions, PartialOverloading, PO);
8267}
8268
8269/// Determine whether a given function template has a simple explicit specifier
8270/// or a non-value-dependent explicit-specification that evaluates to true.
8271static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8272 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8273}
8274
8275static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8276 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8277 ExplicitSpecKind::Unresolved;
8278}
8279
8280static void AddTemplateOverloadCandidateImmediately(
8281 Sema &S, OverloadCandidateSet &CandidateSet,
8282 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8283 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8284 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8285 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8286 bool AggregateCandidateDeduction) {
8287
8288 // If the function template has a non-dependent explicit specification,
8289 // exclude it now if appropriate; we are not permitted to perform deduction
8290 // and substitution in this case.
8291 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8292 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8293 Candidate.FoundDecl = FoundDecl;
8294 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8295 Candidate.Viable = false;
8296 Candidate.FailureKind = ovl_fail_explicit;
8297 return;
8298 }
8299
8300 // C++ [over.match.funcs]p7:
8301 // In each case where a candidate is a function template, candidate
8302 // function template specializations are generated using template argument
8303 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8304 // candidate functions in the usual way.113) A given name can refer to one
8305 // or more function templates and also to a set of overloaded non-template
8306 // functions. In such a case, the candidate functions generated from each
8307 // function template are combined with the set of non-template candidate
8308 // functions.
8309 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8310 FunctionTemplate->getTemplateDepth());
8311 FunctionDecl *Specialization = nullptr;
8312 ConversionSequenceList Conversions;
8313 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8314 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8315 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8316 /*PartialOrdering=*/false,
8317 /*ObjectType=*/QualType(),
8318 /*ObjectClassification=*/Expr::Classification(),
8319 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8320 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8321 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8322 bool OnlyInitializeNonUserDefinedConversions) {
8323 return S.CheckNonDependentConversions(
8324 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8325 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8326 SuppressUserConversions,
8327 OnlyInitializeNonUserDefinedConversions),
8328 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8329 });
8330 Result != TemplateDeductionResult::Success) {
8331 OverloadCandidate &Candidate =
8332 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8333 Candidate.FoundDecl = FoundDecl;
8334 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8335 Candidate.Viable = false;
8336 Candidate.RewriteKind =
8337 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8338 Candidate.IsSurrogate = false;
8339 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8340 // Ignore the object argument if there is one, since we don't have an object
8341 // type.
8342 Candidate.TookAddressOfOverload =
8343 CandidateSet.getKind() ==
8344 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8345
8346 Candidate.IgnoreObjectArgument =
8347 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8348 !cast<CXXMethodDecl>(Val: Candidate.Function)
8349 ->isExplicitObjectMemberFunction() &&
8350 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8351
8352 Candidate.ExplicitCallArguments = Args.size();
8353 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8354 Candidate.FailureKind = ovl_fail_bad_conversion;
8355 else {
8356 Candidate.FailureKind = ovl_fail_bad_deduction;
8357 Candidate.DeductionFailure =
8358 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8359 }
8360 return;
8361 }
8362
8363 // Add the function template specialization produced by template argument
8364 // deduction as a candidate.
8365 assert(Specialization && "Missing function template specialization?");
8366 S.AddOverloadCandidate(
8367 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8368 PartialOverloading, AllowExplicit,
8369 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8370 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8371 StrictPackMatch: Info.hasStrictPackMatch());
8372}
8373
8374void Sema::AddTemplateOverloadCandidate(
8375 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8376 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8377 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8378 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8379 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8380 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8381 return;
8382
8383 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8384
8385 if (ExplicitTemplateArgs ||
8386 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8387 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8388 DependentExplicitSpecifier)) {
8389
8390 AddTemplateOverloadCandidateImmediately(
8391 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8392 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8393 IsADLCandidate, PO, AggregateCandidateDeduction);
8394
8395 if (DependentExplicitSpecifier)
8396 CandidateSet.DisableResolutionByPerfectCandidate();
8397 return;
8398 }
8399
8400 CandidateSet.AddDeferredTemplateCandidate(
8401 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8402 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8403 AggregateCandidateDeduction);
8404}
8405
8406bool Sema::CheckNonDependentConversions(
8407 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8408 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8409 ConversionSequenceList &Conversions,
8410 CheckNonDependentConversionsFlag UserConversionFlag,
8411 CXXRecordDecl *ActingContext, QualType ObjectType,
8412 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8413 // FIXME: The cases in which we allow explicit conversions for constructor
8414 // arguments never consider calling a constructor template. It's not clear
8415 // that is correct.
8416 const bool AllowExplicit = false;
8417
8418 bool ForOverloadSetAddressResolution =
8419 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8420 auto *FD = FunctionTemplate->getTemplatedDecl();
8421 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8422 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8423 !isa<CXXConstructorDecl>(Val: Method);
8424 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8425
8426 if (Conversions.empty())
8427 Conversions =
8428 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8429
8430 // Overload resolution is always an unevaluated context.
8431 EnterExpressionEvaluationContext Unevaluated(
8432 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8433
8434 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8435 // require that, but this check should never result in a hard error, and
8436 // overload resolution is permitted to sidestep instantiations.
8437 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8438 !ObjectType.isNull()) {
8439 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8440 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8441 !ParamTypes[0]->isDependentType()) {
8442 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8443 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8444 Method, ActingContext, /*InOverloadResolution=*/true,
8445 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8446 : QualType());
8447 if (Conversions[ConvIdx].isBad())
8448 return true;
8449 }
8450 }
8451
8452 // A speculative workaround for self-dependent constraint bugs that manifest
8453 // after CWG2369.
8454 // FIXME: Add references to the standard once P3606 is adopted.
8455 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8456 QualType ArgType) {
8457 ParamType = ParamType.getNonReferenceType();
8458 ArgType = ArgType.getNonReferenceType();
8459 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8460 if (PointerConv) {
8461 ParamType = ParamType->getPointeeType();
8462 ArgType = ArgType->getPointeeType();
8463 }
8464
8465 if (auto *RD = ParamType->getAsCXXRecordDecl();
8466 RD && RD->hasDefinition() &&
8467 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8468 auto Info = getConstructorInfo(ND);
8469 if (!Info)
8470 return false;
8471 CXXConstructorDecl *Ctor = Info.Constructor;
8472 /// isConvertingConstructor takes copy/move constructors into
8473 /// account!
8474 return !Ctor->isCopyOrMoveConstructor() &&
8475 Ctor->isConvertingConstructor(
8476 /*AllowExplicit=*/true);
8477 }))
8478 return true;
8479 if (auto *RD = ArgType->getAsCXXRecordDecl();
8480 RD && RD->hasDefinition() &&
8481 !RD->getVisibleConversionFunctions().empty())
8482 return true;
8483
8484 return false;
8485 };
8486
8487 unsigned Offset =
8488 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8489 : 0;
8490
8491 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8492 I != N; ++I) {
8493 QualType ParamType = ParamTypes[I + Offset];
8494 if (!ParamType->isDependentType()) {
8495 unsigned ConvIdx;
8496 if (PO == OverloadCandidateParamOrder::Reversed) {
8497 ConvIdx = Args.size() - 1 - I;
8498 assert(Args.size() + ThisConversions == 2 &&
8499 "number of args (including 'this') must be exactly 2 for "
8500 "reversed order");
8501 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8502 // would also be 0. 'this' got ConvIdx = 1 previously.
8503 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8504 } else {
8505 // For members, 'this' got ConvIdx = 0 previously.
8506 ConvIdx = ThisConversions + I;
8507 }
8508 if (Conversions[ConvIdx].isInitialized())
8509 continue;
8510 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8511 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8512 continue;
8513 Conversions[ConvIdx] = TryCopyInitialization(
8514 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8515 /*InOverloadResolution=*/true,
8516 /*AllowObjCWritebackConversion=*/
8517 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8518 if (Conversions[ConvIdx].isBad())
8519 return true;
8520 }
8521 }
8522
8523 return false;
8524}
8525
8526/// Determine whether this is an allowable conversion from the result
8527/// of an explicit conversion operator to the expected type, per C++
8528/// [over.match.conv]p1 and [over.match.ref]p1.
8529///
8530/// \param ConvType The return type of the conversion function.
8531///
8532/// \param ToType The type we are converting to.
8533///
8534/// \param AllowObjCPointerConversion Allow a conversion from one
8535/// Objective-C pointer to another.
8536///
8537/// \returns true if the conversion is allowable, false otherwise.
8538static bool isAllowableExplicitConversion(Sema &S,
8539 QualType ConvType, QualType ToType,
8540 bool AllowObjCPointerConversion) {
8541 QualType ToNonRefType = ToType.getNonReferenceType();
8542
8543 // Easy case: the types are the same.
8544 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8545 return true;
8546
8547 // Allow qualification conversions.
8548 bool ObjCLifetimeConversion;
8549 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8550 ObjCLifetimeConversion))
8551 return true;
8552
8553 // If we're not allowed to consider Objective-C pointer conversions,
8554 // we're done.
8555 if (!AllowObjCPointerConversion)
8556 return false;
8557
8558 // Is this an Objective-C pointer conversion?
8559 bool IncompatibleObjC = false;
8560 QualType ConvertedType;
8561 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8562 IncompatibleObjC);
8563}
8564
8565void Sema::AddConversionCandidate(
8566 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8567 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8568 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8569 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8570 assert(!Conversion->getDescribedFunctionTemplate() &&
8571 "Conversion function templates use AddTemplateConversionCandidate");
8572 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8573 if (!CandidateSet.isNewCandidate(F: Conversion))
8574 return;
8575
8576 // If the conversion function has an undeduced return type, trigger its
8577 // deduction now.
8578 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8579 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8580 return;
8581 ConvType = Conversion->getConversionType().getNonReferenceType();
8582 }
8583
8584 // If we don't allow any conversion of the result type, ignore conversion
8585 // functions that don't convert to exactly (possibly cv-qualified) T.
8586 if (!AllowResultConversion &&
8587 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8588 return;
8589
8590 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8591 // operator is only a candidate if its return type is the target type or
8592 // can be converted to the target type with a qualification conversion.
8593 //
8594 // FIXME: Include such functions in the candidate list and explain why we
8595 // can't select them.
8596 if (Conversion->isExplicit() &&
8597 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8598 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8599 return;
8600
8601 // Overload resolution is always an unevaluated context.
8602 EnterExpressionEvaluationContext Unevaluated(
8603 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8604
8605 // Add this candidate
8606 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8607 Candidate.FoundDecl = FoundDecl;
8608 Candidate.Function = Conversion;
8609 Candidate.FinalConversion.setAsIdentityConversion();
8610 Candidate.FinalConversion.setFromType(ConvType);
8611 Candidate.FinalConversion.setAllToTypes(ToType);
8612 Candidate.HasFinalConversion = true;
8613 Candidate.Viable = true;
8614 Candidate.ExplicitCallArguments = 1;
8615 Candidate.StrictPackMatch = StrictPackMatch;
8616
8617 // Explicit functions are not actually candidates at all if we're not
8618 // allowing them in this context, but keep them around so we can point
8619 // to them in diagnostics.
8620 if (!AllowExplicit && Conversion->isExplicit()) {
8621 Candidate.Viable = false;
8622 Candidate.FailureKind = ovl_fail_explicit;
8623 return;
8624 }
8625
8626 // C++ [over.match.funcs]p4:
8627 // For conversion functions, the function is considered to be a member of
8628 // the class of the implicit implied object argument for the purpose of
8629 // defining the type of the implicit object parameter.
8630 //
8631 // Determine the implicit conversion sequence for the implicit
8632 // object parameter.
8633 QualType ObjectType = From->getType();
8634 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8635 ObjectType = FromPtrType->getPointeeType();
8636 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8637 // C++23 [over.best.ics.general]
8638 // However, if the target is [...]
8639 // - the object parameter of a user-defined conversion function
8640 // [...] user-defined conversion sequences are not considered.
8641 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8642 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8643 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8644 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8645 /*SuppressUserConversion*/ true);
8646
8647 if (Candidate.Conversions[0].isBad()) {
8648 Candidate.Viable = false;
8649 Candidate.FailureKind = ovl_fail_bad_conversion;
8650 return;
8651 }
8652
8653 if (Conversion->getTrailingRequiresClause()) {
8654 ConstraintSatisfaction Satisfaction;
8655 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8656 !Satisfaction.IsSatisfied) {
8657 Candidate.Viable = false;
8658 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8659 return;
8660 }
8661 }
8662
8663 // We won't go through a user-defined type conversion function to convert a
8664 // derived to base as such conversions are given Conversion Rank. They only
8665 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8666 QualType FromCanon
8667 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8668 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8669 if (FromCanon == ToCanon ||
8670 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8671 Candidate.Viable = false;
8672 Candidate.FailureKind = ovl_fail_trivial_conversion;
8673 return;
8674 }
8675
8676 // To determine what the conversion from the result of calling the
8677 // conversion function to the type we're eventually trying to
8678 // convert to (ToType), we need to synthesize a call to the
8679 // conversion function and attempt copy initialization from it. This
8680 // makes sure that we get the right semantics with respect to
8681 // lvalues/rvalues and the type. Fortunately, we can allocate this
8682 // call on the stack and we don't need its arguments to be
8683 // well-formed.
8684 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8685 VK_LValue, From->getBeginLoc());
8686 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8687 Context.getPointerType(T: Conversion->getType()),
8688 CK_FunctionToPointerDecay, &ConversionRef,
8689 VK_PRValue, FPOptionsOverride());
8690
8691 QualType ConversionType = Conversion->getConversionType();
8692 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8693 Candidate.Viable = false;
8694 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8695 return;
8696 }
8697
8698 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8699
8700 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8701
8702 // Introduce a temporary expression with the right type and value category
8703 // that we can use for deduction purposes.
8704 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8705
8706 ImplicitConversionSequence ICS =
8707 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8708 /*SuppressUserConversions=*/true,
8709 /*InOverloadResolution=*/false,
8710 /*AllowObjCWritebackConversion=*/false);
8711
8712 switch (ICS.getKind()) {
8713 case ImplicitConversionSequence::StandardConversion:
8714 Candidate.FinalConversion = ICS.Standard;
8715 Candidate.HasFinalConversion = true;
8716
8717 // C++ [over.ics.user]p3:
8718 // If the user-defined conversion is specified by a specialization of a
8719 // conversion function template, the second standard conversion sequence
8720 // shall have exact match rank.
8721 if (Conversion->getPrimaryTemplate() &&
8722 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8723 Candidate.Viable = false;
8724 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8725 return;
8726 }
8727
8728 // C++0x [dcl.init.ref]p5:
8729 // In the second case, if the reference is an rvalue reference and
8730 // the second standard conversion sequence of the user-defined
8731 // conversion sequence includes an lvalue-to-rvalue conversion, the
8732 // program is ill-formed.
8733 if (ToType->isRValueReferenceType() &&
8734 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8735 Candidate.Viable = false;
8736 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8737 return;
8738 }
8739 break;
8740
8741 case ImplicitConversionSequence::BadConversion:
8742 Candidate.Viable = false;
8743 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8744 return;
8745
8746 default:
8747 llvm_unreachable(
8748 "Can only end up with a standard conversion sequence or failure");
8749 }
8750
8751 if (EnableIfAttr *FailedAttr =
8752 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8753 Candidate.Viable = false;
8754 Candidate.FailureKind = ovl_fail_enable_if;
8755 Candidate.DeductionFailure.Data = FailedAttr;
8756 return;
8757 }
8758
8759 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8760 Candidate.Viable = false;
8761 Candidate.FailureKind = ovl_non_default_multiversion_function;
8762 }
8763}
8764
8765static void AddTemplateConversionCandidateImmediately(
8766 Sema &S, OverloadCandidateSet &CandidateSet,
8767 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8768 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8769 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8770 bool AllowResultConversion) {
8771
8772 // If the function template has a non-dependent explicit specification,
8773 // exclude it now if appropriate; we are not permitted to perform deduction
8774 // and substitution in this case.
8775 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8776 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8777 Candidate.FoundDecl = FoundDecl;
8778 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8779 Candidate.Viable = false;
8780 Candidate.FailureKind = ovl_fail_explicit;
8781 return;
8782 }
8783
8784 QualType ObjectType = From->getType();
8785 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8786
8787 TemplateDeductionInfo Info(CandidateSet.getLocation());
8788 CXXConversionDecl *Specialization = nullptr;
8789 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8790 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8791 Specialization, Info);
8792 Result != TemplateDeductionResult::Success) {
8793 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8794 Candidate.FoundDecl = FoundDecl;
8795 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8796 Candidate.Viable = false;
8797 Candidate.FailureKind = ovl_fail_bad_deduction;
8798 Candidate.ExplicitCallArguments = 1;
8799 Candidate.DeductionFailure =
8800 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8801 return;
8802 }
8803
8804 // Add the conversion function template specialization produced by
8805 // template argument deduction as a candidate.
8806 assert(Specialization && "Missing function template specialization?");
8807 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8808 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8809 AllowExplicit, AllowResultConversion,
8810 StrictPackMatch: Info.hasStrictPackMatch());
8811}
8812
8813void Sema::AddTemplateConversionCandidate(
8814 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8815 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8816 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8817 bool AllowExplicit, bool AllowResultConversion) {
8818 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8819 "Only conversion function templates permitted here");
8820
8821 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8822 return;
8823
8824 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8825 CandidateSet.getKind() ==
8826 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8827 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8828 AddTemplateConversionCandidateImmediately(
8829 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8830 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8831 AllowResultConversion);
8832
8833 CandidateSet.DisableResolutionByPerfectCandidate();
8834 return;
8835 }
8836
8837 CandidateSet.AddDeferredConversionTemplateCandidate(
8838 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8839 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8840}
8841
8842void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8843 DeclAccessPair FoundDecl,
8844 CXXRecordDecl *ActingContext,
8845 const FunctionProtoType *Proto,
8846 Expr *Object,
8847 ArrayRef<Expr *> Args,
8848 OverloadCandidateSet& CandidateSet) {
8849 if (!CandidateSet.isNewCandidate(F: Conversion))
8850 return;
8851
8852 // Overload resolution is always an unevaluated context.
8853 EnterExpressionEvaluationContext Unevaluated(
8854 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8855
8856 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8857 Candidate.FoundDecl = FoundDecl;
8858 Candidate.Function = nullptr;
8859 Candidate.Surrogate = Conversion;
8860 Candidate.IsSurrogate = true;
8861 Candidate.Viable = true;
8862 Candidate.ExplicitCallArguments = Args.size();
8863
8864 // Determine the implicit conversion sequence for the implicit
8865 // object parameter.
8866 ImplicitConversionSequence ObjectInit;
8867 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8868 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8869 ToType: Conversion->getParamDecl(i: 0)->getType(),
8870 /*SuppressUserConversions=*/false,
8871 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8872 } else {
8873 ObjectInit = TryObjectArgumentInitialization(
8874 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8875 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8876 }
8877
8878 if (ObjectInit.isBad()) {
8879 Candidate.Viable = false;
8880 Candidate.FailureKind = ovl_fail_bad_conversion;
8881 Candidate.Conversions[0] = ObjectInit;
8882 return;
8883 }
8884
8885 // The first conversion is actually a user-defined conversion whose
8886 // first conversion is ObjectInit's standard conversion (which is
8887 // effectively a reference binding). Record it as such.
8888 Candidate.Conversions[0].setUserDefined();
8889 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8890 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8891 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8892 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8893 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8894 Candidate.Conversions[0].UserDefined.After
8895 = Candidate.Conversions[0].UserDefined.Before;
8896 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8897
8898 // Find the
8899 unsigned NumParams = Proto->getNumParams();
8900
8901 // (C++ 13.3.2p2): A candidate function having fewer than m
8902 // parameters is viable only if it has an ellipsis in its parameter
8903 // list (8.3.5).
8904 if (Args.size() > NumParams && !Proto->isVariadic()) {
8905 Candidate.Viable = false;
8906 Candidate.FailureKind = ovl_fail_too_many_arguments;
8907 return;
8908 }
8909
8910 // Function types don't have any default arguments, so just check if
8911 // we have enough arguments.
8912 if (Args.size() < NumParams) {
8913 // Not enough arguments.
8914 Candidate.Viable = false;
8915 Candidate.FailureKind = ovl_fail_too_few_arguments;
8916 return;
8917 }
8918
8919 // Determine the implicit conversion sequences for each of the
8920 // arguments.
8921 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8922 if (ArgIdx < NumParams) {
8923 // (C++ 13.3.2p3): for F to be a viable function, there shall
8924 // exist for each argument an implicit conversion sequence
8925 // (13.3.3.1) that converts that argument to the corresponding
8926 // parameter of F.
8927 QualType ParamType = Proto->getParamType(i: ArgIdx);
8928 Candidate.Conversions[ArgIdx + 1]
8929 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8930 /*SuppressUserConversions=*/false,
8931 /*InOverloadResolution=*/false,
8932 /*AllowObjCWritebackConversion=*/
8933 getLangOpts().ObjCAutoRefCount);
8934 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8935 Candidate.Viable = false;
8936 Candidate.FailureKind = ovl_fail_bad_conversion;
8937 return;
8938 }
8939 } else {
8940 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8941 // argument for which there is no corresponding parameter is
8942 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8943 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8944 }
8945 }
8946
8947 if (Conversion->getTrailingRequiresClause()) {
8948 ConstraintSatisfaction Satisfaction;
8949 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8950 /*ForOverloadResolution*/ true) ||
8951 !Satisfaction.IsSatisfied) {
8952 Candidate.Viable = false;
8953 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8954 return;
8955 }
8956 }
8957
8958 if (EnableIfAttr *FailedAttr =
8959 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8960 Candidate.Viable = false;
8961 Candidate.FailureKind = ovl_fail_enable_if;
8962 Candidate.DeductionFailure.Data = FailedAttr;
8963 return;
8964 }
8965}
8966
8967void Sema::AddNonMemberOperatorCandidates(
8968 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8969 OverloadCandidateSet &CandidateSet,
8970 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8971 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8972 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8973 ArrayRef<Expr *> FunctionArgs = Args;
8974
8975 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8976 FunctionDecl *FD =
8977 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8978
8979 // Don't consider rewritten functions if we're not rewriting.
8980 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8981 continue;
8982
8983 assert(!isa<CXXMethodDecl>(FD) &&
8984 "unqualified operator lookup found a member function");
8985
8986 if (FunTmpl) {
8987 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8988 Args: FunctionArgs, CandidateSet);
8989 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8990
8991 // As template candidates are not deduced immediately,
8992 // persist the array in the overload set.
8993 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8994 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8995 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8996 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8997 IsADLCandidate: ADLCallKind::NotADL,
8998 PO: OverloadCandidateParamOrder::Reversed);
8999 }
9000 } else {
9001 if (ExplicitTemplateArgs)
9002 continue;
9003 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
9004 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
9005 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
9006 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9007 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
9008 PO: OverloadCandidateParamOrder::Reversed);
9009 }
9010 }
9011}
9012
9013void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
9014 SourceLocation OpLoc,
9015 ArrayRef<Expr *> Args,
9016 OverloadCandidateSet &CandidateSet,
9017 OverloadCandidateParamOrder PO) {
9018 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9019
9020 // C++ [over.match.oper]p3:
9021 // For a unary operator @ with an operand of a type whose
9022 // cv-unqualified version is T1, and for a binary operator @ with
9023 // a left operand of a type whose cv-unqualified version is T1 and
9024 // a right operand of a type whose cv-unqualified version is T2,
9025 // three sets of candidate functions, designated member
9026 // candidates, non-member candidates and built-in candidates, are
9027 // constructed as follows:
9028 QualType T1 = Args[0]->getType();
9029
9030 // -- If T1 is a complete class type or a class currently being
9031 // defined, the set of member candidates is the result of the
9032 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9033 // the set of member candidates is empty.
9034 if (T1->isRecordType()) {
9035 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
9036 auto *T1RD = T1->getAsCXXRecordDecl();
9037 // Complete the type if it can be completed.
9038 // If the type is neither complete nor being defined, bail out now.
9039 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9040 return;
9041
9042 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9043 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
9044 Operators.suppressAccessDiagnostics();
9045
9046 for (LookupResult::iterator Oper = Operators.begin(),
9047 OperEnd = Operators.end();
9048 Oper != OperEnd; ++Oper) {
9049 if (Oper->getAsFunction() &&
9050 PO == OverloadCandidateParamOrder::Reversed &&
9051 !CandidateSet.getRewriteInfo().shouldAddReversed(
9052 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
9053 continue;
9054 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
9055 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
9056 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
9057 }
9058 }
9059}
9060
9061void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
9062 OverloadCandidateSet& CandidateSet,
9063 bool IsAssignmentOperator,
9064 unsigned NumContextualBoolArguments) {
9065 // Overload resolution is always an unevaluated context.
9066 EnterExpressionEvaluationContext Unevaluated(
9067 *this, Sema::ExpressionEvaluationContext::Unevaluated);
9068
9069 // Add this candidate
9070 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
9071 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
9072 Candidate.Function = nullptr;
9073 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
9074
9075 // Determine the implicit conversion sequences for each of the
9076 // arguments.
9077 Candidate.Viable = true;
9078 Candidate.ExplicitCallArguments = Args.size();
9079 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9080 // C++ [over.match.oper]p4:
9081 // For the built-in assignment operators, conversions of the
9082 // left operand are restricted as follows:
9083 // -- no temporaries are introduced to hold the left operand, and
9084 // -- no user-defined conversions are applied to the left
9085 // operand to achieve a type match with the left-most
9086 // parameter of a built-in candidate.
9087 //
9088 // We block these conversions by turning off user-defined
9089 // conversions, since that is the only way that initialization of
9090 // a reference to a non-class type can occur from something that
9091 // is not of the same type.
9092 if (ArgIdx < NumContextualBoolArguments) {
9093 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9094 "Contextual conversion to bool requires bool type");
9095 Candidate.Conversions[ArgIdx]
9096 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9097 } else {
9098 Candidate.Conversions[ArgIdx]
9099 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9100 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9101 /*InOverloadResolution=*/false,
9102 /*AllowObjCWritebackConversion=*/
9103 getLangOpts().ObjCAutoRefCount);
9104 }
9105 if (Candidate.Conversions[ArgIdx].isBad()) {
9106 Candidate.Viable = false;
9107 Candidate.FailureKind = ovl_fail_bad_conversion;
9108 break;
9109 }
9110 }
9111}
9112
9113namespace {
9114
9115/// BuiltinCandidateTypeSet - A set of types that will be used for the
9116/// candidate operator functions for built-in operators (C++
9117/// [over.built]). The types are separated into pointer types and
9118/// enumeration types.
9119class BuiltinCandidateTypeSet {
9120 /// TypeSet - A set of types.
9121 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9122
9123 /// PointerTypes - The set of pointer types that will be used in the
9124 /// built-in candidates.
9125 TypeSet PointerTypes;
9126
9127 /// MemberPointerTypes - The set of member pointer types that will be
9128 /// used in the built-in candidates.
9129 TypeSet MemberPointerTypes;
9130
9131 /// EnumerationTypes - The set of enumeration types that will be
9132 /// used in the built-in candidates.
9133 TypeSet EnumerationTypes;
9134
9135 /// The set of vector types that will be used in the built-in
9136 /// candidates.
9137 TypeSet VectorTypes;
9138
9139 /// The set of matrix types that will be used in the built-in
9140 /// candidates.
9141 TypeSet MatrixTypes;
9142
9143 /// The set of _BitInt types that will be used in the built-in candidates.
9144 TypeSet BitIntTypes;
9145
9146 /// A flag indicating non-record types are viable candidates
9147 bool HasNonRecordTypes;
9148
9149 /// A flag indicating whether either arithmetic or enumeration types
9150 /// were present in the candidate set.
9151 bool HasArithmeticOrEnumeralTypes;
9152
9153 /// A flag indicating whether the nullptr type was present in the
9154 /// candidate set.
9155 bool HasNullPtrType;
9156
9157 /// Sema - The semantic analysis instance where we are building the
9158 /// candidate type set.
9159 Sema &SemaRef;
9160
9161 /// Context - The AST context in which we will build the type sets.
9162 ASTContext &Context;
9163
9164 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9165 const Qualifiers &VisibleQuals);
9166 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9167
9168public:
9169 /// iterator - Iterates through the types that are part of the set.
9170 typedef TypeSet::iterator iterator;
9171
9172 BuiltinCandidateTypeSet(Sema &SemaRef)
9173 : HasNonRecordTypes(false),
9174 HasArithmeticOrEnumeralTypes(false),
9175 HasNullPtrType(false),
9176 SemaRef(SemaRef),
9177 Context(SemaRef.Context) { }
9178
9179 void AddTypesConvertedFrom(QualType Ty,
9180 SourceLocation Loc,
9181 bool AllowUserConversions,
9182 bool AllowExplicitConversions,
9183 const Qualifiers &VisibleTypeConversionsQuals);
9184
9185 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9186 llvm::iterator_range<iterator> member_pointer_types() {
9187 return MemberPointerTypes;
9188 }
9189 llvm::iterator_range<iterator> enumeration_types() {
9190 return EnumerationTypes;
9191 }
9192 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9193 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9194 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9195
9196 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9197 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9198 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9199 bool hasNullPtrType() const { return HasNullPtrType; }
9200};
9201
9202} // end anonymous namespace
9203
9204/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9205/// the set of pointer types along with any more-qualified variants of
9206/// that type. For example, if @p Ty is "int const *", this routine
9207/// will add "int const *", "int const volatile *", "int const
9208/// restrict *", and "int const volatile restrict *" to the set of
9209/// pointer types. Returns true if the add of @p Ty itself succeeded,
9210/// false otherwise.
9211///
9212/// FIXME: what to do about extended qualifiers?
9213bool
9214BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9215 const Qualifiers &VisibleQuals) {
9216
9217 // Insert this type.
9218 if (!PointerTypes.insert(X: Ty))
9219 return false;
9220
9221 QualType PointeeTy;
9222 const PointerType *PointerTy = Ty->getAs<PointerType>();
9223 bool buildObjCPtr = false;
9224 if (!PointerTy) {
9225 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9226 PointeeTy = PTy->getPointeeType();
9227 buildObjCPtr = true;
9228 } else {
9229 PointeeTy = PointerTy->getPointeeType();
9230 }
9231
9232 // Don't add qualified variants of arrays. For one, they're not allowed
9233 // (the qualifier would sink to the element type), and for another, the
9234 // only overload situation where it matters is subscript or pointer +- int,
9235 // and those shouldn't have qualifier variants anyway.
9236 if (PointeeTy->isArrayType())
9237 return true;
9238
9239 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9240 bool hasVolatile = VisibleQuals.hasVolatile();
9241 bool hasRestrict = VisibleQuals.hasRestrict();
9242
9243 // Iterate through all strict supersets of BaseCVR.
9244 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9245 if ((CVR | BaseCVR) != CVR) continue;
9246 // Skip over volatile if no volatile found anywhere in the types.
9247 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9248
9249 // Skip over restrict if no restrict found anywhere in the types, or if
9250 // the type cannot be restrict-qualified.
9251 if ((CVR & Qualifiers::Restrict) &&
9252 (!hasRestrict ||
9253 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9254 continue;
9255
9256 // Build qualified pointee type.
9257 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9258
9259 // Build qualified pointer type.
9260 QualType QPointerTy;
9261 if (!buildObjCPtr)
9262 QPointerTy = Context.getPointerType(T: QPointeeTy);
9263 else
9264 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9265
9266 // Insert qualified pointer type.
9267 PointerTypes.insert(X: QPointerTy);
9268 }
9269
9270 return true;
9271}
9272
9273/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9274/// to the set of pointer types along with any more-qualified variants of
9275/// that type. For example, if @p Ty is "int const *", this routine
9276/// will add "int const *", "int const volatile *", "int const
9277/// restrict *", and "int const volatile restrict *" to the set of
9278/// pointer types. Returns true if the add of @p Ty itself succeeded,
9279/// false otherwise.
9280///
9281/// FIXME: what to do about extended qualifiers?
9282bool
9283BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9284 QualType Ty) {
9285 // Insert this type.
9286 if (!MemberPointerTypes.insert(X: Ty))
9287 return false;
9288
9289 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9290 assert(PointerTy && "type was not a member pointer type!");
9291
9292 QualType PointeeTy = PointerTy->getPointeeType();
9293 // Don't add qualified variants of arrays. For one, they're not allowed
9294 // (the qualifier would sink to the element type), and for another, the
9295 // only overload situation where it matters is subscript or pointer +- int,
9296 // and those shouldn't have qualifier variants anyway.
9297 if (PointeeTy->isArrayType())
9298 return true;
9299 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9300
9301 // Iterate through all strict supersets of the pointee type's CVR
9302 // qualifiers.
9303 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9304 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9305 if ((CVR | BaseCVR) != CVR) continue;
9306
9307 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9308 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9309 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9310 }
9311
9312 return true;
9313}
9314
9315/// AddTypesConvertedFrom - Add each of the types to which the type @p
9316/// Ty can be implicit converted to the given set of @p Types. We're
9317/// primarily interested in pointer types and enumeration types. We also
9318/// take member pointer types, for the conditional operator.
9319/// AllowUserConversions is true if we should look at the conversion
9320/// functions of a class type, and AllowExplicitConversions if we
9321/// should also include the explicit conversion functions of a class
9322/// type.
9323void
9324BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9325 SourceLocation Loc,
9326 bool AllowUserConversions,
9327 bool AllowExplicitConversions,
9328 const Qualifiers &VisibleQuals) {
9329 // Only deal with canonical types.
9330 Ty = Context.getCanonicalType(T: Ty);
9331
9332 // Look through reference types; they aren't part of the type of an
9333 // expression for the purposes of conversions.
9334 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9335 Ty = RefTy->getPointeeType();
9336
9337 // If we're dealing with an array type, decay to the pointer.
9338 if (Ty->isArrayType())
9339 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9340
9341 // Otherwise, we don't care about qualifiers on the type.
9342 Ty = Ty.getLocalUnqualifiedType();
9343
9344 // Flag if we ever add a non-record type.
9345 bool TyIsRec = Ty->isRecordType();
9346 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9347
9348 // Flag if we encounter an arithmetic type.
9349 HasArithmeticOrEnumeralTypes =
9350 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9351
9352 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9353 PointerTypes.insert(X: Ty);
9354 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9355 // Insert our type, and its more-qualified variants, into the set
9356 // of types.
9357 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9358 return;
9359 } else if (Ty->isMemberPointerType()) {
9360 // Member pointers are far easier, since the pointee can't be converted.
9361 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9362 return;
9363 } else if (Ty->isEnumeralType()) {
9364 HasArithmeticOrEnumeralTypes = true;
9365 EnumerationTypes.insert(X: Ty);
9366 } else if (Ty->isBitIntType()) {
9367 HasArithmeticOrEnumeralTypes = true;
9368 BitIntTypes.insert(X: Ty);
9369 } else if (Ty->isVectorType()) {
9370 // We treat vector types as arithmetic types in many contexts as an
9371 // extension.
9372 HasArithmeticOrEnumeralTypes = true;
9373 VectorTypes.insert(X: Ty);
9374 } else if (Ty->isMatrixType()) {
9375 // Similar to vector types, we treat vector types as arithmetic types in
9376 // many contexts as an extension.
9377 HasArithmeticOrEnumeralTypes = true;
9378 MatrixTypes.insert(X: Ty);
9379 } else if (Ty->isNullPtrType()) {
9380 HasNullPtrType = true;
9381 } else if (AllowUserConversions && TyIsRec) {
9382 // No conversion functions in incomplete types.
9383 if (!SemaRef.isCompleteType(Loc, T: Ty))
9384 return;
9385
9386 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9387 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9388 if (isa<UsingShadowDecl>(Val: D))
9389 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9390
9391 // Skip conversion function templates; they don't tell us anything
9392 // about which builtin types we can convert to.
9393 if (isa<FunctionTemplateDecl>(Val: D))
9394 continue;
9395
9396 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9397 if (AllowExplicitConversions || !Conv->isExplicit()) {
9398 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9399 VisibleQuals);
9400 }
9401 }
9402 }
9403}
9404/// Helper function for adjusting address spaces for the pointer or reference
9405/// operands of builtin operators depending on the argument.
9406static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9407 Expr *Arg) {
9408 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9409}
9410
9411/// Helper function for AddBuiltinOperatorCandidates() that adds
9412/// the volatile- and non-volatile-qualified assignment operators for the
9413/// given type to the candidate set.
9414static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9415 QualType T,
9416 ArrayRef<Expr *> Args,
9417 OverloadCandidateSet &CandidateSet) {
9418 QualType ParamTypes[2];
9419
9420 // T& operator=(T&, T)
9421 ParamTypes[0] = S.Context.getLValueReferenceType(
9422 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9423 ParamTypes[1] = T;
9424 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9425 /*IsAssignmentOperator=*/true);
9426
9427 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9428 // volatile T& operator=(volatile T&, T)
9429 ParamTypes[0] = S.Context.getLValueReferenceType(
9430 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9431 Arg: Args[0]));
9432 ParamTypes[1] = T;
9433 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9434 /*IsAssignmentOperator=*/true);
9435 }
9436}
9437
9438/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9439/// if any, found in visible type conversion functions found in ArgExpr's type.
9440static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9441 Qualifiers VRQuals;
9442 CXXRecordDecl *ClassDecl;
9443 if (const MemberPointerType *RHSMPType =
9444 ArgExpr->getType()->getAs<MemberPointerType>())
9445 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9446 else
9447 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9448 if (!ClassDecl) {
9449 // Just to be safe, assume the worst case.
9450 VRQuals.addVolatile();
9451 VRQuals.addRestrict();
9452 return VRQuals;
9453 }
9454 if (!ClassDecl->hasDefinition())
9455 return VRQuals;
9456
9457 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9458 if (isa<UsingShadowDecl>(Val: D))
9459 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9460 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9461 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9462 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9463 CanTy = ResTypeRef->getPointeeType();
9464 // Need to go down the pointer/mempointer chain and add qualifiers
9465 // as see them.
9466 bool done = false;
9467 while (!done) {
9468 if (CanTy.isRestrictQualified())
9469 VRQuals.addRestrict();
9470 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9471 CanTy = ResTypePtr->getPointeeType();
9472 else if (const MemberPointerType *ResTypeMPtr =
9473 CanTy->getAs<MemberPointerType>())
9474 CanTy = ResTypeMPtr->getPointeeType();
9475 else
9476 done = true;
9477 if (CanTy.isVolatileQualified())
9478 VRQuals.addVolatile();
9479 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9480 return VRQuals;
9481 }
9482 }
9483 }
9484 return VRQuals;
9485}
9486
9487// Note: We're currently only handling qualifiers that are meaningful for the
9488// LHS of compound assignment overloading.
9489static void forAllQualifierCombinationsImpl(
9490 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9491 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9492 // _Atomic
9493 if (Available.hasAtomic()) {
9494 Available.removeAtomic();
9495 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9496 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9497 return;
9498 }
9499
9500 // volatile
9501 if (Available.hasVolatile()) {
9502 Available.removeVolatile();
9503 assert(!Applied.hasVolatile());
9504 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9505 Callback);
9506 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9507 return;
9508 }
9509
9510 Callback(Applied);
9511}
9512
9513static void forAllQualifierCombinations(
9514 QualifiersAndAtomic Quals,
9515 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9516 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9517 Callback);
9518}
9519
9520static QualType makeQualifiedLValueReferenceType(QualType Base,
9521 QualifiersAndAtomic Quals,
9522 Sema &S) {
9523 if (Quals.hasAtomic())
9524 Base = S.Context.getAtomicType(T: Base);
9525 if (Quals.hasVolatile())
9526 Base = S.Context.getVolatileType(T: Base);
9527 return S.Context.getLValueReferenceType(T: Base);
9528}
9529
9530namespace {
9531
9532/// Helper class to manage the addition of builtin operator overload
9533/// candidates. It provides shared state and utility methods used throughout
9534/// the process, as well as a helper method to add each group of builtin
9535/// operator overloads from the standard to a candidate set.
9536class BuiltinOperatorOverloadBuilder {
9537 // Common instance state available to all overload candidate addition methods.
9538 Sema &S;
9539 ArrayRef<Expr *> Args;
9540 QualifiersAndAtomic VisibleTypeConversionsQuals;
9541 bool HasArithmeticOrEnumeralCandidateType;
9542 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9543 OverloadCandidateSet &CandidateSet;
9544
9545 static constexpr int ArithmeticTypesCap = 26;
9546 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9547
9548 // Define some indices used to iterate over the arithmetic types in
9549 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9550 // types are that preserved by promotion (C++ [over.built]p2).
9551 unsigned FirstIntegralType,
9552 LastIntegralType;
9553 unsigned FirstPromotedIntegralType,
9554 LastPromotedIntegralType;
9555 unsigned FirstPromotedArithmeticType,
9556 LastPromotedArithmeticType;
9557 unsigned NumArithmeticTypes;
9558
9559 void InitArithmeticTypes() {
9560 // Start of promoted types.
9561 FirstPromotedArithmeticType = 0;
9562 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9563 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9564 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9565 if (S.Context.getTargetInfo().hasFloat128Type())
9566 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9567 if (S.Context.getTargetInfo().hasIbm128Type())
9568 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9569
9570 // Start of integral types.
9571 FirstIntegralType = ArithmeticTypes.size();
9572 FirstPromotedIntegralType = ArithmeticTypes.size();
9573 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9574 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9575 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9576 if (S.Context.getTargetInfo().hasInt128Type() ||
9577 (S.Context.getAuxTargetInfo() &&
9578 S.Context.getAuxTargetInfo()->hasInt128Type()))
9579 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9580 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9581 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9582 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9583 if (S.Context.getTargetInfo().hasInt128Type() ||
9584 (S.Context.getAuxTargetInfo() &&
9585 S.Context.getAuxTargetInfo()->hasInt128Type()))
9586 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9587
9588 /// We add candidates for the unique, unqualified _BitInt types present in
9589 /// the candidate type set. The candidate set already handled ensuring the
9590 /// type is unqualified and canonical, but because we're adding from N
9591 /// different sets, we need to do some extra work to unique things. Insert
9592 /// the candidates into a unique set, then move from that set into the list
9593 /// of arithmetic types.
9594 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9595 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9596 for (QualType BitTy : Candidate.bitint_types())
9597 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9598 }
9599 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9600 LastPromotedIntegralType = ArithmeticTypes.size();
9601 LastPromotedArithmeticType = ArithmeticTypes.size();
9602 // End of promoted types.
9603
9604 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9605 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9606 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9607 if (S.Context.getLangOpts().Char8)
9608 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9609 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9610 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9611 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9612 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9613 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9614 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9615 LastIntegralType = ArithmeticTypes.size();
9616 NumArithmeticTypes = ArithmeticTypes.size();
9617 // End of integral types.
9618 // FIXME: What about complex? What about half?
9619
9620 // We don't know for sure how many bit-precise candidates were involved, so
9621 // we subtract those from the total when testing whether we're under the
9622 // cap or not.
9623 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9624 ArithmeticTypesCap &&
9625 "Enough inline storage for all arithmetic types.");
9626 }
9627
9628 /// Helper method to factor out the common pattern of adding overloads
9629 /// for '++' and '--' builtin operators.
9630 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9631 bool HasVolatile,
9632 bool HasRestrict) {
9633 QualType ParamTypes[2] = {
9634 S.Context.getLValueReferenceType(T: CandidateTy),
9635 S.Context.IntTy
9636 };
9637
9638 // Non-volatile version.
9639 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9640
9641 // Use a heuristic to reduce number of builtin candidates in the set:
9642 // add volatile version only if there are conversions to a volatile type.
9643 if (HasVolatile) {
9644 ParamTypes[0] =
9645 S.Context.getLValueReferenceType(
9646 T: S.Context.getVolatileType(T: CandidateTy));
9647 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9648 }
9649
9650 // Add restrict version only if there are conversions to a restrict type
9651 // and our candidate type is a non-restrict-qualified pointer.
9652 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9653 !CandidateTy.isRestrictQualified()) {
9654 ParamTypes[0]
9655 = S.Context.getLValueReferenceType(
9656 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9657 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9658
9659 if (HasVolatile) {
9660 ParamTypes[0]
9661 = S.Context.getLValueReferenceType(
9662 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9663 CVR: (Qualifiers::Volatile |
9664 Qualifiers::Restrict)));
9665 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9666 }
9667 }
9668
9669 }
9670
9671 /// Helper to add an overload candidate for a binary builtin with types \p L
9672 /// and \p R.
9673 void AddCandidate(QualType L, QualType R) {
9674 QualType LandR[2] = {L, R};
9675 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9676 }
9677
9678public:
9679 BuiltinOperatorOverloadBuilder(
9680 Sema &S, ArrayRef<Expr *> Args,
9681 QualifiersAndAtomic VisibleTypeConversionsQuals,
9682 bool HasArithmeticOrEnumeralCandidateType,
9683 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9684 OverloadCandidateSet &CandidateSet)
9685 : S(S), Args(Args),
9686 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9687 HasArithmeticOrEnumeralCandidateType(
9688 HasArithmeticOrEnumeralCandidateType),
9689 CandidateTypes(CandidateTypes),
9690 CandidateSet(CandidateSet) {
9691
9692 InitArithmeticTypes();
9693 }
9694
9695 // Increment is deprecated for bool since C++17.
9696 //
9697 // C++ [over.built]p3:
9698 //
9699 // For every pair (T, VQ), where T is an arithmetic type other
9700 // than bool, and VQ is either volatile or empty, there exist
9701 // candidate operator functions of the form
9702 //
9703 // VQ T& operator++(VQ T&);
9704 // T operator++(VQ T&, int);
9705 //
9706 // C++ [over.built]p4:
9707 //
9708 // For every pair (T, VQ), where T is an arithmetic type other
9709 // than bool, and VQ is either volatile or empty, there exist
9710 // candidate operator functions of the form
9711 //
9712 // VQ T& operator--(VQ T&);
9713 // T operator--(VQ T&, int);
9714 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9715 if (!HasArithmeticOrEnumeralCandidateType)
9716 return;
9717
9718 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9719 const auto TypeOfT = ArithmeticTypes[Arith];
9720 if (TypeOfT == S.Context.BoolTy) {
9721 if (Op == OO_MinusMinus)
9722 continue;
9723 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9724 continue;
9725 }
9726 addPlusPlusMinusMinusStyleOverloads(
9727 CandidateTy: TypeOfT,
9728 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9729 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9730 }
9731 }
9732
9733 // C++ [over.built]p5:
9734 //
9735 // For every pair (T, VQ), where T is a cv-qualified or
9736 // cv-unqualified object type, and VQ is either volatile or
9737 // empty, there exist candidate operator functions of the form
9738 //
9739 // T*VQ& operator++(T*VQ&);
9740 // T*VQ& operator--(T*VQ&);
9741 // T* operator++(T*VQ&, int);
9742 // T* operator--(T*VQ&, int);
9743 void addPlusPlusMinusMinusPointerOverloads() {
9744 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9745 // Skip pointer types that aren't pointers to object types.
9746 if (!PtrTy->getPointeeType()->isObjectType())
9747 continue;
9748
9749 addPlusPlusMinusMinusStyleOverloads(
9750 CandidateTy: PtrTy,
9751 HasVolatile: (!PtrTy.isVolatileQualified() &&
9752 VisibleTypeConversionsQuals.hasVolatile()),
9753 HasRestrict: (!PtrTy.isRestrictQualified() &&
9754 VisibleTypeConversionsQuals.hasRestrict()));
9755 }
9756 }
9757
9758 // C++ [over.built]p6:
9759 // For every cv-qualified or cv-unqualified object type T, there
9760 // exist candidate operator functions of the form
9761 //
9762 // T& operator*(T*);
9763 //
9764 // C++ [over.built]p7:
9765 // For every function type T that does not have cv-qualifiers or a
9766 // ref-qualifier, there exist candidate operator functions of the form
9767 // T& operator*(T*);
9768 void addUnaryStarPointerOverloads() {
9769 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9770 QualType PointeeTy = ParamTy->getPointeeType();
9771 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9772 continue;
9773
9774 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9775 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9776 continue;
9777
9778 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9779 }
9780 }
9781
9782 // C++ [over.built]p9:
9783 // For every promoted arithmetic type T, there exist candidate
9784 // operator functions of the form
9785 //
9786 // T operator+(T);
9787 // T operator-(T);
9788 void addUnaryPlusOrMinusArithmeticOverloads() {
9789 if (!HasArithmeticOrEnumeralCandidateType)
9790 return;
9791
9792 for (unsigned Arith = FirstPromotedArithmeticType;
9793 Arith < LastPromotedArithmeticType; ++Arith) {
9794 QualType ArithTy = ArithmeticTypes[Arith];
9795 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9796 }
9797
9798 // Extension: We also add these operators for vector types.
9799 for (QualType VecTy : CandidateTypes[0].vector_types())
9800 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9801 }
9802
9803 // C++ [over.built]p8:
9804 // For every type T, there exist candidate operator functions of
9805 // the form
9806 //
9807 // T* operator+(T*);
9808 void addUnaryPlusPointerOverloads() {
9809 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9810 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9811 }
9812
9813 // C++ [over.built]p10:
9814 // For every promoted integral type T, there exist candidate
9815 // operator functions of the form
9816 //
9817 // T operator~(T);
9818 void addUnaryTildePromotedIntegralOverloads() {
9819 if (!HasArithmeticOrEnumeralCandidateType)
9820 return;
9821
9822 for (unsigned Int = FirstPromotedIntegralType;
9823 Int < LastPromotedIntegralType; ++Int) {
9824 QualType IntTy = ArithmeticTypes[Int];
9825 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9826 }
9827
9828 // Extension: We also add this operator for vector types.
9829 for (QualType VecTy : CandidateTypes[0].vector_types())
9830 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9831 }
9832
9833 // C++ [over.match.oper]p16:
9834 // For every pointer to member type T or type std::nullptr_t, there
9835 // exist candidate operator functions of the form
9836 //
9837 // bool operator==(T,T);
9838 // bool operator!=(T,T);
9839 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9840 /// Set of (canonical) types that we've already handled.
9841 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9842
9843 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9844 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9845 // Don't add the same builtin candidate twice.
9846 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9847 continue;
9848
9849 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9850 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9851 }
9852
9853 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9854 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9855 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9856 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9857 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9858 }
9859 }
9860 }
9861 }
9862
9863 // C++ [over.built]p15:
9864 //
9865 // For every T, where T is an enumeration type or a pointer type,
9866 // there exist candidate operator functions of the form
9867 //
9868 // bool operator<(T, T);
9869 // bool operator>(T, T);
9870 // bool operator<=(T, T);
9871 // bool operator>=(T, T);
9872 // bool operator==(T, T);
9873 // bool operator!=(T, T);
9874 // R operator<=>(T, T)
9875 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9876 // C++ [over.match.oper]p3:
9877 // [...]the built-in candidates include all of the candidate operator
9878 // functions defined in 13.6 that, compared to the given operator, [...]
9879 // do not have the same parameter-type-list as any non-template non-member
9880 // candidate.
9881 //
9882 // Note that in practice, this only affects enumeration types because there
9883 // aren't any built-in candidates of record type, and a user-defined operator
9884 // must have an operand of record or enumeration type. Also, the only other
9885 // overloaded operator with enumeration arguments, operator=,
9886 // cannot be overloaded for enumeration types, so this is the only place
9887 // where we must suppress candidates like this.
9888 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9889 UserDefinedBinaryOperators;
9890
9891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9892 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9893 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9894 CEnd = CandidateSet.end();
9895 C != CEnd; ++C) {
9896 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9897 continue;
9898
9899 if (C->Function->isFunctionTemplateSpecialization())
9900 continue;
9901
9902 // We interpret "same parameter-type-list" as applying to the
9903 // "synthesized candidate, with the order of the two parameters
9904 // reversed", not to the original function.
9905 bool Reversed = C->isReversed();
9906 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9907 ->getType()
9908 .getUnqualifiedType();
9909 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9910 ->getType()
9911 .getUnqualifiedType();
9912
9913 // Skip if either parameter isn't of enumeral type.
9914 if (!FirstParamType->isEnumeralType() ||
9915 !SecondParamType->isEnumeralType())
9916 continue;
9917
9918 // Add this operator to the set of known user-defined operators.
9919 UserDefinedBinaryOperators.insert(
9920 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9921 y: S.Context.getCanonicalType(T: SecondParamType)));
9922 }
9923 }
9924 }
9925
9926 /// Set of (canonical) types that we've already handled.
9927 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9928
9929 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9930 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9931 // Don't add the same builtin candidate twice.
9932 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9933 continue;
9934 if (IsSpaceship && PtrTy->isFunctionPointerType())
9935 continue;
9936
9937 QualType ParamTypes[2] = {PtrTy, PtrTy};
9938 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9939 }
9940 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9941 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9942
9943 // Don't add the same builtin candidate twice, or if a user defined
9944 // candidate exists.
9945 if (!AddedTypes.insert(Ptr: CanonType).second ||
9946 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9947 y&: CanonType)))
9948 continue;
9949 QualType ParamTypes[2] = {EnumTy, EnumTy};
9950 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9951 }
9952 }
9953 }
9954
9955 // C++ [over.built]p13:
9956 //
9957 // For every cv-qualified or cv-unqualified object type T
9958 // there exist candidate operator functions of the form
9959 //
9960 // T* operator+(T*, ptrdiff_t);
9961 // T& operator[](T*, ptrdiff_t); [BELOW]
9962 // T* operator-(T*, ptrdiff_t);
9963 // T* operator+(ptrdiff_t, T*);
9964 // T& operator[](ptrdiff_t, T*); [BELOW]
9965 //
9966 // C++ [over.built]p14:
9967 //
9968 // For every T, where T is a pointer to object type, there
9969 // exist candidate operator functions of the form
9970 //
9971 // ptrdiff_t operator-(T, T);
9972 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9973 /// Set of (canonical) types that we've already handled.
9974 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9975
9976 for (int Arg = 0; Arg < 2; ++Arg) {
9977 QualType AsymmetricParamTypes[2] = {
9978 S.Context.getPointerDiffType(),
9979 S.Context.getPointerDiffType(),
9980 };
9981 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9982 QualType PointeeTy = PtrTy->getPointeeType();
9983 if (!PointeeTy->isObjectType())
9984 continue;
9985
9986 AsymmetricParamTypes[Arg] = PtrTy;
9987 if (Arg == 0 || Op == OO_Plus) {
9988 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9989 // T* operator+(ptrdiff_t, T*);
9990 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9991 }
9992 if (Op == OO_Minus) {
9993 // ptrdiff_t operator-(T, T);
9994 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9995 continue;
9996
9997 QualType ParamTypes[2] = {PtrTy, PtrTy};
9998 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9999 }
10000 }
10001 }
10002 }
10003
10004 // C++ [over.built]p12:
10005 //
10006 // For every pair of promoted arithmetic types L and R, there
10007 // exist candidate operator functions of the form
10008 //
10009 // LR operator*(L, R);
10010 // LR operator/(L, R);
10011 // LR operator+(L, R);
10012 // LR operator-(L, R);
10013 // bool operator<(L, R);
10014 // bool operator>(L, R);
10015 // bool operator<=(L, R);
10016 // bool operator>=(L, R);
10017 // bool operator==(L, R);
10018 // bool operator!=(L, R);
10019 //
10020 // where LR is the result of the usual arithmetic conversions
10021 // between types L and R.
10022 //
10023 // C++ [over.built]p24:
10024 //
10025 // For every pair of promoted arithmetic types L and R, there exist
10026 // candidate operator functions of the form
10027 //
10028 // LR operator?(bool, L, R);
10029 //
10030 // where LR is the result of the usual arithmetic conversions
10031 // between types L and R.
10032 // Our candidates ignore the first parameter.
10033 void addGenericBinaryArithmeticOverloads() {
10034 if (!HasArithmeticOrEnumeralCandidateType)
10035 return;
10036
10037 for (unsigned Left = FirstPromotedArithmeticType;
10038 Left < LastPromotedArithmeticType; ++Left) {
10039 for (unsigned Right = FirstPromotedArithmeticType;
10040 Right < LastPromotedArithmeticType; ++Right) {
10041 QualType LandR[2] = { ArithmeticTypes[Left],
10042 ArithmeticTypes[Right] };
10043 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10044 }
10045 }
10046
10047 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10048 // conditional operator for vector types.
10049 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10050 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10051 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10052 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10053 }
10054 }
10055
10056 /// Add binary operator overloads for each candidate matrix type M1, M2:
10057 /// * (M1, M1) -> M1
10058 /// * (M1, M1.getElementType()) -> M1
10059 /// * (M2.getElementType(), M2) -> M2
10060 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10061 void addMatrixBinaryArithmeticOverloads() {
10062 if (!HasArithmeticOrEnumeralCandidateType)
10063 return;
10064
10065 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10066 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
10067 AddCandidate(L: M1, R: M1);
10068 }
10069
10070 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10071 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
10072 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
10073 AddCandidate(L: M2, R: M2);
10074 }
10075 }
10076
10077 // C++2a [over.built]p14:
10078 //
10079 // For every integral type T there exists a candidate operator function
10080 // of the form
10081 //
10082 // std::strong_ordering operator<=>(T, T)
10083 //
10084 // C++2a [over.built]p15:
10085 //
10086 // For every pair of floating-point types L and R, there exists a candidate
10087 // operator function of the form
10088 //
10089 // std::partial_ordering operator<=>(L, R);
10090 //
10091 // FIXME: The current specification for integral types doesn't play nice with
10092 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10093 // comparisons. Under the current spec this can lead to ambiguity during
10094 // overload resolution. For example:
10095 //
10096 // enum A : int {a};
10097 // auto x = (a <=> (long)42);
10098 //
10099 // error: call is ambiguous for arguments 'A' and 'long'.
10100 // note: candidate operator<=>(int, int)
10101 // note: candidate operator<=>(long, long)
10102 //
10103 // To avoid this error, this function deviates from the specification and adds
10104 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10105 // arithmetic types (the same as the generic relational overloads).
10106 //
10107 // For now this function acts as a placeholder.
10108 void addThreeWayArithmeticOverloads() {
10109 addGenericBinaryArithmeticOverloads();
10110 }
10111
10112 // C++ [over.built]p17:
10113 //
10114 // For every pair of promoted integral types L and R, there
10115 // exist candidate operator functions of the form
10116 //
10117 // LR operator%(L, R);
10118 // LR operator&(L, R);
10119 // LR operator^(L, R);
10120 // LR operator|(L, R);
10121 // L operator<<(L, R);
10122 // L operator>>(L, R);
10123 //
10124 // where LR is the result of the usual arithmetic conversions
10125 // between types L and R.
10126 void addBinaryBitwiseArithmeticOverloads() {
10127 if (!HasArithmeticOrEnumeralCandidateType)
10128 return;
10129
10130 for (unsigned Left = FirstPromotedIntegralType;
10131 Left < LastPromotedIntegralType; ++Left) {
10132 for (unsigned Right = FirstPromotedIntegralType;
10133 Right < LastPromotedIntegralType; ++Right) {
10134 QualType LandR[2] = { ArithmeticTypes[Left],
10135 ArithmeticTypes[Right] };
10136 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10137 }
10138 }
10139 }
10140
10141 // C++ [over.built]p20:
10142 //
10143 // For every pair (T, VQ), where T is an enumeration or
10144 // pointer to member type and VQ is either volatile or
10145 // empty, there exist candidate operator functions of the form
10146 //
10147 // VQ T& operator=(VQ T&, T);
10148 void addAssignmentMemberPointerOrEnumeralOverloads() {
10149 /// Set of (canonical) types that we've already handled.
10150 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10151
10152 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10153 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10154 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10155 continue;
10156
10157 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10158 }
10159
10160 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10161 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10162 continue;
10163
10164 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10165 }
10166 }
10167 }
10168
10169 // C++ [over.built]p19:
10170 //
10171 // For every pair (T, VQ), where T is any type and VQ is either
10172 // volatile or empty, there exist candidate operator functions
10173 // of the form
10174 //
10175 // T*VQ& operator=(T*VQ&, T*);
10176 //
10177 // C++ [over.built]p21:
10178 //
10179 // For every pair (T, VQ), where T is a cv-qualified or
10180 // cv-unqualified object type and VQ is either volatile or
10181 // empty, there exist candidate operator functions of the form
10182 //
10183 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10184 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10185 void addAssignmentPointerOverloads(bool isEqualOp) {
10186 /// Set of (canonical) types that we've already handled.
10187 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10188
10189 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10190 // If this is operator=, keep track of the builtin candidates we added.
10191 if (isEqualOp)
10192 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10193 else if (!PtrTy->getPointeeType()->isObjectType())
10194 continue;
10195
10196 // non-volatile version
10197 QualType ParamTypes[2] = {
10198 S.Context.getLValueReferenceType(T: PtrTy),
10199 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10200 };
10201 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10202 /*IsAssignmentOperator=*/ isEqualOp);
10203
10204 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10205 VisibleTypeConversionsQuals.hasVolatile();
10206 if (NeedVolatile) {
10207 // volatile version
10208 ParamTypes[0] =
10209 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10210 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10211 /*IsAssignmentOperator=*/isEqualOp);
10212 }
10213
10214 if (!PtrTy.isRestrictQualified() &&
10215 VisibleTypeConversionsQuals.hasRestrict()) {
10216 // restrict version
10217 ParamTypes[0] =
10218 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10219 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10220 /*IsAssignmentOperator=*/isEqualOp);
10221
10222 if (NeedVolatile) {
10223 // volatile restrict version
10224 ParamTypes[0] =
10225 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10226 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10227 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10228 /*IsAssignmentOperator=*/isEqualOp);
10229 }
10230 }
10231 }
10232
10233 if (isEqualOp) {
10234 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10235 // Make sure we don't add the same candidate twice.
10236 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10237 continue;
10238
10239 QualType ParamTypes[2] = {
10240 S.Context.getLValueReferenceType(T: PtrTy),
10241 PtrTy,
10242 };
10243
10244 // non-volatile version
10245 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10246 /*IsAssignmentOperator=*/true);
10247
10248 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10249 VisibleTypeConversionsQuals.hasVolatile();
10250 if (NeedVolatile) {
10251 // volatile version
10252 ParamTypes[0] = S.Context.getLValueReferenceType(
10253 T: S.Context.getVolatileType(T: PtrTy));
10254 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10255 /*IsAssignmentOperator=*/true);
10256 }
10257
10258 if (!PtrTy.isRestrictQualified() &&
10259 VisibleTypeConversionsQuals.hasRestrict()) {
10260 // restrict version
10261 ParamTypes[0] = S.Context.getLValueReferenceType(
10262 T: S.Context.getRestrictType(T: PtrTy));
10263 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10264 /*IsAssignmentOperator=*/true);
10265
10266 if (NeedVolatile) {
10267 // volatile restrict version
10268 ParamTypes[0] =
10269 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10270 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10271 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10272 /*IsAssignmentOperator=*/true);
10273 }
10274 }
10275 }
10276 }
10277 }
10278
10279 // C++ [over.built]p18:
10280 //
10281 // For every triple (L, VQ, R), where L is an arithmetic type,
10282 // VQ is either volatile or empty, and R is a promoted
10283 // arithmetic type, there exist candidate operator functions of
10284 // the form
10285 //
10286 // VQ L& operator=(VQ L&, R);
10287 // VQ L& operator*=(VQ L&, R);
10288 // VQ L& operator/=(VQ L&, R);
10289 // VQ L& operator+=(VQ L&, R);
10290 // VQ L& operator-=(VQ L&, R);
10291 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10292 if (!HasArithmeticOrEnumeralCandidateType)
10293 return;
10294
10295 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10296 for (unsigned Right = FirstPromotedArithmeticType;
10297 Right < LastPromotedArithmeticType; ++Right) {
10298 QualType ParamTypes[2];
10299 ParamTypes[1] = ArithmeticTypes[Right];
10300 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10301 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10302
10303 forAllQualifierCombinations(
10304 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10305 ParamTypes[0] =
10306 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10307 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10308 /*IsAssignmentOperator=*/isEqualOp);
10309 });
10310 }
10311 }
10312
10313 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10314 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10315 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10316 QualType ParamTypes[2];
10317 ParamTypes[1] = Vec2Ty;
10318 // Add this built-in operator as a candidate (VQ is empty).
10319 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10320 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10321 /*IsAssignmentOperator=*/isEqualOp);
10322
10323 // Add this built-in operator as a candidate (VQ is 'volatile').
10324 if (VisibleTypeConversionsQuals.hasVolatile()) {
10325 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10326 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10327 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10328 /*IsAssignmentOperator=*/isEqualOp);
10329 }
10330 }
10331 }
10332
10333 // C++ [over.built]p22:
10334 //
10335 // For every triple (L, VQ, R), where L is an integral type, VQ
10336 // is either volatile or empty, and R is a promoted integral
10337 // type, there exist candidate operator functions of the form
10338 //
10339 // VQ L& operator%=(VQ L&, R);
10340 // VQ L& operator<<=(VQ L&, R);
10341 // VQ L& operator>>=(VQ L&, R);
10342 // VQ L& operator&=(VQ L&, R);
10343 // VQ L& operator^=(VQ L&, R);
10344 // VQ L& operator|=(VQ L&, R);
10345 void addAssignmentIntegralOverloads() {
10346 if (!HasArithmeticOrEnumeralCandidateType)
10347 return;
10348
10349 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10350 for (unsigned Right = FirstPromotedIntegralType;
10351 Right < LastPromotedIntegralType; ++Right) {
10352 QualType ParamTypes[2];
10353 ParamTypes[1] = ArithmeticTypes[Right];
10354 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10355 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10356
10357 forAllQualifierCombinations(
10358 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10359 ParamTypes[0] =
10360 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10361 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10362 });
10363 }
10364 }
10365 }
10366
10367 // C++ [over.operator]p23:
10368 //
10369 // There also exist candidate operator functions of the form
10370 //
10371 // bool operator!(bool);
10372 // bool operator&&(bool, bool);
10373 // bool operator||(bool, bool);
10374 void addExclaimOverload() {
10375 QualType ParamTy = S.Context.BoolTy;
10376 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10377 /*IsAssignmentOperator=*/false,
10378 /*NumContextualBoolArguments=*/1);
10379 }
10380 void addAmpAmpOrPipePipeOverload() {
10381 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10382 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10383 /*IsAssignmentOperator=*/false,
10384 /*NumContextualBoolArguments=*/2);
10385 }
10386
10387 // C++ [over.built]p13:
10388 //
10389 // For every cv-qualified or cv-unqualified object type T there
10390 // exist candidate operator functions of the form
10391 //
10392 // T* operator+(T*, ptrdiff_t); [ABOVE]
10393 // T& operator[](T*, ptrdiff_t);
10394 // T* operator-(T*, ptrdiff_t); [ABOVE]
10395 // T* operator+(ptrdiff_t, T*); [ABOVE]
10396 // T& operator[](ptrdiff_t, T*);
10397 void addSubscriptOverloads() {
10398 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10399 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10400 QualType PointeeType = PtrTy->getPointeeType();
10401 if (!PointeeType->isObjectType())
10402 continue;
10403
10404 // T& operator[](T*, ptrdiff_t)
10405 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10406 }
10407
10408 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10409 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10410 QualType PointeeType = PtrTy->getPointeeType();
10411 if (!PointeeType->isObjectType())
10412 continue;
10413
10414 // T& operator[](ptrdiff_t, T*)
10415 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10416 }
10417 }
10418
10419 // C++ [over.built]p11:
10420 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10421 // C1 is the same type as C2 or is a derived class of C2, T is an object
10422 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10423 // there exist candidate operator functions of the form
10424 //
10425 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10426 //
10427 // where CV12 is the union of CV1 and CV2.
10428 void addArrowStarOverloads() {
10429 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10430 QualType C1Ty = PtrTy;
10431 QualType C1;
10432 QualifierCollector Q1;
10433 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10434 if (!isa<RecordType>(Val: C1))
10435 continue;
10436 // heuristic to reduce number of builtin candidates in the set.
10437 // Add volatile/restrict version only if there are conversions to a
10438 // volatile/restrict type.
10439 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10440 continue;
10441 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10442 continue;
10443 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10444 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10445 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10446 *D2 = mptr->getMostRecentCXXRecordDecl();
10447 if (!declaresSameEntity(D1, D2) &&
10448 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10449 break;
10450 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10451 // build CV12 T&
10452 QualType T = mptr->getPointeeType();
10453 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10454 T.isVolatileQualified())
10455 continue;
10456 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10457 T.isRestrictQualified())
10458 continue;
10459 T = Q1.apply(Context: S.Context, QT: T);
10460 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10461 }
10462 }
10463 }
10464
10465 // Note that we don't consider the first argument, since it has been
10466 // contextually converted to bool long ago. The candidates below are
10467 // therefore added as binary.
10468 //
10469 // C++ [over.built]p25:
10470 // For every type T, where T is a pointer, pointer-to-member, or scoped
10471 // enumeration type, there exist candidate operator functions of the form
10472 //
10473 // T operator?(bool, T, T);
10474 //
10475 void addConditionalOperatorOverloads() {
10476 /// Set of (canonical) types that we've already handled.
10477 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10478
10479 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10480 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10481 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10482 continue;
10483
10484 QualType ParamTypes[2] = {PtrTy, PtrTy};
10485 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10486 }
10487
10488 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10489 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10490 continue;
10491
10492 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10493 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10494 }
10495
10496 if (S.getLangOpts().CPlusPlus11) {
10497 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10498 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10499 continue;
10500
10501 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10502 continue;
10503
10504 QualType ParamTypes[2] = {EnumTy, EnumTy};
10505 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10506 }
10507 }
10508 }
10509 }
10510};
10511
10512} // end anonymous namespace
10513
10514void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10515 SourceLocation OpLoc,
10516 ArrayRef<Expr *> Args,
10517 OverloadCandidateSet &CandidateSet) {
10518 // Find all of the types that the arguments can convert to, but only
10519 // if the operator we're looking at has built-in operator candidates
10520 // that make use of these types. Also record whether we encounter non-record
10521 // candidate types or either arithmetic or enumeral candidate types.
10522 QualifiersAndAtomic VisibleTypeConversionsQuals;
10523 VisibleTypeConversionsQuals.addConst();
10524 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10525 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10526 if (Args[ArgIdx]->getType()->isAtomicType())
10527 VisibleTypeConversionsQuals.addAtomic();
10528 }
10529
10530 bool HasNonRecordCandidateType = false;
10531 bool HasArithmeticOrEnumeralCandidateType = false;
10532 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10533 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10534 CandidateTypes.emplace_back(Args&: *this);
10535 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10536 Loc: OpLoc,
10537 AllowUserConversions: true,
10538 AllowExplicitConversions: (Op == OO_Exclaim ||
10539 Op == OO_AmpAmp ||
10540 Op == OO_PipePipe),
10541 VisibleQuals: VisibleTypeConversionsQuals);
10542 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10543 CandidateTypes[ArgIdx].hasNonRecordTypes();
10544 HasArithmeticOrEnumeralCandidateType =
10545 HasArithmeticOrEnumeralCandidateType ||
10546 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10547 }
10548
10549 // Exit early when no non-record types have been added to the candidate set
10550 // for any of the arguments to the operator.
10551 //
10552 // We can't exit early for !, ||, or &&, since there we have always have
10553 // 'bool' overloads.
10554 if (!HasNonRecordCandidateType &&
10555 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10556 return;
10557
10558 // Setup an object to manage the common state for building overloads.
10559 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10560 VisibleTypeConversionsQuals,
10561 HasArithmeticOrEnumeralCandidateType,
10562 CandidateTypes, CandidateSet);
10563
10564 // Dispatch over the operation to add in only those overloads which apply.
10565 switch (Op) {
10566 case OO_None:
10567 case NUM_OVERLOADED_OPERATORS:
10568 llvm_unreachable("Expected an overloaded operator");
10569
10570 case OO_New:
10571 case OO_Delete:
10572 case OO_Array_New:
10573 case OO_Array_Delete:
10574 case OO_Call:
10575 llvm_unreachable(
10576 "Special operators don't use AddBuiltinOperatorCandidates");
10577
10578 case OO_Comma:
10579 case OO_Arrow:
10580 case OO_Coawait:
10581 // C++ [over.match.oper]p3:
10582 // -- For the operator ',', the unary operator '&', the
10583 // operator '->', or the operator 'co_await', the
10584 // built-in candidates set is empty.
10585 break;
10586
10587 case OO_Plus: // '+' is either unary or binary
10588 if (Args.size() == 1)
10589 OpBuilder.addUnaryPlusPointerOverloads();
10590 [[fallthrough]];
10591
10592 case OO_Minus: // '-' is either unary or binary
10593 if (Args.size() == 1) {
10594 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10595 } else {
10596 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10597 OpBuilder.addGenericBinaryArithmeticOverloads();
10598 OpBuilder.addMatrixBinaryArithmeticOverloads();
10599 }
10600 break;
10601
10602 case OO_Star: // '*' is either unary or binary
10603 if (Args.size() == 1)
10604 OpBuilder.addUnaryStarPointerOverloads();
10605 else {
10606 OpBuilder.addGenericBinaryArithmeticOverloads();
10607 OpBuilder.addMatrixBinaryArithmeticOverloads();
10608 }
10609 break;
10610
10611 case OO_Slash:
10612 OpBuilder.addGenericBinaryArithmeticOverloads();
10613 break;
10614
10615 case OO_PlusPlus:
10616 case OO_MinusMinus:
10617 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10618 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10619 break;
10620
10621 case OO_EqualEqual:
10622 case OO_ExclaimEqual:
10623 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10624 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10625 OpBuilder.addGenericBinaryArithmeticOverloads();
10626 break;
10627
10628 case OO_Less:
10629 case OO_Greater:
10630 case OO_LessEqual:
10631 case OO_GreaterEqual:
10632 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10633 OpBuilder.addGenericBinaryArithmeticOverloads();
10634 break;
10635
10636 case OO_Spaceship:
10637 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10638 OpBuilder.addThreeWayArithmeticOverloads();
10639 break;
10640
10641 case OO_Percent:
10642 case OO_Caret:
10643 case OO_Pipe:
10644 case OO_LessLess:
10645 case OO_GreaterGreater:
10646 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10647 break;
10648
10649 case OO_Amp: // '&' is either unary or binary
10650 if (Args.size() == 1)
10651 // C++ [over.match.oper]p3:
10652 // -- For the operator ',', the unary operator '&', or the
10653 // operator '->', the built-in candidates set is empty.
10654 break;
10655
10656 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10657 break;
10658
10659 case OO_Tilde:
10660 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10661 break;
10662
10663 case OO_Equal:
10664 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10665 [[fallthrough]];
10666
10667 case OO_PlusEqual:
10668 case OO_MinusEqual:
10669 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10670 [[fallthrough]];
10671
10672 case OO_StarEqual:
10673 case OO_SlashEqual:
10674 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10675 break;
10676
10677 case OO_PercentEqual:
10678 case OO_LessLessEqual:
10679 case OO_GreaterGreaterEqual:
10680 case OO_AmpEqual:
10681 case OO_CaretEqual:
10682 case OO_PipeEqual:
10683 OpBuilder.addAssignmentIntegralOverloads();
10684 break;
10685
10686 case OO_Exclaim:
10687 OpBuilder.addExclaimOverload();
10688 break;
10689
10690 case OO_AmpAmp:
10691 case OO_PipePipe:
10692 OpBuilder.addAmpAmpOrPipePipeOverload();
10693 break;
10694
10695 case OO_Subscript:
10696 if (Args.size() == 2)
10697 OpBuilder.addSubscriptOverloads();
10698 break;
10699
10700 case OO_ArrowStar:
10701 OpBuilder.addArrowStarOverloads();
10702 break;
10703
10704 case OO_Conditional:
10705 OpBuilder.addConditionalOperatorOverloads();
10706 OpBuilder.addGenericBinaryArithmeticOverloads();
10707 break;
10708 }
10709}
10710
10711void
10712Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10713 SourceLocation Loc,
10714 ArrayRef<Expr *> Args,
10715 TemplateArgumentListInfo *ExplicitTemplateArgs,
10716 OverloadCandidateSet& CandidateSet,
10717 bool PartialOverloading) {
10718 ADLResult Fns;
10719
10720 // FIXME: This approach for uniquing ADL results (and removing
10721 // redundant candidates from the set) relies on pointer-equality,
10722 // which means we need to key off the canonical decl. However,
10723 // always going back to the canonical decl might not get us the
10724 // right set of default arguments. What default arguments are
10725 // we supposed to consider on ADL candidates, anyway?
10726
10727 // FIXME: Pass in the explicit template arguments?
10728 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10729
10730 ArrayRef<Expr *> ReversedArgs;
10731
10732 // Erase all of the candidates we already knew about.
10733 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10734 CandEnd = CandidateSet.end();
10735 Cand != CandEnd; ++Cand)
10736 if (Cand->Function) {
10737 FunctionDecl *Fn = Cand->Function;
10738 Fns.erase(D: Fn);
10739 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10740 Fns.erase(D: FunTmpl);
10741 }
10742
10743 // For each of the ADL candidates we found, add it to the overload
10744 // set.
10745 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10746 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10747
10748 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10749 if (ExplicitTemplateArgs)
10750 continue;
10751
10752 AddOverloadCandidate(
10753 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10754 PartialOverloading, /*AllowExplicit=*/true,
10755 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10756 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10757 AddOverloadCandidate(
10758 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10759 /*SuppressUserConversions=*/false, PartialOverloading,
10760 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10761 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10762 }
10763 } else {
10764 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10765 AddTemplateOverloadCandidate(
10766 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10767 /*SuppressUserConversions=*/false, PartialOverloading,
10768 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10769 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10770 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10771
10772 // As template candidates are not deduced immediately,
10773 // persist the array in the overload set.
10774 if (ReversedArgs.empty())
10775 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10776
10777 AddTemplateOverloadCandidate(
10778 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10779 /*SuppressUserConversions=*/false, PartialOverloading,
10780 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10781 PO: OverloadCandidateParamOrder::Reversed);
10782 }
10783 }
10784 }
10785}
10786
10787namespace {
10788enum class Comparison { Equal, Better, Worse };
10789}
10790
10791/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10792/// overload resolution.
10793///
10794/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10795/// Cand1's first N enable_if attributes have precisely the same conditions as
10796/// Cand2's first N enable_if attributes (where N = the number of enable_if
10797/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10798///
10799/// Note that you can have a pair of candidates such that Cand1's enable_if
10800/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10801/// worse than Cand1's.
10802static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10803 const FunctionDecl *Cand2) {
10804 // Common case: One (or both) decls don't have enable_if attrs.
10805 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10806 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10807 if (!Cand1Attr || !Cand2Attr) {
10808 if (Cand1Attr == Cand2Attr)
10809 return Comparison::Equal;
10810 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10811 }
10812
10813 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10814 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10815
10816 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10817 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10818 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10819 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10820
10821 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10822 // has fewer enable_if attributes than Cand2, and vice versa.
10823 if (!Cand1A)
10824 return Comparison::Worse;
10825 if (!Cand2A)
10826 return Comparison::Better;
10827
10828 Cand1ID.clear();
10829 Cand2ID.clear();
10830
10831 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10832 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10833 if (Cand1ID != Cand2ID)
10834 return Comparison::Worse;
10835 }
10836
10837 return Comparison::Equal;
10838}
10839
10840static Comparison
10841isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10842 const OverloadCandidate &Cand2) {
10843 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10844 !Cand2.Function->isMultiVersion())
10845 return Comparison::Equal;
10846
10847 // If both are invalid, they are equal. If one of them is invalid, the other
10848 // is better.
10849 if (Cand1.Function->isInvalidDecl()) {
10850 if (Cand2.Function->isInvalidDecl())
10851 return Comparison::Equal;
10852 return Comparison::Worse;
10853 }
10854 if (Cand2.Function->isInvalidDecl())
10855 return Comparison::Better;
10856
10857 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10858 // cpu_dispatch, else arbitrarily based on the identifiers.
10859 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10860 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10861 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10862 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10863
10864 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10865 return Comparison::Equal;
10866
10867 if (Cand1CPUDisp && !Cand2CPUDisp)
10868 return Comparison::Better;
10869 if (Cand2CPUDisp && !Cand1CPUDisp)
10870 return Comparison::Worse;
10871
10872 if (Cand1CPUSpec && Cand2CPUSpec) {
10873 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10874 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10875 ? Comparison::Better
10876 : Comparison::Worse;
10877
10878 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10879 FirstDiff = std::mismatch(
10880 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10881 first2: Cand2CPUSpec->cpus_begin(),
10882 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10883 return LHS->getName() == RHS->getName();
10884 });
10885
10886 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10887 "Two different cpu-specific versions should not have the same "
10888 "identifier list, otherwise they'd be the same decl!");
10889 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10890 ? Comparison::Better
10891 : Comparison::Worse;
10892 }
10893 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10894}
10895
10896/// Compute the type of the implicit object parameter for the given function,
10897/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10898/// null QualType if there is a 'matches anything' implicit object parameter.
10899static std::optional<QualType>
10900getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10901 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10902 return std::nullopt;
10903
10904 auto *M = cast<CXXMethodDecl>(Val: F);
10905 // Static member functions' object parameters match all types.
10906 if (M->isStatic())
10907 return QualType();
10908 return M->getFunctionObjectParameterReferenceType();
10909}
10910
10911// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10912// represent the same entity.
10913static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10914 const FunctionDecl *F2) {
10915 if (declaresSameEntity(D1: F1, D2: F2))
10916 return true;
10917 auto PT1 = F1->getPrimaryTemplate();
10918 auto PT2 = F2->getPrimaryTemplate();
10919 if (PT1 && PT2) {
10920 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10921 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10922 D2: PT2->getInstantiatedFromMemberTemplate()))
10923 return true;
10924 }
10925 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10926 // different functions with same params). Consider removing this (as no test
10927 // fail w/o it).
10928 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10929 if (First) {
10930 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10931 return *T;
10932 }
10933 assert(I < F->getNumParams());
10934 return F->getParamDecl(i: I++)->getType();
10935 };
10936
10937 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10938 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10939
10940 if (F1NumParams != F2NumParams)
10941 return false;
10942
10943 unsigned I1 = 0, I2 = 0;
10944 for (unsigned I = 0; I != F1NumParams; ++I) {
10945 QualType T1 = NextParam(F1, I1, I == 0);
10946 QualType T2 = NextParam(F2, I2, I == 0);
10947 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10948 if (!Context.hasSameUnqualifiedType(T1, T2))
10949 return false;
10950 }
10951 return true;
10952}
10953
10954/// We're allowed to use constraints partial ordering only if the candidates
10955/// have the same parameter types:
10956/// [over.match.best.general]p2.6
10957/// F1 and F2 are non-template functions with the same
10958/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10959static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10960 FunctionDecl *Fn2,
10961 bool IsFn1Reversed,
10962 bool IsFn2Reversed) {
10963 assert(Fn1 && Fn2);
10964 if (Fn1->isVariadic() != Fn2->isVariadic())
10965 return false;
10966
10967 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10968 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10969 return false;
10970
10971 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10972 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10973 if (Mem1 && Mem2) {
10974 // if they are member functions, both are direct members of the same class,
10975 // and
10976 if (Mem1->getParent() != Mem2->getParent())
10977 return false;
10978 // if both are non-static member functions, they have the same types for
10979 // their object parameters
10980 if (Mem1->isInstance() && Mem2->isInstance() &&
10981 !S.getASTContext().hasSameType(
10982 T1: Mem1->getFunctionObjectParameterReferenceType(),
10983 T2: Mem2->getFunctionObjectParameterReferenceType()))
10984 return false;
10985 }
10986 return true;
10987}
10988
10989static FunctionDecl *
10990getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10991 bool IsFn1Reversed, bool IsFn2Reversed) {
10992 if (!Fn1 || !Fn2)
10993 return nullptr;
10994
10995 // C++ [temp.constr.order]:
10996 // A non-template function F1 is more partial-ordering-constrained than a
10997 // non-template function F2 if:
10998 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10999 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11000
11001 if (Cand1IsSpecialization || Cand2IsSpecialization)
11002 return nullptr;
11003
11004 // - they have the same non-object-parameter-type-lists, and [...]
11005 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11006 IsFn2Reversed))
11007 return nullptr;
11008
11009 // - the declaration of F1 is more constrained than the declaration of F2.
11010 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
11011}
11012
11013/// isBetterOverloadCandidate - Determines whether the first overload
11014/// candidate is a better candidate than the second (C++ 13.3.3p1).
11015bool clang::isBetterOverloadCandidate(
11016 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11017 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
11018 bool PartialOverloading) {
11019 // Define viable functions to be better candidates than non-viable
11020 // functions.
11021 if (!Cand2.Viable)
11022 return Cand1.Viable;
11023 else if (!Cand1.Viable)
11024 return false;
11025
11026 // [CUDA] A function with 'never' preference is marked not viable, therefore
11027 // is never shown up here. The worst preference shown up here is 'wrong side',
11028 // e.g. an H function called by a HD function in device compilation. This is
11029 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11030 // function which is called only by an H function. A deferred diagnostic will
11031 // be triggered if it is emitted. However a wrong-sided function is still
11032 // a viable candidate here.
11033 //
11034 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11035 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11036 // can be emitted, Cand1 is not better than Cand2. This rule should have
11037 // precedence over other rules.
11038 //
11039 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11040 // other rules should be used to determine which is better. This is because
11041 // host/device based overloading resolution is mostly for determining
11042 // viability of a function. If two functions are both viable, other factors
11043 // should take precedence in preference, e.g. the standard-defined preferences
11044 // like argument conversion ranks or enable_if partial-ordering. The
11045 // preference for pass-object-size parameters is probably most similar to a
11046 // type-based-overloading decision and so should take priority.
11047 //
11048 // If other rules cannot determine which is better, CUDA preference will be
11049 // used again to determine which is better.
11050 //
11051 // TODO: Currently IdentifyPreference does not return correct values
11052 // for functions called in global variable initializers due to missing
11053 // correct context about device/host. Therefore we can only enforce this
11054 // rule when there is a caller. We should enforce this rule for functions
11055 // in global variable initializers once proper context is added.
11056 //
11057 // TODO: We can only enable the hostness based overloading resolution when
11058 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11059 // overloading resolution diagnostics.
11060 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11061 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11062 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11063 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
11064 bool IsCand1ImplicitHD =
11065 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
11066 bool IsCand2ImplicitHD =
11067 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
11068 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
11069 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11070 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11071 // The implicit HD function may be a function in a system header which
11072 // is forced by pragma. In device compilation, if we prefer HD candidates
11073 // over wrong-sided candidates, overloading resolution may change, which
11074 // may result in non-deferrable diagnostics. As a workaround, we let
11075 // implicit HD candidates take equal preference as wrong-sided candidates.
11076 // This will preserve the overloading resolution.
11077 // TODO: We still need special handling of implicit HD functions since
11078 // they may incur other diagnostics to be deferred. We should make all
11079 // host/device related diagnostics deferrable and remove special handling
11080 // of implicit HD functions.
11081 auto EmitThreshold =
11082 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11083 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11084 ? SemaCUDA::CFP_Never
11085 : SemaCUDA::CFP_WrongSide;
11086 auto Cand1Emittable = P1 > EmitThreshold;
11087 auto Cand2Emittable = P2 > EmitThreshold;
11088 if (Cand1Emittable && !Cand2Emittable)
11089 return true;
11090 if (!Cand1Emittable && Cand2Emittable)
11091 return false;
11092 }
11093 }
11094
11095 // C++ [over.match.best]p1: (Changed in C++23)
11096 //
11097 // -- if F is a static member function, ICS1(F) is defined such
11098 // that ICS1(F) is neither better nor worse than ICS1(G) for
11099 // any function G, and, symmetrically, ICS1(G) is neither
11100 // better nor worse than ICS1(F).
11101 unsigned StartArg = 0;
11102 if (!Cand1.TookAddressOfOverload &&
11103 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11104 StartArg = 1;
11105
11106 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11107 // We don't allow incompatible pointer conversions in C++.
11108 if (!S.getLangOpts().CPlusPlus)
11109 return ICS.isStandard() &&
11110 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11111
11112 // The only ill-formed conversion we allow in C++ is the string literal to
11113 // char* conversion, which is only considered ill-formed after C++11.
11114 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11115 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11116 };
11117
11118 // Define functions that don't require ill-formed conversions for a given
11119 // argument to be better candidates than functions that do.
11120 unsigned NumArgs = Cand1.Conversions.size();
11121 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11122 bool HasBetterConversion = false;
11123 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11124 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11125 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11126 if (Cand1Bad != Cand2Bad) {
11127 if (Cand1Bad)
11128 return false;
11129 HasBetterConversion = true;
11130 }
11131 }
11132
11133 if (HasBetterConversion)
11134 return true;
11135
11136 // C++ [over.match.best]p1:
11137 // A viable function F1 is defined to be a better function than another
11138 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11139 // conversion sequence than ICSi(F2), and then...
11140 bool HasWorseConversion = false;
11141 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11142 switch (CompareImplicitConversionSequences(S, Loc,
11143 ICS1: Cand1.Conversions[ArgIdx],
11144 ICS2: Cand2.Conversions[ArgIdx])) {
11145 case ImplicitConversionSequence::Better:
11146 // Cand1 has a better conversion sequence.
11147 HasBetterConversion = true;
11148 break;
11149
11150 case ImplicitConversionSequence::Worse:
11151 if (Cand1.Function && Cand2.Function &&
11152 Cand1.isReversed() != Cand2.isReversed() &&
11153 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11154 // Work around large-scale breakage caused by considering reversed
11155 // forms of operator== in C++20:
11156 //
11157 // When comparing a function against a reversed function, if we have a
11158 // better conversion for one argument and a worse conversion for the
11159 // other, the implicit conversion sequences are treated as being equally
11160 // good.
11161 //
11162 // This prevents a comparison function from being considered ambiguous
11163 // with a reversed form that is written in the same way.
11164 //
11165 // We diagnose this as an extension from CreateOverloadedBinOp.
11166 HasWorseConversion = true;
11167 break;
11168 }
11169
11170 // Cand1 can't be better than Cand2.
11171 return false;
11172
11173 case ImplicitConversionSequence::Indistinguishable:
11174 // Do nothing.
11175 break;
11176 }
11177 }
11178
11179 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11180 // ICSj(F2), or, if not that,
11181 if (HasBetterConversion && !HasWorseConversion)
11182 return true;
11183
11184 // -- the context is an initialization by user-defined conversion
11185 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11186 // from the return type of F1 to the destination type (i.e.,
11187 // the type of the entity being initialized) is a better
11188 // conversion sequence than the standard conversion sequence
11189 // from the return type of F2 to the destination type.
11190 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11191 Cand1.Function && Cand2.Function &&
11192 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11193 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11194
11195 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11196 // First check whether we prefer one of the conversion functions over the
11197 // other. This only distinguishes the results in non-standard, extension
11198 // cases such as the conversion from a lambda closure type to a function
11199 // pointer or block.
11200 ImplicitConversionSequence::CompareKind Result =
11201 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11202 if (Result == ImplicitConversionSequence::Indistinguishable)
11203 Result = CompareStandardConversionSequences(S, Loc,
11204 SCS1: Cand1.FinalConversion,
11205 SCS2: Cand2.FinalConversion);
11206
11207 if (Result != ImplicitConversionSequence::Indistinguishable)
11208 return Result == ImplicitConversionSequence::Better;
11209
11210 // FIXME: Compare kind of reference binding if conversion functions
11211 // convert to a reference type used in direct reference binding, per
11212 // C++14 [over.match.best]p1 section 2 bullet 3.
11213 }
11214
11215 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11216 // as combined with the resolution to CWG issue 243.
11217 //
11218 // When the context is initialization by constructor ([over.match.ctor] or
11219 // either phase of [over.match.list]), a constructor is preferred over
11220 // a conversion function.
11221 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11222 Cand1.Function && Cand2.Function &&
11223 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11224 isa<CXXConstructorDecl>(Val: Cand2.Function))
11225 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11226
11227 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11228 return Cand2.StrictPackMatch;
11229
11230 // -- F1 is a non-template function and F2 is a function template
11231 // specialization, or, if not that,
11232 bool Cand1IsSpecialization = Cand1.Function &&
11233 Cand1.Function->getPrimaryTemplate();
11234 bool Cand2IsSpecialization = Cand2.Function &&
11235 Cand2.Function->getPrimaryTemplate();
11236 if (Cand1IsSpecialization != Cand2IsSpecialization)
11237 return Cand2IsSpecialization;
11238
11239 // -- F1 and F2 are function template specializations, and the function
11240 // template for F1 is more specialized than the template for F2
11241 // according to the partial ordering rules described in 14.5.5.2, or,
11242 // if not that,
11243 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11244 const auto *Obj1Context =
11245 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11246 const auto *Obj2Context =
11247 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11248 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11249 FT1: Cand1.Function->getPrimaryTemplate(),
11250 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11251 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11252 : TPOC_Call,
11253 NumCallArguments1: Cand1.ExplicitCallArguments,
11254 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11255 : QualType{},
11256 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11257 : QualType{},
11258 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11259 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11260 }
11261 }
11262
11263 // -— F1 and F2 are non-template functions and F1 is more
11264 // partial-ordering-constrained than F2 [...],
11265 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11266 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11267 IsFn2Reversed: Cand2.isReversed());
11268 F && F == Cand1.Function)
11269 return true;
11270
11271 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11272 // class B of D, and for all arguments the corresponding parameters of
11273 // F1 and F2 have the same type.
11274 // FIXME: Implement the "all parameters have the same type" check.
11275 bool Cand1IsInherited =
11276 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11277 bool Cand2IsInherited =
11278 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11279 if (Cand1IsInherited != Cand2IsInherited)
11280 return Cand2IsInherited;
11281 else if (Cand1IsInherited) {
11282 assert(Cand2IsInherited);
11283 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11284 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11285 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11286 return true;
11287 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11288 return false;
11289 // Inherited from sibling base classes: still ambiguous.
11290 }
11291
11292 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11293 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11294 // with reversed order of parameters and F1 is not
11295 //
11296 // We rank reversed + different operator as worse than just reversed, but
11297 // that comparison can never happen, because we only consider reversing for
11298 // the maximally-rewritten operator (== or <=>).
11299 if (Cand1.RewriteKind != Cand2.RewriteKind)
11300 return Cand1.RewriteKind < Cand2.RewriteKind;
11301
11302 // Check C++17 tie-breakers for deduction guides.
11303 {
11304 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11305 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11306 if (Guide1 && Guide2) {
11307 // -- F1 is generated from a deduction-guide and F2 is not
11308 if (Guide1->isImplicit() != Guide2->isImplicit())
11309 return Guide2->isImplicit();
11310
11311 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11312 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11313 return true;
11314 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11315 return false;
11316
11317 // --F1 is generated from a non-template constructor and F2 is generated
11318 // from a constructor template
11319 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11320 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11321 if (Constructor1 && Constructor2) {
11322 bool isC1Templated = Constructor1->getTemplatedKind() !=
11323 FunctionDecl::TemplatedKind::TK_NonTemplate;
11324 bool isC2Templated = Constructor2->getTemplatedKind() !=
11325 FunctionDecl::TemplatedKind::TK_NonTemplate;
11326 if (isC1Templated != isC2Templated)
11327 return isC2Templated;
11328 }
11329 }
11330 }
11331
11332 // Check for enable_if value-based overload resolution.
11333 if (Cand1.Function && Cand2.Function) {
11334 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11335 if (Cmp != Comparison::Equal)
11336 return Cmp == Comparison::Better;
11337 }
11338
11339 bool HasPS1 = Cand1.Function != nullptr &&
11340 functionHasPassObjectSizeParams(FD: Cand1.Function);
11341 bool HasPS2 = Cand2.Function != nullptr &&
11342 functionHasPassObjectSizeParams(FD: Cand2.Function);
11343 if (HasPS1 != HasPS2 && HasPS1)
11344 return true;
11345
11346 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11347 if (MV == Comparison::Better)
11348 return true;
11349 if (MV == Comparison::Worse)
11350 return false;
11351
11352 // If other rules cannot determine which is better, CUDA preference is used
11353 // to determine which is better.
11354 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11355 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11356 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11357 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11358 }
11359
11360 // General member function overloading is handled above, so this only handles
11361 // constructors with address spaces.
11362 // This only handles address spaces since C++ has no other
11363 // qualifier that can be used with constructors.
11364 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11365 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11366 if (CD1 && CD2) {
11367 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11368 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11369 if (AS1 != AS2) {
11370 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11371 return true;
11372 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11373 return false;
11374 }
11375 }
11376
11377 return false;
11378}
11379
11380/// Determine whether two declarations are "equivalent" for the purposes of
11381/// name lookup and overload resolution. This applies when the same internal/no
11382/// linkage entity is defined by two modules (probably by textually including
11383/// the same header). In such a case, we don't consider the declarations to
11384/// declare the same entity, but we also don't want lookups with both
11385/// declarations visible to be ambiguous in some cases (this happens when using
11386/// a modularized libstdc++).
11387bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11388 const NamedDecl *B) {
11389 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11390 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11391 if (!VA || !VB)
11392 return false;
11393
11394 // The declarations must be declaring the same name as an internal linkage
11395 // entity in different modules.
11396 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11397 DC: VB->getDeclContext()->getRedeclContext()) ||
11398 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11399 VA->isExternallyVisible() || VB->isExternallyVisible())
11400 return false;
11401
11402 // Check that the declarations appear to be equivalent.
11403 //
11404 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11405 // For constants and functions, we should check the initializer or body is
11406 // the same. For non-constant variables, we shouldn't allow it at all.
11407 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11408 return true;
11409
11410 // Enum constants within unnamed enumerations will have different types, but
11411 // may still be similar enough to be interchangeable for our purposes.
11412 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11413 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11414 // Only handle anonymous enums. If the enumerations were named and
11415 // equivalent, they would have been merged to the same type.
11416 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11417 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11418 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11419 !Context.hasSameType(T1: EnumA->getIntegerType(),
11420 T2: EnumB->getIntegerType()))
11421 return false;
11422 // Allow this only if the value is the same for both enumerators.
11423 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11424 }
11425 }
11426
11427 // Nothing else is sufficiently similar.
11428 return false;
11429}
11430
11431void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11432 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11433 assert(D && "Unknown declaration");
11434 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11435
11436 Module *M = getOwningModule(Entity: D);
11437 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11438 << !M << (M ? M->getFullModuleName() : "");
11439
11440 for (auto *E : Equiv) {
11441 Module *M = getOwningModule(Entity: E);
11442 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11443 << !M << (M ? M->getFullModuleName() : "");
11444 }
11445}
11446
11447bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11448 return FailureKind == ovl_fail_bad_deduction &&
11449 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11450 TemplateDeductionResult::ConstraintsNotSatisfied &&
11451 static_cast<CNSInfo *>(DeductionFailure.Data)
11452 ->Satisfaction.ContainsErrors;
11453}
11454
11455void OverloadCandidateSet::AddDeferredTemplateCandidate(
11456 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11457 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11458 bool PartialOverloading, bool AllowExplicit,
11459 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11460 bool AggregateCandidateDeduction) {
11461
11462 auto *C =
11463 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11464
11465 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11466 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11467 /*AllowObjCConversionOnExplicit=*/false,
11468 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11469 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11470 .FunctionTemplate: FunctionTemplate,
11471 .FoundDecl: FoundDecl,
11472 .Args: Args,
11473 .IsADLCandidate: IsADLCandidate,
11474 .PO: PO};
11475
11476 HasDeferredTemplateConstructors |=
11477 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11478}
11479
11480void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11481 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11482 CXXRecordDecl *ActingContext, QualType ObjectType,
11483 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11484 bool SuppressUserConversions, bool PartialOverloading,
11485 OverloadCandidateParamOrder PO) {
11486
11487 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11488
11489 auto *C =
11490 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11491
11492 C = new (C) DeferredMethodTemplateOverloadCandidate{
11493 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11494 /*AllowObjCConversionOnExplicit=*/false,
11495 /*AllowResultConversion=*/false,
11496 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11497 /*AggregateCandidateDeduction=*/false},
11498 .FunctionTemplate: MethodTmpl,
11499 .FoundDecl: FoundDecl,
11500 .Args: Args,
11501 .ActingContext: ActingContext,
11502 .ObjectClassification: ObjectClassification,
11503 .ObjectType: ObjectType,
11504 .PO: PO};
11505}
11506
11507void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11508 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11509 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11510 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11511 bool AllowResultConversion) {
11512
11513 auto *C =
11514 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11515
11516 C = new (C) DeferredConversionTemplateOverloadCandidate{
11517 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11518 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11519 /*AllowExplicit=*/false,
11520 /*SuppressUserConversions=*/false,
11521 /*PartialOverloading*/ false,
11522 /*AggregateCandidateDeduction=*/false},
11523 .FunctionTemplate: FunctionTemplate,
11524 .FoundDecl: FoundDecl,
11525 .ActingContext: ActingContext,
11526 .From: From,
11527 .ToType: ToType};
11528}
11529
11530static void
11531AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11532 DeferredMethodTemplateOverloadCandidate &C) {
11533
11534 AddMethodTemplateCandidateImmediately(
11535 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11536 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11537 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11538}
11539
11540static void
11541AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11542 DeferredFunctionTemplateOverloadCandidate &C) {
11543 AddTemplateOverloadCandidateImmediately(
11544 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11545 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11546 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11547 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11548}
11549
11550static void
11551AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11552 DeferredConversionTemplateOverloadCandidate &C) {
11553 return AddTemplateConversionCandidateImmediately(
11554 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11555 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11556 AllowResultConversion: C.AllowResultConversion);
11557}
11558
11559void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11560 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11561 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11562 while (Cand) {
11563 switch (Cand->Kind) {
11564 case DeferredTemplateOverloadCandidate::Function:
11565 AddTemplateOverloadCandidate(
11566 S, CandidateSet&: *this,
11567 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11568 break;
11569 case DeferredTemplateOverloadCandidate::Method:
11570 AddTemplateOverloadCandidate(
11571 S, CandidateSet&: *this,
11572 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11573 break;
11574 case DeferredTemplateOverloadCandidate::Conversion:
11575 AddTemplateOverloadCandidate(
11576 S, CandidateSet&: *this,
11577 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11578 break;
11579 }
11580 Cand = Cand->Next;
11581 }
11582 FirstDeferredCandidate = nullptr;
11583 DeferredCandidatesCount = 0;
11584}
11585
11586OverloadingResult
11587OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11588 Best->Best = true;
11589 if (Best->Function && Best->Function->isDeleted())
11590 return OR_Deleted;
11591 return OR_Success;
11592}
11593
11594void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11595 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11596 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11597 // are accepted by both clang and NVCC. However, during a particular
11598 // compilation mode only one call variant is viable. We need to
11599 // exclude non-viable overload candidates from consideration based
11600 // only on their host/device attributes. Specifically, if one
11601 // candidate call is WrongSide and the other is SameSide, we ignore
11602 // the WrongSide candidate.
11603 // We only need to remove wrong-sided candidates here if
11604 // -fgpu-exclude-wrong-side-overloads is off. When
11605 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11606 // uniformly in isBetterOverloadCandidate.
11607 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11608 return;
11609 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11610
11611 bool ContainsSameSideCandidate =
11612 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11613 // Check viable function only.
11614 return Cand->Viable && Cand->Function &&
11615 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11616 SemaCUDA::CFP_SameSide;
11617 });
11618
11619 if (!ContainsSameSideCandidate)
11620 return;
11621
11622 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11623 // Check viable function only to avoid unnecessary data copying/moving.
11624 return Cand->Viable && Cand->Function &&
11625 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11626 SemaCUDA::CFP_WrongSide;
11627 };
11628 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11629}
11630
11631/// Computes the best viable function (C++ 13.3.3)
11632/// within an overload candidate set.
11633///
11634/// \param Loc The location of the function name (or operator symbol) for
11635/// which overload resolution occurs.
11636///
11637/// \param Best If overload resolution was successful or found a deleted
11638/// function, \p Best points to the candidate function found.
11639///
11640/// \returns The result of overload resolution.
11641OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11642 SourceLocation Loc,
11643 iterator &Best) {
11644
11645 assert((shouldDeferTemplateArgumentDeduction(S) ||
11646 DeferredCandidatesCount == 0) &&
11647 "Unexpected deferred template candidates");
11648
11649 bool TwoPhaseResolution =
11650 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11651
11652 if (TwoPhaseResolution) {
11653 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11654 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11655 if (!(HasDeferredTemplateConstructors &&
11656 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11657 return Res;
11658 }
11659 }
11660
11661 InjectNonDeducedTemplateCandidates(S);
11662 return BestViableFunctionImpl(S, Loc, Best);
11663}
11664
11665OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11666 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11667
11668 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11669 Candidates.reserve(N: this->Candidates.size());
11670 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11671 result: std::back_inserter(x&: Candidates),
11672 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11673
11674 if (S.getLangOpts().CUDA)
11675 CudaExcludeWrongSideCandidates(S, Candidates);
11676
11677 Best = end();
11678 for (auto *Cand : Candidates) {
11679 Cand->Best = false;
11680 if (Cand->Viable) {
11681 if (Best == end() ||
11682 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11683 Best = Cand;
11684 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11685 // This candidate has constraint that we were unable to evaluate because
11686 // it referenced an expression that contained an error. Rather than fall
11687 // back onto a potentially unintended candidate (made worse by
11688 // subsuming constraints), treat this as 'no viable candidate'.
11689 Best = end();
11690 return OR_No_Viable_Function;
11691 }
11692 }
11693
11694 // If we didn't find any viable functions, abort.
11695 if (Best == end())
11696 return OR_No_Viable_Function;
11697
11698 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11699 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11700 PendingBest.push_back(Elt: &*Best);
11701 Best->Best = true;
11702
11703 // Make sure that this function is better than every other viable
11704 // function. If not, we have an ambiguity.
11705 while (!PendingBest.empty()) {
11706 auto *Curr = PendingBest.pop_back_val();
11707 for (auto *Cand : Candidates) {
11708 if (Cand->Viable && !Cand->Best &&
11709 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11710 PendingBest.push_back(Elt: Cand);
11711 Cand->Best = true;
11712
11713 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11714 B: Curr->Function))
11715 EquivalentCands.push_back(Elt: Cand->Function);
11716 else
11717 Best = end();
11718 }
11719 }
11720 }
11721
11722 if (Best == end())
11723 return OR_Ambiguous;
11724
11725 OverloadingResult R = ResultForBestCandidate(Best);
11726
11727 if (!EquivalentCands.empty())
11728 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11729 Equiv: EquivalentCands);
11730 return R;
11731}
11732
11733namespace {
11734
11735enum OverloadCandidateKind {
11736 oc_function,
11737 oc_method,
11738 oc_reversed_binary_operator,
11739 oc_constructor,
11740 oc_implicit_default_constructor,
11741 oc_implicit_copy_constructor,
11742 oc_implicit_move_constructor,
11743 oc_implicit_copy_assignment,
11744 oc_implicit_move_assignment,
11745 oc_implicit_equality_comparison,
11746 oc_inherited_constructor
11747};
11748
11749enum OverloadCandidateSelect {
11750 ocs_non_template,
11751 ocs_template,
11752 ocs_described_template,
11753};
11754
11755static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11756ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11757 const FunctionDecl *Fn,
11758 OverloadCandidateRewriteKind CRK,
11759 std::string &Description) {
11760
11761 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11762 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11763 isTemplate = true;
11764 Description = S.getTemplateArgumentBindingsText(
11765 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11766 }
11767
11768 OverloadCandidateSelect Select = [&]() {
11769 if (!Description.empty())
11770 return ocs_described_template;
11771 return isTemplate ? ocs_template : ocs_non_template;
11772 }();
11773
11774 OverloadCandidateKind Kind = [&]() {
11775 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11776 return oc_implicit_equality_comparison;
11777
11778 if (CRK & CRK_Reversed)
11779 return oc_reversed_binary_operator;
11780
11781 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11782 if (!Ctor->isImplicit()) {
11783 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11784 return oc_inherited_constructor;
11785 else
11786 return oc_constructor;
11787 }
11788
11789 if (Ctor->isDefaultConstructor())
11790 return oc_implicit_default_constructor;
11791
11792 if (Ctor->isMoveConstructor())
11793 return oc_implicit_move_constructor;
11794
11795 assert(Ctor->isCopyConstructor() &&
11796 "unexpected sort of implicit constructor");
11797 return oc_implicit_copy_constructor;
11798 }
11799
11800 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11801 // This actually gets spelled 'candidate function' for now, but
11802 // it doesn't hurt to split it out.
11803 if (!Meth->isImplicit())
11804 return oc_method;
11805
11806 if (Meth->isMoveAssignmentOperator())
11807 return oc_implicit_move_assignment;
11808
11809 if (Meth->isCopyAssignmentOperator())
11810 return oc_implicit_copy_assignment;
11811
11812 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11813 return oc_method;
11814 }
11815
11816 return oc_function;
11817 }();
11818
11819 return std::make_pair(x&: Kind, y&: Select);
11820}
11821
11822void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11823 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11824 // set.
11825 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11826 S.Diag(Loc: FoundDecl->getLocation(),
11827 DiagID: diag::note_ovl_candidate_inherited_constructor)
11828 << Shadow->getNominatedBaseClass();
11829}
11830
11831} // end anonymous namespace
11832
11833static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11834 const FunctionDecl *FD) {
11835 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11836 bool AlwaysTrue;
11837 if (EnableIf->getCond()->isValueDependent() ||
11838 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11839 return false;
11840 if (!AlwaysTrue)
11841 return false;
11842 }
11843 return true;
11844}
11845
11846/// Returns true if we can take the address of the function.
11847///
11848/// \param Complain - If true, we'll emit a diagnostic
11849/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11850/// we in overload resolution?
11851/// \param Loc - The location of the statement we're complaining about. Ignored
11852/// if we're not complaining, or if we're in overload resolution.
11853static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11854 bool Complain,
11855 bool InOverloadResolution,
11856 SourceLocation Loc) {
11857 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11858 if (Complain) {
11859 if (InOverloadResolution)
11860 S.Diag(Loc: FD->getBeginLoc(),
11861 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11862 else
11863 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11864 }
11865 return false;
11866 }
11867
11868 if (FD->getTrailingRequiresClause()) {
11869 ConstraintSatisfaction Satisfaction;
11870 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11871 return false;
11872 if (!Satisfaction.IsSatisfied) {
11873 if (Complain) {
11874 if (InOverloadResolution) {
11875 SmallString<128> TemplateArgString;
11876 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11877 TemplateArgString += " ";
11878 TemplateArgString += S.getTemplateArgumentBindingsText(
11879 Params: FunTmpl->getTemplateParameters(),
11880 Args: *FD->getTemplateSpecializationArgs());
11881 }
11882
11883 S.Diag(Loc: FD->getBeginLoc(),
11884 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11885 << TemplateArgString;
11886 } else
11887 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11888 << FD;
11889 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11890 }
11891 return false;
11892 }
11893 }
11894
11895 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11896 return P->hasAttr<PassObjectSizeAttr>();
11897 });
11898 if (I == FD->param_end())
11899 return true;
11900
11901 if (Complain) {
11902 // Add one to ParamNo because it's user-facing
11903 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11904 if (InOverloadResolution)
11905 S.Diag(Loc: FD->getLocation(),
11906 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11907 << ParamNo;
11908 else
11909 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11910 << FD << ParamNo;
11911 }
11912 return false;
11913}
11914
11915static bool checkAddressOfCandidateIsAvailable(Sema &S,
11916 const FunctionDecl *FD) {
11917 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11918 /*InOverloadResolution=*/true,
11919 /*Loc=*/SourceLocation());
11920}
11921
11922bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11923 bool Complain,
11924 SourceLocation Loc) {
11925 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11926 /*InOverloadResolution=*/false,
11927 Loc);
11928}
11929
11930// Don't print candidates other than the one that matches the calling
11931// convention of the call operator, since that is guaranteed to exist.
11932static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11933 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11934
11935 if (!ConvD)
11936 return false;
11937 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11938 if (!RD->isLambda())
11939 return false;
11940
11941 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11942 CallingConv CallOpCC =
11943 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11944 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11945 CallingConv ConvToCC =
11946 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11947
11948 return ConvToCC != CallOpCC;
11949}
11950
11951// Notes the location of an overload candidate.
11952void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11953 OverloadCandidateRewriteKind RewriteKind,
11954 QualType DestType, bool TakingAddress) {
11955 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11956 return;
11957 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11958 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11959 return;
11960 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11961 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11962 return;
11963 if (shouldSkipNotingLambdaConversionDecl(Fn))
11964 return;
11965
11966 std::string FnDesc;
11967 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11968 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11969 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11970 << (unsigned)KSPair.first << (unsigned)KSPair.second
11971 << Fn << FnDesc;
11972
11973 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11974 Diag(Loc: Fn->getLocation(), PD);
11975 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11976}
11977
11978static void
11979MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11980 // Perhaps the ambiguity was caused by two atomic constraints that are
11981 // 'identical' but not equivalent:
11982 //
11983 // void foo() requires (sizeof(T) > 4) { } // #1
11984 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11985 //
11986 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11987 // #2 to subsume #1, but these constraint are not considered equivalent
11988 // according to the subsumption rules because they are not the same
11989 // source-level construct. This behavior is quite confusing and we should try
11990 // to help the user figure out what happened.
11991
11992 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11993 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11994 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11995 if (!I->Function)
11996 continue;
11997 SmallVector<AssociatedConstraint, 3> AC;
11998 if (auto *Template = I->Function->getPrimaryTemplate())
11999 Template->getAssociatedConstraints(AC);
12000 else
12001 I->Function->getAssociatedConstraints(ACs&: AC);
12002 if (AC.empty())
12003 continue;
12004 if (FirstCand == nullptr) {
12005 FirstCand = I->Function;
12006 FirstAC = AC;
12007 } else if (SecondCand == nullptr) {
12008 SecondCand = I->Function;
12009 SecondAC = AC;
12010 } else {
12011 // We have more than one pair of constrained functions - this check is
12012 // expensive and we'd rather not try to diagnose it.
12013 return;
12014 }
12015 }
12016 if (!SecondCand)
12017 return;
12018 // The diagnostic can only happen if there are associated constraints on
12019 // both sides (there needs to be some identical atomic constraint).
12020 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
12021 D2: SecondCand, AC2: SecondAC))
12022 // Just show the user one diagnostic, they'll probably figure it out
12023 // from here.
12024 return;
12025}
12026
12027// Notes the location of all overload candidates designated through
12028// OverloadedExpr
12029void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12030 bool TakingAddress) {
12031 assert(OverloadedExpr->getType() == Context.OverloadTy);
12032
12033 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
12034 OverloadExpr *OvlExpr = Ovl.Expression;
12035
12036 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12037 IEnd = OvlExpr->decls_end();
12038 I != IEnd; ++I) {
12039 if (FunctionTemplateDecl *FunTmpl =
12040 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12041 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
12042 TakingAddress);
12043 } else if (FunctionDecl *Fun
12044 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12045 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
12046 }
12047 }
12048}
12049
12050/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12051/// "lead" diagnostic; it will be given two arguments, the source and
12052/// target types of the conversion.
12053void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
12054 Sema &S,
12055 SourceLocation CaretLoc,
12056 const PartialDiagnostic &PDiag) const {
12057 S.Diag(Loc: CaretLoc, PD: PDiag)
12058 << Ambiguous.getFromType() << Ambiguous.getToType();
12059 unsigned CandsShown = 0;
12060 AmbiguousConversionSequence::const_iterator I, E;
12061 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12062 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12063 break;
12064 ++CandsShown;
12065 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
12066 }
12067 S.Diags.overloadCandidatesShown(N: CandsShown);
12068 if (I != E)
12069 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12070}
12071
12072static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
12073 unsigned I, bool TakingCandidateAddress) {
12074 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12075 assert(Conv.isBad());
12076 assert(Cand->Function && "for now, candidate must be a function");
12077 FunctionDecl *Fn = Cand->Function;
12078
12079 // There's a conversion slot for the object argument if this is a
12080 // non-constructor method. Note that 'I' corresponds the
12081 // conversion-slot index.
12082 bool isObjectArgument = false;
12083 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12084 !isa<CXXConstructorDecl>(Val: Fn)) {
12085 if (I == 0)
12086 isObjectArgument = true;
12087 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12088 I--;
12089 }
12090
12091 std::string FnDesc;
12092 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12093 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12094 Description&: FnDesc);
12095
12096 Expr *FromExpr = Conv.Bad.FromExpr;
12097 QualType FromTy = Conv.Bad.getFromType();
12098 QualType ToTy = Conv.Bad.getToType();
12099 SourceRange ToParamRange;
12100
12101 // FIXME: In presence of parameter packs we can't determine parameter range
12102 // reliably, as we don't have access to instantiation.
12103 bool HasParamPack =
12104 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12105 return Parm->isParameterPack();
12106 });
12107 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12108 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12109
12110 if (FromTy == S.Context.OverloadTy) {
12111 assert(FromExpr && "overload set argument came from implicit argument?");
12112 Expr *E = FromExpr->IgnoreParens();
12113 if (isa<UnaryOperator>(Val: E))
12114 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12115 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12116
12117 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12118 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12119 << ToParamRange << ToTy << Name << I + 1;
12120 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12121 return;
12122 }
12123
12124 // Do some hand-waving analysis to see if the non-viability is due
12125 // to a qualifier mismatch.
12126 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12127 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12128 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12129 CToTy = RT->getPointeeType();
12130 else {
12131 // TODO: detect and diagnose the full richness of const mismatches.
12132 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12133 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12134 CFromTy = FromPT->getPointeeType();
12135 CToTy = ToPT->getPointeeType();
12136 }
12137 }
12138
12139 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12140 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12141 Qualifiers FromQs = CFromTy.getQualifiers();
12142 Qualifiers ToQs = CToTy.getQualifiers();
12143
12144 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12145 if (isObjectArgument)
12146 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12147 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12148 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12149 else
12150 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12151 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12152 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12153 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12154 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12155 return;
12156 }
12157
12158 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12159 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12160 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12161 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12162 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12163 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12164 return;
12165 }
12166
12167 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12168 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12169 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12170 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12171 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12172 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12173 return;
12174 }
12175
12176 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12177 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12178 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12179 << FromTy << !!FromQs.getPointerAuth()
12180 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12181 << ToQs.getPointerAuth().getAsString() << I + 1
12182 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12183 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12184 return;
12185 }
12186
12187 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12188 assert(CVR && "expected qualifiers mismatch");
12189
12190 if (isObjectArgument) {
12191 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12192 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12193 << FromTy << (CVR - 1);
12194 } else {
12195 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12196 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12197 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12198 }
12199 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12200 return;
12201 }
12202
12203 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12204 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12205 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12206 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12207 << (unsigned)isObjectArgument << I + 1
12208 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12209 << ToParamRange;
12210 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12211 return;
12212 }
12213
12214 // Special diagnostic for failure to convert an initializer list, since
12215 // telling the user that it has type void is not useful.
12216 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12217 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12218 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12219 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12220 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12221 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12222 ? 2
12223 : 0);
12224 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12225 return;
12226 }
12227
12228 // Diagnose references or pointers to incomplete types differently,
12229 // since it's far from impossible that the incompleteness triggered
12230 // the failure.
12231 QualType TempFromTy = FromTy.getNonReferenceType();
12232 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12233 TempFromTy = PTy->getPointeeType();
12234 if (TempFromTy->isIncompleteType()) {
12235 // Emit the generic diagnostic and, optionally, add the hints to it.
12236 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12237 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12238 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12239 << (unsigned)(Cand->Fix.Kind);
12240
12241 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12242 return;
12243 }
12244
12245 // Diagnose base -> derived pointer conversions.
12246 unsigned BaseToDerivedConversion = 0;
12247 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12248 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12249 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12250 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12251 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12252 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12253 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12254 Base: FromPtrTy->getPointeeType()))
12255 BaseToDerivedConversion = 1;
12256 }
12257 } else if (const ObjCObjectPointerType *FromPtrTy
12258 = FromTy->getAs<ObjCObjectPointerType>()) {
12259 if (const ObjCObjectPointerType *ToPtrTy
12260 = ToTy->getAs<ObjCObjectPointerType>())
12261 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12262 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12263 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12264 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12265 FromIface->isSuperClassOf(I: ToIface))
12266 BaseToDerivedConversion = 2;
12267 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12268 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12269 Ctx: S.getASTContext()) &&
12270 !FromTy->isIncompleteType() &&
12271 !ToRefTy->getPointeeType()->isIncompleteType() &&
12272 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12273 BaseToDerivedConversion = 3;
12274 }
12275 }
12276
12277 if (BaseToDerivedConversion) {
12278 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12279 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12280 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12281 << I + 1;
12282 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12283 return;
12284 }
12285
12286 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12287 isa<PointerType>(Val: CToTy)) {
12288 Qualifiers FromQs = CFromTy.getQualifiers();
12289 Qualifiers ToQs = CToTy.getQualifiers();
12290 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12291 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12292 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12293 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12294 << I + 1;
12295 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12296 return;
12297 }
12298 }
12299
12300 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12301 return;
12302
12303 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12304 // although this is almost always an error and we advise against it.
12305 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12306 ToTy == S.Context.getLogicalOperationType()) {
12307 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12308 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12309 << Conv.Bad.FromExpr << ToTy;
12310 return;
12311 }
12312
12313 // Emit the generic diagnostic and, optionally, add the hints to it.
12314 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12315 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12316 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12317 << (unsigned)(Cand->Fix.Kind);
12318
12319 // Check that location of Fn is not in system header.
12320 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12321 // If we can fix the conversion, suggest the FixIts.
12322 for (const FixItHint &HI : Cand->Fix.Hints)
12323 FDiag << HI;
12324 }
12325
12326 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12327
12328 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12329}
12330
12331/// Additional arity mismatch diagnosis specific to a function overload
12332/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12333/// over a candidate in any candidate set.
12334static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12335 unsigned NumArgs, bool IsAddressOf = false) {
12336 assert(Cand->Function && "Candidate is required to be a function.");
12337 FunctionDecl *Fn = Cand->Function;
12338 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12339 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12340
12341 // With invalid overloaded operators, it's possible that we think we
12342 // have an arity mismatch when in fact it looks like we have the
12343 // right number of arguments, because only overloaded operators have
12344 // the weird behavior of overloading member and non-member functions.
12345 // Just don't report anything.
12346 if (Fn->isInvalidDecl() &&
12347 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12348 return true;
12349
12350 if (NumArgs < MinParams) {
12351 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12352 (Cand->FailureKind == ovl_fail_bad_deduction &&
12353 Cand->DeductionFailure.getResult() ==
12354 TemplateDeductionResult::TooFewArguments));
12355 } else {
12356 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12357 (Cand->FailureKind == ovl_fail_bad_deduction &&
12358 Cand->DeductionFailure.getResult() ==
12359 TemplateDeductionResult::TooManyArguments));
12360 }
12361
12362 return false;
12363}
12364
12365/// General arity mismatch diagnosis over a candidate in a candidate set.
12366static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12367 unsigned NumFormalArgs,
12368 bool IsAddressOf = false) {
12369 assert(isa<FunctionDecl>(D) &&
12370 "The templated declaration should at least be a function"
12371 " when diagnosing bad template argument deduction due to too many"
12372 " or too few arguments");
12373
12374 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12375
12376 // TODO: treat calls to a missing default constructor as a special case
12377 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12378 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12379 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12380
12381 // at least / at most / exactly
12382 bool HasExplicitObjectParam =
12383 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12384
12385 unsigned ParamCount =
12386 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12387 unsigned mode, modeCount;
12388
12389 if (NumFormalArgs < MinParams) {
12390 if (MinParams != ParamCount || FnTy->isVariadic() ||
12391 FnTy->isTemplateVariadic())
12392 mode = 0; // "at least"
12393 else
12394 mode = 2; // "exactly"
12395 modeCount = MinParams;
12396 } else {
12397 if (MinParams != ParamCount)
12398 mode = 1; // "at most"
12399 else
12400 mode = 2; // "exactly"
12401 modeCount = ParamCount;
12402 }
12403
12404 std::string Description;
12405 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12406 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12407
12408 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12409 if (modeCount == 1 && !IsAddressOf &&
12410 FirstNonObjectParamIdx < Fn->getNumParams() &&
12411 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12412 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12413 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12414 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12415 << NumFormalArgs << HasExplicitObjectParam
12416 << Fn->getParametersSourceRange();
12417 else
12418 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12419 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12420 << Description << mode << modeCount << NumFormalArgs
12421 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12422
12423 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12424}
12425
12426/// Arity mismatch diagnosis specific to a function overload candidate.
12427static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12428 unsigned NumFormalArgs) {
12429 assert(Cand->Function && "Candidate must be a function");
12430 FunctionDecl *Fn = Cand->Function;
12431 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12432 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12433 IsAddressOf: Cand->TookAddressOfOverload);
12434}
12435
12436static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12437 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12438 return TD;
12439 llvm_unreachable("Unsupported: Getting the described template declaration"
12440 " for bad deduction diagnosis");
12441}
12442
12443/// Diagnose a failed template-argument deduction.
12444static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12445 DeductionFailureInfo &DeductionFailure,
12446 unsigned NumArgs, bool TakingCandidateAddress,
12447 TemplateSpecCandidateSetKind CandidateSetKind =
12448 TemplateSpecCandidateSetKind::Normal) {
12449 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12450 NamedDecl *ParamD;
12451 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12452 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12453 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12454 switch (DeductionFailure.getResult()) {
12455 case TemplateDeductionResult::Success:
12456 llvm_unreachable(
12457 "TemplateDeductionResult::Success while diagnosing bad deduction");
12458 case TemplateDeductionResult::NonDependentConversionFailure:
12459 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12460 "while diagnosing bad deduction");
12461 case TemplateDeductionResult::Invalid:
12462 case TemplateDeductionResult::AlreadyDiagnosed:
12463 return;
12464
12465 case TemplateDeductionResult::Incomplete: {
12466 assert(ParamD && "no parameter found for incomplete deduction result");
12467 S.Diag(Loc: Templated->getLocation(),
12468 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12469 << ParamD->getDeclName();
12470 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12471 return;
12472 }
12473
12474 case TemplateDeductionResult::IncompletePack: {
12475 assert(ParamD && "no parameter found for incomplete deduction result");
12476 S.Diag(Loc: Templated->getLocation(),
12477 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12478 << ParamD->getDeclName()
12479 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12480 << *DeductionFailure.getFirstArg();
12481 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12482 return;
12483 }
12484
12485 case TemplateDeductionResult::Underqualified: {
12486 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12487 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12488
12489 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12490
12491 // Param will have been canonicalized, but it should just be a
12492 // qualified version of ParamD, so move the qualifiers to that.
12493 QualifierCollector Qs;
12494 Qs.strip(type: Param);
12495 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12496 assert(S.Context.hasSameType(Param, NonCanonParam));
12497
12498 // Arg has also been canonicalized, but there's nothing we can do
12499 // about that. It also doesn't matter as much, because it won't
12500 // have any template parameters in it (because deduction isn't
12501 // done on dependent types).
12502 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12503
12504 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12505 << ParamD->getDeclName() << Arg << NonCanonParam;
12506 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12507 return;
12508 }
12509
12510 case TemplateDeductionResult::Inconsistent: {
12511 assert(ParamD && "no parameter found for inconsistent deduction result");
12512 int which = 0;
12513 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12514 which = 0;
12515 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12516 // Deduction might have failed because we deduced arguments of two
12517 // different types for a non-type template parameter.
12518 // FIXME: Use a different TDK value for this.
12519 QualType T1 =
12520 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12521 QualType T2 =
12522 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12523 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12524 S.Diag(Loc: Templated->getLocation(),
12525 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12526 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12527 << *DeductionFailure.getSecondArg() << T2;
12528 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12529 return;
12530 }
12531
12532 which = 1;
12533 } else {
12534 which = 2;
12535 }
12536
12537 // Tweak the diagnostic if the problem is that we deduced packs of
12538 // different arities. We'll print the actual packs anyway in case that
12539 // includes additional useful information.
12540 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12541 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12542 DeductionFailure.getFirstArg()->pack_size() !=
12543 DeductionFailure.getSecondArg()->pack_size()) {
12544 which = 3;
12545 }
12546
12547 S.Diag(Loc: Templated->getLocation(),
12548 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12549 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12550 << *DeductionFailure.getSecondArg();
12551 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12552 return;
12553 }
12554
12555 case TemplateDeductionResult::InvalidExplicitArguments: {
12556 assert(ParamD && "no parameter found for invalid explicit arguments");
12557
12558 auto Diag = S.Diag(Loc: Templated->getLocation(),
12559 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch);
12560 if (ParamD->getDeclName())
12561 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12562 else
12563 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12564 << (getDepthAndIndex(ND: ParamD).second + 1);
12565 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12566 SmallString<128> DiagContent;
12567 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: DiagContent);
12568 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12569 } else {
12570 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12571 }
12572
12573 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12574 return;
12575 }
12576 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12577 // Format the template argument list into the argument string.
12578 SmallString<128> TemplateArgString;
12579 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12580 TemplateArgString = " ";
12581 TemplateArgString += S.getTemplateArgumentBindingsText(
12582 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12583 if (TemplateArgString.size() == 1)
12584 TemplateArgString.clear();
12585 S.Diag(Loc: Templated->getLocation(),
12586 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12587 << TemplateArgString;
12588
12589 S.DiagnoseUnsatisfiedConstraint(
12590 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12591 return;
12592 }
12593 case TemplateDeductionResult::TooManyArguments:
12594 case TemplateDeductionResult::TooFewArguments:
12595 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12596 return;
12597
12598 case TemplateDeductionResult::InstantiationDepth:
12599 S.Diag(Loc: Templated->getLocation(),
12600 DiagID: diag::note_ovl_candidate_instantiation_depth);
12601 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12602 return;
12603
12604 case TemplateDeductionResult::SubstitutionFailure: {
12605 // Format the template argument list into the argument string.
12606 SmallString<128> TemplateArgString;
12607 if (TemplateArgumentList *Args =
12608 DeductionFailure.getTemplateArgumentList()) {
12609 TemplateArgString = " ";
12610 TemplateArgString += S.getTemplateArgumentBindingsText(
12611 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12612 if (TemplateArgString.size() == 1)
12613 TemplateArgString.clear();
12614 }
12615
12616 // If this candidate was disabled by enable_if, say so.
12617 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12618 if (PDiag && PDiag->second.getDiagID() ==
12619 diag::err_typename_nested_not_found_enable_if) {
12620 // FIXME: Use the source range of the condition, and the fully-qualified
12621 // name of the enable_if template. These are both present in PDiag.
12622 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12623 << "'enable_if'" << TemplateArgString;
12624 return;
12625 }
12626
12627 // We found a specific requirement that disabled the enable_if.
12628 if (PDiag && PDiag->second.getDiagID() ==
12629 diag::err_typename_nested_not_found_requirement) {
12630 S.Diag(Loc: Templated->getLocation(),
12631 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12632 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12633 return;
12634 }
12635
12636 // Format the SFINAE diagnostic into the argument string.
12637 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12638 // formatted message in another diagnostic.
12639 SmallString<128> SFINAEArgString;
12640 SourceRange R;
12641 if (PDiag) {
12642 SFINAEArgString = ": ";
12643 R = SourceRange(PDiag->first, PDiag->first);
12644 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12645 }
12646
12647 S.Diag(Loc: Templated->getLocation(),
12648 DiagID: diag::note_ovl_candidate_substitution_failure)
12649 << TemplateArgString << SFINAEArgString << R;
12650 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12651 return;
12652 }
12653
12654 case TemplateDeductionResult::DeducedMismatch:
12655 case TemplateDeductionResult::DeducedMismatchNested: {
12656 // Format the template argument list into the argument string.
12657 SmallString<128> TemplateArgString;
12658 if (TemplateArgumentList *Args =
12659 DeductionFailure.getTemplateArgumentList()) {
12660 TemplateArgString = " ";
12661 TemplateArgString += S.getTemplateArgumentBindingsText(
12662 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12663 if (TemplateArgString.size() == 1)
12664 TemplateArgString.clear();
12665 }
12666
12667 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12668 << (*DeductionFailure.getCallArgIndex() + 1)
12669 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12670 << TemplateArgString
12671 << (DeductionFailure.getResult() ==
12672 TemplateDeductionResult::DeducedMismatchNested);
12673 break;
12674 }
12675
12676 case TemplateDeductionResult::NonDeducedMismatch: {
12677 // FIXME: Provide a source location to indicate what we couldn't match.
12678 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12679 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12680 if (FirstTA.getKind() == TemplateArgument::Template &&
12681 SecondTA.getKind() == TemplateArgument::Template) {
12682 TemplateName FirstTN = FirstTA.getAsTemplate();
12683 TemplateName SecondTN = SecondTA.getAsTemplate();
12684 if (FirstTN.getKind() == TemplateName::Template &&
12685 SecondTN.getKind() == TemplateName::Template) {
12686 if (FirstTN.getAsTemplateDecl()->getName() ==
12687 SecondTN.getAsTemplateDecl()->getName()) {
12688 // FIXME: This fixes a bad diagnostic where both templates are named
12689 // the same. This particular case is a bit difficult since:
12690 // 1) It is passed as a string to the diagnostic printer.
12691 // 2) The diagnostic printer only attempts to find a better
12692 // name for types, not decls.
12693 // Ideally, this should folded into the diagnostic printer.
12694 S.Diag(Loc: Templated->getLocation(),
12695 DiagID: CandidateSetKind ==
12696 TemplateSpecCandidateSetKind::FriendTemplate
12697 ? diag::note_friend_template_non_deduced_mismatch_qualified
12698 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12699 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12700 return;
12701 }
12702 }
12703 }
12704
12705 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12706 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12707 return;
12708
12709 // FIXME: For generic lambda parameters, check if the function is a lambda
12710 // call operator, and if so, emit a prettier and more informative
12711 // diagnostic that mentions 'auto' and lambda in addition to
12712 // (or instead of?) the canonical template type parameters.
12713 S.Diag(Loc: Templated->getLocation(),
12714 DiagID: CandidateSetKind == TemplateSpecCandidateSetKind::FriendTemplate
12715 ? diag::note_friend_template_non_deduced_mismatch
12716 : diag::note_ovl_candidate_non_deduced_mismatch)
12717 << FirstTA << SecondTA;
12718 return;
12719 }
12720 // TODO: diagnose these individually, then kill off
12721 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12722 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12723 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12724 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12725 return;
12726 case TemplateDeductionResult::CUDATargetMismatch:
12727 S.Diag(Loc: Templated->getLocation(),
12728 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12729 return;
12730 }
12731}
12732
12733/// Diagnose a failed template-argument deduction, for function calls.
12734static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12735 unsigned NumArgs,
12736 bool TakingCandidateAddress) {
12737 assert(Cand->Function && "Candidate must be a function");
12738 FunctionDecl *Fn = Cand->Function;
12739 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12740 if (TDK == TemplateDeductionResult::TooFewArguments ||
12741 TDK == TemplateDeductionResult::TooManyArguments) {
12742 if (CheckArityMismatch(S, Cand, NumArgs))
12743 return;
12744 }
12745 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12746 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12747}
12748
12749/// CUDA: diagnose an invalid call across targets.
12750static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12751 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12752 assert(Cand->Function && "Candidate must be a Function.");
12753 FunctionDecl *Callee = Cand->Function;
12754
12755 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12756 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12757
12758 std::string FnDesc;
12759 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12760 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12761 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12762
12763 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12764 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12765 << FnDesc /* Ignored */
12766 << CalleeTarget << CallerTarget;
12767
12768 // This could be an implicit constructor for which we could not infer the
12769 // target due to a collsion. Diagnose that case.
12770 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12771 if (Meth != nullptr && Meth->isImplicit()) {
12772 CXXRecordDecl *ParentClass = Meth->getParent();
12773 CXXSpecialMemberKind CSM;
12774
12775 switch (FnKindPair.first) {
12776 default:
12777 return;
12778 case oc_implicit_default_constructor:
12779 CSM = CXXSpecialMemberKind::DefaultConstructor;
12780 break;
12781 case oc_implicit_copy_constructor:
12782 CSM = CXXSpecialMemberKind::CopyConstructor;
12783 break;
12784 case oc_implicit_move_constructor:
12785 CSM = CXXSpecialMemberKind::MoveConstructor;
12786 break;
12787 case oc_implicit_copy_assignment:
12788 CSM = CXXSpecialMemberKind::CopyAssignment;
12789 break;
12790 case oc_implicit_move_assignment:
12791 CSM = CXXSpecialMemberKind::MoveAssignment;
12792 break;
12793 };
12794
12795 bool ConstRHS = false;
12796 if (Meth->getNumParams()) {
12797 if (const ReferenceType *RT =
12798 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12799 ConstRHS = RT->getPointeeType().isConstQualified();
12800 }
12801 }
12802
12803 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12804 /* ConstRHS */ ConstRHS,
12805 /* Diagnose */ true);
12806 }
12807}
12808
12809static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12810 assert(Cand->Function && "Candidate must be a function");
12811 FunctionDecl *Callee = Cand->Function;
12812 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12813
12814 S.Diag(Loc: Callee->getLocation(),
12815 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12816 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12817}
12818
12819static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12820 assert(Cand->Function && "Candidate must be a function");
12821 FunctionDecl *Fn = Cand->Function;
12822 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12823 assert(ES.isExplicit() && "not an explicit candidate");
12824
12825 unsigned Kind;
12826 switch (Fn->getDeclKind()) {
12827 case Decl::Kind::CXXConstructor:
12828 Kind = 0;
12829 break;
12830 case Decl::Kind::CXXConversion:
12831 Kind = 1;
12832 break;
12833 case Decl::Kind::CXXDeductionGuide:
12834 Kind = Fn->isImplicit() ? 0 : 2;
12835 break;
12836 default:
12837 llvm_unreachable("invalid Decl");
12838 }
12839
12840 // Note the location of the first (in-class) declaration; a redeclaration
12841 // (particularly an out-of-class definition) will typically lack the
12842 // 'explicit' specifier.
12843 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12844 FunctionDecl *First = Fn->getFirstDecl();
12845 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12846 First = Pattern->getFirstDecl();
12847
12848 S.Diag(Loc: First->getLocation(),
12849 DiagID: diag::note_ovl_candidate_explicit)
12850 << Kind << (ES.getExpr() ? 1 : 0)
12851 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12852}
12853
12854static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12855 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12856 if (!DG)
12857 return;
12858 TemplateDecl *OriginTemplate =
12859 DG->getDeclName().getCXXDeductionGuideTemplate();
12860 // We want to always print synthesized deduction guides for type aliases.
12861 // They would retain the explicit bit of the corresponding constructor.
12862 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12863 return;
12864 std::string FunctionProto;
12865 llvm::raw_string_ostream OS(FunctionProto);
12866 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12867 if (!Template) {
12868 // This also could be an instantiation. Find out the primary template.
12869 FunctionDecl *Pattern =
12870 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12871 if (!Pattern) {
12872 // The implicit deduction guide is built on an explicit non-template
12873 // deduction guide. Currently, this might be the case only for type
12874 // aliases.
12875 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12876 // gets merged.
12877 assert(OriginTemplate->isTypeAlias() &&
12878 "Non-template implicit deduction guides are only possible for "
12879 "type aliases");
12880 DG->print(Out&: OS);
12881 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12882 << FunctionProto;
12883 return;
12884 }
12885 Template = Pattern->getDescribedFunctionTemplate();
12886 assert(Template && "Cannot find the associated function template of "
12887 "CXXDeductionGuideDecl?");
12888 }
12889 Template->print(Out&: OS);
12890 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12891 << FunctionProto;
12892}
12893
12894/// Generates a 'note' diagnostic for an overload candidate. We've
12895/// already generated a primary error at the call site.
12896///
12897/// It really does need to be a single diagnostic with its caret
12898/// pointed at the candidate declaration. Yes, this creates some
12899/// major challenges of technical writing. Yes, this makes pointing
12900/// out problems with specific arguments quite awkward. It's still
12901/// better than generating twenty screens of text for every failed
12902/// overload.
12903///
12904/// It would be great to be able to express per-candidate problems
12905/// more richly for those diagnostic clients that cared, but we'd
12906/// still have to be just as careful with the default diagnostics.
12907/// \param CtorDestAS Addr space of object being constructed (for ctor
12908/// candidates only).
12909static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12910 unsigned NumArgs,
12911 bool TakingCandidateAddress,
12912 LangAS CtorDestAS = LangAS::Default) {
12913 assert(Cand->Function && "Candidate must be a function");
12914 FunctionDecl *Fn = Cand->Function;
12915 if (shouldSkipNotingLambdaConversionDecl(Fn))
12916 return;
12917
12918 // There is no physical candidate declaration to point to for OpenCL builtins.
12919 // Except for failed conversions, the notes are identical for each candidate,
12920 // so do not generate such notes.
12921 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12922 Cand->FailureKind != ovl_fail_bad_conversion)
12923 return;
12924
12925 // Skip implicit member functions when trying to resolve
12926 // the address of a an overload set for a function pointer.
12927 if (Cand->TookAddressOfOverload &&
12928 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12929 return;
12930
12931 // Note deleted candidates, but only if they're viable.
12932 if (Cand->Viable) {
12933 if (Fn->isDeleted()) {
12934 std::string FnDesc;
12935 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12936 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12937 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12938
12939 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12940 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12941 << (Fn->isDeleted()
12942 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12943 : 0);
12944 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12945 return;
12946 }
12947
12948 // We don't really have anything else to say about viable candidates.
12949 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12950 return;
12951 }
12952
12953 // If this is a synthesized deduction guide we're deducing against, add a note
12954 // for it. These deduction guides are not explicitly spelled in the source
12955 // code, so simply printing a deduction failure note mentioning synthesized
12956 // template parameters or pointing to the header of the surrounding RecordDecl
12957 // would be confusing.
12958 //
12959 // We prefer adding such notes at the end of the deduction failure because
12960 // duplicate code snippets appearing in the diagnostic would likely become
12961 // noisy.
12962 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12963
12964 switch (Cand->FailureKind) {
12965 case ovl_fail_too_many_arguments:
12966 case ovl_fail_too_few_arguments:
12967 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12968
12969 case ovl_fail_bad_deduction:
12970 return DiagnoseBadDeduction(S, Cand, NumArgs,
12971 TakingCandidateAddress);
12972
12973 case ovl_fail_illegal_constructor: {
12974 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12975 << (Fn->getPrimaryTemplate() ? 1 : 0);
12976 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12977 return;
12978 }
12979
12980 case ovl_fail_object_addrspace_mismatch: {
12981 Qualifiers QualsForPrinting;
12982 QualsForPrinting.setAddressSpace(CtorDestAS);
12983 S.Diag(Loc: Fn->getLocation(),
12984 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12985 << QualsForPrinting;
12986 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12987 return;
12988 }
12989
12990 case ovl_fail_trivial_conversion:
12991 case ovl_fail_bad_final_conversion:
12992 case ovl_fail_final_conversion_not_exact:
12993 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12994
12995 case ovl_fail_bad_conversion: {
12996 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12997 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12998 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12999 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13000
13001 // FIXME: this currently happens when we're called from SemaInit
13002 // when user-conversion overload fails. Figure out how to handle
13003 // those conditions and diagnose them well.
13004 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13005 }
13006
13007 case ovl_fail_bad_target:
13008 return DiagnoseBadTarget(S, Cand);
13009
13010 case ovl_fail_enable_if:
13011 return DiagnoseFailedEnableIfAttr(S, Cand);
13012
13013 case ovl_fail_explicit:
13014 return DiagnoseFailedExplicitSpec(S, Cand);
13015
13016 case ovl_fail_inhctor_slice:
13017 // It's generally not interesting to note copy/move constructors here.
13018 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
13019 return;
13020 S.Diag(Loc: Fn->getLocation(),
13021 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
13022 << (Fn->getPrimaryTemplate() ? 1 : 0)
13023 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
13024 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13025 return;
13026
13027 case ovl_fail_addr_not_available: {
13028 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
13029 (void)Available;
13030 assert(!Available);
13031 break;
13032 }
13033 case ovl_non_default_multiversion_function:
13034 // Do nothing, these should simply be ignored.
13035 break;
13036
13037 case ovl_fail_constraints_not_satisfied: {
13038 std::string FnDesc;
13039 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13040 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
13041 CRK: Cand->getRewriteKind(), Description&: FnDesc);
13042
13043 S.Diag(Loc: Fn->getLocation(),
13044 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
13045 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13046 << FnDesc /* Ignored */;
13047 ConstraintSatisfaction Satisfaction;
13048 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
13049 /*ForOverloadResolution=*/true))
13050 break;
13051 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13052 }
13053 }
13054}
13055
13056static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
13057 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
13058 return;
13059
13060 // Desugar the type of the surrogate down to a function type,
13061 // retaining as many typedefs as possible while still showing
13062 // the function type (and, therefore, its parameter types).
13063 QualType FnType = Cand->Surrogate->getConversionType();
13064 bool isLValueReference = false;
13065 bool isRValueReference = false;
13066 bool isPointer = false;
13067 if (const LValueReferenceType *FnTypeRef =
13068 FnType->getAs<LValueReferenceType>()) {
13069 FnType = FnTypeRef->getPointeeType();
13070 isLValueReference = true;
13071 } else if (const RValueReferenceType *FnTypeRef =
13072 FnType->getAs<RValueReferenceType>()) {
13073 FnType = FnTypeRef->getPointeeType();
13074 isRValueReference = true;
13075 }
13076 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13077 FnType = FnTypePtr->getPointeeType();
13078 isPointer = true;
13079 }
13080 // Desugar down to a function type.
13081 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13082 // Reconstruct the pointer/reference as appropriate.
13083 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
13084 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13085 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13086
13087 if (!Cand->Viable &&
13088 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13089 S.Diag(Loc: Cand->Surrogate->getLocation(),
13090 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13091 << Cand->Surrogate;
13092 ConstraintSatisfaction Satisfaction;
13093 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13094 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13095 } else {
13096 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13097 << FnType;
13098 }
13099}
13100
13101static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13102 SourceLocation OpLoc,
13103 OverloadCandidate *Cand) {
13104 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13105 std::string TypeStr("operator");
13106 TypeStr += Opc;
13107 TypeStr += "(";
13108 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13109 if (Cand->Conversions.size() == 1) {
13110 TypeStr += ")";
13111 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13112 } else {
13113 TypeStr += ", ";
13114 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13115 TypeStr += ")";
13116 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13117 }
13118}
13119
13120static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13121 OverloadCandidate *Cand) {
13122 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13123 if (ICS.isBad()) break; // all meaningless after first invalid
13124 if (!ICS.isAmbiguous()) continue;
13125
13126 ICS.DiagnoseAmbiguousConversion(
13127 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13128 }
13129}
13130
13131static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13132 if (Cand->Function)
13133 return Cand->Function->getLocation();
13134 if (Cand->IsSurrogate)
13135 return Cand->Surrogate->getLocation();
13136 return SourceLocation();
13137}
13138
13139static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13140 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13141 case TemplateDeductionResult::Success:
13142 case TemplateDeductionResult::NonDependentConversionFailure:
13143 case TemplateDeductionResult::AlreadyDiagnosed:
13144 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13145
13146 case TemplateDeductionResult::Invalid:
13147 case TemplateDeductionResult::Incomplete:
13148 case TemplateDeductionResult::IncompletePack:
13149 return 1;
13150
13151 case TemplateDeductionResult::Underqualified:
13152 case TemplateDeductionResult::Inconsistent:
13153 return 2;
13154
13155 case TemplateDeductionResult::SubstitutionFailure:
13156 case TemplateDeductionResult::DeducedMismatch:
13157 case TemplateDeductionResult::ConstraintsNotSatisfied:
13158 case TemplateDeductionResult::DeducedMismatchNested:
13159 case TemplateDeductionResult::NonDeducedMismatch:
13160 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13161 case TemplateDeductionResult::CUDATargetMismatch:
13162 return 3;
13163
13164 case TemplateDeductionResult::InstantiationDepth:
13165 return 4;
13166
13167 case TemplateDeductionResult::InvalidExplicitArguments:
13168 return 5;
13169
13170 case TemplateDeductionResult::TooManyArguments:
13171 case TemplateDeductionResult::TooFewArguments:
13172 return 6;
13173 }
13174 llvm_unreachable("Unhandled deduction result");
13175}
13176
13177namespace {
13178
13179struct CompareOverloadCandidatesForDisplay {
13180 Sema &S;
13181 SourceLocation Loc;
13182 size_t NumArgs;
13183 OverloadCandidateSet::CandidateSetKind CSK;
13184
13185 CompareOverloadCandidatesForDisplay(
13186 Sema &S, SourceLocation Loc, size_t NArgs,
13187 OverloadCandidateSet::CandidateSetKind CSK)
13188 : S(S), NumArgs(NArgs), CSK(CSK) {}
13189
13190 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13191 // If there are too many or too few arguments, that's the high-order bit we
13192 // want to sort by, even if the immediate failure kind was something else.
13193 if (C->FailureKind == ovl_fail_too_many_arguments ||
13194 C->FailureKind == ovl_fail_too_few_arguments)
13195 return static_cast<OverloadFailureKind>(C->FailureKind);
13196
13197 if (C->Function) {
13198 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13199 return ovl_fail_too_many_arguments;
13200 if (NumArgs < C->Function->getMinRequiredArguments())
13201 return ovl_fail_too_few_arguments;
13202 }
13203
13204 return static_cast<OverloadFailureKind>(C->FailureKind);
13205 }
13206
13207 bool operator()(const OverloadCandidate *L,
13208 const OverloadCandidate *R) {
13209 // Fast-path this check.
13210 if (L == R) return false;
13211
13212 // Order first by viability.
13213 if (L->Viable) {
13214 if (!R->Viable) return true;
13215
13216 if (int Ord = CompareConversions(L: *L, R: *R))
13217 return Ord < 0;
13218 // Use other tie breakers.
13219 } else if (R->Viable)
13220 return false;
13221
13222 assert(L->Viable == R->Viable);
13223
13224 // Criteria by which we can sort non-viable candidates:
13225 if (!L->Viable) {
13226 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13227 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13228
13229 // 1. Arity mismatches come after other candidates.
13230 if (LFailureKind == ovl_fail_too_many_arguments ||
13231 LFailureKind == ovl_fail_too_few_arguments) {
13232 if (RFailureKind == ovl_fail_too_many_arguments ||
13233 RFailureKind == ovl_fail_too_few_arguments) {
13234 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13235 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13236 if (LDist == RDist) {
13237 if (LFailureKind == RFailureKind)
13238 // Sort non-surrogates before surrogates.
13239 return !L->IsSurrogate && R->IsSurrogate;
13240 // Sort candidates requiring fewer parameters than there were
13241 // arguments given after candidates requiring more parameters
13242 // than there were arguments given.
13243 return LFailureKind == ovl_fail_too_many_arguments;
13244 }
13245 return LDist < RDist;
13246 }
13247 return false;
13248 }
13249 if (RFailureKind == ovl_fail_too_many_arguments ||
13250 RFailureKind == ovl_fail_too_few_arguments)
13251 return true;
13252
13253 // 2. Bad conversions come first and are ordered by the number
13254 // of bad conversions and quality of good conversions.
13255 if (LFailureKind == ovl_fail_bad_conversion) {
13256 if (RFailureKind != ovl_fail_bad_conversion)
13257 return true;
13258
13259 // The conversion that can be fixed with a smaller number of changes,
13260 // comes first.
13261 unsigned numLFixes = L->Fix.NumConversionsFixed;
13262 unsigned numRFixes = R->Fix.NumConversionsFixed;
13263 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13264 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13265 if (numLFixes != numRFixes) {
13266 return numLFixes < numRFixes;
13267 }
13268
13269 // If there's any ordering between the defined conversions...
13270 if (int Ord = CompareConversions(L: *L, R: *R))
13271 return Ord < 0;
13272 } else if (RFailureKind == ovl_fail_bad_conversion)
13273 return false;
13274
13275 if (LFailureKind == ovl_fail_bad_deduction) {
13276 if (RFailureKind != ovl_fail_bad_deduction)
13277 return true;
13278
13279 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13280 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13281 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13282 if (LRank != RRank)
13283 return LRank < RRank;
13284 }
13285 } else if (RFailureKind == ovl_fail_bad_deduction)
13286 return false;
13287
13288 // TODO: others?
13289 }
13290
13291 // Sort everything else by location.
13292 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13293 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13294
13295 // Put candidates without locations (e.g. builtins) at the end.
13296 if (LLoc.isValid() && RLoc.isValid())
13297 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13298 if (LLoc.isValid() && !RLoc.isValid())
13299 return true;
13300 if (RLoc.isValid() && !LLoc.isValid())
13301 return false;
13302 assert(!LLoc.isValid() && !RLoc.isValid());
13303 // For builtins and other functions without locations, fallback to the order
13304 // in which they were added into the candidate set.
13305 return L < R;
13306 }
13307
13308private:
13309 struct ConversionSignals {
13310 unsigned KindRank = 0;
13311 ImplicitConversionRank Rank = ICR_Exact_Match;
13312
13313 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13314 ConversionSignals Sig;
13315 Sig.KindRank = Seq.getKindRank();
13316 if (Seq.isStandard())
13317 Sig.Rank = Seq.Standard.getRank();
13318 else if (Seq.isUserDefined())
13319 Sig.Rank = Seq.UserDefined.After.getRank();
13320 // We intend StaticObjectArgumentConversion to compare the same as
13321 // StandardConversion with ICR_ExactMatch rank.
13322 return Sig;
13323 }
13324
13325 static ConversionSignals ForObjectArgument() {
13326 // We intend StaticObjectArgumentConversion to compare the same as
13327 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13328 return {};
13329 }
13330 };
13331
13332 // Returns -1 if conversions in L are considered better.
13333 // 0 if they are considered indistinguishable.
13334 // 1 if conversions in R are better.
13335 int CompareConversions(const OverloadCandidate &L,
13336 const OverloadCandidate &R) {
13337 // We cannot use `isBetterOverloadCandidate` because it is defined
13338 // according to the C++ standard and provides a partial order, but we need
13339 // a total order as this function is used in sort.
13340 assert(L.Conversions.size() == R.Conversions.size());
13341 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13342 auto LS = L.IgnoreObjectArgument && I == 0
13343 ? ConversionSignals::ForObjectArgument()
13344 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13345 auto RS = R.IgnoreObjectArgument
13346 ? ConversionSignals::ForObjectArgument()
13347 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13348 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13349 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13350 ? -1
13351 : 1;
13352 }
13353 // FIXME: find a way to compare templates for being more or less
13354 // specialized that provides a strict weak ordering.
13355 return 0;
13356 }
13357};
13358}
13359
13360/// CompleteNonViableCandidate - Normally, overload resolution only
13361/// computes up to the first bad conversion. Produces the FixIt set if
13362/// possible.
13363static void
13364CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13365 ArrayRef<Expr *> Args,
13366 OverloadCandidateSet::CandidateSetKind CSK) {
13367 assert(!Cand->Viable);
13368
13369 // Don't do anything on failures other than bad conversion.
13370 if (Cand->FailureKind != ovl_fail_bad_conversion)
13371 return;
13372
13373 // We only want the FixIts if all the arguments can be corrected.
13374 bool Unfixable = false;
13375 // Use a implicit copy initialization to check conversion fixes.
13376 Cand->Fix.setConversionChecker(TryCopyInitialization);
13377
13378 // Attempt to fix the bad conversion.
13379 unsigned ConvCount = Cand->Conversions.size();
13380 for (unsigned ConvIdx =
13381 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13382 : 0);
13383 /**/; ++ConvIdx) {
13384 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13385 if (Cand->Conversions[ConvIdx].isInitialized() &&
13386 Cand->Conversions[ConvIdx].isBad()) {
13387 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13388 break;
13389 }
13390 }
13391
13392 // FIXME: this should probably be preserved from the overload
13393 // operation somehow.
13394 bool SuppressUserConversions = false;
13395
13396 unsigned ConvIdx = 0;
13397 unsigned ArgIdx = 0;
13398 ArrayRef<QualType> ParamTypes;
13399 bool Reversed = Cand->isReversed();
13400
13401 if (Cand->IsSurrogate) {
13402 QualType ConvType
13403 = Cand->Surrogate->getConversionType().getNonReferenceType();
13404 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13405 ConvType = ConvPtrType->getPointeeType();
13406 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13407 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13408 ConvIdx = 1;
13409 } else if (Cand->Function) {
13410 ParamTypes =
13411 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13412 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13413 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13414 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13415 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13416 ConvIdx = 1;
13417 if (CSK == OverloadCandidateSet::CSK_Operator &&
13418 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13419 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13420 OO_Subscript)
13421 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13422 ArgIdx = 1;
13423 }
13424 } else {
13425 // Builtin operator.
13426 assert(ConvCount <= 3);
13427 ParamTypes = Cand->BuiltinParamTypes;
13428 }
13429
13430 // Fill in the rest of the conversions.
13431 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13432 ConvIdx != ConvCount && ArgIdx < Args.size();
13433 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13434 if (Cand->Conversions[ConvIdx].isInitialized()) {
13435 // We've already checked this conversion.
13436 } else if (ParamIdx < ParamTypes.size()) {
13437 if (ParamTypes[ParamIdx]->isDependentType())
13438 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13439 Args[ArgIdx]->getType());
13440 else {
13441 Cand->Conversions[ConvIdx] =
13442 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13443 SuppressUserConversions,
13444 /*InOverloadResolution=*/true,
13445 /*AllowObjCWritebackConversion=*/
13446 S.getLangOpts().ObjCAutoRefCount);
13447 // Store the FixIt in the candidate if it exists.
13448 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13449 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13450 }
13451 } else
13452 Cand->Conversions[ConvIdx].setEllipsis();
13453 }
13454}
13455
13456SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13457 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13458 SourceLocation OpLoc,
13459 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13460
13461 InjectNonDeducedTemplateCandidates(S);
13462
13463 // Sort the candidates by viability and position. Sorting directly would
13464 // be prohibitive, so we make a set of pointers and sort those.
13465 SmallVector<OverloadCandidate*, 32> Cands;
13466 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13467 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13468 Cand != LastCand; ++Cand) {
13469 if (!Filter(*Cand))
13470 continue;
13471 switch (OCD) {
13472 case OCD_AllCandidates:
13473 if (!Cand->Viable) {
13474 if (!Cand->Function && !Cand->IsSurrogate) {
13475 // This a non-viable builtin candidate. We do not, in general,
13476 // want to list every possible builtin candidate.
13477 continue;
13478 }
13479 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13480 }
13481 break;
13482
13483 case OCD_ViableCandidates:
13484 if (!Cand->Viable)
13485 continue;
13486 break;
13487
13488 case OCD_AmbiguousCandidates:
13489 if (!Cand->Best)
13490 continue;
13491 break;
13492 }
13493
13494 Cands.push_back(Elt: Cand);
13495 }
13496
13497 llvm::stable_sort(
13498 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13499
13500 return Cands;
13501}
13502
13503bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13504 SourceLocation OpLoc) {
13505 bool DeferHint = false;
13506 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13507 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13508 // host device candidates.
13509 auto WrongSidedCands =
13510 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13511 return (Cand.Viable == false &&
13512 Cand.FailureKind == ovl_fail_bad_target) ||
13513 (Cand.Function &&
13514 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13515 Cand.Function->template hasAttr<CUDADeviceAttr>());
13516 });
13517 DeferHint = !WrongSidedCands.empty();
13518 }
13519 return DeferHint;
13520}
13521
13522/// When overload resolution fails, prints diagnostic messages containing the
13523/// candidates in the candidate set.
13524void OverloadCandidateSet::NoteCandidates(
13525 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13526 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13527 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13528
13529 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13530
13531 {
13532 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13533 S.Diag(Loc: PD.first, PD: PD.second);
13534 }
13535
13536 // In WebAssembly we don't want to emit further diagnostics if a table is
13537 // passed as an argument to a function.
13538 bool NoteCands = true;
13539 for (const Expr *Arg : Args) {
13540 if (Arg->getType()->isWebAssemblyTableType())
13541 NoteCands = false;
13542 }
13543
13544 if (NoteCands)
13545 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13546
13547 if (OCD == OCD_AmbiguousCandidates)
13548 MaybeDiagnoseAmbiguousConstraints(S,
13549 Cands: {Candidates.begin(), Candidates.end()});
13550}
13551
13552void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13553 ArrayRef<OverloadCandidate *> Cands,
13554 StringRef Opc, SourceLocation OpLoc) {
13555 bool ReportedAmbiguousConversions = false;
13556
13557 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13558 unsigned CandsShown = 0;
13559 auto I = Cands.begin(), E = Cands.end();
13560 for (; I != E; ++I) {
13561 OverloadCandidate *Cand = *I;
13562
13563 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13564 ShowOverloads == Ovl_Best) {
13565 break;
13566 }
13567 ++CandsShown;
13568
13569 if (Cand->Function)
13570 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13571 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13572 else if (Cand->IsSurrogate)
13573 NoteSurrogateCandidate(S, Cand);
13574 else {
13575 assert(Cand->Viable &&
13576 "Non-viable built-in candidates are not added to Cands.");
13577 // Generally we only see ambiguities including viable builtin
13578 // operators if overload resolution got screwed up by an
13579 // ambiguous user-defined conversion.
13580 //
13581 // FIXME: It's quite possible for different conversions to see
13582 // different ambiguities, though.
13583 if (!ReportedAmbiguousConversions) {
13584 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13585 ReportedAmbiguousConversions = true;
13586 }
13587
13588 // If this is a viable builtin, print it.
13589 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13590 }
13591 }
13592
13593 // Inform S.Diags that we've shown an overload set with N elements. This may
13594 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13595 S.Diags.overloadCandidatesShown(N: CandsShown);
13596
13597 if (I != E) {
13598 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13599 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13600 }
13601}
13602
13603bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
13604 const Sema &S) const {
13605 if (S.getLangOpts().CUDA) {
13606 auto *Caller = S.getCurFunctionDecl(AllowLambda: true);
13607 // Overloading based on __host__ and __device__ attributes takes
13608 // higher priority, HD functions may favor template candidates even when a
13609 // non-template candidate would be a perfect match.
13610 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13611 Caller->hasAttr<CUDADeviceAttr>())
13612 return false;
13613 }
13614
13615 return
13616 // For user defined conversion we need to check against different
13617 // combination of CV qualifiers and look at any explicit specifier, so
13618 // always deduce template candidates.
13619 Kind != CSK_InitByUserDefinedConversion
13620 // When doing code completion, we want to see all the
13621 // viable candidates.
13622 && Kind != CSK_CodeCompletion;
13623}
13624
13625static SourceLocation
13626GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13627 return Cand->Specialization ? Cand->Specialization->getLocation()
13628 : SourceLocation();
13629}
13630
13631namespace {
13632struct CompareTemplateSpecCandidatesForDisplay {
13633 Sema &S;
13634 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13635
13636 bool operator()(const TemplateSpecCandidate *L,
13637 const TemplateSpecCandidate *R) {
13638 // Fast-path this check.
13639 if (L == R)
13640 return false;
13641
13642 // Assuming that both candidates are not matches...
13643
13644 // Sort by the ranking of deduction failures.
13645 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13646 return RankDeductionFailure(DFI: L->DeductionFailure) <
13647 RankDeductionFailure(DFI: R->DeductionFailure);
13648
13649 // Sort everything else by location.
13650 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13651 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13652
13653 // Put candidates without locations (e.g. builtins) at the end.
13654 if (LLoc.isInvalid())
13655 return false;
13656 if (RLoc.isInvalid())
13657 return true;
13658
13659 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13660 }
13661};
13662}
13663
13664/// Diagnose a template argument deduction failure.
13665/// We are treating these failures as overload failures due to bad
13666/// deductions.
13667void TemplateSpecCandidate::NoteDeductionFailure(
13668 Sema &S, bool ForTakingAddress,
13669 TemplateSpecCandidateSetKind CandidateSetKind) {
13670 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13671 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress,
13672 CandidateSetKind);
13673}
13674
13675void TemplateSpecCandidateSet::destroyCandidates() {
13676 for (iterator i = begin(), e = end(); i != e; ++i) {
13677 i->DeductionFailure.Destroy();
13678 }
13679}
13680
13681void TemplateSpecCandidateSet::clear() {
13682 destroyCandidates();
13683 Candidates.clear();
13684}
13685
13686/// NoteCandidates - When no template specialization match is found, prints
13687/// diagnostic messages containing the non-matching specializations that form
13688/// the candidate set.
13689/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13690/// OCD == OCD_AllCandidates and Cand->Viable == false.
13691void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13692 // Sort the candidates by position (assuming no candidate is a match).
13693 // Sorting directly would be prohibitive, so we make a set of pointers
13694 // and sort those.
13695 SmallVector<TemplateSpecCandidate *, 32> Cands;
13696 Cands.reserve(N: size());
13697 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13698 if (Cand->Specialization)
13699 Cands.push_back(Elt: Cand);
13700 // Otherwise, this is a non-matching builtin candidate. We do not,
13701 // in general, want to list every possible builtin candidate.
13702 }
13703
13704 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13705
13706 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13707 // for generalization purposes (?).
13708 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13709
13710 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13711 unsigned CandsShown = 0;
13712 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13713 TemplateSpecCandidate *Cand = *I;
13714
13715 // Set an arbitrary limit on the number of candidates we'll spam
13716 // the user with. FIXME: This limit should depend on details of the
13717 // candidate list.
13718 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13719 break;
13720 ++CandsShown;
13721
13722 assert(Cand->Specialization &&
13723 "Non-matching built-in candidates are not added to Cands.");
13724 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13725 }
13726
13727 if (I != E)
13728 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13729}
13730
13731// [PossiblyAFunctionType] --> [Return]
13732// NonFunctionType --> NonFunctionType
13733// R (A) --> R(A)
13734// R (*)(A) --> R (A)
13735// R (&)(A) --> R (A)
13736// R (S::*)(A) --> R (A)
13737QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13738 QualType Ret = PossiblyAFunctionType;
13739 if (const PointerType *ToTypePtr =
13740 PossiblyAFunctionType->getAs<PointerType>())
13741 Ret = ToTypePtr->getPointeeType();
13742 else if (const ReferenceType *ToTypeRef =
13743 PossiblyAFunctionType->getAs<ReferenceType>())
13744 Ret = ToTypeRef->getPointeeType();
13745 else if (const MemberPointerType *MemTypePtr =
13746 PossiblyAFunctionType->getAs<MemberPointerType>())
13747 Ret = MemTypePtr->getPointeeType();
13748 Ret =
13749 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13750 return Ret;
13751}
13752
13753static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13754 bool Complain = true) {
13755 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13756 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13757 return true;
13758
13759 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13760 if (S.getLangOpts().CPlusPlus17 &&
13761 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13762 !S.ResolveExceptionSpec(Loc, FPT))
13763 return true;
13764
13765 return false;
13766}
13767
13768namespace {
13769// A helper class to help with address of function resolution
13770// - allows us to avoid passing around all those ugly parameters
13771class AddressOfFunctionResolver {
13772 Sema& S;
13773 Expr* SourceExpr;
13774 const QualType& TargetType;
13775 QualType TargetFunctionType; // Extracted function type from target type
13776
13777 bool Complain;
13778 //DeclAccessPair& ResultFunctionAccessPair;
13779 ASTContext& Context;
13780
13781 bool TargetTypeIsNonStaticMemberFunction;
13782 bool FoundNonTemplateFunction;
13783 bool StaticMemberFunctionFromBoundPointer;
13784 bool HasComplained;
13785
13786 OverloadExpr::FindResult OvlExprInfo;
13787 OverloadExpr *OvlExpr;
13788 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13789 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13790 TemplateSpecCandidateSet FailedCandidates;
13791
13792public:
13793 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13794 const QualType &TargetType, bool Complain)
13795 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13796 Complain(Complain), Context(S.getASTContext()),
13797 TargetTypeIsNonStaticMemberFunction(
13798 !!TargetType->getAs<MemberPointerType>()),
13799 FoundNonTemplateFunction(false),
13800 StaticMemberFunctionFromBoundPointer(false),
13801 HasComplained(false),
13802 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13803 OvlExpr(OvlExprInfo.Expression),
13804 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13805 ExtractUnqualifiedFunctionTypeFromTargetType();
13806
13807 if (TargetFunctionType->isFunctionType()) {
13808 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13809 if (!UME->isImplicitAccess() &&
13810 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13811 StaticMemberFunctionFromBoundPointer = true;
13812 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13813 DeclAccessPair dap;
13814 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13815 ovl: OvlExpr, Complain: false, Found: &dap)) {
13816 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13817 if (!Method->isStatic()) {
13818 // If the target type is a non-function type and the function found
13819 // is a non-static member function, pretend as if that was the
13820 // target, it's the only possible type to end up with.
13821 TargetTypeIsNonStaticMemberFunction = true;
13822
13823 // And skip adding the function if its not in the proper form.
13824 // We'll diagnose this due to an empty set of functions.
13825 if (!OvlExprInfo.HasFormOfMemberPointer)
13826 return;
13827 }
13828
13829 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13830 }
13831 return;
13832 }
13833
13834 if (OvlExpr->hasExplicitTemplateArgs())
13835 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13836
13837 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13838 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13839 EliminateSuboptimalCudaMatches();
13840
13841 // C++ [over.over]p4:
13842 // If more than one function is selected, [...]
13843 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13844 if (FoundNonTemplateFunction) {
13845 EliminateAllTemplateMatches();
13846 EliminateLessPartialOrderingConstrainedMatches();
13847 } else
13848 EliminateAllExceptMostSpecializedTemplate();
13849 }
13850 }
13851 }
13852
13853 bool hasComplained() const { return HasComplained; }
13854
13855private:
13856 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13857 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13858 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13859 }
13860
13861 /// \return true if A is considered a better overload candidate for the
13862 /// desired type than B.
13863 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13864 // If A doesn't have exactly the correct type, we don't want to classify it
13865 // as "better" than anything else. This way, the user is required to
13866 // disambiguate for us if there are multiple candidates and no exact match.
13867 return candidateHasExactlyCorrectType(FD: A) &&
13868 (!candidateHasExactlyCorrectType(FD: B) ||
13869 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13870 }
13871
13872 /// \return true if we were able to eliminate all but one overload candidate,
13873 /// false otherwise.
13874 bool eliminiateSuboptimalOverloadCandidates() {
13875 // Same algorithm as overload resolution -- one pass to pick the "best",
13876 // another pass to be sure that nothing is better than the best.
13877 auto Best = Matches.begin();
13878 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13879 if (isBetterCandidate(A: I->second, B: Best->second))
13880 Best = I;
13881
13882 const FunctionDecl *BestFn = Best->second;
13883 auto IsBestOrInferiorToBest = [this, BestFn](
13884 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13885 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13886 };
13887
13888 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13889 // option, so we can potentially give the user a better error
13890 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13891 return false;
13892 Matches[0] = *Best;
13893 Matches.resize(N: 1);
13894 return true;
13895 }
13896
13897 bool isTargetTypeAFunction() const {
13898 return TargetFunctionType->isFunctionType();
13899 }
13900
13901 // [ToType] [Return]
13902
13903 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13904 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13905 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13906 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13907 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13908 }
13909
13910 // return true if any matching specializations were found
13911 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13912 const DeclAccessPair& CurAccessFunPair) {
13913 if (CXXMethodDecl *Method
13914 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13915 // Skip non-static function templates when converting to pointer, and
13916 // static when converting to member pointer.
13917 bool CanConvertToFunctionPointer =
13918 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13919 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13920 return false;
13921 }
13922 else if (TargetTypeIsNonStaticMemberFunction)
13923 return false;
13924
13925 // C++ [over.over]p2:
13926 // If the name is a function template, template argument deduction is
13927 // done (14.8.2.2), and if the argument deduction succeeds, the
13928 // resulting template argument list is used to generate a single
13929 // function template specialization, which is added to the set of
13930 // overloaded functions considered.
13931 FunctionDecl *Specialization = nullptr;
13932 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13933 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13934 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13935 Specialization, Info, /*IsAddressOfFunction*/ true);
13936 Result != TemplateDeductionResult::Success) {
13937 // Make a note of the failed deduction for diagnostics.
13938 FailedCandidates.addCandidate()
13939 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13940 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13941 return false;
13942 }
13943
13944 // Template argument deduction ensures that we have an exact match or
13945 // compatible pointer-to-function arguments that would be adjusted by ICS.
13946 // This function template specicalization works.
13947 assert(S.isSameOrCompatibleFunctionType(
13948 Context.getCanonicalType(Specialization->getType()),
13949 Context.getCanonicalType(TargetFunctionType)));
13950
13951 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13952 return false;
13953
13954 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13955 return true;
13956 }
13957
13958 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13959 const DeclAccessPair& CurAccessFunPair) {
13960 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13961 // Skip non-static functions when converting to pointer, and static
13962 // when converting to member pointer.
13963 bool CanConvertToFunctionPointer =
13964 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13965 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13966 return false;
13967 }
13968 else if (TargetTypeIsNonStaticMemberFunction)
13969 return false;
13970
13971 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13972 if (S.getLangOpts().CUDA) {
13973 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13974 if (!(Caller && Caller->isImplicit()) &&
13975 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13976 return false;
13977 }
13978 if (FunDecl->isMultiVersion()) {
13979 const auto *TA = FunDecl->getAttr<TargetAttr>();
13980 if (TA && !TA->isDefaultVersion())
13981 return false;
13982 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13983 if (TVA && !TVA->isDefaultVersion())
13984 return false;
13985 }
13986
13987 // If any candidate has a placeholder return type, trigger its deduction
13988 // now.
13989 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13990 Complain)) {
13991 HasComplained |= Complain;
13992 return false;
13993 }
13994
13995 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13996 return false;
13997
13998 // If we're in C, we need to support types that aren't exactly identical.
13999 if (!S.getLangOpts().CPlusPlus ||
14000 candidateHasExactlyCorrectType(FD: FunDecl)) {
14001 Matches.push_back(Elt: std::make_pair(
14002 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
14003 FoundNonTemplateFunction = true;
14004 return true;
14005 }
14006 }
14007
14008 return false;
14009 }
14010
14011 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14012 bool Ret = false;
14013
14014 // If the overload expression doesn't have the form of a pointer to
14015 // member, don't try to convert it to a pointer-to-member type.
14016 if (IsInvalidFormOfPointerToMemberFunction())
14017 return false;
14018
14019 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14020 E = OvlExpr->decls_end();
14021 I != E; ++I) {
14022 // Look through any using declarations to find the underlying function.
14023 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14024
14025 // C++ [over.over]p3:
14026 // Non-member functions and static member functions match
14027 // targets of type "pointer-to-function" or "reference-to-function."
14028 // Nonstatic member functions match targets of
14029 // type "pointer-to-member-function."
14030 // Note that according to DR 247, the containing class does not matter.
14031 if (FunctionTemplateDecl *FunctionTemplate
14032 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
14033 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
14034 Ret = true;
14035 }
14036 // If we have explicit template arguments supplied, skip non-templates.
14037 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14038 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
14039 Ret = true;
14040 }
14041 assert(Ret || Matches.empty());
14042 return Ret;
14043 }
14044
14045 void EliminateAllExceptMostSpecializedTemplate() {
14046 // [...] and any given function template specialization F1 is
14047 // eliminated if the set contains a second function template
14048 // specialization whose function template is more specialized
14049 // than the function template of F1 according to the partial
14050 // ordering rules of 14.5.5.2.
14051
14052 // The algorithm specified above is quadratic. We instead use a
14053 // two-pass algorithm (similar to the one used to identify the
14054 // best viable function in an overload set) that identifies the
14055 // best function template (if it exists).
14056
14057 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14058 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14059 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
14060
14061 // TODO: It looks like FailedCandidates does not serve much purpose
14062 // here, since the no_viable diagnostic has index 0.
14063 UnresolvedSetIterator Result = S.getMostSpecialized(
14064 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
14065 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
14066 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
14067 << Matches[0].second->getDeclName(),
14068 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
14069 << (unsigned)oc_function << (unsigned)ocs_described_template,
14070 Complain, TargetType: TargetFunctionType);
14071
14072 if (Result != MatchesCopy.end()) {
14073 // Make it the first and only element
14074 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14075 Matches[0].second = cast<FunctionDecl>(Val: *Result);
14076 Matches.resize(N: 1);
14077 } else
14078 HasComplained |= Complain;
14079 }
14080
14081 void EliminateAllTemplateMatches() {
14082 // [...] any function template specializations in the set are
14083 // eliminated if the set also contains a non-template function, [...]
14084 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14085 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14086 ++I;
14087 else {
14088 Matches[I] = Matches[--N];
14089 Matches.resize(N);
14090 }
14091 }
14092 }
14093
14094 void EliminateLessPartialOrderingConstrainedMatches() {
14095 // C++ [over.over]p5:
14096 // [...] Any given non-template function F0 is eliminated if the set
14097 // contains a second non-template function that is more
14098 // partial-ordering-constrained than F0. [...]
14099 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14100 "Call EliminateAllTemplateMatches() first");
14101 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14102 Results.push_back(Elt: Matches[0]);
14103 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14104 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14105 FunctionDecl *F = getMorePartialOrderingConstrained(
14106 S, Fn1: Matches[I].second, Fn2: Results[0].second,
14107 /*IsFn1Reversed=*/false,
14108 /*IsFn2Reversed=*/false);
14109 if (!F) {
14110 Results.push_back(Elt: Matches[I]);
14111 continue;
14112 }
14113 if (F == Matches[I].second) {
14114 Results.clear();
14115 Results.push_back(Elt: Matches[I]);
14116 }
14117 }
14118 std::swap(LHS&: Matches, RHS&: Results);
14119 }
14120
14121 void EliminateSuboptimalCudaMatches() {
14122 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14123 Matches);
14124 }
14125
14126public:
14127 void ComplainNoMatchesFound() const {
14128 assert(Matches.empty());
14129 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14130 << OvlExpr->getName() << TargetFunctionType
14131 << OvlExpr->getSourceRange();
14132 if (FailedCandidates.empty())
14133 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14134 /*TakingAddress=*/true);
14135 else {
14136 // We have some deduction failure messages. Use them to diagnose
14137 // the function templates, and diagnose the non-template candidates
14138 // normally.
14139 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14140 IEnd = OvlExpr->decls_end();
14141 I != IEnd; ++I)
14142 if (FunctionDecl *Fun =
14143 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14144 if (!functionHasPassObjectSizeParams(FD: Fun))
14145 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14146 /*TakingAddress=*/true);
14147 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14148 }
14149 }
14150
14151 bool IsInvalidFormOfPointerToMemberFunction() const {
14152 return TargetTypeIsNonStaticMemberFunction &&
14153 !OvlExprInfo.HasFormOfMemberPointer;
14154 }
14155
14156 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14157 // TODO: Should we condition this on whether any functions might
14158 // have matched, or is it more appropriate to do that in callers?
14159 // TODO: a fixit wouldn't hurt.
14160 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14161 << TargetType << OvlExpr->getSourceRange();
14162 }
14163
14164 bool IsStaticMemberFunctionFromBoundPointer() const {
14165 return StaticMemberFunctionFromBoundPointer;
14166 }
14167
14168 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14169 S.Diag(Loc: OvlExpr->getBeginLoc(),
14170 DiagID: diag::err_invalid_form_pointer_member_function)
14171 << OvlExpr->getSourceRange();
14172 }
14173
14174 void ComplainOfInvalidConversion() const {
14175 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14176 << OvlExpr->getName() << TargetType;
14177 }
14178
14179 void ComplainMultipleMatchesFound() const {
14180 assert(Matches.size() > 1);
14181 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14182 << OvlExpr->getName() << OvlExpr->getSourceRange();
14183 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14184 /*TakingAddress=*/true);
14185 }
14186
14187 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14188
14189 int getNumMatches() const { return Matches.size(); }
14190
14191 FunctionDecl* getMatchingFunctionDecl() const {
14192 if (Matches.size() != 1) return nullptr;
14193 return Matches[0].second;
14194 }
14195
14196 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14197 if (Matches.size() != 1) return nullptr;
14198 return &Matches[0].first;
14199 }
14200};
14201}
14202
14203FunctionDecl *
14204Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14205 QualType TargetType,
14206 bool Complain,
14207 DeclAccessPair &FoundResult,
14208 bool *pHadMultipleCandidates) {
14209 assert(AddressOfExpr->getType() == Context.OverloadTy);
14210
14211 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14212 Complain);
14213 int NumMatches = Resolver.getNumMatches();
14214 FunctionDecl *Fn = nullptr;
14215 bool ShouldComplain = Complain && !Resolver.hasComplained();
14216 if (NumMatches == 0 && ShouldComplain) {
14217 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14218 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14219 else
14220 Resolver.ComplainNoMatchesFound();
14221 }
14222 else if (NumMatches > 1 && ShouldComplain)
14223 Resolver.ComplainMultipleMatchesFound();
14224 else if (NumMatches == 1) {
14225 Fn = Resolver.getMatchingFunctionDecl();
14226 assert(Fn);
14227 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14228 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14229 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14230 if (Complain) {
14231 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14232 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14233 else
14234 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14235 }
14236 }
14237
14238 if (pHadMultipleCandidates)
14239 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14240 return Fn;
14241}
14242
14243FunctionDecl *
14244Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14245 OverloadExpr::FindResult R = OverloadExpr::find(E);
14246 OverloadExpr *Ovl = R.Expression;
14247 bool IsResultAmbiguous = false;
14248 FunctionDecl *Result = nullptr;
14249 DeclAccessPair DAP;
14250 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14251
14252 // Return positive for better, negative for worse, 0 for equal preference.
14253 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14254 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14255 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14256 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14257 };
14258
14259 // Don't use the AddressOfResolver because we're specifically looking for
14260 // cases where we have one overload candidate that lacks
14261 // enable_if/pass_object_size/...
14262 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14263 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14264 if (!FD)
14265 return nullptr;
14266
14267 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14268 continue;
14269
14270 // If we found a better result, update Result.
14271 auto FoundBetter = [&]() {
14272 IsResultAmbiguous = false;
14273 DAP = I.getPair();
14274 Result = FD;
14275 };
14276
14277 // We have more than one result - see if it is more
14278 // partial-ordering-constrained than the previous one.
14279 if (Result) {
14280 // Check CUDA preference first. If the candidates have differennt CUDA
14281 // preference, choose the one with higher CUDA preference. Otherwise,
14282 // choose the one with more constraints.
14283 if (getLangOpts().CUDA) {
14284 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14285 // FD has different preference than Result.
14286 if (PreferenceByCUDA != 0) {
14287 // FD is more preferable than Result.
14288 if (PreferenceByCUDA > 0)
14289 FoundBetter();
14290 continue;
14291 }
14292 }
14293 // FD has the same CUDA preference than Result. Continue to check
14294 // constraints.
14295
14296 // C++ [over.over]p5:
14297 // [...] Any given non-template function F0 is eliminated if the set
14298 // contains a second non-template function that is more
14299 // partial-ordering-constrained than F0 [...]
14300 FunctionDecl *MoreConstrained =
14301 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14302 /*IsFn1Reversed=*/false,
14303 /*IsFn2Reversed=*/false);
14304 if (MoreConstrained != FD) {
14305 if (!MoreConstrained) {
14306 IsResultAmbiguous = true;
14307 AmbiguousDecls.push_back(Elt: FD);
14308 }
14309 continue;
14310 }
14311 // FD is more constrained - replace Result with it.
14312 }
14313 FoundBetter();
14314 }
14315
14316 if (IsResultAmbiguous)
14317 return nullptr;
14318
14319 if (Result) {
14320 // We skipped over some ambiguous declarations which might be ambiguous with
14321 // the selected result.
14322 for (FunctionDecl *Skipped : AmbiguousDecls) {
14323 // If skipped candidate has different CUDA preference than the result,
14324 // there is no ambiguity. Otherwise check whether they have different
14325 // constraints.
14326 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14327 continue;
14328 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14329 return nullptr;
14330 }
14331 Pair = DAP;
14332 }
14333 return Result;
14334}
14335
14336bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14337 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14338 Expr *E = SrcExpr.get();
14339 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14340
14341 DeclAccessPair DAP;
14342 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14343 if (!Found || Found->isCPUDispatchMultiVersion() ||
14344 Found->isCPUSpecificMultiVersion())
14345 return false;
14346
14347 // Emitting multiple diagnostics for a function that is both inaccessible and
14348 // unavailable is consistent with our behavior elsewhere. So, always check
14349 // for both.
14350 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14351 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14352 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14353 if (Res.isInvalid())
14354 return false;
14355 Expr *Fixed = Res.get();
14356 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14357 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14358 else
14359 SrcExpr = Fixed;
14360 return true;
14361}
14362
14363FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14364 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14365 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14366 // C++ [over.over]p1:
14367 // [...] [Note: any redundant set of parentheses surrounding the
14368 // overloaded function name is ignored (5.1). ]
14369 // C++ [over.over]p1:
14370 // [...] The overloaded function name can be preceded by the &
14371 // operator.
14372
14373 // If we didn't actually find any template-ids, we're done.
14374 if (!ovl->hasExplicitTemplateArgs())
14375 return nullptr;
14376
14377 TemplateArgumentListInfo ExplicitTemplateArgs;
14378 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14379
14380 // Look through all of the overloaded functions, searching for one
14381 // whose type matches exactly.
14382 FunctionDecl *Matched = nullptr;
14383 for (UnresolvedSetIterator I = ovl->decls_begin(),
14384 E = ovl->decls_end(); I != E; ++I) {
14385 // C++0x [temp.arg.explicit]p3:
14386 // [...] In contexts where deduction is done and fails, or in contexts
14387 // where deduction is not done, if a template argument list is
14388 // specified and it, along with any default template arguments,
14389 // identifies a single function template specialization, then the
14390 // template-id is an lvalue for the function template specialization.
14391 FunctionTemplateDecl *FunctionTemplate =
14392 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14393 if (!FunctionTemplate)
14394 continue;
14395
14396 // C++ [over.over]p2:
14397 // If the name is a function template, template argument deduction is
14398 // done (14.8.2.2), and if the argument deduction succeeds, the
14399 // resulting template argument list is used to generate a single
14400 // function template specialization, which is added to the set of
14401 // overloaded functions considered.
14402 FunctionDecl *Specialization = nullptr;
14403 TemplateDeductionInfo Info(ovl->getNameLoc());
14404 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14405 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14406 /*IsAddressOfFunction*/ true);
14407 Result != TemplateDeductionResult::Success) {
14408 // Make a note of the failed deduction for diagnostics.
14409 if (FailedTSC)
14410 FailedTSC->addCandidate().set(
14411 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14412 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14413 continue;
14414 }
14415
14416 assert(Specialization && "no specialization and no error?");
14417
14418 // C++ [temp.deduct.call]p6:
14419 // [...] If all successful deductions yield the same deduced A, that
14420 // deduced A is the result of deduction; otherwise, the parameter is
14421 // treated as a non-deduced context.
14422 if (Matched) {
14423 if (ForTypeDeduction &&
14424 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14425 Arg: Specialization->getType()))
14426 continue;
14427 // Multiple matches; we can't resolve to a single declaration.
14428 if (Complain) {
14429 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14430 << ovl->getName();
14431 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14432 }
14433 return nullptr;
14434 }
14435
14436 Matched = Specialization;
14437 if (FoundResult) *FoundResult = I.getPair();
14438 }
14439
14440 if (Matched &&
14441 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14442 return nullptr;
14443
14444 return Matched;
14445}
14446
14447bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14448 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14449 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14450 unsigned DiagIDForComplaining) {
14451 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14452
14453 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14454
14455 DeclAccessPair found;
14456 ExprResult SingleFunctionExpression;
14457 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14458 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14459 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14460 SrcExpr = ExprError();
14461 return true;
14462 }
14463
14464 // It is only correct to resolve to an instance method if we're
14465 // resolving a form that's permitted to be a pointer to member.
14466 // Otherwise we'll end up making a bound member expression, which
14467 // is illegal in all the contexts we resolve like this.
14468 if (!ovl.HasFormOfMemberPointer &&
14469 isa<CXXMethodDecl>(Val: fn) &&
14470 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14471 if (!complain) return false;
14472
14473 Diag(Loc: ovl.Expression->getExprLoc(),
14474 DiagID: diag::err_bound_member_function)
14475 << 0 << ovl.Expression->getSourceRange();
14476
14477 // TODO: I believe we only end up here if there's a mix of
14478 // static and non-static candidates (otherwise the expression
14479 // would have 'bound member' type, not 'overload' type).
14480 // Ideally we would note which candidate was chosen and why
14481 // the static candidates were rejected.
14482 SrcExpr = ExprError();
14483 return true;
14484 }
14485
14486 // Fix the expression to refer to 'fn'.
14487 SingleFunctionExpression =
14488 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14489
14490 // If desired, do function-to-pointer decay.
14491 if (doFunctionPointerConversion) {
14492 SingleFunctionExpression =
14493 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14494 if (SingleFunctionExpression.isInvalid()) {
14495 SrcExpr = ExprError();
14496 return true;
14497 }
14498 }
14499 }
14500
14501 if (!SingleFunctionExpression.isUsable()) {
14502 if (complain) {
14503 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14504 << ovl.Expression->getName()
14505 << DestTypeForComplaining
14506 << OpRangeForComplaining
14507 << ovl.Expression->getQualifierLoc().getSourceRange();
14508 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14509
14510 SrcExpr = ExprError();
14511 return true;
14512 }
14513
14514 return false;
14515 }
14516
14517 SrcExpr = SingleFunctionExpression;
14518 return true;
14519}
14520
14521/// Add a single candidate to the overload set.
14522static void AddOverloadedCallCandidate(Sema &S,
14523 DeclAccessPair FoundDecl,
14524 TemplateArgumentListInfo *ExplicitTemplateArgs,
14525 ArrayRef<Expr *> Args,
14526 OverloadCandidateSet &CandidateSet,
14527 bool PartialOverloading,
14528 bool KnownValid) {
14529 NamedDecl *Callee = FoundDecl.getDecl();
14530 if (isa<UsingShadowDecl>(Val: Callee))
14531 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14532
14533 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14534 if (ExplicitTemplateArgs) {
14535 assert(!KnownValid && "Explicit template arguments?");
14536 return;
14537 }
14538 // Prevent ill-formed function decls to be added as overload candidates.
14539 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14540 return;
14541
14542 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14543 /*SuppressUserConversions=*/false,
14544 PartialOverloading);
14545 return;
14546 }
14547
14548 if (FunctionTemplateDecl *FuncTemplate
14549 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14550 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14551 ExplicitTemplateArgs, Args, CandidateSet,
14552 /*SuppressUserConversions=*/false,
14553 PartialOverloading);
14554 return;
14555 }
14556
14557 assert(!KnownValid && "unhandled case in overloaded call candidate");
14558}
14559
14560void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14561 ArrayRef<Expr *> Args,
14562 OverloadCandidateSet &CandidateSet,
14563 bool PartialOverloading) {
14564
14565#ifndef NDEBUG
14566 // Verify that ArgumentDependentLookup is consistent with the rules
14567 // in C++0x [basic.lookup.argdep]p3:
14568 //
14569 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14570 // and let Y be the lookup set produced by argument dependent
14571 // lookup (defined as follows). If X contains
14572 //
14573 // -- a declaration of a class member, or
14574 //
14575 // -- a block-scope function declaration that is not a
14576 // using-declaration, or
14577 //
14578 // -- a declaration that is neither a function or a function
14579 // template
14580 //
14581 // then Y is empty.
14582
14583 if (ULE->requiresADL()) {
14584 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14585 E = ULE->decls_end(); I != E; ++I) {
14586 assert(!(*I)->getDeclContext()->isRecord());
14587 assert(isa<UsingShadowDecl>(*I) ||
14588 !(*I)->getDeclContext()->isFunctionOrMethod());
14589 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14590 }
14591 }
14592#endif
14593
14594 // It would be nice to avoid this copy.
14595 TemplateArgumentListInfo TABuffer;
14596 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14597 if (ULE->hasExplicitTemplateArgs()) {
14598 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14599 ExplicitTemplateArgs = &TABuffer;
14600 }
14601
14602 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14603 E = ULE->decls_end(); I != E; ++I)
14604 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14605 CandidateSet, PartialOverloading,
14606 /*KnownValid*/ true);
14607
14608 if (ULE->requiresADL())
14609 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14610 Args, ExplicitTemplateArgs,
14611 CandidateSet, PartialOverloading);
14612}
14613
14614void Sema::AddOverloadedCallCandidates(
14615 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14616 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14617 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14618 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14619 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14620}
14621
14622/// Determine whether a declaration with the specified name could be moved into
14623/// a different namespace.
14624static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14625 switch (Name.getCXXOverloadedOperator()) {
14626 case OO_New: case OO_Array_New:
14627 case OO_Delete: case OO_Array_Delete:
14628 return false;
14629
14630 default:
14631 return true;
14632 }
14633}
14634
14635/// Attempt to recover from an ill-formed use of a non-dependent name in a
14636/// template, where the non-dependent name was declared after the template
14637/// was defined. This is common in code written for compilers which do not
14638/// correctly implement two-stage name lookup.
14639///
14640/// Returns true if a viable candidate was found and a diagnostic was issued.
14641static bool DiagnoseTwoPhaseLookup(
14642 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14643 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14644 const OverloadCandidateSet &ResolvedCandidates,
14645 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14646 CXXRecordDecl **FoundInClass = nullptr) {
14647 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14648 return false;
14649
14650 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14651 if (DC->isTransparentContext())
14652 continue;
14653
14654 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14655
14656 if (!R.empty()) {
14657 R.suppressDiagnostics();
14658
14659 OverloadCandidateSet Candidates(FnLoc, CSK);
14660 // We have performed a BestViableFunction over these candidates, so
14661 // exclude them.
14662 for (auto &Cand : ResolvedCandidates) {
14663 if (Cand.Function)
14664 Candidates.exclude(F: Cand.Function);
14665 else if (Cand.IsSurrogate)
14666 Candidates.exclude(F: Cand.Surrogate);
14667 }
14668 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14669 CandidateSet&: Candidates);
14670
14671 OverloadCandidateSet::iterator Best;
14672 OverloadingResult OR =
14673 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14674
14675 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14676 // We either found non-function declarations or a best viable function
14677 // at class scope. A class-scope lookup result disables ADL. Don't
14678 // look past this, but let the caller know that we found something that
14679 // either is, or might be, usable in this class.
14680 if (FoundInClass) {
14681 *FoundInClass = RD;
14682 if (OR == OR_Success) {
14683 R.clear();
14684 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14685 R.resolveKind();
14686 }
14687 }
14688 return false;
14689 }
14690
14691 if (OR != OR_Success) {
14692 // There wasn't a unique best function or function template.
14693 return false;
14694 }
14695
14696 // Find the namespaces where ADL would have looked, and suggest
14697 // declaring the function there instead.
14698 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14699 Sema::AssociatedClassSet AssociatedClasses;
14700 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14701 AssociatedNamespaces,
14702 AssociatedClasses);
14703 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14704 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14705 DeclContext *Std = SemaRef.getStdNamespace();
14706 for (Sema::AssociatedNamespaceSet::iterator
14707 it = AssociatedNamespaces.begin(),
14708 end = AssociatedNamespaces.end(); it != end; ++it) {
14709 // Never suggest declaring a function within namespace 'std'.
14710 if (Std && Std->Encloses(DC: *it))
14711 continue;
14712
14713 // Never suggest declaring a function within a namespace with a
14714 // reserved name, like __gnu_cxx.
14715 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14716 if (NS &&
14717 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14718 continue;
14719
14720 SuggestedNamespaces.insert(X: *it);
14721 }
14722 }
14723
14724 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14725 << R.getLookupName();
14726 if (SuggestedNamespaces.empty()) {
14727 SemaRef.Diag(Loc: Best->Function->getLocation(),
14728 DiagID: diag::note_not_found_by_two_phase_lookup)
14729 << R.getLookupName() << 0;
14730 } else if (SuggestedNamespaces.size() == 1) {
14731 SemaRef.Diag(Loc: Best->Function->getLocation(),
14732 DiagID: diag::note_not_found_by_two_phase_lookup)
14733 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14734 } else {
14735 // FIXME: It would be useful to list the associated namespaces here,
14736 // but the diagnostics infrastructure doesn't provide a way to produce
14737 // a localized representation of a list of items.
14738 SemaRef.Diag(Loc: Best->Function->getLocation(),
14739 DiagID: diag::note_not_found_by_two_phase_lookup)
14740 << R.getLookupName() << 2;
14741 }
14742
14743 // Try to recover by calling this function.
14744 return true;
14745 }
14746
14747 R.clear();
14748 }
14749
14750 return false;
14751}
14752
14753/// Attempt to recover from ill-formed use of a non-dependent operator in a
14754/// template, where the non-dependent operator was declared after the template
14755/// was defined.
14756///
14757/// Returns true if a viable candidate was found and a diagnostic was issued.
14758static bool DiagnoseTwoPhaseOperatorLookup(
14759 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14760 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14761 DeclarationName OpName =
14762 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14763 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14764 return DiagnoseTwoPhaseLookup(
14765 SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R, CSK: OverloadCandidateSet::CSK_Operator,
14766 ResolvedCandidates: ResolvedCandidateSet,
14767 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14768}
14769
14770namespace {
14771class BuildRecoveryCallExprRAII {
14772 Sema &SemaRef;
14773 Sema::SatisfactionStackResetRAII SatStack;
14774
14775public:
14776 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14777 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14778 SemaRef.IsBuildingRecoveryCallExpr = true;
14779 }
14780
14781 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14782};
14783}
14784
14785/// Attempts to recover from a call where no functions were found.
14786///
14787/// This function will do one of three things:
14788/// * Diagnose, recover, and return a recovery expression.
14789/// * Diagnose, fail to recover, and return ExprError().
14790/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14791/// expected to diagnose as appropriate.
14792static ExprResult
14793BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14794 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14795 MutableArrayRef<Expr *> Args, SourceLocation RParenLoc,
14796 const OverloadCandidateSet &ResolvedCandidateSet,
14797 bool AllowTypoCorrection) {
14798 // Do not try to recover if it is already building a recovery call.
14799 // This stops infinite loops for template instantiations like
14800 //
14801 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14802 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14803 if (SemaRef.IsBuildingRecoveryCallExpr)
14804 return ExprResult();
14805 BuildRecoveryCallExprRAII RCE(SemaRef);
14806
14807 CXXScopeSpec SS;
14808 SS.Adopt(Other: ULE->getQualifierLoc());
14809 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14810
14811 TemplateArgumentListInfo TABuffer;
14812 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14813 if (ULE->hasExplicitTemplateArgs()) {
14814 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14815 ExplicitTemplateArgs = &TABuffer;
14816 }
14817
14818 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14819 Sema::LookupOrdinaryName);
14820 CXXRecordDecl *FoundInClass = nullptr;
14821 if (DiagnoseTwoPhaseLookup(
14822 SemaRef, FnLoc: Fn->getExprLoc(), SS, R, CSK: OverloadCandidateSet::CSK_Normal,
14823 ResolvedCandidates: ResolvedCandidateSet, ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14824 // OK, diagnosed a two-phase lookup issue.
14825 } else if (ResolvedCandidateSet.empty()) {
14826 // Try to recover from an empty lookup with typo correction.
14827 R.clear();
14828 NoTypoCorrectionCCC NoTypoValidator{};
14829 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14830 ExplicitTemplateArgs != nullptr,
14831 dyn_cast<MemberExpr>(Val: Fn));
14832 CorrectionCandidateCallback &Validator =
14833 AllowTypoCorrection
14834 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14835 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14836 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14837 Args))
14838 return ExprError();
14839 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14840 // We found a usable declaration of the name in a dependent base of some
14841 // enclosing class.
14842 // FIXME: We should also explain why the candidates found by name lookup
14843 // were not viable.
14844 if (SemaRef.DiagnoseDependentMemberLookup(R))
14845 return ExprError();
14846 } else {
14847 // We had viable candidates and couldn't recover; let the caller diagnose
14848 // this.
14849 return ExprResult();
14850 }
14851
14852 // If we get here, we should have issued a diagnostic and formed a recovery
14853 // lookup result.
14854 assert(!R.empty() && "lookup results empty despite recovery");
14855
14856 // If recovery created an ambiguity, just bail out.
14857 if (R.isAmbiguous()) {
14858 R.suppressDiagnostics();
14859 return ExprError();
14860 }
14861
14862 // Build an implicit member call if appropriate. Just drop the
14863 // casts and such from the call, we don't really care.
14864 ExprResult NewFn = ExprError();
14865 if ((*R.begin())->isCXXClassMember())
14866 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14867 TemplateArgs: ExplicitTemplateArgs, S);
14868 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14869 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14870 TemplateArgs: ExplicitTemplateArgs);
14871 else
14872 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14873
14874 if (NewFn.isInvalid())
14875 return ExprError();
14876
14877 // This shouldn't cause an infinite loop because we're giving it
14878 // an expression with viable lookup results, which should never
14879 // end up here.
14880 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14881 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14882 RParenLoc);
14883}
14884
14885bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14886 UnresolvedLookupExpr *ULE,
14887 MultiExprArg Args,
14888 SourceLocation RParenLoc,
14889 OverloadCandidateSet *CandidateSet,
14890 ExprResult *Result) {
14891#ifndef NDEBUG
14892 if (ULE->requiresADL()) {
14893 // To do ADL, we must have found an unqualified name.
14894 assert(!ULE->getQualifier() && "qualified name with ADL");
14895
14896 // We don't perform ADL for implicit declarations of builtins.
14897 // Verify that this was correctly set up.
14898 FunctionDecl *F;
14899 if (ULE->decls_begin() != ULE->decls_end() &&
14900 ULE->decls_begin() + 1 == ULE->decls_end() &&
14901 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14902 F->getBuiltinID() && F->isImplicit())
14903 llvm_unreachable("performing ADL for builtin");
14904
14905 // We don't perform ADL in C.
14906 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14907 }
14908#endif
14909
14910 UnbridgedCastsSet UnbridgedCasts;
14911 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14912 *Result = ExprError();
14913 return true;
14914 }
14915
14916 // Add the functions denoted by the callee to the set of candidate
14917 // functions, including those from argument-dependent lookup.
14918 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14919
14920 if (getLangOpts().MSVCCompat &&
14921 CurContext->isDependentContext() && !isSFINAEContext() &&
14922 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14923
14924 OverloadCandidateSet::iterator Best;
14925 if (CandidateSet->empty() ||
14926 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14927 OR_No_Viable_Function) {
14928 // In Microsoft mode, if we are inside a template class member function
14929 // then create a type dependent CallExpr. The goal is to postpone name
14930 // lookup to instantiation time to be able to search into type dependent
14931 // base classes.
14932 CallExpr *CE =
14933 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14934 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14935 CE->markDependentForPostponedNameLookup();
14936 *Result = CE;
14937 return true;
14938 }
14939 }
14940
14941 if (CandidateSet->empty())
14942 return false;
14943
14944 UnbridgedCasts.restore();
14945 return false;
14946}
14947
14948// Guess at what the return type for an unresolvable overload should be.
14949static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14950 OverloadCandidateSet::iterator *Best) {
14951 std::optional<QualType> Result;
14952 // Adjust Type after seeing a candidate.
14953 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14954 if (!Candidate.Function)
14955 return;
14956 if (Candidate.Function->isInvalidDecl())
14957 return;
14958 QualType T = Candidate.Function->getReturnType();
14959 if (T.isNull())
14960 return;
14961 if (!Result)
14962 Result = T;
14963 else if (Result != T)
14964 Result = QualType();
14965 };
14966
14967 // Look for an unambiguous type from a progressively larger subset.
14968 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14969 //
14970 // First, consider only the best candidate.
14971 if (Best && *Best != CS.end())
14972 ConsiderCandidate(**Best);
14973 // Next, consider only viable candidates.
14974 if (!Result)
14975 for (const auto &C : CS)
14976 if (C.Viable)
14977 ConsiderCandidate(C);
14978 // Finally, consider all candidates.
14979 if (!Result)
14980 for (const auto &C : CS)
14981 ConsiderCandidate(C);
14982
14983 if (!Result)
14984 return QualType();
14985 auto Value = *Result;
14986 if (Value.isNull() || Value->isUndeducedType())
14987 return QualType();
14988 return Value;
14989}
14990
14991/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14992/// the completed call expression. If overload resolution fails, emits
14993/// diagnostics and returns ExprError()
14994static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14995 UnresolvedLookupExpr *ULE,
14996 SourceLocation LParenLoc,
14997 MultiExprArg Args,
14998 SourceLocation RParenLoc,
14999 Expr *ExecConfig,
15000 OverloadCandidateSet *CandidateSet,
15001 OverloadCandidateSet::iterator *Best,
15002 OverloadingResult OverloadResult,
15003 bool AllowTypoCorrection) {
15004 switch (OverloadResult) {
15005 case OR_Success: {
15006 FunctionDecl *FDecl = (*Best)->Function;
15007 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
15008 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
15009 return ExprError();
15010 ExprResult Res =
15011 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15012 if (Res.isInvalid())
15013 return ExprError();
15014 return SemaRef.BuildResolvedCallExpr(
15015 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15016 /*IsExecConfig=*/false,
15017 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15018 }
15019
15020 case OR_No_Viable_Function: {
15021 if (*Best != CandidateSet->end() &&
15022 CandidateSet->getKind() ==
15023 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
15024 if (CXXMethodDecl *M =
15025 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
15026 M && M->isImplicitObjectMemberFunction()) {
15027 CandidateSet->NoteCandidates(
15028 PD: PartialDiagnosticAt(
15029 Fn->getBeginLoc(),
15030 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
15031 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15032 return ExprError();
15033 }
15034 }
15035
15036 // Try to recover by looking for viable functions which the user might
15037 // have meant to call.
15038 ExprResult Recovery =
15039 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15040 ResolvedCandidateSet: *CandidateSet, AllowTypoCorrection);
15041 if (Recovery.isInvalid() || Recovery.isUsable())
15042 return Recovery;
15043
15044 // If the user passes in a function that we can't take the address of, we
15045 // generally end up emitting really bad error messages. Here, we attempt to
15046 // emit better ones.
15047 for (const Expr *Arg : Args) {
15048 if (!Arg->getType()->isFunctionType())
15049 continue;
15050 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
15051 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
15052 if (FD &&
15053 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15054 Loc: Arg->getExprLoc()))
15055 return ExprError();
15056 }
15057 }
15058
15059 CandidateSet->NoteCandidates(
15060 PD: PartialDiagnosticAt(
15061 Fn->getBeginLoc(),
15062 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
15063 << ULE->getName() << Fn->getSourceRange()),
15064 S&: SemaRef, OCD: OCD_AllCandidates, Args);
15065 break;
15066 }
15067
15068 case OR_Ambiguous:
15069 CandidateSet->NoteCandidates(
15070 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
15071 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
15072 << ULE->getName() << Fn->getSourceRange()),
15073 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15074 break;
15075
15076 case OR_Deleted: {
15077 FunctionDecl *FDecl = (*Best)->Function;
15078 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
15079 Range: Fn->getSourceRange(), Name: ULE->getName(),
15080 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
15081
15082 // We emitted an error for the unavailable/deleted function call but keep
15083 // the call in the AST.
15084 ExprResult Res =
15085 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15086 if (Res.isInvalid())
15087 return ExprError();
15088 return SemaRef.BuildResolvedCallExpr(
15089 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15090 /*IsExecConfig=*/false,
15091 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15092 }
15093 }
15094
15095 // Overload resolution failed, try to recover.
15096 SmallVector<Expr *, 8> SubExprs = {Fn};
15097 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
15098 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
15099 T: chooseRecoveryType(CS&: *CandidateSet, Best));
15100}
15101
15102static void markUnaddressableCandidatesUnviable(Sema &S,
15103 OverloadCandidateSet &CS) {
15104 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15105 if (I->Viable &&
15106 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
15107 I->Viable = false;
15108 I->FailureKind = ovl_fail_addr_not_available;
15109 }
15110 }
15111}
15112
15113ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
15114 UnresolvedLookupExpr *ULE,
15115 SourceLocation LParenLoc,
15116 MultiExprArg Args,
15117 SourceLocation RParenLoc,
15118 Expr *ExecConfig,
15119 bool AllowTypoCorrection,
15120 bool CalleesAddressIsTaken) {
15121
15122 OverloadCandidateSet::CandidateSetKind CSK =
15123 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15124 : OverloadCandidateSet::CSK_Normal;
15125
15126 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15127 ExprResult result;
15128
15129 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15130 Result: &result))
15131 return result;
15132
15133 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15134 // functions that aren't addressible are considered unviable.
15135 if (CalleesAddressIsTaken)
15136 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15137
15138 OverloadCandidateSet::iterator Best;
15139 OverloadingResult OverloadResult =
15140 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15141
15142 // [C++23][over.call.func]
15143 // if overload resolution selects a non-static member function,
15144 // the call is ill-formed;
15145 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15146 Best != CandidateSet.end()) {
15147 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15148 M && M->isImplicitObjectMemberFunction()) {
15149 OverloadResult = OR_No_Viable_Function;
15150 }
15151 }
15152
15153 // Model the case with a call to a templated function whose definition
15154 // encloses the call and whose return type contains a placeholder type as if
15155 // the UnresolvedLookupExpr was type-dependent.
15156 if (OverloadResult == OR_Success) {
15157 const FunctionDecl *FDecl = Best->Function;
15158 if (LangOpts.CUDA)
15159 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15160 if (FDecl && FDecl->isTemplateInstantiation() &&
15161 FDecl->getReturnType()->isUndeducedType()) {
15162
15163 // Creating dependent CallExpr is not okay if the enclosing context itself
15164 // is not dependent. This situation notably arises if a non-dependent
15165 // member function calls the later-defined overloaded static function.
15166 //
15167 // For example, in
15168 // class A {
15169 // void c() { callee(1); }
15170 // static auto callee(auto x) { }
15171 // };
15172 //
15173 // Here callee(1) is unresolved at the call site, but is not inside a
15174 // dependent context. There will be no further attempt to resolve this
15175 // call if it is made dependent.
15176
15177 if (const auto *TP =
15178 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15179 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15180 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15181 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15182 }
15183 }
15184 }
15185
15186 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15187 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15188 OverloadResult, AllowTypoCorrection);
15189}
15190
15191ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15192 NestedNameSpecifierLoc NNSLoc,
15193 DeclarationNameInfo DNI,
15194 const UnresolvedSetImpl &Fns,
15195 bool PerformADL) {
15196 return UnresolvedLookupExpr::Create(
15197 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15198 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15199}
15200
15201ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15202 CXXConversionDecl *Method,
15203 bool HadMultipleCandidates) {
15204 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15205 // the FoundDecl as it impedes TransformMemberExpr.
15206 // We go a bit further here: if there's no difference in UnderlyingDecl,
15207 // then using FoundDecl vs Method shouldn't make a difference either.
15208 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15209 FoundDecl = Method;
15210 // Convert the expression to match the conversion function's implicit object
15211 // parameter.
15212 ExprResult Exp;
15213 if (Method->isExplicitObjectMemberFunction())
15214 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15215 else
15216 Exp = PerformImplicitObjectArgumentInitialization(
15217 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15218 if (Exp.isInvalid())
15219 return true;
15220
15221 if (Method->getParent()->isLambda() &&
15222 Method->getConversionType()->isBlockPointerType()) {
15223 // This is a lambda conversion to block pointer; check if the argument
15224 // was a LambdaExpr.
15225 Expr *SubE = E;
15226 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15227 if (CE && CE->getCastKind() == CK_NoOp)
15228 SubE = CE->getSubExpr();
15229 SubE = SubE->IgnoreParens();
15230 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15231 SubE = BE->getSubExpr();
15232 if (isa<LambdaExpr>(Val: SubE)) {
15233 // For the conversion to block pointer on a lambda expression, we
15234 // construct a special BlockLiteral instead; this doesn't really make
15235 // a difference in ARC, but outside of ARC the resulting block literal
15236 // follows the normal lifetime rules for block literals instead of being
15237 // autoreleased.
15238 PushExpressionEvaluationContext(
15239 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15240 ExprResult BlockExp = BuildBlockForLambdaConversion(
15241 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15242 PopExpressionEvaluationContext();
15243
15244 // FIXME: This note should be produced by a CodeSynthesisContext.
15245 if (BlockExp.isInvalid())
15246 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15247 return BlockExp;
15248 }
15249 }
15250 CallExpr *CE;
15251 QualType ResultType = Method->getReturnType();
15252 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15253 ResultType = ResultType.getNonLValueExprType(Context);
15254 if (Method->isExplicitObjectMemberFunction()) {
15255 ExprResult FnExpr =
15256 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15257 HadMultipleCandidates, Loc: E->getBeginLoc());
15258 if (FnExpr.isInvalid())
15259 return ExprError();
15260 Expr *ObjectParam = Exp.get();
15261 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15262 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15263 FPFeatures: CurFPFeatureOverrides());
15264 CE->setUsesMemberSyntax(true);
15265 } else {
15266 MemberExpr *ME =
15267 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15268 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15269 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15270 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15271 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15272
15273 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15274 RP: Exp.get()->getEndLoc(),
15275 FPFeatures: CurFPFeatureOverrides());
15276 }
15277
15278 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15279 Proto: Method->getType()->castAs<FunctionProtoType>()))
15280 return ExprError();
15281
15282 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15283}
15284
15285void Sema::LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
15286 OverloadedOperatorKind Op,
15287 const UnresolvedSetImpl &Fns,
15288 ArrayRef<Expr *> Args, bool PerformADL) {
15289 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15290
15291 SourceLocation OpLoc = CandidateSet.getLocation();
15292 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15293
15294 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15295 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15296 if (PerformADL)
15297 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15298 /*ExplicitTemplateArgs*/ nullptr,
15299 CandidateSet);
15300 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15301}
15302
15303ExprResult
15304Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15305 const UnresolvedSetImpl &Fns,
15306 Expr *Input, bool PerformADL) {
15307 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15308 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15309 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15310 // TODO: provide better source location info.
15311 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15312
15313 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15314 return ExprError();
15315
15316 Expr *Args[2] = { Input, nullptr };
15317 unsigned NumArgs = 1;
15318
15319 // For post-increment and post-decrement, add the implicit '0' as
15320 // the second argument, so that we know this is a post-increment or
15321 // post-decrement.
15322 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15323 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15324 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15325 l: SourceLocation());
15326 NumArgs = 2;
15327 }
15328
15329 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15330
15331 if (Input->isTypeDependent()) {
15332 ExprValueKind VK = ExprValueKind::VK_PRValue;
15333 // [C++26][expr.unary.op][expr.pre.incr]
15334 // The * operator yields an lvalue of type
15335 // The pre/post increment operators yied an lvalue.
15336 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15337 VK = VK_LValue;
15338
15339 if (Fns.empty())
15340 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15341 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15342 FPFeatures: CurFPFeatureOverrides());
15343
15344 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15345 ExprResult Fn = CreateUnresolvedLookupExpr(
15346 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15347 if (Fn.isInvalid())
15348 return ExprError();
15349 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15350 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15351 FPFeatures: CurFPFeatureOverrides());
15352 }
15353
15354 // Build an empty overload set.
15355 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15356 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, Args: ArgsArray, PerformADL);
15357
15358 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15359
15360 // Perform overload resolution.
15361 OverloadCandidateSet::iterator Best;
15362 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15363 case OR_Success: {
15364 // We found a built-in operator or an overloaded operator.
15365 FunctionDecl *FnDecl = Best->Function;
15366
15367 if (FnDecl) {
15368 Expr *Base = nullptr;
15369 // We matched an overloaded operator. Build a call to that
15370 // operator.
15371
15372 // Convert the arguments.
15373 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15374 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15375
15376 ExprResult InputInit;
15377 if (Method->isExplicitObjectMemberFunction())
15378 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15379 else
15380 InputInit = PerformImplicitObjectArgumentInitialization(
15381 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15382 if (InputInit.isInvalid())
15383 return ExprError();
15384 Base = Input = InputInit.get();
15385 } else {
15386 // Convert the arguments.
15387 ExprResult InputInit
15388 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15389 Context,
15390 Parm: FnDecl->getParamDecl(i: 0)),
15391 EqualLoc: SourceLocation(),
15392 Init: Input);
15393 if (InputInit.isInvalid())
15394 return ExprError();
15395 Input = InputInit.get();
15396 }
15397
15398 // Build the actual expression node.
15399 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15400 Base, HadMultipleCandidates,
15401 Loc: OpLoc);
15402 if (FnExpr.isInvalid())
15403 return ExprError();
15404
15405 // Determine the result type.
15406 QualType ResultTy = FnDecl->getReturnType();
15407 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15408 ResultTy = ResultTy.getNonLValueExprType(Context);
15409
15410 Args[0] = Input;
15411 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15412 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15413 FPFeatures: CurFPFeatureOverrides(),
15414 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15415
15416 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15417 return ExprError();
15418
15419 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15420 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15421 return ExprError();
15422 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15423 } else {
15424 // We matched a built-in operator. Convert the arguments, then
15425 // break out so that we will build the appropriate built-in
15426 // operator node.
15427 ExprResult InputRes = PerformImplicitConversion(
15428 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15429 Action: AssignmentAction::Passing,
15430 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15431 if (InputRes.isInvalid())
15432 return ExprError();
15433 Input = InputRes.get();
15434 break;
15435 }
15436 }
15437
15438 case OR_No_Viable_Function:
15439 // This is an erroneous use of an operator which can be overloaded by
15440 // a non-member function. Check for non-member operators which were
15441 // defined too late to be candidates.
15442 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray,
15443 ResolvedCandidateSet: CandidateSet))
15444 // FIXME: Recover by calling the found function.
15445 return ExprError();
15446
15447 // No viable function; fall through to handling this as a
15448 // built-in operator, which will produce an error message for us.
15449 break;
15450
15451 case OR_Ambiguous:
15452 CandidateSet.NoteCandidates(
15453 PD: PartialDiagnosticAt(OpLoc,
15454 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15455 << UnaryOperator::getOpcodeStr(Op: Opc)
15456 << Input->getType() << Input->getSourceRange()),
15457 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15458 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15459 return ExprError();
15460
15461 case OR_Deleted: {
15462 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15463 // object whose method was called. Later in NoteCandidates size of ArgsArray
15464 // is passed further and it eventually ends up compared to number of
15465 // function candidate parameters which never includes the object parameter,
15466 // so slice ArgsArray to make sure apples are compared to apples.
15467 StringLiteral *Msg = Best->Function->getDeletedMessage();
15468 CandidateSet.NoteCandidates(
15469 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15470 << UnaryOperator::getOpcodeStr(Op: Opc)
15471 << (Msg != nullptr)
15472 << (Msg ? Msg->getString() : StringRef())
15473 << Input->getSourceRange()),
15474 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15475 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15476 return ExprError();
15477 }
15478 }
15479
15480 // Either we found no viable overloaded operator or we matched a
15481 // built-in operator. In either case, fall through to trying to
15482 // build a built-in operation.
15483 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15484}
15485
15486void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15487 OverloadedOperatorKind Op,
15488 const UnresolvedSetImpl &Fns,
15489 ArrayRef<Expr *> Args, bool PerformADL) {
15490 SourceLocation OpLoc = CandidateSet.getLocation();
15491
15492 OverloadedOperatorKind ExtraOp =
15493 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15494 ? getRewrittenOverloadedOperator(Kind: Op)
15495 : OO_None;
15496
15497 // Add the candidates from the given function set. This also adds the
15498 // rewritten candidates using these functions if necessary.
15499 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15500
15501 // As template candidates are not deduced immediately,
15502 // persist the array in the overload set.
15503 ArrayRef<Expr *> ReversedArgs;
15504 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15505 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15506 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15507
15508 // Add operator candidates that are member functions.
15509 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15510 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15511 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15512 PO: OverloadCandidateParamOrder::Reversed);
15513
15514 // In C++20, also add any rewritten member candidates.
15515 if (ExtraOp) {
15516 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15517 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15518 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15519 PO: OverloadCandidateParamOrder::Reversed);
15520 }
15521
15522 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15523 // performed for an assignment operator (nor for operator[] nor operator->,
15524 // which don't get here).
15525 if (Op != OO_Equal && PerformADL) {
15526 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15527 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15528 /*ExplicitTemplateArgs*/ nullptr,
15529 CandidateSet);
15530 if (ExtraOp) {
15531 DeclarationName ExtraOpName =
15532 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15533 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15534 /*ExplicitTemplateArgs*/ nullptr,
15535 CandidateSet);
15536 }
15537 }
15538
15539 // Add builtin operator candidates.
15540 //
15541 // FIXME: We don't add any rewritten candidates here. This is strictly
15542 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15543 // resulting in our selecting a rewritten builtin candidate. For example:
15544 //
15545 // enum class E { e };
15546 // bool operator!=(E, E) requires false;
15547 // bool k = E::e != E::e;
15548 //
15549 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15550 // it seems unreasonable to consider rewritten builtin candidates. A core
15551 // issue has been filed proposing to removed this requirement.
15552 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15553}
15554
15555ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15556 BinaryOperatorKind Opc,
15557 const UnresolvedSetImpl &Fns, Expr *LHS,
15558 Expr *RHS, bool PerformADL,
15559 bool AllowRewrittenCandidates,
15560 FunctionDecl *DefaultedFn) {
15561 Expr *Args[2] = { LHS, RHS };
15562 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15563
15564 if (!getLangOpts().CPlusPlus20)
15565 AllowRewrittenCandidates = false;
15566
15567 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15568
15569 // If either side is type-dependent, create an appropriate dependent
15570 // expression.
15571 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15572 if (Fns.empty()) {
15573 // If there are no functions to store, just build a dependent
15574 // BinaryOperator or CompoundAssignment.
15575 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15576 return CompoundAssignOperator::Create(
15577 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15578 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15579 CompResultType: Context.DependentTy);
15580 return BinaryOperator::Create(
15581 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15582 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15583 }
15584
15585 // FIXME: save results of ADL from here?
15586 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15587 // TODO: provide better source location info in DNLoc component.
15588 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15589 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15590 ExprResult Fn = CreateUnresolvedLookupExpr(
15591 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15592 if (Fn.isInvalid())
15593 return ExprError();
15594 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15595 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15596 FPFeatures: CurFPFeatureOverrides());
15597 }
15598
15599 // If this is the .* operator, which is not overloadable, just
15600 // create a built-in binary operator.
15601 if (Opc == BO_PtrMemD) {
15602 auto CheckPlaceholder = [&](Expr *&Arg) {
15603 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15604 if (Res.isUsable())
15605 Arg = Res.get();
15606 return !Res.isUsable();
15607 };
15608
15609 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15610 // expression that contains placeholders (in either the LHS or RHS).
15611 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15612 return ExprError();
15613 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15614 }
15615
15616 // Always do placeholder-like conversions on the RHS.
15617 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15618 return ExprError();
15619
15620 // Do placeholder-like conversion on the LHS; note that we should
15621 // not get here with a PseudoObject LHS.
15622 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15623 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15624 return ExprError();
15625
15626 // If this is the assignment operator, we only perform overload resolution
15627 // if the left-hand side is a class or enumeration type. This is actually
15628 // a hack. The standard requires that we do overload resolution between the
15629 // various built-in candidates, but as DR507 points out, this can lead to
15630 // problems. So we do it this way, which pretty much follows what GCC does.
15631 // Note that we go the traditional code path for compound assignment forms.
15632 // In HLSL, user-defined structs/classes do not have constructors or
15633 // overloadable assignment operators, so we can take this shortcut too.
15634 const Type *LHSTy = Args[0]->getType().getTypePtr();
15635 if (Opc == BO_Assign &&
15636 (!LHSTy->isOverloadableType() ||
15637 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15638 !LHSTy->getAsCXXRecordDecl()->isHLSLBuiltinRecord())))
15639 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15640
15641 // Build the overload set.
15642 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15643 OverloadCandidateSet::OperatorRewriteInfo(
15644 Op, OpLoc, AllowRewrittenCandidates));
15645 if (DefaultedFn)
15646 CandidateSet.exclude(F: DefaultedFn);
15647 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15648
15649 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15650
15651 // Perform overload resolution.
15652 OverloadCandidateSet::iterator Best;
15653 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15654 case OR_Success: {
15655 // We found a built-in operator or an overloaded operator.
15656 FunctionDecl *FnDecl = Best->Function;
15657
15658 bool IsReversed = Best->isReversed();
15659 if (IsReversed)
15660 std::swap(a&: Args[0], b&: Args[1]);
15661
15662 if (FnDecl) {
15663
15664 if (FnDecl->isInvalidDecl())
15665 return ExprError();
15666
15667 Expr *Base = nullptr;
15668 // We matched an overloaded operator. Build a call to that
15669 // operator.
15670
15671 OverloadedOperatorKind ChosenOp =
15672 FnDecl->getDeclName().getCXXOverloadedOperator();
15673
15674 // C++2a [over.match.oper]p9:
15675 // If a rewritten operator== candidate is selected by overload
15676 // resolution for an operator@, its return type shall be cv bool
15677 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15678 !FnDecl->getReturnType()->isBooleanType()) {
15679 bool IsExtension =
15680 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15681 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15682 : diag::err_ovl_rewrite_equalequal_not_bool)
15683 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15684 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15685 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15686 if (!IsExtension)
15687 return ExprError();
15688 }
15689
15690 if (AllowRewrittenCandidates && !IsReversed &&
15691 CandidateSet.getRewriteInfo().isReversible()) {
15692 // We could have reversed this operator, but didn't. Check if some
15693 // reversed form was a viable candidate, and if so, if it had a
15694 // better conversion for either parameter. If so, this call is
15695 // formally ambiguous, and allowing it is an extension.
15696 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15697 for (OverloadCandidate &Cand : CandidateSet) {
15698 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15699 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15700 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15701 if (CompareImplicitConversionSequences(
15702 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15703 ICS2: Best->Conversions[ArgIdx]) ==
15704 ImplicitConversionSequence::Better) {
15705 AmbiguousWith.push_back(Elt: Cand.Function);
15706 break;
15707 }
15708 }
15709 }
15710 }
15711
15712 if (!AmbiguousWith.empty()) {
15713 bool AmbiguousWithSelf =
15714 AmbiguousWith.size() == 1 &&
15715 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15716 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15717 << BinaryOperator::getOpcodeStr(Op: Opc)
15718 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15719 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15720 if (AmbiguousWithSelf) {
15721 Diag(Loc: FnDecl->getLocation(),
15722 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15723 // Mark member== const or provide matching != to disallow reversed
15724 // args. Eg.
15725 // struct S { bool operator==(const S&); };
15726 // S()==S();
15727 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15728 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15729 !MD->isConst() &&
15730 !MD->hasCXXExplicitFunctionObjectParameter() &&
15731 Context.hasSameUnqualifiedType(
15732 T1: MD->getFunctionObjectParameterType(),
15733 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15734 Context.hasSameUnqualifiedType(
15735 T1: MD->getFunctionObjectParameterType(),
15736 T2: Args[0]->getType()) &&
15737 Context.hasSameUnqualifiedType(
15738 T1: MD->getFunctionObjectParameterType(),
15739 T2: Args[1]->getType()))
15740 Diag(Loc: FnDecl->getLocation(),
15741 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15742 } else {
15743 Diag(Loc: FnDecl->getLocation(),
15744 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15745 for (auto *F : AmbiguousWith)
15746 Diag(Loc: F->getLocation(),
15747 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15748 }
15749 }
15750 }
15751
15752 // Check for nonnull = nullable.
15753 // This won't be caught in the arg's initialization: the parameter to
15754 // the assignment operator is not marked nonnull.
15755 if (Op == OO_Equal)
15756 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15757 SrcType: Args[1]->getType(), Loc: OpLoc);
15758
15759 // Convert the arguments.
15760 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15761 // Best->Access is only meaningful for class members.
15762 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15763
15764 ExprResult Arg0, Arg1;
15765 unsigned ParamIdx = 0;
15766 if (Method->isExplicitObjectMemberFunction()) {
15767 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15768 ParamIdx = 1;
15769 } else {
15770 Arg0 = PerformImplicitObjectArgumentInitialization(
15771 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15772 }
15773 Arg1 = PerformCopyInitialization(
15774 Entity: InitializedEntity::InitializeParameter(
15775 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15776 EqualLoc: SourceLocation(), Init: Args[1]);
15777 if (Arg0.isInvalid() || Arg1.isInvalid())
15778 return ExprError();
15779
15780 Base = Args[0] = Arg0.getAs<Expr>();
15781 Args[1] = RHS = Arg1.getAs<Expr>();
15782 } else {
15783 // Convert the arguments.
15784 ExprResult Arg0 = PerformCopyInitialization(
15785 Entity: InitializedEntity::InitializeParameter(Context,
15786 Parm: FnDecl->getParamDecl(i: 0)),
15787 EqualLoc: SourceLocation(), Init: Args[0]);
15788 if (Arg0.isInvalid())
15789 return ExprError();
15790
15791 ExprResult Arg1 =
15792 PerformCopyInitialization(
15793 Entity: InitializedEntity::InitializeParameter(Context,
15794 Parm: FnDecl->getParamDecl(i: 1)),
15795 EqualLoc: SourceLocation(), Init: Args[1]);
15796 if (Arg1.isInvalid())
15797 return ExprError();
15798 Args[0] = LHS = Arg0.getAs<Expr>();
15799 Args[1] = RHS = Arg1.getAs<Expr>();
15800 }
15801
15802 // Build the actual expression node.
15803 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15804 FoundDecl: Best->FoundDecl, Base,
15805 HadMultipleCandidates, Loc: OpLoc);
15806 if (FnExpr.isInvalid())
15807 return ExprError();
15808
15809 // Determine the result type.
15810 QualType ResultTy = FnDecl->getReturnType();
15811 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15812 ResultTy = ResultTy.getNonLValueExprType(Context);
15813
15814 CallExpr *TheCall;
15815 ArrayRef<const Expr *> ArgsArray(Args, 2);
15816 const Expr *ImplicitThis = nullptr;
15817
15818 // We always create a CXXOperatorCallExpr, even for explicit object
15819 // members; CodeGen should take care not to emit the this pointer.
15820 TheCall = CXXOperatorCallExpr::Create(
15821 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15822 FPFeatures: CurFPFeatureOverrides(),
15823 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15824 IsReversed);
15825
15826 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15827 Method && Method->isImplicitObjectMemberFunction()) {
15828 // Cut off the implicit 'this'.
15829 ImplicitThis = ArgsArray[0];
15830 ArgsArray = ArgsArray.slice(N: 1);
15831 }
15832
15833 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15834 FD: FnDecl))
15835 return ExprError();
15836
15837 if (Op == OO_Equal) {
15838 // Check for a self move.
15839 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15840 // lifetime check.
15841 checkAssignmentLifetime(
15842 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15843 Init: Args[1]);
15844 }
15845 if (ImplicitThis) {
15846 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15847 QualType ThisTypeFromDecl = Context.getPointerType(
15848 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15849
15850 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15851 ParamTy: ThisTypeFromDecl);
15852 }
15853
15854 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15855 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15856 CallType: VariadicCallType::DoesNotApply);
15857
15858 ExprResult R = MaybeBindToTemporary(E: TheCall);
15859 if (R.isInvalid())
15860 return ExprError();
15861
15862 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15863 if (R.isInvalid())
15864 return ExprError();
15865
15866 // For a rewritten candidate, we've already reversed the arguments
15867 // if needed. Perform the rest of the rewrite now.
15868 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15869 (Op == OO_Spaceship && IsReversed)) {
15870 if (Op == OO_ExclaimEqual) {
15871 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15872 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15873 } else {
15874 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15875 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15876 Expr *ZeroLiteral =
15877 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15878
15879 Sema::CodeSynthesisContext Ctx;
15880 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15881 Ctx.Entity = FnDecl;
15882 pushCodeSynthesisContext(Ctx);
15883
15884 R = CreateOverloadedBinOp(
15885 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15886 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15887 /*AllowRewrittenCandidates=*/false);
15888
15889 popCodeSynthesisContext();
15890 }
15891 if (R.isInvalid())
15892 return ExprError();
15893 } else {
15894 assert(ChosenOp == Op && "unexpected operator name");
15895 }
15896
15897 // Make a note in the AST if we did any rewriting.
15898 if (Best->RewriteKind != CRK_None)
15899 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15900
15901 return R;
15902 } else {
15903 // We matched a built-in operator. Convert the arguments, then
15904 // break out so that we will build the appropriate built-in
15905 // operator node.
15906 ExprResult ArgsRes0 = PerformImplicitConversion(
15907 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15908 Action: AssignmentAction::Passing,
15909 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15910 if (ArgsRes0.isInvalid())
15911 return ExprError();
15912 Args[0] = ArgsRes0.get();
15913
15914 ExprResult ArgsRes1 = PerformImplicitConversion(
15915 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15916 Action: AssignmentAction::Passing,
15917 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15918 if (ArgsRes1.isInvalid())
15919 return ExprError();
15920 Args[1] = ArgsRes1.get();
15921 break;
15922 }
15923 }
15924
15925 case OR_No_Viable_Function: {
15926 // C++ [over.match.oper]p9:
15927 // If the operator is the operator , [...] and there are no
15928 // viable functions, then the operator is assumed to be the
15929 // built-in operator and interpreted according to clause 5.
15930 if (Opc == BO_Comma)
15931 break;
15932
15933 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15934 // compare result using '==' and '<'.
15935 if (DefaultedFn && Opc == BO_Cmp) {
15936 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15937 RHS: Args[1], DefaultedFn);
15938 if (E.isInvalid() || E.isUsable())
15939 return E;
15940 }
15941
15942 // For class as left operand for assignment or compound assignment
15943 // operator do not fall through to handling in built-in, but report that
15944 // no overloaded assignment operator found
15945 ExprResult Result = ExprError();
15946 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15947 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15948 Args, OpLoc);
15949 DeferDiagsRAII DDR(*this,
15950 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15951 if (Args[0]->getType()->isRecordType() &&
15952 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15953 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15954 << BinaryOperator::getOpcodeStr(Op: Opc)
15955 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15956 if (Args[0]->getType()->isIncompleteType()) {
15957 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15958 << Args[0]->getType()
15959 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15960 }
15961 } else {
15962 // This is an erroneous use of an operator which can be overloaded by
15963 // a non-member function. Check for non-member operators which were
15964 // defined too late to be candidates.
15965 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args,
15966 ResolvedCandidateSet: CandidateSet))
15967 // FIXME: Recover by calling the found function.
15968 return ExprError();
15969
15970 // No viable function; try to create a built-in operation, which will
15971 // produce an error. Then, show the non-viable candidates.
15972 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15973 }
15974 assert(Result.isInvalid() &&
15975 "C++ binary operator overloading is missing candidates!");
15976 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15977 return Result;
15978 }
15979
15980 case OR_Ambiguous:
15981 CandidateSet.NoteCandidates(
15982 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15983 << BinaryOperator::getOpcodeStr(Op: Opc)
15984 << Args[0]->getType()
15985 << Args[1]->getType()
15986 << Args[0]->getSourceRange()
15987 << Args[1]->getSourceRange()),
15988 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15989 OpLoc);
15990 return ExprError();
15991
15992 case OR_Deleted: {
15993 if (isImplicitlyDeleted(FD: Best->Function)) {
15994 FunctionDecl *DeletedFD = Best->Function;
15995 FunctionDecl::DefaultedFunctionKind DFK =
15996 DeletedFD->getDefaultedFunctionKind();
15997 if (DFK.isSpecialMember()) {
15998 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15999 << Args[0]->getType() << DFK.asSpecialMember();
16000 } else {
16001 assert(DFK.isComparison());
16002 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
16003 << Args[0]->getType() << DeletedFD;
16004 }
16005
16006 // The user probably meant to call this special member. Just
16007 // explain why it's deleted.
16008 NoteDeletedFunction(FD: DeletedFD);
16009 return ExprError();
16010 }
16011
16012 StringLiteral *Msg = Best->Function->getDeletedMessage();
16013 CandidateSet.NoteCandidates(
16014 PD: PartialDiagnosticAt(
16015 OpLoc,
16016 PDiag(DiagID: diag::err_ovl_deleted_oper)
16017 << getOperatorSpelling(Operator: Best->Function->getDeclName()
16018 .getCXXOverloadedOperator())
16019 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16020 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16021 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
16022 OpLoc);
16023 return ExprError();
16024 }
16025 }
16026
16027 // We matched a built-in operator; build it.
16028 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
16029}
16030
16031ExprResult Sema::BuildSynthesizedThreeWayComparison(
16032 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16033 FunctionDecl *DefaultedFn) {
16034 const ComparisonCategoryInfo *Info =
16035 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
16036 // If we're not producing a known comparison category type, we can't
16037 // synthesize a three-way comparison. Let the caller diagnose this.
16038 if (!Info)
16039 return ExprResult((Expr*)nullptr);
16040
16041 // If we ever want to perform this synthesis more generally, we will need to
16042 // apply the temporary materialization conversion to the operands.
16043 assert(LHS->isGLValue() && RHS->isGLValue() &&
16044 "cannot use prvalue expressions more than once");
16045 Expr *OrigLHS = LHS;
16046 Expr *OrigRHS = RHS;
16047
16048 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16049 // each of them multiple times below.
16050 LHS = new (Context)
16051 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16052 LHS->getObjectKind(), LHS);
16053 RHS = new (Context)
16054 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16055 RHS->getObjectKind(), RHS);
16056
16057 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
16058 DefaultedFn);
16059 if (Eq.isInvalid())
16060 return ExprError();
16061
16062 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
16063 AllowRewrittenCandidates: true, DefaultedFn);
16064 if (Less.isInvalid())
16065 return ExprError();
16066
16067 ExprResult Greater;
16068 if (Info->isPartial()) {
16069 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
16070 DefaultedFn);
16071 if (Greater.isInvalid())
16072 return ExprError();
16073 }
16074
16075 // Form the list of comparisons we're going to perform.
16076 struct Comparison {
16077 ExprResult Cmp;
16078 ComparisonCategoryResult Result;
16079 } Comparisons[4] =
16080 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
16081 : ComparisonCategoryResult::Equivalent},
16082 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
16083 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
16084 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
16085 };
16086
16087 int I = Info->isPartial() ? 3 : 2;
16088
16089 // Combine the comparisons with suitable conditional expressions.
16090 ExprResult Result;
16091 for (; I >= 0; --I) {
16092 // Build a reference to the comparison category constant.
16093 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
16094 // FIXME: Missing a constant for a comparison category. Diagnose this?
16095 if (!VI)
16096 return ExprResult((Expr*)nullptr);
16097 ExprResult ThisResult =
16098 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
16099 if (ThisResult.isInvalid())
16100 return ExprError();
16101
16102 // Build a conditional unless this is the final case.
16103 if (Result.get()) {
16104 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
16105 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
16106 if (Result.isInvalid())
16107 return ExprError();
16108 } else {
16109 Result = ThisResult;
16110 }
16111 }
16112
16113 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16114 // bind the OpaqueValueExprs before they're (repeatedly) used.
16115 Expr *SyntacticForm = BinaryOperator::Create(
16116 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
16117 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
16118 FPFeatures: CurFPFeatureOverrides());
16119 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16120 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
16121}
16122
16123static bool PrepareArgumentsForCallToObjectOfClassType(
16124 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16125 MultiExprArg Args, SourceLocation LParenLoc) {
16126
16127 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16128 unsigned NumParams = Proto->getNumParams();
16129 unsigned NumArgsSlots =
16130 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16131 // Build the full argument list for the method call (the implicit object
16132 // parameter is placed at the beginning of the list).
16133 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16134 bool IsError = false;
16135 // Initialize the implicit object parameter.
16136 // Check the argument types.
16137 for (unsigned i = 0; i != NumParams; i++) {
16138 Expr *Arg;
16139 if (i < Args.size()) {
16140 Arg = Args[i];
16141 ExprResult InputInit =
16142 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16143 Context&: S.Context, Parm: Method->getParamDecl(i)),
16144 EqualLoc: SourceLocation(), Init: Arg);
16145 IsError |= InputInit.isInvalid();
16146 Arg = InputInit.getAs<Expr>();
16147 } else {
16148 ExprResult DefArg =
16149 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16150 if (DefArg.isInvalid()) {
16151 IsError = true;
16152 break;
16153 }
16154 Arg = DefArg.getAs<Expr>();
16155 }
16156
16157 MethodArgs.push_back(Elt: Arg);
16158 }
16159 return IsError;
16160}
16161
16162ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16163 SourceLocation RLoc,
16164 Expr *Base,
16165 MultiExprArg ArgExpr) {
16166 SmallVector<Expr *, 2> Args;
16167 Args.push_back(Elt: Base);
16168 for (auto *e : ArgExpr) {
16169 Args.push_back(Elt: e);
16170 }
16171 DeclarationName OpName =
16172 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16173
16174 SourceRange Range = ArgExpr.empty()
16175 ? SourceRange{}
16176 : SourceRange(ArgExpr.front()->getBeginLoc(),
16177 ArgExpr.back()->getEndLoc());
16178
16179 // If either side is type-dependent, create an appropriate dependent
16180 // expression.
16181 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16182
16183 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16184 // CHECKME: no 'operator' keyword?
16185 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16186 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16187 ExprResult Fn = CreateUnresolvedLookupExpr(
16188 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16189 if (Fn.isInvalid())
16190 return ExprError();
16191 // Can't add any actual overloads yet
16192
16193 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16194 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16195 FPFeatures: CurFPFeatureOverrides());
16196 }
16197
16198 // Handle placeholders
16199 UnbridgedCastsSet UnbridgedCasts;
16200 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16201 return ExprError();
16202 }
16203 // Build an empty overload set.
16204 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16205
16206 // Subscript can only be overloaded as a member function.
16207
16208 // Add operator candidates that are member functions.
16209 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16210
16211 // Add builtin operator candidates.
16212 if (Args.size() == 2)
16213 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16214
16215 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16216
16217 // Perform overload resolution.
16218 OverloadCandidateSet::iterator Best;
16219 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16220 case OR_Success: {
16221 // We found a built-in operator or an overloaded operator.
16222 FunctionDecl *FnDecl = Best->Function;
16223
16224 if (FnDecl) {
16225 // We matched an overloaded operator. Build a call to that
16226 // operator.
16227
16228 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16229
16230 // Convert the arguments.
16231 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16232 SmallVector<Expr *, 2> MethodArgs;
16233
16234 // Initialize the object parameter.
16235 if (Method->isExplicitObjectMemberFunction()) {
16236 ExprResult Res =
16237 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16238 if (Res.isInvalid())
16239 return ExprError();
16240 Args[0] = Res.get();
16241 ArgExpr = Args;
16242 } else {
16243 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16244 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16245 if (Arg0.isInvalid())
16246 return ExprError();
16247
16248 MethodArgs.push_back(Elt: Arg0.get());
16249 }
16250
16251 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16252 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16253 if (IsError)
16254 return ExprError();
16255
16256 // Build the actual expression node.
16257 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16258 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16259 ExprResult FnExpr =
16260 CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base,
16261 HadMultipleCandidates, NameInfo: OpLocInfo);
16262 if (FnExpr.isInvalid())
16263 return ExprError();
16264
16265 // Determine the result type
16266 QualType ResultTy = FnDecl->getReturnType();
16267 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16268 ResultTy = ResultTy.getNonLValueExprType(Context);
16269
16270 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16271 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16272 FPFeatures: CurFPFeatureOverrides());
16273
16274 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16275 return ExprError();
16276
16277 if (CheckFunctionCall(FDecl: Method, TheCall,
16278 Proto: Method->getType()->castAs<FunctionProtoType>()))
16279 return ExprError();
16280
16281 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16282 Decl: FnDecl);
16283 } else {
16284 // We matched a built-in operator. Convert the arguments, then
16285 // break out so that we will build the appropriate built-in
16286 // operator node.
16287 ExprResult ArgsRes0 = PerformImplicitConversion(
16288 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16289 Action: AssignmentAction::Passing,
16290 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16291 if (ArgsRes0.isInvalid())
16292 return ExprError();
16293 Args[0] = ArgsRes0.get();
16294
16295 ExprResult ArgsRes1 = PerformImplicitConversion(
16296 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16297 Action: AssignmentAction::Passing,
16298 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16299 if (ArgsRes1.isInvalid())
16300 return ExprError();
16301 Args[1] = ArgsRes1.get();
16302
16303 break;
16304 }
16305 }
16306
16307 case OR_No_Viable_Function: {
16308 PartialDiagnostic PD =
16309 CandidateSet.empty()
16310 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16311 << Args[0]->getType() << /*subscript*/ 0
16312 << Args[0]->getSourceRange() << Range)
16313 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16314 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16315 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16316 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16317 return ExprError();
16318 }
16319
16320 case OR_Ambiguous:
16321 if (Args.size() == 2) {
16322 CandidateSet.NoteCandidates(
16323 PD: PartialDiagnosticAt(
16324 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16325 << "[]" << Args[0]->getType() << Args[1]->getType()
16326 << Args[0]->getSourceRange() << Range),
16327 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16328 } else {
16329 CandidateSet.NoteCandidates(
16330 PD: PartialDiagnosticAt(LLoc,
16331 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16332 << Args[0]->getType()
16333 << Args[0]->getSourceRange() << Range),
16334 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16335 }
16336 return ExprError();
16337
16338 case OR_Deleted: {
16339 StringLiteral *Msg = Best->Function->getDeletedMessage();
16340 CandidateSet.NoteCandidates(
16341 PD: PartialDiagnosticAt(LLoc,
16342 PDiag(DiagID: diag::err_ovl_deleted_oper)
16343 << "[]" << (Msg != nullptr)
16344 << (Msg ? Msg->getString() : StringRef())
16345 << Args[0]->getSourceRange() << Range),
16346 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16347 return ExprError();
16348 }
16349 }
16350
16351 // We matched a built-in operator; build it.
16352 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16353}
16354
16355ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16356 SourceLocation LParenLoc,
16357 MultiExprArg Args,
16358 SourceLocation RParenLoc,
16359 Expr *ExecConfig, bool IsExecConfig,
16360 bool AllowRecovery) {
16361 assert(MemExprE->getType() == Context.BoundMemberTy ||
16362 MemExprE->getType() == Context.OverloadTy);
16363
16364 // Dig out the member expression. This holds both the object
16365 // argument and the member function we're referring to.
16366 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16367
16368 // Determine whether this is a call to a pointer-to-member function.
16369 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16370 assert(op->getType() == Context.BoundMemberTy);
16371 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16372
16373 QualType fnType =
16374 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16375
16376 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16377 QualType resultType = proto->getCallResultType(Context);
16378 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16379
16380 // Check that the object type isn't more qualified than the
16381 // member function we're calling.
16382 Qualifiers funcQuals = proto->getMethodQuals();
16383
16384 QualType objectType = op->getLHS()->getType();
16385 if (op->getOpcode() == BO_PtrMemI)
16386 objectType = objectType->castAs<PointerType>()->getPointeeType();
16387 Qualifiers objectQuals = objectType.getQualifiers();
16388
16389 Qualifiers difference = objectQuals - funcQuals;
16390 difference.removeObjCGCAttr();
16391 difference.removeAddressSpace();
16392 if (difference) {
16393 std::string qualsString = difference.getAsString();
16394 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16395 << fnType.getUnqualifiedType()
16396 << qualsString
16397 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16398 }
16399
16400 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16401 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16402 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16403
16404 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16405 CE: call, FD: nullptr))
16406 return ExprError();
16407
16408 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16409 return ExprError();
16410
16411 if (CheckOtherCall(TheCall: call, Proto: proto))
16412 return ExprError();
16413
16414 return MaybeBindToTemporary(E: call);
16415 }
16416
16417 // We only try to build a recovery expr at this level if we can preserve
16418 // the return type, otherwise we return ExprError() and let the caller
16419 // recover.
16420 auto BuildRecoveryExpr = [&](QualType Type) {
16421 if (!AllowRecovery)
16422 return ExprError();
16423 std::vector<Expr *> SubExprs = {MemExprE};
16424 llvm::append_range(C&: SubExprs, R&: Args);
16425 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16426 T: Type);
16427 };
16428 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16429 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16430 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16431
16432 UnbridgedCastsSet UnbridgedCasts;
16433 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16434 return ExprError();
16435
16436 MemberExpr *MemExpr;
16437 CXXMethodDecl *Method = nullptr;
16438 bool HadMultipleCandidates = false;
16439 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16440 NestedNameSpecifier Qualifier = std::nullopt;
16441 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16442 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16443 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16444 FoundDecl = MemExpr->getFoundDecl();
16445 Qualifier = MemExpr->getQualifier();
16446 UnbridgedCasts.restore();
16447 } else {
16448 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16449 Qualifier = UnresExpr->getQualifier();
16450
16451 QualType ObjectType = UnresExpr->getBaseType();
16452 Expr::Classification ObjectClassification
16453 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16454 : UnresExpr->getBase()->Classify(Ctx&: Context);
16455
16456 // Add overload candidates
16457 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16458 OverloadCandidateSet::CSK_Normal);
16459
16460 // FIXME: avoid copy.
16461 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16462 if (UnresExpr->hasExplicitTemplateArgs()) {
16463 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16464 TemplateArgs = &TemplateArgsBuffer;
16465 }
16466
16467 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16468 E = UnresExpr->decls_end(); I != E; ++I) {
16469
16470 QualType ExplicitObjectType = ObjectType;
16471
16472 NamedDecl *Func = *I;
16473 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16474 if (isa<UsingShadowDecl>(Val: Func))
16475 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16476
16477 bool HasExplicitParameter = false;
16478 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16479 M && M->hasCXXExplicitFunctionObjectParameter())
16480 HasExplicitParameter = true;
16481 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16482 M &&
16483 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16484 HasExplicitParameter = true;
16485
16486 if (HasExplicitParameter)
16487 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16488
16489 // Microsoft supports direct constructor calls.
16490 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16491 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16492 CandidateSet,
16493 /*SuppressUserConversions*/ false);
16494 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16495 // If explicit template arguments were provided, we can't call a
16496 // non-template member function.
16497 if (TemplateArgs)
16498 continue;
16499
16500 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16501 ObjectClassification, Args, CandidateSet,
16502 /*SuppressUserConversions=*/false);
16503 } else {
16504 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16505 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16506 ObjectType: ExplicitObjectType, ObjectClassification,
16507 Args, CandidateSet,
16508 /*SuppressUserConversions=*/false);
16509 }
16510 }
16511
16512 HadMultipleCandidates = (CandidateSet.size() > 1);
16513
16514 DeclarationName DeclName = UnresExpr->getMemberName();
16515
16516 UnbridgedCasts.restore();
16517
16518 OverloadCandidateSet::iterator Best;
16519 bool Succeeded = false;
16520 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16521 Best)) {
16522 case OR_Success:
16523 Method = cast<CXXMethodDecl>(Val: Best->Function);
16524 FoundDecl = Best->FoundDecl;
16525 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16526 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16527 break;
16528 // If FoundDecl is different from Method (such as if one is a template
16529 // and the other a specialization), make sure DiagnoseUseOfDecl is
16530 // called on both.
16531 // FIXME: This would be more comprehensively addressed by modifying
16532 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16533 // being used.
16534 if (Method != FoundDecl.getDecl() &&
16535 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16536 break;
16537 Succeeded = true;
16538 break;
16539
16540 case OR_No_Viable_Function:
16541 CandidateSet.NoteCandidates(
16542 PD: PartialDiagnosticAt(
16543 UnresExpr->getMemberLoc(),
16544 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16545 << DeclName << MemExprE->getSourceRange()),
16546 S&: *this, OCD: OCD_AllCandidates, Args);
16547 break;
16548 case OR_Ambiguous:
16549 CandidateSet.NoteCandidates(
16550 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16551 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16552 << DeclName << MemExprE->getSourceRange()),
16553 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16554 break;
16555 case OR_Deleted:
16556 DiagnoseUseOfDeletedFunction(
16557 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16558 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16559 break;
16560 }
16561 // Overload resolution fails, try to recover.
16562 if (!Succeeded)
16563 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16564
16565 ExprResult Res =
16566 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16567 if (Res.isInvalid())
16568 return ExprError();
16569 MemExprE = Res.get();
16570
16571 // If overload resolution picked a static member
16572 // build a non-member call based on that function.
16573 if (Method->isStatic()) {
16574 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16575 Config: ExecConfig, IsExecConfig);
16576 }
16577
16578 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16579 }
16580
16581 QualType ResultType = Method->getReturnType();
16582 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16583 ResultType = ResultType.getNonLValueExprType(Context);
16584
16585 assert(Method && "Member call to something that isn't a method?");
16586 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16587
16588 CallExpr *TheCall = nullptr;
16589 llvm::SmallVector<Expr *, 8> NewArgs;
16590 if (Method->isExplicitObjectMemberFunction()) {
16591 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16592 NewArgs))
16593 return ExprError();
16594
16595 // FIXME: avoid copy.
16596 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16597 if (MemExpr->hasExplicitTemplateArgs()) {
16598 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16599 TemplateArgs = &TemplateArgsBuffer;
16600 }
16601
16602 // Build the actual expression node.
16603 ExprResult FnExpr = CreateFunctionRefExpr(
16604 S&: *this, QualifierLoc: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(),
16605 Fn: Method, FoundDecl, Base: MemExpr, HadMultipleCandidates,
16606 NameInfo: MemExpr->getMemberNameInfo(), TemplateArgs);
16607 if (FnExpr.isInvalid())
16608 return ExprError();
16609
16610 TheCall =
16611 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16612 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16613 TheCall->setUsesMemberSyntax(true);
16614 } else {
16615 // Convert the object argument (for a non-static member function call).
16616 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16617 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16618 if (ObjectArg.isInvalid())
16619 return ExprError();
16620 MemExpr->setBase(ObjectArg.get());
16621 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16622 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16623 MinNumArgs: Proto->getNumParams());
16624 }
16625
16626 // Check for a valid return type.
16627 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16628 CE: TheCall, FD: Method))
16629 return BuildRecoveryExpr(ResultType);
16630
16631 // Convert the rest of the arguments
16632 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16633 RParenLoc))
16634 return BuildRecoveryExpr(ResultType);
16635
16636 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16637
16638 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16639 return ExprError();
16640
16641 // In the case the method to call was not selected by the overloading
16642 // resolution process, we still need to handle the enable_if attribute. Do
16643 // that here, so it will not hide previous -- and more relevant -- errors.
16644 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16645 if (const EnableIfAttr *Attr =
16646 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16647 Diag(Loc: MemE->getMemberLoc(),
16648 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16649 << Method << Method->getSourceRange();
16650 Diag(Loc: Method->getLocation(),
16651 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16652 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16653 return ExprError();
16654 }
16655 }
16656
16657 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16658 TheCall->getDirectCallee()->isPureVirtual()) {
16659 const FunctionDecl *MD = TheCall->getDirectCallee();
16660
16661 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16662 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16663 Diag(Loc: MemExpr->getBeginLoc(),
16664 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16665 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16666 << MD->getParent();
16667
16668 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16669 if (getLangOpts().AppleKext)
16670 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16671 << MD->getParent() << MD->getDeclName();
16672 }
16673 }
16674
16675 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16676 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16677 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16678 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16679 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16680 DtorLoc: MemExpr->getMemberLoc());
16681 }
16682
16683 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16684 Decl: TheCall->getDirectCallee());
16685}
16686
16687ExprResult
16688Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16689 SourceLocation LParenLoc,
16690 MultiExprArg Args,
16691 SourceLocation RParenLoc) {
16692 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16693 return ExprError();
16694 ExprResult Object = Obj;
16695
16696 UnbridgedCastsSet UnbridgedCasts;
16697 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16698 return ExprError();
16699
16700 assert(Object.get()->getType()->isRecordType() &&
16701 "Requires object type argument");
16702
16703 // C++ [over.call.object]p1:
16704 // If the primary-expression E in the function call syntax
16705 // evaluates to a class object of type "cv T", then the set of
16706 // candidate functions includes at least the function call
16707 // operators of T. The function call operators of T are obtained by
16708 // ordinary lookup of the name operator() in the context of
16709 // (E).operator().
16710 OverloadCandidateSet CandidateSet(LParenLoc,
16711 OverloadCandidateSet::CSK_Operator);
16712 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16713
16714 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16715 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16716 return true;
16717
16718 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16719 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16720 LookupQualifiedName(R, LookupCtx: Record);
16721 R.suppressAccessDiagnostics();
16722
16723 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16724 Oper != OperEnd; ++Oper) {
16725 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16726 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16727 /*SuppressUserConversion=*/SuppressUserConversions: false);
16728 }
16729
16730 // When calling a lambda, both the call operator, and
16731 // the conversion operator to function pointer
16732 // are considered. But when constraint checking
16733 // on the call operator fails, it will also fail on the
16734 // conversion operator as the constraints are always the same.
16735 // As the user probably does not intend to perform a surrogate call,
16736 // we filter them out to produce better error diagnostics, ie to avoid
16737 // showing 2 failed overloads instead of one.
16738 bool IgnoreSurrogateFunctions = false;
16739 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16740 const OverloadCandidate &Candidate = *CandidateSet.begin();
16741 if (!Candidate.Viable &&
16742 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16743 IgnoreSurrogateFunctions = true;
16744 }
16745
16746 // C++ [over.call.object]p2:
16747 // In addition, for each (non-explicit in C++0x) conversion function
16748 // declared in T of the form
16749 //
16750 // operator conversion-type-id () cv-qualifier;
16751 //
16752 // where cv-qualifier is the same cv-qualification as, or a
16753 // greater cv-qualification than, cv, and where conversion-type-id
16754 // denotes the type "pointer to function of (P1,...,Pn) returning
16755 // R", or the type "reference to pointer to function of
16756 // (P1,...,Pn) returning R", or the type "reference to function
16757 // of (P1,...,Pn) returning R", a surrogate call function [...]
16758 // is also considered as a candidate function. Similarly,
16759 // surrogate call functions are added to the set of candidate
16760 // functions for each conversion function declared in an
16761 // accessible base class provided the function is not hidden
16762 // within T by another intervening declaration.
16763 const auto &Conversions = Record->getVisibleConversionFunctions();
16764 for (auto I = Conversions.begin(), E = Conversions.end();
16765 !IgnoreSurrogateFunctions && I != E; ++I) {
16766 NamedDecl *D = *I;
16767 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16768 if (isa<UsingShadowDecl>(Val: D))
16769 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16770
16771 // Skip over templated conversion functions; they aren't
16772 // surrogates.
16773 if (isa<FunctionTemplateDecl>(Val: D))
16774 continue;
16775
16776 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16777 if (!Conv->isExplicit()) {
16778 // Strip the reference type (if any) and then the pointer type (if
16779 // any) to get down to what might be a function type.
16780 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16781 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16782 ConvType = ConvPtrType->getPointeeType();
16783
16784 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16785 {
16786 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16787 Object: Object.get(), Args, CandidateSet);
16788 }
16789 }
16790 }
16791
16792 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16793
16794 // Perform overload resolution.
16795 OverloadCandidateSet::iterator Best;
16796 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16797 Best)) {
16798 case OR_Success:
16799 // Overload resolution succeeded; we'll build the appropriate call
16800 // below.
16801 break;
16802
16803 case OR_No_Viable_Function: {
16804 PartialDiagnostic PD =
16805 CandidateSet.empty()
16806 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16807 << Object.get()->getType() << /*call*/ 1
16808 << Object.get()->getSourceRange())
16809 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16810 << Object.get()->getType() << Object.get()->getSourceRange());
16811 CandidateSet.NoteCandidates(
16812 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16813 OCD: OCD_AllCandidates, Args);
16814 break;
16815 }
16816 case OR_Ambiguous:
16817 if (!R.isAmbiguous())
16818 CandidateSet.NoteCandidates(
16819 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16820 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16821 << Object.get()->getType()
16822 << Object.get()->getSourceRange()),
16823 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16824 break;
16825
16826 case OR_Deleted: {
16827 // FIXME: Is this diagnostic here really necessary? It seems that
16828 // 1. we don't have any tests for this diagnostic, and
16829 // 2. we already issue err_deleted_function_use for this later on anyway.
16830 StringLiteral *Msg = Best->Function->getDeletedMessage();
16831 CandidateSet.NoteCandidates(
16832 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16833 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16834 << Object.get()->getType() << (Msg != nullptr)
16835 << (Msg ? Msg->getString() : StringRef())
16836 << Object.get()->getSourceRange()),
16837 S&: *this, OCD: OCD_AllCandidates, Args);
16838 break;
16839 }
16840 }
16841
16842 if (Best == CandidateSet.end())
16843 return true;
16844
16845 UnbridgedCasts.restore();
16846
16847 if (Best->Function == nullptr) {
16848 // Since there is no function declaration, this is one of the
16849 // surrogate candidates. Dig out the conversion function.
16850 CXXConversionDecl *Conv
16851 = cast<CXXConversionDecl>(
16852 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16853
16854 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16855 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16856 "Found Decl & conversion-to-functionptr should be same, right?!");
16857 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16858 FoundDecl: Best->FoundDecl);
16859 if (DiagnoseUseOfDecl(D: Conv, Locs: LParenLoc))
16860 return ExprError();
16861 // We selected one of the surrogate functions that converts the
16862 // object parameter to a function pointer. Perform the conversion
16863 // on the object argument, then let BuildCallExpr finish the job.
16864
16865 // Create an implicit member expr to refer to the conversion operator.
16866 // and then call it.
16867 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16868 Method: Conv, HadMultipleCandidates);
16869 if (Call.isInvalid())
16870 return ExprError();
16871 // Record usage of conversion in an implicit cast.
16872 Call = ImplicitCastExpr::Create(
16873 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16874 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16875
16876 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16877 }
16878
16879 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16880
16881 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16882 // that calls this method, using Object for the implicit object
16883 // parameter and passing along the remaining arguments.
16884 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16885
16886 // An error diagnostic has already been printed when parsing the declaration.
16887 if (Method->isInvalidDecl())
16888 return ExprError();
16889
16890 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16891 unsigned NumParams = Proto->getNumParams();
16892
16893 DeclarationNameInfo OpLocInfo(
16894 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16895 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16896 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl, Base: Obj,
16897 HadMultipleCandidates, NameInfo: OpLocInfo);
16898 if (NewFn.isInvalid())
16899 return true;
16900
16901 SmallVector<Expr *, 8> MethodArgs;
16902 MethodArgs.reserve(N: NumParams + 1);
16903
16904 bool IsError = false;
16905
16906 // Initialize the object parameter.
16907 llvm::SmallVector<Expr *, 8> NewArgs;
16908 if (Method->isExplicitObjectMemberFunction()) {
16909 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16910 } else {
16911 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16912 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16913 if (ObjRes.isInvalid())
16914 IsError = true;
16915 else
16916 Object = ObjRes;
16917 MethodArgs.push_back(Elt: Object.get());
16918 }
16919
16920 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16921 S&: *this, MethodArgs, Method, Args, LParenLoc);
16922
16923 // If this is a variadic call, handle args passed through "...".
16924 if (Proto->isVariadic()) {
16925 // Promote the arguments (C99 6.5.2.2p7).
16926 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16927 ExprResult Arg = DefaultVariadicArgumentPromotion(
16928 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16929 IsError |= Arg.isInvalid();
16930 MethodArgs.push_back(Elt: Arg.get());
16931 }
16932 }
16933
16934 if (IsError)
16935 return true;
16936
16937 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16938
16939 // Once we've built TheCall, all of the expressions are properly owned.
16940 QualType ResultTy = Method->getReturnType();
16941 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16942 ResultTy = ResultTy.getNonLValueExprType(Context);
16943
16944 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16945 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16946 FPFeatures: CurFPFeatureOverrides());
16947
16948 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16949 return true;
16950
16951 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16952 return true;
16953
16954 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16955}
16956
16957ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16958 SourceLocation OpLoc,
16959 bool *NoArrowOperatorFound) {
16960 assert(Base->getType()->isRecordType() &&
16961 "left-hand side must have class type");
16962
16963 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16964 return ExprError();
16965
16966 SourceLocation Loc = Base->getExprLoc();
16967
16968 // C++ [over.ref]p1:
16969 //
16970 // [...] An expression x->m is interpreted as (x.operator->())->m
16971 // for a class object x of type T if T::operator->() exists and if
16972 // the operator is selected as the best match function by the
16973 // overload resolution mechanism (13.3).
16974 DeclarationName OpName =
16975 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16976 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16977
16978 if (RequireCompleteType(Loc, T: Base->getType(),
16979 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16980 return ExprError();
16981
16982 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16983 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16984 R.suppressAccessDiagnostics();
16985
16986 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16987 Oper != OperEnd; ++Oper) {
16988 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16989 Args: {}, CandidateSet,
16990 /*SuppressUserConversion=*/SuppressUserConversions: false);
16991 }
16992
16993 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16994
16995 // Perform overload resolution.
16996 OverloadCandidateSet::iterator Best;
16997 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16998 case OR_Success:
16999 // Overload resolution succeeded; we'll build the call below.
17000 break;
17001
17002 case OR_No_Viable_Function: {
17003 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
17004 if (CandidateSet.empty()) {
17005 QualType BaseType = Base->getType();
17006 if (NoArrowOperatorFound) {
17007 // Report this specific error to the caller instead of emitting a
17008 // diagnostic, as requested.
17009 *NoArrowOperatorFound = true;
17010 return ExprError();
17011 }
17012 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
17013 << BaseType << Base->getSourceRange();
17014 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17015 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
17016 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
17017 }
17018 } else
17019 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
17020 << "operator->" << Base->getSourceRange();
17021 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
17022 return ExprError();
17023 }
17024 case OR_Ambiguous:
17025 if (!R.isAmbiguous())
17026 CandidateSet.NoteCandidates(
17027 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
17028 << "->" << Base->getType()
17029 << Base->getSourceRange()),
17030 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
17031 return ExprError();
17032
17033 case OR_Deleted: {
17034 StringLiteral *Msg = Best->Function->getDeletedMessage();
17035 CandidateSet.NoteCandidates(
17036 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
17037 << "->" << (Msg != nullptr)
17038 << (Msg ? Msg->getString() : StringRef())
17039 << Base->getSourceRange()),
17040 S&: *this, OCD: OCD_AllCandidates, Args: Base);
17041 return ExprError();
17042 }
17043 }
17044
17045 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
17046
17047 // Convert the object parameter.
17048 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
17049
17050 if (Method->isExplicitObjectMemberFunction()) {
17051 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
17052 if (R.isInvalid())
17053 return ExprError();
17054 Base = R.get();
17055 } else {
17056 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
17057 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
17058 if (BaseResult.isInvalid())
17059 return ExprError();
17060 Base = BaseResult.get();
17061 }
17062
17063 // Build the operator call.
17064 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
17065 Base, HadMultipleCandidates, Loc: OpLoc);
17066 if (FnExpr.isInvalid())
17067 return ExprError();
17068
17069 QualType ResultTy = Method->getReturnType();
17070 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17071 ResultTy = ResultTy.getNonLValueExprType(Context);
17072
17073 CallExpr *TheCall =
17074 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
17075 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
17076
17077 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
17078 return ExprError();
17079
17080 if (CheckFunctionCall(FDecl: Method, TheCall,
17081 Proto: Method->getType()->castAs<FunctionProtoType>()))
17082 return ExprError();
17083
17084 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17085}
17086
17087ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
17088 DeclarationNameInfo &SuffixInfo,
17089 ArrayRef<Expr*> Args,
17090 SourceLocation LitEndLoc,
17091 TemplateArgumentListInfo *TemplateArgs) {
17092 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17093
17094 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17095 OverloadCandidateSet::CSK_Normal);
17096 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
17097 ExplicitTemplateArgs: TemplateArgs);
17098
17099 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17100
17101 // Perform overload resolution. This will usually be trivial, but might need
17102 // to perform substitutions for a literal operator template.
17103 OverloadCandidateSet::iterator Best;
17104 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
17105 case OR_Success:
17106 case OR_Deleted:
17107 break;
17108
17109 case OR_No_Viable_Function:
17110 CandidateSet.NoteCandidates(
17111 PD: PartialDiagnosticAt(UDSuffixLoc,
17112 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
17113 << R.getLookupName()),
17114 S&: *this, OCD: OCD_AllCandidates, Args);
17115 return ExprError();
17116
17117 case OR_Ambiguous:
17118 CandidateSet.NoteCandidates(
17119 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
17120 << R.getLookupName()),
17121 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
17122 return ExprError();
17123 }
17124
17125 FunctionDecl *FD = Best->Function;
17126 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl, Base: nullptr,
17127 HadMultipleCandidates, NameInfo: SuffixInfo);
17128 if (Fn.isInvalid())
17129 return true;
17130
17131 // Check the argument types. This should almost always be a no-op, except
17132 // that array-to-pointer decay is applied to string literals.
17133 Expr *ConvArgs[2];
17134 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17135 ExprResult InputInit = PerformCopyInitialization(
17136 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17137 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17138 if (InputInit.isInvalid())
17139 return true;
17140 ConvArgs[ArgIdx] = InputInit.get();
17141 }
17142
17143 QualType ResultTy = FD->getReturnType();
17144 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17145 ResultTy = ResultTy.getNonLValueExprType(Context);
17146
17147 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17148 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17149 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17150
17151 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17152 return ExprError();
17153
17154 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17155 return ExprError();
17156
17157 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17158}
17159
17160Sema::ForRangeStatus
17161Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17162 SourceLocation RangeLoc,
17163 const DeclarationNameInfo &NameInfo,
17164 LookupResult &MemberLookup,
17165 OverloadCandidateSet *CandidateSet,
17166 Expr *Range, ExprResult *CallExpr) {
17167 Scope *S = nullptr;
17168
17169 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17170 if (!MemberLookup.empty()) {
17171 ExprResult MemberRef =
17172 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17173 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17174 /*TemplateKWLoc=*/SourceLocation(),
17175 /*FirstQualifierInScope=*/nullptr,
17176 R&: MemberLookup,
17177 /*TemplateArgs=*/nullptr, S);
17178 if (MemberRef.isInvalid()) {
17179 *CallExpr = ExprError();
17180 return FRS_DiagnosticIssued;
17181 }
17182 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17183 if (CallExpr->isInvalid()) {
17184 *CallExpr = ExprError();
17185 return FRS_DiagnosticIssued;
17186 }
17187 } else {
17188 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17189 NNSLoc: NestedNameSpecifierLoc(),
17190 DNI: NameInfo, Fns: UnresolvedSet<0>());
17191 if (FnR.isInvalid())
17192 return FRS_DiagnosticIssued;
17193 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17194
17195 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17196 CandidateSet, Result: CallExpr);
17197 if (CandidateSet->empty() || CandidateSetError) {
17198 *CallExpr = ExprError();
17199 return FRS_NoViableFunction;
17200 }
17201 OverloadCandidateSet::iterator Best;
17202 OverloadingResult OverloadResult =
17203 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17204
17205 if (OverloadResult == OR_No_Viable_Function) {
17206 *CallExpr = ExprError();
17207 return FRS_NoViableFunction;
17208 }
17209 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17210 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17211 OverloadResult,
17212 /*AllowTypoCorrection=*/false);
17213 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17214 *CallExpr = ExprError();
17215 return FRS_DiagnosticIssued;
17216 }
17217 }
17218 return FRS_Success;
17219}
17220
17221ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17222 FunctionDecl *Fn) {
17223 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17224 ExprResult SubExpr =
17225 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17226 if (SubExpr.isInvalid())
17227 return ExprError();
17228 if (SubExpr.get() == PE->getSubExpr())
17229 return PE;
17230
17231 return new (Context)
17232 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17233 }
17234
17235 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17236 ExprResult SubExpr =
17237 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17238 if (SubExpr.isInvalid())
17239 return ExprError();
17240 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17241 SubExpr.get()->getType()) &&
17242 "Implicit cast type cannot be determined from overload");
17243 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17244 if (SubExpr.get() == ICE->getSubExpr())
17245 return ICE;
17246
17247 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17248 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17249 FPO: CurFPFeatureOverrides());
17250 }
17251
17252 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17253 if (!GSE->isResultDependent()) {
17254 ExprResult SubExpr =
17255 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17256 if (SubExpr.isInvalid())
17257 return ExprError();
17258 if (SubExpr.get() == GSE->getResultExpr())
17259 return GSE;
17260
17261 // Replace the resulting type information before rebuilding the generic
17262 // selection expression.
17263 ArrayRef<Expr *> A = GSE->getAssocExprs();
17264 SmallVector<Expr *, 4> AssocExprs(A);
17265 unsigned ResultIdx = GSE->getResultIndex();
17266 AssocExprs[ResultIdx] = SubExpr.get();
17267
17268 if (GSE->isExprPredicate())
17269 return GenericSelectionExpr::Create(
17270 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17271 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17272 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17273 ResultIndex: ResultIdx);
17274 return GenericSelectionExpr::Create(
17275 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17276 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17277 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17278 ResultIndex: ResultIdx);
17279 }
17280 // Rather than fall through to the unreachable, return the original generic
17281 // selection expression.
17282 return GSE;
17283 }
17284
17285 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17286 assert(UnOp->getOpcode() == UO_AddrOf &&
17287 "Can only take the address of an overloaded function");
17288 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17289 if (!Method->isImplicitObjectMemberFunction()) {
17290 // Do nothing: the address of static and
17291 // explicit object member functions is a (non-member) function pointer.
17292 } else {
17293 // Fix the subexpression, which really has to be an
17294 // UnresolvedLookupExpr holding an overloaded member function
17295 // or template.
17296 ExprResult SubExpr =
17297 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17298 if (SubExpr.isInvalid())
17299 return ExprError();
17300 if (SubExpr.get() == UnOp->getSubExpr())
17301 return UnOp;
17302
17303 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17304 Op: SubExpr.get(), MD: Method))
17305 return ExprError();
17306
17307 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17308 "fixed to something other than a decl ref");
17309 NestedNameSpecifier Qualifier =
17310 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17311 assert(Qualifier &&
17312 "fixed to a member ref with no nested name qualifier");
17313
17314 // We have taken the address of a pointer to member
17315 // function. Perform the computation here so that we get the
17316 // appropriate pointer to member type.
17317 QualType MemPtrType = Context.getMemberPointerType(
17318 T: Fn->getType(), Qualifier,
17319 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17320 // Under the MS ABI, lock down the inheritance model now.
17321 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17322 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17323
17324 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17325 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17326 l: UnOp->getOperatorLoc(), CanOverflow: false,
17327 FPFeatures: CurFPFeatureOverrides());
17328 }
17329 }
17330 ExprResult SubExpr =
17331 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17332 if (SubExpr.isInvalid())
17333 return ExprError();
17334 if (SubExpr.get() == UnOp->getSubExpr())
17335 return UnOp;
17336
17337 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17338 InputExpr: SubExpr.get());
17339 }
17340
17341 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17342 if (Found.getAccess() == AS_none) {
17343 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17344 }
17345 // FIXME: avoid copy.
17346 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17347 if (ULE->hasExplicitTemplateArgs()) {
17348 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17349 TemplateArgs = &TemplateArgsBuffer;
17350 }
17351
17352 QualType Type = Fn->getType();
17353 ExprValueKind ValueKind =
17354 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17355 ? VK_LValue
17356 : VK_PRValue;
17357
17358 // FIXME: Duplicated from BuildDeclarationNameExpr.
17359 if (unsigned BID = Fn->getBuiltinID()) {
17360 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17361 Type = Context.BuiltinFnTy;
17362 ValueKind = VK_PRValue;
17363 }
17364 }
17365
17366 DeclRefExpr *DRE = BuildDeclRefExpr(
17367 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17368 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17369 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17370 return DRE;
17371 }
17372
17373 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17374 // FIXME: avoid copy.
17375 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17376 if (MemExpr->hasExplicitTemplateArgs()) {
17377 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17378 TemplateArgs = &TemplateArgsBuffer;
17379 }
17380
17381 Expr *Base;
17382
17383 // If we're filling in a static method where we used to have an
17384 // implicit member access, rewrite to a simple decl ref.
17385 if (MemExpr->isImplicitAccess()) {
17386 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17387 DeclRefExpr *DRE = BuildDeclRefExpr(
17388 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17389 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17390 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17391 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17392 return DRE;
17393 } else {
17394 SourceLocation Loc = MemExpr->getMemberLoc();
17395 if (MemExpr->getQualifier())
17396 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17397 Base =
17398 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17399 }
17400 } else
17401 Base = MemExpr->getBase();
17402
17403 ExprValueKind valueKind;
17404 QualType type;
17405 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17406 valueKind = VK_LValue;
17407 type = Fn->getType();
17408 } else {
17409 valueKind = VK_PRValue;
17410 type = Context.BoundMemberTy;
17411 }
17412
17413 return BuildMemberExpr(
17414 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17415 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17416 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17417 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17418 }
17419
17420 llvm_unreachable("Invalid reference to overloaded function");
17421}
17422
17423ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17424 DeclAccessPair Found,
17425 FunctionDecl *Fn) {
17426 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17427}
17428
17429bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17430 FunctionDecl *Function) {
17431 if (!PartialOverloading || !Function)
17432 return true;
17433 if (Function->isVariadic())
17434 return false;
17435 if (const auto *Proto =
17436 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17437 if (Proto->isTemplateVariadic())
17438 return false;
17439 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17440 if (const auto *Proto =
17441 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17442 if (Proto->isTemplateVariadic())
17443 return false;
17444 return true;
17445}
17446
17447void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17448 DeclarationName Name,
17449 OverloadCandidateSet &CandidateSet,
17450 FunctionDecl *Fn, MultiExprArg Args,
17451 bool IsMember) {
17452 StringLiteral *Msg = Fn->getDeletedMessage();
17453 CandidateSet.NoteCandidates(
17454 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17455 << IsMember << Name << (Msg != nullptr)
17456 << (Msg ? Msg->getString() : StringRef())
17457 << Range),
17458 S&: *this, OCD: OCD_AllCandidates, Args);
17459}
17460