1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/DiagnosticOptions.h"
25#include "clang/Basic/OperatorKinds.h"
26#include "clang/Basic/PartialDiagnostic.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaCUDA.h"
34#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include <algorithm>
44#include <cassert>
45#include <cstddef>
46#include <cstdlib>
47#include <optional>
48
49using namespace clang;
50using namespace sema;
51
52using AllowedExplicit = Sema::AllowedExplicit;
53
54static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
55 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
56 return P->hasAttr<PassObjectSizeAttr>();
57 });
58}
59
60/// A convenience routine for creating a decayed reference to a function.
61static ExprResult CreateFunctionRefExpr(
62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
65 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
66 return ExprError();
67 // If FoundDecl is different from Fn (such as if one is a template
68 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // called on both.
70 // FIXME: This would be more comprehensively addressed by modifying
71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 // being used.
73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
74 return ExprError();
75 DeclRefExpr *DRE = new (S.Context)
76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
77 if (HadMultipleCandidates)
78 DRE->setHadMultipleCandidates(true);
79
80 S.MarkDeclRefReferenced(E: DRE, Base);
81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
83 S.ResolveExceptionSpec(Loc, FPT: FPT);
84 DRE->setType(Fn->getType());
85 }
86 }
87 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(DRE->getType()),
88 CK: CK_FunctionToPointerDecay);
89}
90
91static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
92 bool InOverloadResolution,
93 StandardConversionSequence &SCS,
94 bool CStyle,
95 bool AllowObjCWritebackConversion);
96
97static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
98 QualType &ToType,
99 bool InOverloadResolution,
100 StandardConversionSequence &SCS,
101 bool CStyle);
102static OverloadingResult
103IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
104 UserDefinedConversionSequence& User,
105 OverloadCandidateSet& Conversions,
106 AllowedExplicit AllowExplicit,
107 bool AllowObjCConversionOnExplicit);
108
109static ImplicitConversionSequence::CompareKind
110CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
113
114static ImplicitConversionSequence::CompareKind
115CompareQualificationConversions(Sema &S,
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
119static ImplicitConversionSequence::CompareKind
120CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
123
124/// GetConversionRank - Retrieve the implicit conversion rank
125/// corresponding to the given implicit conversion kind.
126ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
127 static const ImplicitConversionRank Rank[] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
133 ICR_Exact_Match,
134 ICR_Promotion,
135 ICR_Promotion,
136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_OCL_Scalar_Widening,
150 ICR_Complex_Real_Conversion,
151 ICR_Conversion,
152 ICR_Conversion,
153 ICR_Writeback_Conversion,
154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
160 ICR_C_Conversion,
161 ICR_C_Conversion_Extension,
162 ICR_Conversion,
163 ICR_HLSL_Dimension_Reduction,
164 ICR_Conversion,
165 ICR_HLSL_Scalar_Widening,
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
171ImplicitConversionRank
172clang::GetDimensionConversionRank(ImplicitConversionRank Base,
173 ImplicitConversionKind Dimension) {
174 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
175 if (Rank == ICR_HLSL_Scalar_Widening) {
176 if (Base == ICR_Promotion)
177 return ICR_HLSL_Scalar_Widening_Promotion;
178 if (Base == ICR_Conversion)
179 return ICR_HLSL_Scalar_Widening_Conversion;
180 }
181 if (Rank == ICR_HLSL_Dimension_Reduction) {
182 if (Base == ICR_Promotion)
183 return ICR_HLSL_Dimension_Reduction_Promotion;
184 if (Base == ICR_Conversion)
185 return ICR_HLSL_Dimension_Reduction_Conversion;
186 }
187 return Rank;
188}
189
190/// GetImplicitConversionName - Return the name of this kind of
191/// implicit conversion.
192static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
193 static const char *const Name[] = {
194 "No conversion",
195 "Lvalue-to-rvalue",
196 "Array-to-pointer",
197 "Function-to-pointer",
198 "Function pointer conversion",
199 "Qualification",
200 "Integral promotion",
201 "Floating point promotion",
202 "Complex promotion",
203 "Integral conversion",
204 "Floating conversion",
205 "Complex conversion",
206 "Floating-integral conversion",
207 "Pointer conversion",
208 "Pointer-to-member conversion",
209 "Boolean conversion",
210 "Compatible-types conversion",
211 "Derived-to-base conversion",
212 "Vector conversion",
213 "SVE Vector conversion",
214 "RVV Vector conversion",
215 "Vector splat",
216 "Complex-real conversion",
217 "Block Pointer conversion",
218 "Transparent Union Conversion",
219 "Writeback conversion",
220 "OpenCL Zero Event Conversion",
221 "OpenCL Zero Queue Conversion",
222 "C specific type conversion",
223 "Incompatible pointer conversion",
224 "Fixed point conversion",
225 "HLSL vector truncation",
226 "Non-decaying array conversion",
227 "HLSL vector splat",
228 };
229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
230 return Name[Kind];
231}
232
233/// StandardConversionSequence - Set the standard conversion
234/// sequence to the identity conversion.
235void StandardConversionSequence::setAsIdentityConversion() {
236 First = ICK_Identity;
237 Second = ICK_Identity;
238 Dimension = ICK_Identity;
239 Third = ICK_Identity;
240 DeprecatedStringLiteralToCharPtr = false;
241 QualificationIncludesObjCLifetime = false;
242 ReferenceBinding = false;
243 DirectBinding = false;
244 IsLvalueReference = true;
245 BindsToFunctionLvalue = false;
246 BindsToRvalue = false;
247 BindsImplicitObjectArgumentWithoutRefQualifier = false;
248 ObjCLifetimeConversionBinding = false;
249 FromBracedInitList = false;
250 CopyConstructor = nullptr;
251}
252
253/// getRank - Retrieve the rank of this standard conversion sequence
254/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
255/// implicit conversions.
256ImplicitConversionRank StandardConversionSequence::getRank() const {
257 ImplicitConversionRank Rank = ICR_Exact_Match;
258 if (GetConversionRank(Kind: First) > Rank)
259 Rank = GetConversionRank(Kind: First);
260 if (GetConversionRank(Kind: Second) > Rank)
261 Rank = GetConversionRank(Kind: Second);
262 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
263 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
264 if (GetConversionRank(Kind: Third) > Rank)
265 Rank = GetConversionRank(Kind: Third);
266 return Rank;
267}
268
269/// isPointerConversionToBool - Determines whether this conversion is
270/// a conversion of a pointer or pointer-to-member to bool. This is
271/// used as part of the ranking of standard conversion sequences
272/// (C++ 13.3.3.2p4).
273bool StandardConversionSequence::isPointerConversionToBool() const {
274 // Note that FromType has not necessarily been transformed by the
275 // array-to-pointer or function-to-pointer implicit conversions, so
276 // check for their presence as well as checking whether FromType is
277 // a pointer.
278 if (getToType(Idx: 1)->isBooleanType() &&
279 (getFromType()->isPointerType() ||
280 getFromType()->isMemberPointerType() ||
281 getFromType()->isObjCObjectPointerType() ||
282 getFromType()->isBlockPointerType() ||
283 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
284 return true;
285
286 return false;
287}
288
289/// isPointerConversionToVoidPointer - Determines whether this
290/// conversion is a conversion of a pointer to a void pointer. This is
291/// used as part of the ranking of standard conversion sequences (C++
292/// 13.3.3.2p4).
293bool
294StandardConversionSequence::
295isPointerConversionToVoidPointer(ASTContext& Context) const {
296 QualType FromType = getFromType();
297 QualType ToType = getToType(Idx: 1);
298
299 // Note that FromType has not necessarily been transformed by the
300 // array-to-pointer implicit conversion, so check for its presence
301 // and redo the conversion to get a pointer.
302 if (First == ICK_Array_To_Pointer)
303 FromType = Context.getArrayDecayedType(T: FromType);
304
305 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
306 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
307 return ToPtrType->getPointeeType()->isVoidType();
308
309 return false;
310}
311
312/// Skip any implicit casts which could be either part of a narrowing conversion
313/// or after one in an implicit conversion.
314static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
315 const Expr *Converted) {
316 // We can have cleanups wrapping the converted expression; these need to be
317 // preserved so that destructors run if necessary.
318 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
319 Expr *Inner =
320 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
321 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
322 objects: EWC->getObjects());
323 }
324
325 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
326 switch (ICE->getCastKind()) {
327 case CK_NoOp:
328 case CK_IntegralCast:
329 case CK_IntegralToBoolean:
330 case CK_IntegralToFloating:
331 case CK_BooleanToSignedIntegral:
332 case CK_FloatingToIntegral:
333 case CK_FloatingToBoolean:
334 case CK_FloatingCast:
335 Converted = ICE->getSubExpr();
336 continue;
337
338 default:
339 return Converted;
340 }
341 }
342
343 return Converted;
344}
345
346/// Check if this standard conversion sequence represents a narrowing
347/// conversion, according to C++11 [dcl.init.list]p7.
348///
349/// \param Ctx The AST context.
350/// \param Converted The result of applying this standard conversion sequence.
351/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
352/// value of the expression prior to the narrowing conversion.
353/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
354/// type of the expression prior to the narrowing conversion.
355/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
356/// from floating point types to integral types should be ignored.
357NarrowingKind StandardConversionSequence::getNarrowingKind(
358 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
359 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
360 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
361 "narrowing check outside C++");
362
363 // C++11 [dcl.init.list]p7:
364 // A narrowing conversion is an implicit conversion ...
365 QualType FromType = getToType(Idx: 0);
366 QualType ToType = getToType(Idx: 1);
367
368 // A conversion to an enumeration type is narrowing if the conversion to
369 // the underlying type is narrowing. This only arises for expressions of
370 // the form 'Enum{init}'.
371 if (auto *ET = ToType->getAs<EnumType>())
372 ToType = ET->getDecl()->getIntegerType();
373
374 switch (Second) {
375 // 'bool' is an integral type; dispatch to the right place to handle it.
376 case ICK_Boolean_Conversion:
377 if (FromType->isRealFloatingType())
378 goto FloatingIntegralConversion;
379 if (FromType->isIntegralOrUnscopedEnumerationType())
380 goto IntegralConversion;
381 // -- from a pointer type or pointer-to-member type to bool, or
382 return NK_Type_Narrowing;
383
384 // -- from a floating-point type to an integer type, or
385 //
386 // -- from an integer type or unscoped enumeration type to a floating-point
387 // type, except where the source is a constant expression and the actual
388 // value after conversion will fit into the target type and will produce
389 // the original value when converted back to the original type, or
390 case ICK_Floating_Integral:
391 FloatingIntegralConversion:
392 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
393 return NK_Type_Narrowing;
394 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
395 ToType->isRealFloatingType()) {
396 if (IgnoreFloatToIntegralConversion)
397 return NK_Not_Narrowing;
398 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
399 assert(Initializer && "Unknown conversion expression");
400
401 // If it's value-dependent, we can't tell whether it's narrowing.
402 if (Initializer->isValueDependent())
403 return NK_Dependent_Narrowing;
404
405 if (std::optional<llvm::APSInt> IntConstantValue =
406 Initializer->getIntegerConstantExpr(Ctx)) {
407 // Convert the integer to the floating type.
408 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
409 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
410 RM: llvm::APFloat::rmNearestTiesToEven);
411 // And back.
412 llvm::APSInt ConvertedValue = *IntConstantValue;
413 bool ignored;
414 Result.convertToInteger(Result&: ConvertedValue,
415 RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
416 // If the resulting value is different, this was a narrowing conversion.
417 if (*IntConstantValue != ConvertedValue) {
418 ConstantValue = APValue(*IntConstantValue);
419 ConstantType = Initializer->getType();
420 return NK_Constant_Narrowing;
421 }
422 } else {
423 // Variables are always narrowings.
424 return NK_Variable_Narrowing;
425 }
426 }
427 return NK_Not_Narrowing;
428
429 // -- from long double to double or float, or from double to float, except
430 // where the source is a constant expression and the actual value after
431 // conversion is within the range of values that can be represented (even
432 // if it cannot be represented exactly), or
433 case ICK_Floating_Conversion:
434 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
435 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
436 // FromType is larger than ToType.
437 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
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 Expr::EvalResult R;
444 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
445 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)) {
446 // Constant!
447 if (Ctx.getLangOpts().C23)
448 ConstantValue = R.Val;
449 assert(ConstantValue.isFloat());
450 llvm::APFloat FloatVal = ConstantValue.getFloat();
451 // Convert the source value into the target type.
452 bool ignored;
453 llvm::APFloat Converted = FloatVal;
454 llvm::APFloat::opStatus ConvertStatus =
455 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
456 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
457 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
458 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
459 if (Ctx.getLangOpts().C23) {
460 if (FloatVal.isNaN() && Converted.isNaN() &&
461 !FloatVal.isSignaling() && !Converted.isSignaling()) {
462 // Quiet NaNs are considered the same value, regardless of
463 // payloads.
464 return NK_Not_Narrowing;
465 }
466 // For normal values, check exact equality.
467 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
468 ConstantType = Initializer->getType();
469 return NK_Constant_Narrowing;
470 }
471 } else {
472 // If there was no overflow, the source value is within the range of
473 // values that can be represented.
474 if (ConvertStatus & llvm::APFloat::opOverflow) {
475 ConstantType = Initializer->getType();
476 return NK_Constant_Narrowing;
477 }
478 }
479 } else {
480 return NK_Variable_Narrowing;
481 }
482 }
483 return NK_Not_Narrowing;
484
485 // -- from an integer type or unscoped enumeration type to an integer type
486 // that cannot represent all the values of the original type, except where
487 // (CWG2627) -- the source is a bit-field whose width w is less than that
488 // of its type (or, for an enumeration type, its underlying type) and the
489 // target type can represent all the values of a hypothetical extended
490 // integer type with width w and with the same signedness as the original
491 // type or
492 // -- the source is a constant expression and the actual value after
493 // conversion will fit into the target type and will produce the original
494 // value when converted back to the original type.
495 case ICK_Integral_Conversion:
496 IntegralConversion: {
497 assert(FromType->isIntegralOrUnscopedEnumerationType());
498 assert(ToType->isIntegralOrUnscopedEnumerationType());
499 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
500 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
501 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
502 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
503
504 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
505 bool ToSigned, unsigned ToWidth) {
506 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
507 !(FromSigned && !ToSigned);
508 };
509
510 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
511 return NK_Not_Narrowing;
512
513 // Not all values of FromType can be represented in ToType.
514 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
515
516 bool DependentBitField = false;
517 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
518 if (BitField->getBitWidth()->isValueDependent())
519 DependentBitField = true;
520 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
521 BitFieldWidth < FromWidth) {
522 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
523 return NK_Not_Narrowing;
524
525 // The initializer will be truncated to the bit-field width
526 FromWidth = BitFieldWidth;
527 }
528 }
529
530 // If it's value-dependent, we can't tell whether it's narrowing.
531 if (Initializer->isValueDependent())
532 return NK_Dependent_Narrowing;
533
534 std::optional<llvm::APSInt> OptInitializerValue =
535 Initializer->getIntegerConstantExpr(Ctx);
536 if (!OptInitializerValue) {
537 // If the bit-field width was dependent, it might end up being small
538 // enough to fit in the target type (unless the target type is unsigned
539 // and the source type is signed, in which case it will never fit)
540 if (DependentBitField && !(FromSigned && !ToSigned))
541 return NK_Dependent_Narrowing;
542
543 // Otherwise, such a conversion is always narrowing
544 return NK_Variable_Narrowing;
545 }
546 llvm::APSInt &InitializerValue = *OptInitializerValue;
547 bool Narrowing = false;
548 if (FromWidth < ToWidth) {
549 // Negative -> unsigned is narrowing. Otherwise, more bits is never
550 // narrowing.
551 if (InitializerValue.isSigned() && InitializerValue.isNegative())
552 Narrowing = true;
553 } else {
554 // Add a bit to the InitializerValue so we don't have to worry about
555 // signed vs. unsigned comparisons.
556 InitializerValue =
557 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
558 // Convert the initializer to and from the target width and signed-ness.
559 llvm::APSInt ConvertedValue = InitializerValue;
560 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
561 ConvertedValue.setIsSigned(ToSigned);
562 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
563 ConvertedValue.setIsSigned(InitializerValue.isSigned());
564 // If the result is different, this was a narrowing conversion.
565 if (ConvertedValue != InitializerValue)
566 Narrowing = true;
567 }
568 if (Narrowing) {
569 ConstantType = Initializer->getType();
570 ConstantValue = APValue(InitializerValue);
571 return NK_Constant_Narrowing;
572 }
573
574 return NK_Not_Narrowing;
575 }
576 case ICK_Complex_Real:
577 if (FromType->isComplexType() && !ToType->isComplexType())
578 return NK_Type_Narrowing;
579 return NK_Not_Narrowing;
580
581 case ICK_Floating_Promotion:
582 if (Ctx.getLangOpts().C23) {
583 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
584 Expr::EvalResult R;
585 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
586 ConstantValue = R.Val;
587 assert(ConstantValue.isFloat());
588 llvm::APFloat FloatVal = ConstantValue.getFloat();
589 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
590 // value, the unqualified versions of the type of the initializer and
591 // the corresponding real type of the object declared shall be
592 // compatible.
593 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
594 ConstantType = Initializer->getType();
595 return NK_Constant_Narrowing;
596 }
597 }
598 }
599 return NK_Not_Narrowing;
600 default:
601 // Other kinds of conversions are not narrowings.
602 return NK_Not_Narrowing;
603 }
604}
605
606/// dump - Print this standard conversion sequence to standard
607/// error. Useful for debugging overloading issues.
608LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
609 raw_ostream &OS = llvm::errs();
610 bool PrintedSomething = false;
611 if (First != ICK_Identity) {
612 OS << GetImplicitConversionName(Kind: First);
613 PrintedSomething = true;
614 }
615
616 if (Second != ICK_Identity) {
617 if (PrintedSomething) {
618 OS << " -> ";
619 }
620 OS << GetImplicitConversionName(Kind: Second);
621
622 if (CopyConstructor) {
623 OS << " (by copy constructor)";
624 } else if (DirectBinding) {
625 OS << " (direct reference binding)";
626 } else if (ReferenceBinding) {
627 OS << " (reference binding)";
628 }
629 PrintedSomething = true;
630 }
631
632 if (Third != ICK_Identity) {
633 if (PrintedSomething) {
634 OS << " -> ";
635 }
636 OS << GetImplicitConversionName(Kind: Third);
637 PrintedSomething = true;
638 }
639
640 if (!PrintedSomething) {
641 OS << "No conversions required";
642 }
643}
644
645/// dump - Print this user-defined conversion sequence to standard
646/// error. Useful for debugging overloading issues.
647void UserDefinedConversionSequence::dump() const {
648 raw_ostream &OS = llvm::errs();
649 if (Before.First || Before.Second || Before.Third) {
650 Before.dump();
651 OS << " -> ";
652 }
653 if (ConversionFunction)
654 OS << '\'' << *ConversionFunction << '\'';
655 else
656 OS << "aggregate initialization";
657 if (After.First || After.Second || After.Third) {
658 OS << " -> ";
659 After.dump();
660 }
661}
662
663/// dump - Print this implicit conversion sequence to standard
664/// error. Useful for debugging overloading issues.
665void ImplicitConversionSequence::dump() const {
666 raw_ostream &OS = llvm::errs();
667 if (hasInitializerListContainerType())
668 OS << "Worst list element conversion: ";
669 switch (ConversionKind) {
670 case StandardConversion:
671 OS << "Standard conversion: ";
672 Standard.dump();
673 break;
674 case UserDefinedConversion:
675 OS << "User-defined conversion: ";
676 UserDefined.dump();
677 break;
678 case EllipsisConversion:
679 OS << "Ellipsis conversion";
680 break;
681 case AmbiguousConversion:
682 OS << "Ambiguous conversion";
683 break;
684 case BadConversion:
685 OS << "Bad conversion";
686 break;
687 }
688
689 OS << "\n";
690}
691
692void AmbiguousConversionSequence::construct() {
693 new (&conversions()) ConversionSet();
694}
695
696void AmbiguousConversionSequence::destruct() {
697 conversions().~ConversionSet();
698}
699
700void
701AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
702 FromTypePtr = O.FromTypePtr;
703 ToTypePtr = O.ToTypePtr;
704 new (&conversions()) ConversionSet(O.conversions());
705}
706
707namespace {
708 // Structure used by DeductionFailureInfo to store
709 // template argument information.
710 struct DFIArguments {
711 TemplateArgument FirstArg;
712 TemplateArgument SecondArg;
713 };
714 // Structure used by DeductionFailureInfo to store
715 // template parameter and template argument information.
716 struct DFIParamWithArguments : DFIArguments {
717 TemplateParameter Param;
718 };
719 // Structure used by DeductionFailureInfo to store template argument
720 // information and the index of the problematic call argument.
721 struct DFIDeducedMismatchArgs : DFIArguments {
722 TemplateArgumentList *TemplateArgs;
723 unsigned CallArgIndex;
724 };
725 // Structure used by DeductionFailureInfo to store information about
726 // unsatisfied constraints.
727 struct CNSInfo {
728 TemplateArgumentList *TemplateArgs;
729 ConstraintSatisfaction Satisfaction;
730 };
731}
732
733/// Convert from Sema's representation of template deduction information
734/// to the form used in overload-candidate information.
735DeductionFailureInfo
736clang::MakeDeductionFailureInfo(ASTContext &Context,
737 TemplateDeductionResult TDK,
738 TemplateDeductionInfo &Info) {
739 DeductionFailureInfo Result;
740 Result.Result = static_cast<unsigned>(TDK);
741 Result.HasDiagnostic = false;
742 switch (TDK) {
743 case TemplateDeductionResult::Invalid:
744 case TemplateDeductionResult::InstantiationDepth:
745 case TemplateDeductionResult::TooManyArguments:
746 case TemplateDeductionResult::TooFewArguments:
747 case TemplateDeductionResult::MiscellaneousDeductionFailure:
748 case TemplateDeductionResult::CUDATargetMismatch:
749 Result.Data = nullptr;
750 break;
751
752 case TemplateDeductionResult::Incomplete:
753 case TemplateDeductionResult::InvalidExplicitArguments:
754 Result.Data = Info.Param.getOpaqueValue();
755 break;
756
757 case TemplateDeductionResult::DeducedMismatch:
758 case TemplateDeductionResult::DeducedMismatchNested: {
759 // FIXME: Should allocate from normal heap so that we can free this later.
760 auto *Saved = new (Context) DFIDeducedMismatchArgs;
761 Saved->FirstArg = Info.FirstArg;
762 Saved->SecondArg = Info.SecondArg;
763 Saved->TemplateArgs = Info.takeSugared();
764 Saved->CallArgIndex = Info.CallArgIndex;
765 Result.Data = Saved;
766 break;
767 }
768
769 case TemplateDeductionResult::NonDeducedMismatch: {
770 // FIXME: Should allocate from normal heap so that we can free this later.
771 DFIArguments *Saved = new (Context) DFIArguments;
772 Saved->FirstArg = Info.FirstArg;
773 Saved->SecondArg = Info.SecondArg;
774 Result.Data = Saved;
775 break;
776 }
777
778 case TemplateDeductionResult::IncompletePack:
779 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
780 case TemplateDeductionResult::Inconsistent:
781 case TemplateDeductionResult::Underqualified: {
782 // FIXME: Should allocate from normal heap so that we can free this later.
783 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
784 Saved->Param = Info.Param;
785 Saved->FirstArg = Info.FirstArg;
786 Saved->SecondArg = Info.SecondArg;
787 Result.Data = Saved;
788 break;
789 }
790
791 case TemplateDeductionResult::SubstitutionFailure:
792 Result.Data = Info.takeSugared();
793 if (Info.hasSFINAEDiagnostic()) {
794 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
795 SourceLocation(), PartialDiagnostic::NullDiagnostic());
796 Info.takeSFINAEDiagnostic(PD&: *Diag);
797 Result.HasDiagnostic = true;
798 }
799 break;
800
801 case TemplateDeductionResult::ConstraintsNotSatisfied: {
802 CNSInfo *Saved = new (Context) CNSInfo;
803 Saved->TemplateArgs = Info.takeSugared();
804 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
805 Result.Data = Saved;
806 break;
807 }
808
809 case TemplateDeductionResult::Success:
810 case TemplateDeductionResult::NonDependentConversionFailure:
811 case TemplateDeductionResult::AlreadyDiagnosed:
812 llvm_unreachable("not a deduction failure");
813 }
814
815 return Result;
816}
817
818void DeductionFailureInfo::Destroy() {
819 switch (static_cast<TemplateDeductionResult>(Result)) {
820 case TemplateDeductionResult::Success:
821 case TemplateDeductionResult::Invalid:
822 case TemplateDeductionResult::InstantiationDepth:
823 case TemplateDeductionResult::Incomplete:
824 case TemplateDeductionResult::TooManyArguments:
825 case TemplateDeductionResult::TooFewArguments:
826 case TemplateDeductionResult::InvalidExplicitArguments:
827 case TemplateDeductionResult::CUDATargetMismatch:
828 case TemplateDeductionResult::NonDependentConversionFailure:
829 break;
830
831 case TemplateDeductionResult::IncompletePack:
832 case TemplateDeductionResult::Inconsistent:
833 case TemplateDeductionResult::Underqualified:
834 case TemplateDeductionResult::DeducedMismatch:
835 case TemplateDeductionResult::DeducedMismatchNested:
836 case TemplateDeductionResult::NonDeducedMismatch:
837 // FIXME: Destroy the data?
838 Data = nullptr;
839 break;
840
841 case TemplateDeductionResult::SubstitutionFailure:
842 // FIXME: Destroy the template argument list?
843 Data = nullptr;
844 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
845 Diag->~PartialDiagnosticAt();
846 HasDiagnostic = false;
847 }
848 break;
849
850 case TemplateDeductionResult::ConstraintsNotSatisfied:
851 // FIXME: Destroy the template argument list?
852 Data = nullptr;
853 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
854 Diag->~PartialDiagnosticAt();
855 HasDiagnostic = false;
856 }
857 break;
858
859 // Unhandled
860 case TemplateDeductionResult::MiscellaneousDeductionFailure:
861 case TemplateDeductionResult::AlreadyDiagnosed:
862 break;
863 }
864}
865
866PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
867 if (HasDiagnostic)
868 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
869 return nullptr;
870}
871
872TemplateParameter DeductionFailureInfo::getTemplateParameter() {
873 switch (static_cast<TemplateDeductionResult>(Result)) {
874 case TemplateDeductionResult::Success:
875 case TemplateDeductionResult::Invalid:
876 case TemplateDeductionResult::InstantiationDepth:
877 case TemplateDeductionResult::TooManyArguments:
878 case TemplateDeductionResult::TooFewArguments:
879 case TemplateDeductionResult::SubstitutionFailure:
880 case TemplateDeductionResult::DeducedMismatch:
881 case TemplateDeductionResult::DeducedMismatchNested:
882 case TemplateDeductionResult::NonDeducedMismatch:
883 case TemplateDeductionResult::CUDATargetMismatch:
884 case TemplateDeductionResult::NonDependentConversionFailure:
885 case TemplateDeductionResult::ConstraintsNotSatisfied:
886 return TemplateParameter();
887
888 case TemplateDeductionResult::Incomplete:
889 case TemplateDeductionResult::InvalidExplicitArguments:
890 return TemplateParameter::getFromOpaqueValue(VP: Data);
891
892 case TemplateDeductionResult::IncompletePack:
893 case TemplateDeductionResult::Inconsistent:
894 case TemplateDeductionResult::Underqualified:
895 return static_cast<DFIParamWithArguments*>(Data)->Param;
896
897 // Unhandled
898 case TemplateDeductionResult::MiscellaneousDeductionFailure:
899 case TemplateDeductionResult::AlreadyDiagnosed:
900 break;
901 }
902
903 return TemplateParameter();
904}
905
906TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
907 switch (static_cast<TemplateDeductionResult>(Result)) {
908 case TemplateDeductionResult::Success:
909 case TemplateDeductionResult::Invalid:
910 case TemplateDeductionResult::InstantiationDepth:
911 case TemplateDeductionResult::TooManyArguments:
912 case TemplateDeductionResult::TooFewArguments:
913 case TemplateDeductionResult::Incomplete:
914 case TemplateDeductionResult::IncompletePack:
915 case TemplateDeductionResult::InvalidExplicitArguments:
916 case TemplateDeductionResult::Inconsistent:
917 case TemplateDeductionResult::Underqualified:
918 case TemplateDeductionResult::NonDeducedMismatch:
919 case TemplateDeductionResult::CUDATargetMismatch:
920 case TemplateDeductionResult::NonDependentConversionFailure:
921 return nullptr;
922
923 case TemplateDeductionResult::DeducedMismatch:
924 case TemplateDeductionResult::DeducedMismatchNested:
925 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
926
927 case TemplateDeductionResult::SubstitutionFailure:
928 return static_cast<TemplateArgumentList*>(Data);
929
930 case TemplateDeductionResult::ConstraintsNotSatisfied:
931 return static_cast<CNSInfo*>(Data)->TemplateArgs;
932
933 // Unhandled
934 case TemplateDeductionResult::MiscellaneousDeductionFailure:
935 case TemplateDeductionResult::AlreadyDiagnosed:
936 break;
937 }
938
939 return nullptr;
940}
941
942const TemplateArgument *DeductionFailureInfo::getFirstArg() {
943 switch (static_cast<TemplateDeductionResult>(Result)) {
944 case TemplateDeductionResult::Success:
945 case TemplateDeductionResult::Invalid:
946 case TemplateDeductionResult::InstantiationDepth:
947 case TemplateDeductionResult::Incomplete:
948 case TemplateDeductionResult::TooManyArguments:
949 case TemplateDeductionResult::TooFewArguments:
950 case TemplateDeductionResult::InvalidExplicitArguments:
951 case TemplateDeductionResult::SubstitutionFailure:
952 case TemplateDeductionResult::CUDATargetMismatch:
953 case TemplateDeductionResult::NonDependentConversionFailure:
954 case TemplateDeductionResult::ConstraintsNotSatisfied:
955 return nullptr;
956
957 case TemplateDeductionResult::IncompletePack:
958 case TemplateDeductionResult::Inconsistent:
959 case TemplateDeductionResult::Underqualified:
960 case TemplateDeductionResult::DeducedMismatch:
961 case TemplateDeductionResult::DeducedMismatchNested:
962 case TemplateDeductionResult::NonDeducedMismatch:
963 return &static_cast<DFIArguments*>(Data)->FirstArg;
964
965 // Unhandled
966 case TemplateDeductionResult::MiscellaneousDeductionFailure:
967 case TemplateDeductionResult::AlreadyDiagnosed:
968 break;
969 }
970
971 return nullptr;
972}
973
974const TemplateArgument *DeductionFailureInfo::getSecondArg() {
975 switch (static_cast<TemplateDeductionResult>(Result)) {
976 case TemplateDeductionResult::Success:
977 case TemplateDeductionResult::Invalid:
978 case TemplateDeductionResult::InstantiationDepth:
979 case TemplateDeductionResult::Incomplete:
980 case TemplateDeductionResult::IncompletePack:
981 case TemplateDeductionResult::TooManyArguments:
982 case TemplateDeductionResult::TooFewArguments:
983 case TemplateDeductionResult::InvalidExplicitArguments:
984 case TemplateDeductionResult::SubstitutionFailure:
985 case TemplateDeductionResult::CUDATargetMismatch:
986 case TemplateDeductionResult::NonDependentConversionFailure:
987 case TemplateDeductionResult::ConstraintsNotSatisfied:
988 return nullptr;
989
990 case TemplateDeductionResult::Inconsistent:
991 case TemplateDeductionResult::Underqualified:
992 case TemplateDeductionResult::DeducedMismatch:
993 case TemplateDeductionResult::DeducedMismatchNested:
994 case TemplateDeductionResult::NonDeducedMismatch:
995 return &static_cast<DFIArguments*>(Data)->SecondArg;
996
997 // Unhandled
998 case TemplateDeductionResult::MiscellaneousDeductionFailure:
999 case TemplateDeductionResult::AlreadyDiagnosed:
1000 break;
1001 }
1002
1003 return nullptr;
1004}
1005
1006UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1007 switch (static_cast<TemplateDeductionResult>(Result)) {
1008 case TemplateDeductionResult::DeducedMismatch:
1009 case TemplateDeductionResult::DeducedMismatchNested:
1010 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1011
1012 default:
1013 return std::nullopt;
1014 }
1015}
1016
1017static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1018 const FunctionDecl *Y) {
1019 if (!X || !Y)
1020 return false;
1021 if (X->getNumParams() != Y->getNumParams())
1022 return false;
1023 // FIXME: when do rewritten comparison operators
1024 // with explicit object parameters correspond?
1025 // https://cplusplus.github.io/CWG/issues/2797.html
1026 for (unsigned I = 0; I < X->getNumParams(); ++I)
1027 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1028 T2: Y->getParamDecl(i: I)->getType()))
1029 return false;
1030 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1031 auto *FTY = Y->getDescribedFunctionTemplate();
1032 if (!FTY)
1033 return false;
1034 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1035 Y: FTY->getTemplateParameters()))
1036 return false;
1037 }
1038 return true;
1039}
1040
1041static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1042 Expr *FirstOperand, FunctionDecl *EqFD) {
1043 assert(EqFD->getOverloadedOperator() ==
1044 OverloadedOperatorKind::OO_EqualEqual);
1045 // C++2a [over.match.oper]p4:
1046 // A non-template function or function template F named operator== is a
1047 // rewrite target with first operand o unless a search for the name operator!=
1048 // in the scope S from the instantiation context of the operator expression
1049 // finds a function or function template that would correspond
1050 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1051 // scope of the class type of o if F is a class member, and the namespace
1052 // scope of which F is a member otherwise. A function template specialization
1053 // named operator== is a rewrite target if its function template is a rewrite
1054 // target.
1055 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1056 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1057 if (isa<CXXMethodDecl>(Val: EqFD)) {
1058 // If F is a class member, search scope is class type of first operand.
1059 QualType RHS = FirstOperand->getType();
1060 auto *RHSRec = RHS->getAs<RecordType>();
1061 if (!RHSRec)
1062 return true;
1063 LookupResult Members(S, NotEqOp, OpLoc,
1064 Sema::LookupNameKind::LookupMemberName);
1065 S.LookupQualifiedName(Members, RHSRec->getDecl());
1066 Members.suppressAccessDiagnostics();
1067 for (NamedDecl *Op : Members)
1068 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1069 return false;
1070 return true;
1071 }
1072 // Otherwise the search scope is the namespace scope of which F is a member.
1073 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1074 auto *NotEqFD = Op->getAsFunction();
1075 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1076 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1077 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1078 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
1079 cast<Decl>(Op->getLexicalDeclContext())))
1080 return false;
1081 }
1082 return true;
1083}
1084
1085bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1086 OverloadedOperatorKind Op) {
1087 if (!AllowRewrittenCandidates)
1088 return false;
1089 return Op == OO_EqualEqual || Op == OO_Spaceship;
1090}
1091
1092bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1093 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1094 auto Op = FD->getOverloadedOperator();
1095 if (!allowsReversed(Op))
1096 return false;
1097 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1098 assert(OriginalArgs.size() == 2);
1099 if (!shouldAddReversedEqEq(
1100 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1101 return false;
1102 }
1103 // Don't bother adding a reversed candidate that can never be a better
1104 // match than the non-reversed version.
1105 return FD->getNumNonObjectParams() != 2 ||
1106 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
1107 FD->getParamDecl(1)->getType()) ||
1108 FD->hasAttr<EnableIfAttr>();
1109}
1110
1111void OverloadCandidateSet::destroyCandidates() {
1112 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1113 for (auto &C : i->Conversions)
1114 C.~ImplicitConversionSequence();
1115 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1116 i->DeductionFailure.Destroy();
1117 }
1118}
1119
1120void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1121 destroyCandidates();
1122 SlabAllocator.Reset();
1123 NumInlineBytesUsed = 0;
1124 Candidates.clear();
1125 Functions.clear();
1126 Kind = CSK;
1127 FirstDeferredCandidate = nullptr;
1128 DeferredCandidatesCount = 0;
1129 HasDeferredTemplateConstructors = false;
1130 ResolutionByPerfectCandidateIsDisabled = false;
1131}
1132
1133namespace {
1134 class UnbridgedCastsSet {
1135 struct Entry {
1136 Expr **Addr;
1137 Expr *Saved;
1138 };
1139 SmallVector<Entry, 2> Entries;
1140
1141 public:
1142 void save(Sema &S, Expr *&E) {
1143 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1144 Entry entry = { .Addr: &E, .Saved: E };
1145 Entries.push_back(Elt: entry);
1146 E = S.ObjC().stripARCUnbridgedCast(e: E);
1147 }
1148
1149 void restore() {
1150 for (SmallVectorImpl<Entry>::iterator
1151 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1152 *i->Addr = i->Saved;
1153 }
1154 };
1155}
1156
1157/// checkPlaceholderForOverload - Do any interesting placeholder-like
1158/// preprocessing on the given expression.
1159///
1160/// \param unbridgedCasts a collection to which to add unbridged casts;
1161/// without this, they will be immediately diagnosed as errors
1162///
1163/// Return true on unrecoverable error.
1164static bool
1165checkPlaceholderForOverload(Sema &S, Expr *&E,
1166 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1167 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1168 // We can't handle overloaded expressions here because overload
1169 // resolution might reasonably tweak them.
1170 if (placeholder->getKind() == BuiltinType::Overload) return false;
1171
1172 // If the context potentially accepts unbridged ARC casts, strip
1173 // the unbridged cast and add it to the collection for later restoration.
1174 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1175 unbridgedCasts) {
1176 unbridgedCasts->save(S, E);
1177 return false;
1178 }
1179
1180 // Go ahead and check everything else.
1181 ExprResult result = S.CheckPlaceholderExpr(E);
1182 if (result.isInvalid())
1183 return true;
1184
1185 E = result.get();
1186 return false;
1187 }
1188
1189 // Nothing to do.
1190 return false;
1191}
1192
1193/// checkArgPlaceholdersForOverload - Check a set of call operands for
1194/// placeholders.
1195static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1196 UnbridgedCastsSet &unbridged) {
1197 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1198 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1199 return true;
1200
1201 return false;
1202}
1203
1204OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1205 const LookupResult &Old, NamedDecl *&Match,
1206 bool NewIsUsingDecl) {
1207 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1208 I != E; ++I) {
1209 NamedDecl *OldD = *I;
1210
1211 bool OldIsUsingDecl = false;
1212 if (isa<UsingShadowDecl>(Val: OldD)) {
1213 OldIsUsingDecl = true;
1214
1215 // We can always introduce two using declarations into the same
1216 // context, even if they have identical signatures.
1217 if (NewIsUsingDecl) continue;
1218
1219 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1220 }
1221
1222 // A using-declaration does not conflict with another declaration
1223 // if one of them is hidden.
1224 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1225 continue;
1226
1227 // If either declaration was introduced by a using declaration,
1228 // we'll need to use slightly different rules for matching.
1229 // Essentially, these rules are the normal rules, except that
1230 // function templates hide function templates with different
1231 // return types or template parameter lists.
1232 bool UseMemberUsingDeclRules =
1233 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1234 !New->getFriendObjectKind();
1235
1236 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1237 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1238 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1239 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1240 continue;
1241 }
1242
1243 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1244 !shouldLinkPossiblyHiddenDecl(*I, New))
1245 continue;
1246
1247 Match = *I;
1248 return OverloadKind::Match;
1249 }
1250
1251 // Builtins that have custom typechecking or have a reference should
1252 // not be overloadable or redeclarable.
1253 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1254 Match = *I;
1255 return OverloadKind::NonFunction;
1256 }
1257 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1258 // We can overload with these, which can show up when doing
1259 // redeclaration checks for UsingDecls.
1260 assert(Old.getLookupKind() == LookupUsingDeclName);
1261 } else if (isa<TagDecl>(Val: OldD)) {
1262 // We can always overload with tags by hiding them.
1263 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1264 // Optimistically assume that an unresolved using decl will
1265 // overload; if it doesn't, we'll have to diagnose during
1266 // template instantiation.
1267 //
1268 // Exception: if the scope is dependent and this is not a class
1269 // member, the using declaration can only introduce an enumerator.
1270 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1271 Match = *I;
1272 return OverloadKind::NonFunction;
1273 }
1274 } else {
1275 // (C++ 13p1):
1276 // Only function declarations can be overloaded; object and type
1277 // declarations cannot be overloaded.
1278 Match = *I;
1279 return OverloadKind::NonFunction;
1280 }
1281 }
1282
1283 // C++ [temp.friend]p1:
1284 // For a friend function declaration that is not a template declaration:
1285 // -- if the name of the friend is a qualified or unqualified template-id,
1286 // [...], otherwise
1287 // -- if the name of the friend is a qualified-id and a matching
1288 // non-template function is found in the specified class or namespace,
1289 // the friend declaration refers to that function, otherwise,
1290 // -- if the name of the friend is a qualified-id and a matching function
1291 // template is found in the specified class or namespace, the friend
1292 // declaration refers to the deduced specialization of that function
1293 // template, otherwise
1294 // -- the name shall be an unqualified-id [...]
1295 // If we get here for a qualified friend declaration, we've just reached the
1296 // third bullet. If the type of the friend is dependent, skip this lookup
1297 // until instantiation.
1298 if (New->getFriendObjectKind() && New->getQualifier() &&
1299 !New->getDescribedFunctionTemplate() &&
1300 !New->getDependentSpecializationInfo() &&
1301 !New->getType()->isDependentType()) {
1302 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1303 TemplateSpecResult.addAllDecls(Other: Old);
1304 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1305 /*QualifiedFriend*/true)) {
1306 New->setInvalidDecl();
1307 return OverloadKind::Overload;
1308 }
1309
1310 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1311 return OverloadKind::Match;
1312 }
1313
1314 return OverloadKind::Overload;
1315}
1316
1317template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1318 assert(D && "function decl should not be null");
1319 if (auto *A = D->getAttr<AttrT>())
1320 return !A->isImplicit();
1321 return false;
1322}
1323
1324static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1325 FunctionDecl *Old,
1326 bool UseMemberUsingDeclRules,
1327 bool ConsiderCudaAttrs,
1328 bool UseOverrideRules = false) {
1329 // C++ [basic.start.main]p2: This function shall not be overloaded.
1330 if (New->isMain())
1331 return false;
1332
1333 // MSVCRT user defined entry points cannot be overloaded.
1334 if (New->isMSVCRTEntryPoint())
1335 return false;
1336
1337 NamedDecl *OldDecl = Old;
1338 NamedDecl *NewDecl = New;
1339 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1340 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1341
1342 // C++ [temp.fct]p2:
1343 // A function template can be overloaded with other function templates
1344 // and with normal (non-template) functions.
1345 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1346 return true;
1347
1348 // Is the function New an overload of the function Old?
1349 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1350 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1351
1352 // Compare the signatures (C++ 1.3.10) of the two functions to
1353 // determine whether they are overloads. If we find any mismatch
1354 // in the signature, they are overloads.
1355
1356 // If either of these functions is a K&R-style function (no
1357 // prototype), then we consider them to have matching signatures.
1358 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1359 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1360 return false;
1361
1362 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1363 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1364
1365 // The signature of a function includes the types of its
1366 // parameters (C++ 1.3.10), which includes the presence or absence
1367 // of the ellipsis; see C++ DR 357).
1368 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1369 return true;
1370
1371 // For member-like friends, the enclosing class is part of the signature.
1372 if ((New->isMemberLikeConstrainedFriend() ||
1373 Old->isMemberLikeConstrainedFriend()) &&
1374 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1375 return true;
1376
1377 // Compare the parameter lists.
1378 // This can only be done once we have establish that friend functions
1379 // inhabit the same context, otherwise we might tried to instantiate
1380 // references to non-instantiated entities during constraint substitution.
1381 // GH78101.
1382 if (NewTemplate) {
1383 OldDecl = OldTemplate;
1384 NewDecl = NewTemplate;
1385 // C++ [temp.over.link]p4:
1386 // The signature of a function template consists of its function
1387 // signature, its return type and its template parameter list. The names
1388 // of the template parameters are significant only for establishing the
1389 // relationship between the template parameters and the rest of the
1390 // signature.
1391 //
1392 // We check the return type and template parameter lists for function
1393 // templates first; the remaining checks follow.
1394 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1395 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1396 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1397 bool SameReturnType = SemaRef.Context.hasSameType(
1398 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1399 // FIXME(GH58571): Match template parameter list even for non-constrained
1400 // template heads. This currently ensures that the code prior to C++20 is
1401 // not newly broken.
1402 bool ConstraintsInTemplateHead =
1403 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1404 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1405 // C++ [namespace.udecl]p11:
1406 // The set of declarations named by a using-declarator that inhabits a
1407 // class C does not include member functions and member function
1408 // templates of a base class that "correspond" to (and thus would
1409 // conflict with) a declaration of a function or function template in
1410 // C.
1411 // Comparing return types is not required for the "correspond" check to
1412 // decide whether a member introduced by a shadow declaration is hidden.
1413 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1414 !SameTemplateParameterList)
1415 return true;
1416 if (!UseMemberUsingDeclRules &&
1417 (!SameTemplateParameterList || !SameReturnType))
1418 return true;
1419 }
1420
1421 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1422 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1423
1424 int OldParamsOffset = 0;
1425 int NewParamsOffset = 0;
1426
1427 // When determining if a method is an overload from a base class, act as if
1428 // the implicit object parameter are of the same type.
1429
1430 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1431 if (M->isExplicitObjectMemberFunction()) {
1432 auto ThisType = M->getFunctionObjectParameterReferenceType();
1433 if (ThisType.isConstQualified())
1434 Q.removeConst();
1435 return Q;
1436 }
1437
1438 // We do not allow overloading based off of '__restrict'.
1439 Q.removeRestrict();
1440
1441 // We may not have applied the implicit const for a constexpr member
1442 // function yet (because we haven't yet resolved whether this is a static
1443 // or non-static member function). Add it now, on the assumption that this
1444 // is a redeclaration of OldMethod.
1445 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1446 (M->isConstexpr() || M->isConsteval()) &&
1447 !isa<CXXConstructorDecl>(Val: NewMethod))
1448 Q.addConst();
1449 return Q;
1450 };
1451
1452 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1453 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1454 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1455
1456 if (OldMethod->isExplicitObjectMemberFunction()) {
1457 BS.Quals.removeVolatile();
1458 DS.Quals.removeVolatile();
1459 }
1460
1461 return BS.Quals == DS.Quals;
1462 };
1463
1464 auto CompareType = [&](QualType Base, QualType D) {
1465 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1466 auto DS = D.getNonReferenceType().getCanonicalType().split();
1467
1468 if (!AreQualifiersEqual(BS, DS))
1469 return false;
1470
1471 if (OldMethod->isImplicitObjectMemberFunction() &&
1472 OldMethod->getParent() != NewMethod->getParent()) {
1473 QualType ParentType =
1474 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1475 .getCanonicalType();
1476 if (ParentType.getTypePtr() != BS.Ty)
1477 return false;
1478 BS.Ty = DS.Ty;
1479 }
1480
1481 // FIXME: should we ignore some type attributes here?
1482 if (BS.Ty != DS.Ty)
1483 return false;
1484
1485 if (Base->isLValueReferenceType())
1486 return D->isLValueReferenceType();
1487 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1488 };
1489
1490 // If the function is a class member, its signature includes the
1491 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1492 auto DiagnoseInconsistentRefQualifiers = [&]() {
1493 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1494 return false;
1495 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1496 return false;
1497 if (OldMethod->isExplicitObjectMemberFunction() ||
1498 NewMethod->isExplicitObjectMemberFunction())
1499 return false;
1500 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1501 NewMethod->getRefQualifier() == RQ_None)) {
1502 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1503 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1504 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1505 return true;
1506 }
1507 return false;
1508 };
1509
1510 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1511 OldParamsOffset++;
1512 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1513 NewParamsOffset++;
1514
1515 if (OldType->getNumParams() - OldParamsOffset !=
1516 NewType->getNumParams() - NewParamsOffset ||
1517 !SemaRef.FunctionParamTypesAreEqual(
1518 {OldType->param_type_begin() + OldParamsOffset,
1519 OldType->param_type_end()},
1520 {NewType->param_type_begin() + NewParamsOffset,
1521 NewType->param_type_end()},
1522 nullptr)) {
1523 return true;
1524 }
1525
1526 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1527 !NewMethod->isStatic()) {
1528 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1529 const CXXMethodDecl *New) {
1530 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1531 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1532
1533 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1534 return F->getRefQualifier() == RQ_None &&
1535 !F->isExplicitObjectMemberFunction();
1536 };
1537
1538 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1539 CompareType(OldObjectType.getNonReferenceType(),
1540 NewObjectType.getNonReferenceType()))
1541 return true;
1542 return CompareType(OldObjectType, NewObjectType);
1543 }(OldMethod, NewMethod);
1544
1545 if (!HaveCorrespondingObjectParameters) {
1546 if (DiagnoseInconsistentRefQualifiers())
1547 return true;
1548 // CWG2554
1549 // and, if at least one is an explicit object member function, ignoring
1550 // object parameters
1551 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1552 !OldMethod->isExplicitObjectMemberFunction()))
1553 return true;
1554 }
1555 }
1556
1557 if (!UseOverrideRules &&
1558 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1559 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1560 OldRC = Old->getTrailingRequiresClause();
1561 if (!NewRC != !OldRC)
1562 return true;
1563 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1564 return true;
1565 if (NewRC &&
1566 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1567 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1568 return true;
1569 }
1570
1571 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1572 NewMethod->isImplicitObjectMemberFunction()) {
1573 if (DiagnoseInconsistentRefQualifiers())
1574 return true;
1575 }
1576
1577 // Though pass_object_size is placed on parameters and takes an argument, we
1578 // consider it to be a function-level modifier for the sake of function
1579 // identity. Either the function has one or more parameters with
1580 // pass_object_size or it doesn't.
1581 if (functionHasPassObjectSizeParams(FD: New) !=
1582 functionHasPassObjectSizeParams(FD: Old))
1583 return true;
1584
1585 // enable_if attributes are an order-sensitive part of the signature.
1586 for (specific_attr_iterator<EnableIfAttr>
1587 NewI = New->specific_attr_begin<EnableIfAttr>(),
1588 NewE = New->specific_attr_end<EnableIfAttr>(),
1589 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1590 OldE = Old->specific_attr_end<EnableIfAttr>();
1591 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1592 if (NewI == NewE || OldI == OldE)
1593 return true;
1594 llvm::FoldingSetNodeID NewID, OldID;
1595 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1596 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1597 if (NewID != OldID)
1598 return true;
1599 }
1600
1601 // At this point, it is known that the two functions have the same signature.
1602 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1603 // Don't allow overloading of destructors. (In theory we could, but it
1604 // would be a giant change to clang.)
1605 if (!isa<CXXDestructorDecl>(New)) {
1606 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1607 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1608 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1609 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1610 "Unexpected invalid target.");
1611
1612 // Allow overloading of functions with same signature and different CUDA
1613 // target attributes.
1614 if (NewTarget != OldTarget) {
1615 // Special case: non-constexpr function is allowed to override
1616 // constexpr virtual function
1617 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1618 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1619 !hasExplicitAttr<CUDAHostAttr>(Old) &&
1620 !hasExplicitAttr<CUDADeviceAttr>(Old) &&
1621 !hasExplicitAttr<CUDAHostAttr>(New) &&
1622 !hasExplicitAttr<CUDADeviceAttr>(New)) {
1623 return false;
1624 }
1625 return true;
1626 }
1627 }
1628 }
1629 }
1630
1631 // The signatures match; this is not an overload.
1632 return false;
1633}
1634
1635bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1636 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1637 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1638 ConsiderCudaAttrs);
1639}
1640
1641bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1642 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1643 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1644 /*UseMemberUsingDeclRules=*/false,
1645 /*ConsiderCudaAttrs=*/true,
1646 /*UseOverrideRules=*/true);
1647}
1648
1649/// Tries a user-defined conversion from From to ToType.
1650///
1651/// Produces an implicit conversion sequence for when a standard conversion
1652/// is not an option. See TryImplicitConversion for more information.
1653static ImplicitConversionSequence
1654TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1655 bool SuppressUserConversions,
1656 AllowedExplicit AllowExplicit,
1657 bool InOverloadResolution,
1658 bool CStyle,
1659 bool AllowObjCWritebackConversion,
1660 bool AllowObjCConversionOnExplicit) {
1661 ImplicitConversionSequence ICS;
1662
1663 if (SuppressUserConversions) {
1664 // We're not in the case above, so there is no conversion that
1665 // we can perform.
1666 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1667 return ICS;
1668 }
1669
1670 // Attempt user-defined conversion.
1671 OverloadCandidateSet Conversions(From->getExprLoc(),
1672 OverloadCandidateSet::CSK_Normal);
1673 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1674 Conversions, AllowExplicit,
1675 AllowObjCConversionOnExplicit)) {
1676 case OR_Success:
1677 case OR_Deleted:
1678 ICS.setUserDefined();
1679 // C++ [over.ics.user]p4:
1680 // A conversion of an expression of class type to the same class
1681 // type is given Exact Match rank, and a conversion of an
1682 // expression of class type to a base class of that type is
1683 // given Conversion rank, in spite of the fact that a copy
1684 // constructor (i.e., a user-defined conversion function) is
1685 // called for those cases.
1686 if (CXXConstructorDecl *Constructor
1687 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1688 QualType FromType;
1689 SourceLocation FromLoc;
1690 // C++11 [over.ics.list]p6, per DR2137:
1691 // C++17 [over.ics.list]p6:
1692 // If C is not an initializer-list constructor and the initializer list
1693 // has a single element of type cv U, where U is X or a class derived
1694 // from X, the implicit conversion sequence has Exact Match rank if U is
1695 // X, or Conversion rank if U is derived from X.
1696 bool FromListInit = false;
1697 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1698 InitList && InitList->getNumInits() == 1 &&
1699 !S.isInitListConstructor(Constructor)) {
1700 const Expr *SingleInit = InitList->getInit(Init: 0);
1701 FromType = SingleInit->getType();
1702 FromLoc = SingleInit->getBeginLoc();
1703 FromListInit = true;
1704 } else {
1705 FromType = From->getType();
1706 FromLoc = From->getBeginLoc();
1707 }
1708 QualType FromCanon =
1709 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1710 QualType ToCanon
1711 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1712 if ((FromCanon == ToCanon ||
1713 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1714 // Turn this into a "standard" conversion sequence, so that it
1715 // gets ranked with standard conversion sequences.
1716 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1717 ICS.setStandard();
1718 ICS.Standard.setAsIdentityConversion();
1719 ICS.Standard.setFromType(FromType);
1720 ICS.Standard.setAllToTypes(ToType);
1721 ICS.Standard.FromBracedInitList = FromListInit;
1722 ICS.Standard.CopyConstructor = Constructor;
1723 ICS.Standard.FoundCopyConstructor = Found;
1724 if (ToCanon != FromCanon)
1725 ICS.Standard.Second = ICK_Derived_To_Base;
1726 }
1727 }
1728 break;
1729
1730 case OR_Ambiguous:
1731 ICS.setAmbiguous();
1732 ICS.Ambiguous.setFromType(From->getType());
1733 ICS.Ambiguous.setToType(ToType);
1734 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1735 Cand != Conversions.end(); ++Cand)
1736 if (Cand->Best)
1737 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1738 break;
1739
1740 // Fall through.
1741 case OR_No_Viable_Function:
1742 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1743 break;
1744 }
1745
1746 return ICS;
1747}
1748
1749/// TryImplicitConversion - Attempt to perform an implicit conversion
1750/// from the given expression (Expr) to the given type (ToType). This
1751/// function returns an implicit conversion sequence that can be used
1752/// to perform the initialization. Given
1753///
1754/// void f(float f);
1755/// void g(int i) { f(i); }
1756///
1757/// this routine would produce an implicit conversion sequence to
1758/// describe the initialization of f from i, which will be a standard
1759/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1760/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1761//
1762/// Note that this routine only determines how the conversion can be
1763/// performed; it does not actually perform the conversion. As such,
1764/// it will not produce any diagnostics if no conversion is available,
1765/// but will instead return an implicit conversion sequence of kind
1766/// "BadConversion".
1767///
1768/// If @p SuppressUserConversions, then user-defined conversions are
1769/// not permitted.
1770/// If @p AllowExplicit, then explicit user-defined conversions are
1771/// permitted.
1772///
1773/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1774/// writeback conversion, which allows __autoreleasing id* parameters to
1775/// be initialized with __strong id* or __weak id* arguments.
1776static ImplicitConversionSequence
1777TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1778 bool SuppressUserConversions,
1779 AllowedExplicit AllowExplicit,
1780 bool InOverloadResolution,
1781 bool CStyle,
1782 bool AllowObjCWritebackConversion,
1783 bool AllowObjCConversionOnExplicit) {
1784 ImplicitConversionSequence ICS;
1785 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1786 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1787 ICS.setStandard();
1788 return ICS;
1789 }
1790
1791 if (!S.getLangOpts().CPlusPlus) {
1792 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1793 return ICS;
1794 }
1795
1796 // C++ [over.ics.user]p4:
1797 // A conversion of an expression of class type to the same class
1798 // type is given Exact Match rank, and a conversion of an
1799 // expression of class type to a base class of that type is
1800 // given Conversion rank, in spite of the fact that a copy/move
1801 // constructor (i.e., a user-defined conversion function) is
1802 // called for those cases.
1803 QualType FromType = From->getType();
1804 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1805 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1806 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1807 ICS.setStandard();
1808 ICS.Standard.setAsIdentityConversion();
1809 ICS.Standard.setFromType(FromType);
1810 ICS.Standard.setAllToTypes(ToType);
1811
1812 // We don't actually check at this point whether there is a valid
1813 // copy/move constructor, since overloading just assumes that it
1814 // exists. When we actually perform initialization, we'll find the
1815 // appropriate constructor to copy the returned object, if needed.
1816 ICS.Standard.CopyConstructor = nullptr;
1817
1818 // Determine whether this is considered a derived-to-base conversion.
1819 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1820 ICS.Standard.Second = ICK_Derived_To_Base;
1821
1822 return ICS;
1823 }
1824
1825 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1826 FromType->isHLSLAttributedResourceType()) {
1827 auto *ToResType = cast<HLSLAttributedResourceType>(Val&: ToType);
1828 auto *FromResType = cast<HLSLAttributedResourceType>(Val&: FromType);
1829 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1830 T2: FromResType->getWrappedType()) &&
1831 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1832 T2: FromResType->getContainedType()) &&
1833 ToResType->getAttrs() == FromResType->getAttrs()) {
1834 ICS.setStandard();
1835 ICS.Standard.setAsIdentityConversion();
1836 ICS.Standard.setFromType(FromType);
1837 ICS.Standard.setAllToTypes(ToType);
1838 return ICS;
1839 }
1840 }
1841
1842 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1843 AllowExplicit, InOverloadResolution, CStyle,
1844 AllowObjCWritebackConversion,
1845 AllowObjCConversionOnExplicit);
1846}
1847
1848ImplicitConversionSequence
1849Sema::TryImplicitConversion(Expr *From, QualType ToType,
1850 bool SuppressUserConversions,
1851 AllowedExplicit AllowExplicit,
1852 bool InOverloadResolution,
1853 bool CStyle,
1854 bool AllowObjCWritebackConversion) {
1855 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1856 AllowExplicit, InOverloadResolution, CStyle,
1857 AllowObjCWritebackConversion,
1858 /*AllowObjCConversionOnExplicit=*/false);
1859}
1860
1861ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1862 AssignmentAction Action,
1863 bool AllowExplicit) {
1864 if (checkPlaceholderForOverload(S&: *this, E&: From))
1865 return ExprError();
1866
1867 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1868 bool AllowObjCWritebackConversion =
1869 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1870 Action == AssignmentAction::Sending);
1871 if (getLangOpts().ObjC)
1872 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1873 SrcType: From->getType(), SrcExpr&: From);
1874 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1875 S&: *this, From, ToType,
1876 /*SuppressUserConversions=*/false,
1877 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1878 /*InOverloadResolution=*/false,
1879 /*CStyle=*/false, AllowObjCWritebackConversion,
1880 /*AllowObjCConversionOnExplicit=*/false);
1881 return PerformImplicitConversion(From, ToType, ICS, Action);
1882}
1883
1884bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1885 QualType &ResultTy) const {
1886 bool Changed = IsFunctionConversion(FromType, ToType);
1887 if (Changed)
1888 ResultTy = ToType;
1889 return Changed;
1890}
1891
1892bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1893 bool *DiscardingCFIUncheckedCallee,
1894 bool *AddingCFIUncheckedCallee) const {
1895 if (DiscardingCFIUncheckedCallee)
1896 *DiscardingCFIUncheckedCallee = false;
1897 if (AddingCFIUncheckedCallee)
1898 *AddingCFIUncheckedCallee = false;
1899
1900 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1901 return false;
1902
1903 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1904 // or F(t noexcept) -> F(t)
1905 // where F adds one of the following at most once:
1906 // - a pointer
1907 // - a member pointer
1908 // - a block pointer
1909 // Changes here need matching changes in FindCompositePointerType.
1910 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1911 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1912 Type::TypeClass TyClass = CanTo->getTypeClass();
1913 if (TyClass != CanFrom->getTypeClass()) return false;
1914 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1915 if (TyClass == Type::Pointer) {
1916 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1917 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1918 } else if (TyClass == Type::BlockPointer) {
1919 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1920 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1921 } else if (TyClass == Type::MemberPointer) {
1922 auto ToMPT = CanTo.castAs<MemberPointerType>();
1923 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1924 // A function pointer conversion cannot change the class of the function.
1925 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1926 FromMPT->getMostRecentCXXRecordDecl()))
1927 return false;
1928 CanTo = ToMPT->getPointeeType();
1929 CanFrom = FromMPT->getPointeeType();
1930 } else {
1931 return false;
1932 }
1933
1934 TyClass = CanTo->getTypeClass();
1935 if (TyClass != CanFrom->getTypeClass()) return false;
1936 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1937 return false;
1938 }
1939
1940 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1941 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1942
1943 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1944 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1945
1946 bool Changed = false;
1947
1948 // Drop 'noreturn' if not present in target type.
1949 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1950 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1951 Changed = true;
1952 }
1953
1954 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1955 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1956
1957 if (FromFPT && ToFPT) {
1958 if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1959 QualType NewTy = Context.getFunctionType(
1960 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1961 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(CFIUncheckedCallee: false));
1962 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1963 FromFn = FromFPT;
1964 Changed = true;
1965 if (DiscardingCFIUncheckedCallee)
1966 *DiscardingCFIUncheckedCallee = true;
1967 } else if (!FromFPT->hasCFIUncheckedCallee() &&
1968 ToFPT->hasCFIUncheckedCallee()) {
1969 QualType NewTy = Context.getFunctionType(
1970 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1971 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(CFIUncheckedCallee: true));
1972 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1973 FromFn = FromFPT;
1974 Changed = true;
1975 if (AddingCFIUncheckedCallee)
1976 *AddingCFIUncheckedCallee = true;
1977 }
1978 }
1979
1980 // Drop 'noexcept' if not present in target type.
1981 if (FromFPT) {
1982 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1983 FromFn = cast<FunctionType>(
1984 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1985 ESI: EST_None)
1986 .getTypePtr());
1987 Changed = true;
1988 }
1989
1990 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1991 // only if the ExtParameterInfo lists of the two function prototypes can be
1992 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1993 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1994 bool CanUseToFPT, CanUseFromFPT;
1995 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
1996 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
1997 CanUseToFPT && !CanUseFromFPT) {
1998 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1999 ExtInfo.ExtParameterInfos =
2000 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2001 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2002 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2003 FromFn = QT->getAs<FunctionType>();
2004 Changed = true;
2005 }
2006
2007 // For C, when called from checkPointerTypesForAssignment,
2008 // we need to not alter FromFn, or else even an innocuous cast
2009 // like dropping effects will fail. In C++ however we do want to
2010 // alter FromFn (because of the way PerformImplicitConversion works).
2011 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2012 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2013
2014 // Transparently add/drop effects; here we are concerned with
2015 // language rules/canonicalization. Adding/dropping effects is a warning.
2016 const auto FromFX = FromFPT->getFunctionEffects();
2017 const auto ToFX = ToFPT->getFunctionEffects();
2018 if (FromFX != ToFX) {
2019 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2020 ExtInfo.FunctionEffects = ToFX;
2021 QualType QT = Context.getFunctionType(
2022 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2023 FromFn = QT->getAs<FunctionType>();
2024 Changed = true;
2025 }
2026 }
2027 }
2028
2029 if (!Changed)
2030 return false;
2031
2032 assert(QualType(FromFn, 0).isCanonical());
2033 if (QualType(FromFn, 0) != CanTo) return false;
2034
2035 return true;
2036}
2037
2038/// Determine whether the conversion from FromType to ToType is a valid
2039/// floating point conversion.
2040///
2041static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2042 QualType ToType) {
2043 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2044 return false;
2045 // FIXME: disable conversions between long double, __ibm128 and __float128
2046 // if their representation is different until there is back end support
2047 // We of course allow this conversion if long double is really double.
2048
2049 // Conversions between bfloat16 and float16 are currently not supported.
2050 if ((FromType->isBFloat16Type() &&
2051 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2052 (ToType->isBFloat16Type() &&
2053 (FromType->isFloat16Type() || FromType->isHalfType())))
2054 return false;
2055
2056 // Conversions between IEEE-quad and IBM-extended semantics are not
2057 // permitted.
2058 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2059 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2060 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2061 &ToSem == &llvm::APFloat::IEEEquad()) ||
2062 (&FromSem == &llvm::APFloat::IEEEquad() &&
2063 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2064 return false;
2065 return true;
2066}
2067
2068static bool IsVectorElementConversion(Sema &S, QualType FromType,
2069 QualType ToType,
2070 ImplicitConversionKind &ICK, Expr *From) {
2071 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2072 return true;
2073
2074 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2075 ICK = ICK_Floating_Promotion;
2076 return true;
2077 }
2078
2079 if (IsFloatingPointConversion(S, FromType, ToType)) {
2080 ICK = ICK_Floating_Conversion;
2081 return true;
2082 }
2083
2084 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2085 ICK = ICK_Boolean_Conversion;
2086 return true;
2087 }
2088
2089 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2090 (FromType->isIntegralOrUnscopedEnumerationType() &&
2091 ToType->isRealFloatingType())) {
2092 ICK = ICK_Floating_Integral;
2093 return true;
2094 }
2095
2096 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2097 ICK = ICK_Integral_Promotion;
2098 return true;
2099 }
2100
2101 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2102 ToType->isIntegralType(Ctx: S.Context)) {
2103 ICK = ICK_Integral_Conversion;
2104 return true;
2105 }
2106
2107 return false;
2108}
2109
2110/// Determine whether the conversion from FromType to ToType is a valid
2111/// vector conversion.
2112///
2113/// \param ICK Will be set to the vector conversion kind, if this is a vector
2114/// conversion.
2115static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2116 ImplicitConversionKind &ICK,
2117 ImplicitConversionKind &ElConv, Expr *From,
2118 bool InOverloadResolution, bool CStyle) {
2119 // We need at least one of these types to be a vector type to have a vector
2120 // conversion.
2121 if (!ToType->isVectorType() && !FromType->isVectorType())
2122 return false;
2123
2124 // Identical types require no conversions.
2125 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2126 return false;
2127
2128 // HLSL allows implicit truncation of vector types.
2129 if (S.getLangOpts().HLSL) {
2130 auto *ToExtType = ToType->getAs<ExtVectorType>();
2131 auto *FromExtType = FromType->getAs<ExtVectorType>();
2132
2133 // If both arguments are vectors, handle possible vector truncation and
2134 // element conversion.
2135 if (ToExtType && FromExtType) {
2136 unsigned FromElts = FromExtType->getNumElements();
2137 unsigned ToElts = ToExtType->getNumElements();
2138 if (FromElts < ToElts)
2139 return false;
2140 if (FromElts == ToElts)
2141 ElConv = ICK_Identity;
2142 else
2143 ElConv = ICK_HLSL_Vector_Truncation;
2144
2145 QualType FromElTy = FromExtType->getElementType();
2146 QualType ToElTy = ToExtType->getElementType();
2147 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2148 return true;
2149 return IsVectorElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2150 }
2151 if (FromExtType && !ToExtType) {
2152 ElConv = ICK_HLSL_Vector_Truncation;
2153 QualType FromElTy = FromExtType->getElementType();
2154 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2155 return true;
2156 return IsVectorElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2157 }
2158 // Fallthrough for the case where ToType is a vector and FromType is not.
2159 }
2160
2161 // There are no conversions between extended vector types, only identity.
2162 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2163 if (FromType->getAs<ExtVectorType>()) {
2164 // There are no conversions between extended vector types other than the
2165 // identity conversion.
2166 return false;
2167 }
2168
2169 // Vector splat from any arithmetic type to a vector.
2170 if (FromType->isArithmeticType()) {
2171 if (S.getLangOpts().HLSL) {
2172 ElConv = ICK_HLSL_Vector_Splat;
2173 QualType ToElTy = ToExtType->getElementType();
2174 return IsVectorElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2175 }
2176 ICK = ICK_Vector_Splat;
2177 return true;
2178 }
2179 }
2180
2181 if (ToType->isSVESizelessBuiltinType() ||
2182 FromType->isSVESizelessBuiltinType())
2183 if (S.Context.areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2184 S.Context.areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2185 ICK = ICK_SVE_Vector_Conversion;
2186 return true;
2187 }
2188
2189 if (ToType->isRVVSizelessBuiltinType() ||
2190 FromType->isRVVSizelessBuiltinType())
2191 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2192 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2193 ICK = ICK_RVV_Vector_Conversion;
2194 return true;
2195 }
2196
2197 // We can perform the conversion between vector types in the following cases:
2198 // 1)vector types are equivalent AltiVec and GCC vector types
2199 // 2)lax vector conversions are permitted and the vector types are of the
2200 // same size
2201 // 3)the destination type does not have the ARM MVE strict-polymorphism
2202 // attribute, which inhibits lax vector conversion for overload resolution
2203 // only
2204 if (ToType->isVectorType() && FromType->isVectorType()) {
2205 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2206 (S.isLaxVectorConversion(FromType, ToType) &&
2207 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2208 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2209 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2210 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2211 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2212 !InOverloadResolution && !CStyle) {
2213 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2214 << FromType << ToType;
2215 }
2216 ICK = ICK_Vector_Conversion;
2217 return true;
2218 }
2219 }
2220
2221 return false;
2222}
2223
2224static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2225 bool InOverloadResolution,
2226 StandardConversionSequence &SCS,
2227 bool CStyle);
2228
2229/// IsStandardConversion - Determines whether there is a standard
2230/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2231/// expression From to the type ToType. Standard conversion sequences
2232/// only consider non-class types; for conversions that involve class
2233/// types, use TryImplicitConversion. If a conversion exists, SCS will
2234/// contain the standard conversion sequence required to perform this
2235/// conversion and this routine will return true. Otherwise, this
2236/// routine will return false and the value of SCS is unspecified.
2237static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2238 bool InOverloadResolution,
2239 StandardConversionSequence &SCS,
2240 bool CStyle,
2241 bool AllowObjCWritebackConversion) {
2242 QualType FromType = From->getType();
2243
2244 // Standard conversions (C++ [conv])
2245 SCS.setAsIdentityConversion();
2246 SCS.IncompatibleObjC = false;
2247 SCS.setFromType(FromType);
2248 SCS.CopyConstructor = nullptr;
2249
2250 // There are no standard conversions for class types in C++, so
2251 // abort early. When overloading in C, however, we do permit them.
2252 if (S.getLangOpts().CPlusPlus &&
2253 (FromType->isRecordType() || ToType->isRecordType()))
2254 return false;
2255
2256 // The first conversion can be an lvalue-to-rvalue conversion,
2257 // array-to-pointer conversion, or function-to-pointer conversion
2258 // (C++ 4p1).
2259
2260 if (FromType == S.Context.OverloadTy) {
2261 DeclAccessPair AccessPair;
2262 if (FunctionDecl *Fn
2263 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2264 Found&: AccessPair)) {
2265 // We were able to resolve the address of the overloaded function,
2266 // so we can convert to the type of that function.
2267 FromType = Fn->getType();
2268 SCS.setFromType(FromType);
2269
2270 // we can sometimes resolve &foo<int> regardless of ToType, so check
2271 // if the type matches (identity) or we are converting to bool
2272 if (!S.Context.hasSameUnqualifiedType(
2273 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2274 // if the function type matches except for [[noreturn]], it's ok
2275 if (!S.IsFunctionConversion(FromType,
2276 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2277 // otherwise, only a boolean conversion is standard
2278 if (!ToType->isBooleanType())
2279 return false;
2280 }
2281
2282 // Check if the "from" expression is taking the address of an overloaded
2283 // function and recompute the FromType accordingly. Take advantage of the
2284 // fact that non-static member functions *must* have such an address-of
2285 // expression.
2286 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2287 if (Method && !Method->isStatic() &&
2288 !Method->isExplicitObjectMemberFunction()) {
2289 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2290 "Non-unary operator on non-static member address");
2291 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2292 == UO_AddrOf &&
2293 "Non-address-of operator on non-static member address");
2294 FromType = S.Context.getMemberPointerType(
2295 T: FromType, /*Qualifier=*/nullptr, Cls: Method->getParent());
2296 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2297 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2298 UO_AddrOf &&
2299 "Non-address-of operator for overloaded function expression");
2300 FromType = S.Context.getPointerType(T: FromType);
2301 }
2302 } else {
2303 return false;
2304 }
2305 }
2306
2307 bool argIsLValue = From->isGLValue();
2308 // To handle conversion from ArrayParameterType to ConstantArrayType
2309 // this block must be above the one below because Array parameters
2310 // do not decay and when handling HLSLOutArgExprs and
2311 // the From expression is an LValue.
2312 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2313 ToType->isConstantArrayType()) {
2314 // HLSL constant array parameters do not decay, so if the argument is a
2315 // constant array and the parameter is an ArrayParameterType we have special
2316 // handling here.
2317 if (ToType->isArrayParameterType()) {
2318 FromType = S.Context.getArrayParameterType(Ty: FromType);
2319 } else if (FromType->isArrayParameterType()) {
2320 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2321 FromType = APT->getConstantArrayType(Ctx: S.Context);
2322 }
2323
2324 SCS.First = ICK_HLSL_Array_RValue;
2325
2326 // Don't consider qualifiers, which include things like address spaces
2327 if (FromType.getCanonicalType().getUnqualifiedType() !=
2328 ToType.getCanonicalType().getUnqualifiedType())
2329 return false;
2330
2331 SCS.setAllToTypes(ToType);
2332 return true;
2333 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2334 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2335 // Lvalue-to-rvalue conversion (C++11 4.1):
2336 // A glvalue (3.10) of a non-function, non-array type T can
2337 // be converted to a prvalue.
2338
2339 SCS.First = ICK_Lvalue_To_Rvalue;
2340
2341 // C11 6.3.2.1p2:
2342 // ... if the lvalue has atomic type, the value has the non-atomic version
2343 // of the type of the lvalue ...
2344 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2345 FromType = Atomic->getValueType();
2346
2347 // If T is a non-class type, the type of the rvalue is the
2348 // cv-unqualified version of T. Otherwise, the type of the rvalue
2349 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2350 // just strip the qualifiers because they don't matter.
2351 FromType = FromType.getUnqualifiedType();
2352 } else if (FromType->isArrayType()) {
2353 // Array-to-pointer conversion (C++ 4.2)
2354 SCS.First = ICK_Array_To_Pointer;
2355
2356 // An lvalue or rvalue of type "array of N T" or "array of unknown
2357 // bound of T" can be converted to an rvalue of type "pointer to
2358 // T" (C++ 4.2p1).
2359 FromType = S.Context.getArrayDecayedType(T: FromType);
2360
2361 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2362 // This conversion is deprecated in C++03 (D.4)
2363 SCS.DeprecatedStringLiteralToCharPtr = true;
2364
2365 // For the purpose of ranking in overload resolution
2366 // (13.3.3.1.1), this conversion is considered an
2367 // array-to-pointer conversion followed by a qualification
2368 // conversion (4.4). (C++ 4.2p2)
2369 SCS.Second = ICK_Identity;
2370 SCS.Third = ICK_Qualification;
2371 SCS.QualificationIncludesObjCLifetime = false;
2372 SCS.setAllToTypes(FromType);
2373 return true;
2374 }
2375 } else if (FromType->isFunctionType() && argIsLValue) {
2376 // Function-to-pointer conversion (C++ 4.3).
2377 SCS.First = ICK_Function_To_Pointer;
2378
2379 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2380 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2381 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2382 return false;
2383
2384 // An lvalue of function type T can be converted to an rvalue of
2385 // type "pointer to T." The result is a pointer to the
2386 // function. (C++ 4.3p1).
2387 FromType = S.Context.getPointerType(T: FromType);
2388 } else {
2389 // We don't require any conversions for the first step.
2390 SCS.First = ICK_Identity;
2391 }
2392 SCS.setToType(Idx: 0, T: FromType);
2393
2394 // The second conversion can be an integral promotion, floating
2395 // point promotion, integral conversion, floating point conversion,
2396 // floating-integral conversion, pointer conversion,
2397 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2398 // For overloading in C, this can also be a "compatible-type"
2399 // conversion.
2400 bool IncompatibleObjC = false;
2401 ImplicitConversionKind SecondICK = ICK_Identity;
2402 ImplicitConversionKind DimensionICK = ICK_Identity;
2403 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2404 // The unqualified versions of the types are the same: there's no
2405 // conversion to do.
2406 SCS.Second = ICK_Identity;
2407 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2408 // Integral promotion (C++ 4.5).
2409 SCS.Second = ICK_Integral_Promotion;
2410 FromType = ToType.getUnqualifiedType();
2411 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2412 // Floating point promotion (C++ 4.6).
2413 SCS.Second = ICK_Floating_Promotion;
2414 FromType = ToType.getUnqualifiedType();
2415 } else if (S.IsComplexPromotion(FromType, ToType)) {
2416 // Complex promotion (Clang extension)
2417 SCS.Second = ICK_Complex_Promotion;
2418 FromType = ToType.getUnqualifiedType();
2419 } else if (ToType->isBooleanType() &&
2420 (FromType->isArithmeticType() ||
2421 FromType->isAnyPointerType() ||
2422 FromType->isBlockPointerType() ||
2423 FromType->isMemberPointerType())) {
2424 // Boolean conversions (C++ 4.12).
2425 SCS.Second = ICK_Boolean_Conversion;
2426 FromType = S.Context.BoolTy;
2427 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2428 ToType->isIntegralType(Ctx: S.Context)) {
2429 // Integral conversions (C++ 4.7).
2430 SCS.Second = ICK_Integral_Conversion;
2431 FromType = ToType.getUnqualifiedType();
2432 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2433 // Complex conversions (C99 6.3.1.6)
2434 SCS.Second = ICK_Complex_Conversion;
2435 FromType = ToType.getUnqualifiedType();
2436 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2437 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2438 // Complex-real conversions (C99 6.3.1.7)
2439 SCS.Second = ICK_Complex_Real;
2440 FromType = ToType.getUnqualifiedType();
2441 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2442 // Floating point conversions (C++ 4.8).
2443 SCS.Second = ICK_Floating_Conversion;
2444 FromType = ToType.getUnqualifiedType();
2445 } else if ((FromType->isRealFloatingType() &&
2446 ToType->isIntegralType(Ctx: S.Context)) ||
2447 (FromType->isIntegralOrUnscopedEnumerationType() &&
2448 ToType->isRealFloatingType())) {
2449
2450 // Floating-integral conversions (C++ 4.9).
2451 SCS.Second = ICK_Floating_Integral;
2452 FromType = ToType.getUnqualifiedType();
2453 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2454 SCS.Second = ICK_Block_Pointer_Conversion;
2455 } else if (AllowObjCWritebackConversion &&
2456 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2457 SCS.Second = ICK_Writeback_Conversion;
2458 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2459 ConvertedType&: FromType, IncompatibleObjC)) {
2460 // Pointer conversions (C++ 4.10).
2461 SCS.Second = ICK_Pointer_Conversion;
2462 SCS.IncompatibleObjC = IncompatibleObjC;
2463 FromType = FromType.getUnqualifiedType();
2464 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2465 InOverloadResolution, ConvertedType&: FromType)) {
2466 // Pointer to member conversions (4.11).
2467 SCS.Second = ICK_Pointer_Member;
2468 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2469 From, InOverloadResolution, CStyle)) {
2470 SCS.Second = SecondICK;
2471 SCS.Dimension = DimensionICK;
2472 FromType = ToType.getUnqualifiedType();
2473 } else if (!S.getLangOpts().CPlusPlus &&
2474 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2475 // Compatible conversions (Clang extension for C function overloading)
2476 SCS.Second = ICK_Compatible_Conversion;
2477 FromType = ToType.getUnqualifiedType();
2478 } else if (IsTransparentUnionStandardConversion(
2479 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2480 SCS.Second = ICK_TransparentUnionConversion;
2481 FromType = ToType;
2482 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2483 CStyle)) {
2484 // tryAtomicConversion has updated the standard conversion sequence
2485 // appropriately.
2486 return true;
2487 } else if (ToType->isEventT() &&
2488 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2489 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2490 SCS.Second = ICK_Zero_Event_Conversion;
2491 FromType = ToType;
2492 } else if (ToType->isQueueT() &&
2493 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2494 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2495 SCS.Second = ICK_Zero_Queue_Conversion;
2496 FromType = ToType;
2497 } else if (ToType->isSamplerT() &&
2498 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2499 SCS.Second = ICK_Compatible_Conversion;
2500 FromType = ToType;
2501 } else if ((ToType->isFixedPointType() &&
2502 FromType->isConvertibleToFixedPointType()) ||
2503 (FromType->isFixedPointType() &&
2504 ToType->isConvertibleToFixedPointType())) {
2505 SCS.Second = ICK_Fixed_Point_Conversion;
2506 FromType = ToType;
2507 } else {
2508 // No second conversion required.
2509 SCS.Second = ICK_Identity;
2510 }
2511 SCS.setToType(Idx: 1, T: FromType);
2512
2513 // The third conversion can be a function pointer conversion or a
2514 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2515 bool ObjCLifetimeConversion;
2516 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2517 // Function pointer conversions (removing 'noexcept') including removal of
2518 // 'noreturn' (Clang extension).
2519 SCS.Third = ICK_Function_Conversion;
2520 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2521 ObjCLifetimeConversion)) {
2522 SCS.Third = ICK_Qualification;
2523 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2524 FromType = ToType;
2525 } else {
2526 // No conversion required
2527 SCS.Third = ICK_Identity;
2528 }
2529
2530 // C++ [over.best.ics]p6:
2531 // [...] Any difference in top-level cv-qualification is
2532 // subsumed by the initialization itself and does not constitute
2533 // a conversion. [...]
2534 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2535 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2536 if (CanonFrom.getLocalUnqualifiedType()
2537 == CanonTo.getLocalUnqualifiedType() &&
2538 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2539 FromType = ToType;
2540 CanonFrom = CanonTo;
2541 }
2542
2543 SCS.setToType(Idx: 2, T: FromType);
2544
2545 // If we have not converted the argument type to the parameter type,
2546 // this is a bad conversion sequence, unless we're resolving an overload in C.
2547 //
2548 // Permit conversions from a function without `cfi_unchecked_callee` to a
2549 // function with `cfi_unchecked_callee`.
2550 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(From: CanonFrom, To: CanonTo))
2551 return true;
2552
2553 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2554 return false;
2555
2556 ExprResult ER = ExprResult{From};
2557 AssignConvertType Conv =
2558 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2559 /*Diagnose=*/false,
2560 /*DiagnoseCFAudited=*/false,
2561 /*ConvertRHS=*/false);
2562 ImplicitConversionKind SecondConv;
2563 switch (Conv) {
2564 case AssignConvertType::Compatible:
2565 case AssignConvertType::
2566 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2567 SecondConv = ICK_C_Only_Conversion;
2568 break;
2569 // For our purposes, discarding qualifiers is just as bad as using an
2570 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2571 // qualifiers, as well.
2572 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2573 case AssignConvertType::IncompatiblePointer:
2574 case AssignConvertType::IncompatiblePointerSign:
2575 SecondConv = ICK_Incompatible_Pointer_Conversion;
2576 break;
2577 default:
2578 return false;
2579 }
2580
2581 // First can only be an lvalue conversion, so we pretend that this was the
2582 // second conversion. First should already be valid from earlier in the
2583 // function.
2584 SCS.Second = SecondConv;
2585 SCS.setToType(Idx: 1, T: ToType);
2586
2587 // Third is Identity, because Second should rank us worse than any other
2588 // conversion. This could also be ICK_Qualification, but it's simpler to just
2589 // lump everything in with the second conversion, and we don't gain anything
2590 // from making this ICK_Qualification.
2591 SCS.Third = ICK_Identity;
2592 SCS.setToType(Idx: 2, T: ToType);
2593 return true;
2594}
2595
2596static bool
2597IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2598 QualType &ToType,
2599 bool InOverloadResolution,
2600 StandardConversionSequence &SCS,
2601 bool CStyle) {
2602
2603 const RecordType *UT = ToType->getAsUnionType();
2604 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2605 return false;
2606 // The field to initialize within the transparent union.
2607 RecordDecl *UD = UT->getDecl();
2608 // It's compatible if the expression matches any of the fields.
2609 for (const auto *it : UD->fields()) {
2610 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2611 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2612 ToType = it->getType();
2613 return true;
2614 }
2615 }
2616 return false;
2617}
2618
2619bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2620 const BuiltinType *To = ToType->getAs<BuiltinType>();
2621 // All integers are built-in.
2622 if (!To) {
2623 return false;
2624 }
2625
2626 // An rvalue of type char, signed char, unsigned char, short int, or
2627 // unsigned short int can be converted to an rvalue of type int if
2628 // int can represent all the values of the source type; otherwise,
2629 // the source rvalue can be converted to an rvalue of type unsigned
2630 // int (C++ 4.5p1).
2631 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2632 !FromType->isEnumeralType()) {
2633 if ( // We can promote any signed, promotable integer type to an int
2634 (FromType->isSignedIntegerType() ||
2635 // We can promote any unsigned integer type whose size is
2636 // less than int to an int.
2637 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2638 return To->getKind() == BuiltinType::Int;
2639 }
2640
2641 return To->getKind() == BuiltinType::UInt;
2642 }
2643
2644 // C++11 [conv.prom]p3:
2645 // A prvalue of an unscoped enumeration type whose underlying type is not
2646 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2647 // following types that can represent all the values of the enumeration
2648 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2649 // unsigned int, long int, unsigned long int, long long int, or unsigned
2650 // long long int. If none of the types in that list can represent all the
2651 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2652 // type can be converted to an rvalue a prvalue of the extended integer type
2653 // with lowest integer conversion rank (4.13) greater than the rank of long
2654 // long in which all the values of the enumeration can be represented. If
2655 // there are two such extended types, the signed one is chosen.
2656 // C++11 [conv.prom]p4:
2657 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2658 // can be converted to a prvalue of its underlying type. Moreover, if
2659 // integral promotion can be applied to its underlying type, a prvalue of an
2660 // unscoped enumeration type whose underlying type is fixed can also be
2661 // converted to a prvalue of the promoted underlying type.
2662 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2663 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2664 // provided for a scoped enumeration.
2665 if (FromEnumType->getDecl()->isScoped())
2666 return false;
2667
2668 // We can perform an integral promotion to the underlying type of the enum,
2669 // even if that's not the promoted type. Note that the check for promoting
2670 // the underlying type is based on the type alone, and does not consider
2671 // the bitfield-ness of the actual source expression.
2672 if (FromEnumType->getDecl()->isFixed()) {
2673 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2674 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2675 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2676 }
2677
2678 // We have already pre-calculated the promotion type, so this is trivial.
2679 if (ToType->isIntegerType() &&
2680 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2681 return Context.hasSameUnqualifiedType(
2682 T1: ToType, T2: FromEnumType->getDecl()->getPromotionType());
2683
2684 // C++ [conv.prom]p5:
2685 // If the bit-field has an enumerated type, it is treated as any other
2686 // value of that type for promotion purposes.
2687 //
2688 // ... so do not fall through into the bit-field checks below in C++.
2689 if (getLangOpts().CPlusPlus)
2690 return false;
2691 }
2692
2693 // C++0x [conv.prom]p2:
2694 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2695 // to an rvalue a prvalue of the first of the following types that can
2696 // represent all the values of its underlying type: int, unsigned int,
2697 // long int, unsigned long int, long long int, or unsigned long long int.
2698 // If none of the types in that list can represent all the values of its
2699 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2700 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2701 // type.
2702 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2703 ToType->isIntegerType()) {
2704 // Determine whether the type we're converting from is signed or
2705 // unsigned.
2706 bool FromIsSigned = FromType->isSignedIntegerType();
2707 uint64_t FromSize = Context.getTypeSize(T: FromType);
2708
2709 // The types we'll try to promote to, in the appropriate
2710 // order. Try each of these types.
2711 QualType PromoteTypes[6] = {
2712 Context.IntTy, Context.UnsignedIntTy,
2713 Context.LongTy, Context.UnsignedLongTy ,
2714 Context.LongLongTy, Context.UnsignedLongLongTy
2715 };
2716 for (int Idx = 0; Idx < 6; ++Idx) {
2717 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2718 if (FromSize < ToSize ||
2719 (FromSize == ToSize &&
2720 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2721 // We found the type that we can promote to. If this is the
2722 // type we wanted, we have a promotion. Otherwise, no
2723 // promotion.
2724 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2725 }
2726 }
2727 }
2728
2729 // An rvalue for an integral bit-field (9.6) can be converted to an
2730 // rvalue of type int if int can represent all the values of the
2731 // bit-field; otherwise, it can be converted to unsigned int if
2732 // unsigned int can represent all the values of the bit-field. If
2733 // the bit-field is larger yet, no integral promotion applies to
2734 // it. If the bit-field has an enumerated type, it is treated as any
2735 // other value of that type for promotion purposes (C++ 4.5p3).
2736 // FIXME: We should delay checking of bit-fields until we actually perform the
2737 // conversion.
2738 //
2739 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2740 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2741 // bit-fields and those whose underlying type is larger than int) for GCC
2742 // compatibility.
2743 if (From) {
2744 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2745 std::optional<llvm::APSInt> BitWidth;
2746 if (FromType->isIntegralType(Ctx: Context) &&
2747 (BitWidth =
2748 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2749 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2750 ToSize = Context.getTypeSize(T: ToType);
2751
2752 // Are we promoting to an int from a bitfield that fits in an int?
2753 if (*BitWidth < ToSize ||
2754 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2755 return To->getKind() == BuiltinType::Int;
2756 }
2757
2758 // Are we promoting to an unsigned int from an unsigned bitfield
2759 // that fits into an unsigned int?
2760 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2761 return To->getKind() == BuiltinType::UInt;
2762 }
2763
2764 return false;
2765 }
2766 }
2767 }
2768
2769 // An rvalue of type bool can be converted to an rvalue of type int,
2770 // with false becoming zero and true becoming one (C++ 4.5p4).
2771 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2772 return true;
2773 }
2774
2775 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2776 // integral type.
2777 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2778 ToType->isIntegerType())
2779 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2780
2781 return false;
2782}
2783
2784bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2785 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2786 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2787 /// An rvalue of type float can be converted to an rvalue of type
2788 /// double. (C++ 4.6p1).
2789 if (FromBuiltin->getKind() == BuiltinType::Float &&
2790 ToBuiltin->getKind() == BuiltinType::Double)
2791 return true;
2792
2793 // C99 6.3.1.5p1:
2794 // When a float is promoted to double or long double, or a
2795 // double is promoted to long double [...].
2796 if (!getLangOpts().CPlusPlus &&
2797 (FromBuiltin->getKind() == BuiltinType::Float ||
2798 FromBuiltin->getKind() == BuiltinType::Double) &&
2799 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2800 ToBuiltin->getKind() == BuiltinType::Float128 ||
2801 ToBuiltin->getKind() == BuiltinType::Ibm128))
2802 return true;
2803
2804 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2805 // or not native half types are enabled.
2806 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2807 (ToBuiltin->getKind() == BuiltinType::Float ||
2808 ToBuiltin->getKind() == BuiltinType::Double))
2809 return true;
2810
2811 // Half can be promoted to float.
2812 if (!getLangOpts().NativeHalfType &&
2813 FromBuiltin->getKind() == BuiltinType::Half &&
2814 ToBuiltin->getKind() == BuiltinType::Float)
2815 return true;
2816 }
2817
2818 return false;
2819}
2820
2821bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2822 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2823 if (!FromComplex)
2824 return false;
2825
2826 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2827 if (!ToComplex)
2828 return false;
2829
2830 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2831 ToType: ToComplex->getElementType()) ||
2832 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2833 ToType: ToComplex->getElementType());
2834}
2835
2836/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2837/// the pointer type FromPtr to a pointer to type ToPointee, with the
2838/// same type qualifiers as FromPtr has on its pointee type. ToType,
2839/// if non-empty, will be a pointer to ToType that may or may not have
2840/// the right set of qualifiers on its pointee.
2841///
2842static QualType
2843BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2844 QualType ToPointee, QualType ToType,
2845 ASTContext &Context,
2846 bool StripObjCLifetime = false) {
2847 assert((FromPtr->getTypeClass() == Type::Pointer ||
2848 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2849 "Invalid similarly-qualified pointer type");
2850
2851 /// Conversions to 'id' subsume cv-qualifier conversions.
2852 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2853 return ToType.getUnqualifiedType();
2854
2855 QualType CanonFromPointee
2856 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2857 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2858 Qualifiers Quals = CanonFromPointee.getQualifiers();
2859
2860 if (StripObjCLifetime)
2861 Quals.removeObjCLifetime();
2862
2863 // Exact qualifier match -> return the pointer type we're converting to.
2864 if (CanonToPointee.getLocalQualifiers() == Quals) {
2865 // ToType is exactly what we need. Return it.
2866 if (!ToType.isNull())
2867 return ToType.getUnqualifiedType();
2868
2869 // Build a pointer to ToPointee. It has the right qualifiers
2870 // already.
2871 if (isa<ObjCObjectPointerType>(Val: ToType))
2872 return Context.getObjCObjectPointerType(OIT: ToPointee);
2873 return Context.getPointerType(T: ToPointee);
2874 }
2875
2876 // Just build a canonical type that has the right qualifiers.
2877 QualType QualifiedCanonToPointee
2878 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
2879
2880 if (isa<ObjCObjectPointerType>(Val: ToType))
2881 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
2882 return Context.getPointerType(T: QualifiedCanonToPointee);
2883}
2884
2885static bool isNullPointerConstantForConversion(Expr *Expr,
2886 bool InOverloadResolution,
2887 ASTContext &Context) {
2888 // Handle value-dependent integral null pointer constants correctly.
2889 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2890 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2891 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2892 return !InOverloadResolution;
2893
2894 return Expr->isNullPointerConstant(Ctx&: Context,
2895 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2896 : Expr::NPC_ValueDependentIsNull);
2897}
2898
2899bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2900 bool InOverloadResolution,
2901 QualType& ConvertedType,
2902 bool &IncompatibleObjC) {
2903 IncompatibleObjC = false;
2904 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2905 IncompatibleObjC))
2906 return true;
2907
2908 // Conversion from a null pointer constant to any Objective-C pointer type.
2909 if (ToType->isObjCObjectPointerType() &&
2910 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2911 ConvertedType = ToType;
2912 return true;
2913 }
2914
2915 // Blocks: Block pointers can be converted to void*.
2916 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2917 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2918 ConvertedType = ToType;
2919 return true;
2920 }
2921 // Blocks: A null pointer constant can be converted to a block
2922 // pointer type.
2923 if (ToType->isBlockPointerType() &&
2924 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2925 ConvertedType = ToType;
2926 return true;
2927 }
2928
2929 // If the left-hand-side is nullptr_t, the right side can be a null
2930 // pointer constant.
2931 if (ToType->isNullPtrType() &&
2932 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2933 ConvertedType = ToType;
2934 return true;
2935 }
2936
2937 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2938 if (!ToTypePtr)
2939 return false;
2940
2941 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2942 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
2943 ConvertedType = ToType;
2944 return true;
2945 }
2946
2947 // Beyond this point, both types need to be pointers
2948 // , including objective-c pointers.
2949 QualType ToPointeeType = ToTypePtr->getPointeeType();
2950 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2951 !getLangOpts().ObjCAutoRefCount) {
2952 ConvertedType = BuildSimilarlyQualifiedPointerType(
2953 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2954 Context);
2955 return true;
2956 }
2957 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2958 if (!FromTypePtr)
2959 return false;
2960
2961 QualType FromPointeeType = FromTypePtr->getPointeeType();
2962
2963 // If the unqualified pointee types are the same, this can't be a
2964 // pointer conversion, so don't do all of the work below.
2965 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
2966 return false;
2967
2968 // An rvalue of type "pointer to cv T," where T is an object type,
2969 // can be converted to an rvalue of type "pointer to cv void" (C++
2970 // 4.10p2).
2971 if (FromPointeeType->isIncompleteOrObjectType() &&
2972 ToPointeeType->isVoidType()) {
2973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2974 ToPointeeType,
2975 ToType, Context,
2976 /*StripObjCLifetime=*/true);
2977 return true;
2978 }
2979
2980 // MSVC allows implicit function to void* type conversion.
2981 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2982 ToPointeeType->isVoidType()) {
2983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2984 ToPointeeType,
2985 ToType, Context);
2986 return true;
2987 }
2988
2989 // When we're overloading in C, we allow a special kind of pointer
2990 // conversion for compatible-but-not-identical pointee types.
2991 if (!getLangOpts().CPlusPlus &&
2992 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
2993 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2994 ToPointeeType,
2995 ToType, Context);
2996 return true;
2997 }
2998
2999 // C++ [conv.ptr]p3:
3000 //
3001 // An rvalue of type "pointer to cv D," where D is a class type,
3002 // can be converted to an rvalue of type "pointer to cv B," where
3003 // B is a base class (clause 10) of D. If B is an inaccessible
3004 // (clause 11) or ambiguous (10.2) base class of D, a program that
3005 // necessitates this conversion is ill-formed. The result of the
3006 // conversion is a pointer to the base class sub-object of the
3007 // derived class object. The null pointer value is converted to
3008 // the null pointer value of the destination type.
3009 //
3010 // Note that we do not check for ambiguity or inaccessibility
3011 // here. That is handled by CheckPointerConversion.
3012 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3013 ToPointeeType->isRecordType() &&
3014 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3015 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3016 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3017 ToPointeeType,
3018 ToType, Context);
3019 return true;
3020 }
3021
3022 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3023 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3024 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3025 ToPointeeType,
3026 ToType, Context);
3027 return true;
3028 }
3029
3030 return false;
3031}
3032
3033/// Adopt the given qualifiers for the given type.
3034static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3035 Qualifiers TQs = T.getQualifiers();
3036
3037 // Check whether qualifiers already match.
3038 if (TQs == Qs)
3039 return T;
3040
3041 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3042 return Context.getQualifiedType(T, Qs);
3043
3044 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3045}
3046
3047bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3048 QualType& ConvertedType,
3049 bool &IncompatibleObjC) {
3050 if (!getLangOpts().ObjC)
3051 return false;
3052
3053 // The set of qualifiers on the type we're converting from.
3054 Qualifiers FromQualifiers = FromType.getQualifiers();
3055
3056 // First, we handle all conversions on ObjC object pointer types.
3057 const ObjCObjectPointerType* ToObjCPtr =
3058 ToType->getAs<ObjCObjectPointerType>();
3059 const ObjCObjectPointerType *FromObjCPtr =
3060 FromType->getAs<ObjCObjectPointerType>();
3061
3062 if (ToObjCPtr && FromObjCPtr) {
3063 // If the pointee types are the same (ignoring qualifications),
3064 // then this is not a pointer conversion.
3065 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3066 T2: FromObjCPtr->getPointeeType()))
3067 return false;
3068
3069 // Conversion between Objective-C pointers.
3070 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3071 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3072 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3073 if (getLangOpts().CPlusPlus && LHS && RHS &&
3074 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3075 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3076 return false;
3077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3078 ToObjCPtr->getPointeeType(),
3079 ToType, Context);
3080 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3081 return true;
3082 }
3083
3084 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3085 // Okay: this is some kind of implicit downcast of Objective-C
3086 // interfaces, which is permitted. However, we're going to
3087 // complain about it.
3088 IncompatibleObjC = true;
3089 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3090 ToObjCPtr->getPointeeType(),
3091 ToType, Context);
3092 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3093 return true;
3094 }
3095 }
3096 // Beyond this point, both types need to be C pointers or block pointers.
3097 QualType ToPointeeType;
3098 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3099 ToPointeeType = ToCPtr->getPointeeType();
3100 else if (const BlockPointerType *ToBlockPtr =
3101 ToType->getAs<BlockPointerType>()) {
3102 // Objective C++: We're able to convert from a pointer to any object
3103 // to a block pointer type.
3104 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3105 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3106 return true;
3107 }
3108 ToPointeeType = ToBlockPtr->getPointeeType();
3109 }
3110 else if (FromType->getAs<BlockPointerType>() &&
3111 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3112 // Objective C++: We're able to convert from a block pointer type to a
3113 // pointer to any object.
3114 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3115 return true;
3116 }
3117 else
3118 return false;
3119
3120 QualType FromPointeeType;
3121 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3122 FromPointeeType = FromCPtr->getPointeeType();
3123 else if (const BlockPointerType *FromBlockPtr =
3124 FromType->getAs<BlockPointerType>())
3125 FromPointeeType = FromBlockPtr->getPointeeType();
3126 else
3127 return false;
3128
3129 // If we have pointers to pointers, recursively check whether this
3130 // is an Objective-C conversion.
3131 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3132 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3133 IncompatibleObjC)) {
3134 // We always complain about this conversion.
3135 IncompatibleObjC = true;
3136 ConvertedType = Context.getPointerType(T: ConvertedType);
3137 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3138 return true;
3139 }
3140 // Allow conversion of pointee being objective-c pointer to another one;
3141 // as in I* to id.
3142 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3143 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3144 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3145 IncompatibleObjC)) {
3146
3147 ConvertedType = Context.getPointerType(T: ConvertedType);
3148 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3149 return true;
3150 }
3151
3152 // If we have pointers to functions or blocks, check whether the only
3153 // differences in the argument and result types are in Objective-C
3154 // pointer conversions. If so, we permit the conversion (but
3155 // complain about it).
3156 const FunctionProtoType *FromFunctionType
3157 = FromPointeeType->getAs<FunctionProtoType>();
3158 const FunctionProtoType *ToFunctionType
3159 = ToPointeeType->getAs<FunctionProtoType>();
3160 if (FromFunctionType && ToFunctionType) {
3161 // If the function types are exactly the same, this isn't an
3162 // Objective-C pointer conversion.
3163 if (Context.getCanonicalType(T: FromPointeeType)
3164 == Context.getCanonicalType(T: ToPointeeType))
3165 return false;
3166
3167 // Perform the quick checks that will tell us whether these
3168 // function types are obviously different.
3169 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3170 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3171 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3172 return false;
3173
3174 bool HasObjCConversion = false;
3175 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3176 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3177 // Okay, the types match exactly. Nothing to do.
3178 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3179 ToType: ToFunctionType->getReturnType(),
3180 ConvertedType, IncompatibleObjC)) {
3181 // Okay, we have an Objective-C pointer conversion.
3182 HasObjCConversion = true;
3183 } else {
3184 // Function types are too different. Abort.
3185 return false;
3186 }
3187
3188 // Check argument types.
3189 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3190 ArgIdx != NumArgs; ++ArgIdx) {
3191 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3192 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3193 if (Context.getCanonicalType(T: FromArgType)
3194 == Context.getCanonicalType(T: ToArgType)) {
3195 // Okay, the types match exactly. Nothing to do.
3196 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3197 ConvertedType, IncompatibleObjC)) {
3198 // Okay, we have an Objective-C pointer conversion.
3199 HasObjCConversion = true;
3200 } else {
3201 // Argument types are too different. Abort.
3202 return false;
3203 }
3204 }
3205
3206 if (HasObjCConversion) {
3207 // We had an Objective-C conversion. Allow this pointer
3208 // conversion, but complain about it.
3209 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3210 IncompatibleObjC = true;
3211 return true;
3212 }
3213 }
3214
3215 return false;
3216}
3217
3218bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3219 QualType& ConvertedType) {
3220 QualType ToPointeeType;
3221 if (const BlockPointerType *ToBlockPtr =
3222 ToType->getAs<BlockPointerType>())
3223 ToPointeeType = ToBlockPtr->getPointeeType();
3224 else
3225 return false;
3226
3227 QualType FromPointeeType;
3228 if (const BlockPointerType *FromBlockPtr =
3229 FromType->getAs<BlockPointerType>())
3230 FromPointeeType = FromBlockPtr->getPointeeType();
3231 else
3232 return false;
3233 // We have pointer to blocks, check whether the only
3234 // differences in the argument and result types are in Objective-C
3235 // pointer conversions. If so, we permit the conversion.
3236
3237 const FunctionProtoType *FromFunctionType
3238 = FromPointeeType->getAs<FunctionProtoType>();
3239 const FunctionProtoType *ToFunctionType
3240 = ToPointeeType->getAs<FunctionProtoType>();
3241
3242 if (!FromFunctionType || !ToFunctionType)
3243 return false;
3244
3245 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3246 return true;
3247
3248 // Perform the quick checks that will tell us whether these
3249 // function types are obviously different.
3250 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3251 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3252 return false;
3253
3254 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3255 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3256 if (FromEInfo != ToEInfo)
3257 return false;
3258
3259 bool IncompatibleObjC = false;
3260 if (Context.hasSameType(FromFunctionType->getReturnType(),
3261 ToFunctionType->getReturnType())) {
3262 // Okay, the types match exactly. Nothing to do.
3263 } else {
3264 QualType RHS = FromFunctionType->getReturnType();
3265 QualType LHS = ToFunctionType->getReturnType();
3266 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3267 !RHS.hasQualifiers() && LHS.hasQualifiers())
3268 LHS = LHS.getUnqualifiedType();
3269
3270 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3271 // OK exact match.
3272 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3273 ConvertedType, IncompatibleObjC)) {
3274 if (IncompatibleObjC)
3275 return false;
3276 // Okay, we have an Objective-C pointer conversion.
3277 }
3278 else
3279 return false;
3280 }
3281
3282 // Check argument types.
3283 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3284 ArgIdx != NumArgs; ++ArgIdx) {
3285 IncompatibleObjC = false;
3286 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3287 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3288 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3289 // Okay, the types match exactly. Nothing to do.
3290 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3291 ConvertedType, IncompatibleObjC)) {
3292 if (IncompatibleObjC)
3293 return false;
3294 // Okay, we have an Objective-C pointer conversion.
3295 } else
3296 // Argument types are too different. Abort.
3297 return false;
3298 }
3299
3300 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3301 bool CanUseToFPT, CanUseFromFPT;
3302 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3303 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3304 NewParamInfos))
3305 return false;
3306
3307 ConvertedType = ToType;
3308 return true;
3309}
3310
3311enum {
3312 ft_default,
3313 ft_different_class,
3314 ft_parameter_arity,
3315 ft_parameter_mismatch,
3316 ft_return_type,
3317 ft_qualifer_mismatch,
3318 ft_noexcept
3319};
3320
3321/// Attempts to get the FunctionProtoType from a Type. Handles
3322/// MemberFunctionPointers properly.
3323static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3324 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3325 return FPT;
3326
3327 if (auto *MPT = FromType->getAs<MemberPointerType>())
3328 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3329
3330 return nullptr;
3331}
3332
3333void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3334 QualType FromType, QualType ToType) {
3335 // If either type is not valid, include no extra info.
3336 if (FromType.isNull() || ToType.isNull()) {
3337 PDiag << ft_default;
3338 return;
3339 }
3340
3341 // Get the function type from the pointers.
3342 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3343 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3344 *ToMember = ToType->castAs<MemberPointerType>();
3345 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3346 ToMember->getMostRecentCXXRecordDecl())) {
3347 PDiag << ft_different_class;
3348 if (ToMember->isSugared())
3349 PDiag << Context.getTypeDeclType(
3350 ToMember->getMostRecentCXXRecordDecl());
3351 else
3352 PDiag << ToMember->getQualifier();
3353 if (FromMember->isSugared())
3354 PDiag << Context.getTypeDeclType(
3355 FromMember->getMostRecentCXXRecordDecl());
3356 else
3357 PDiag << FromMember->getQualifier();
3358 return;
3359 }
3360 FromType = FromMember->getPointeeType();
3361 ToType = ToMember->getPointeeType();
3362 }
3363
3364 if (FromType->isPointerType())
3365 FromType = FromType->getPointeeType();
3366 if (ToType->isPointerType())
3367 ToType = ToType->getPointeeType();
3368
3369 // Remove references.
3370 FromType = FromType.getNonReferenceType();
3371 ToType = ToType.getNonReferenceType();
3372
3373 // Don't print extra info for non-specialized template functions.
3374 if (FromType->isInstantiationDependentType() &&
3375 !FromType->getAs<TemplateSpecializationType>()) {
3376 PDiag << ft_default;
3377 return;
3378 }
3379
3380 // No extra info for same types.
3381 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3382 PDiag << ft_default;
3383 return;
3384 }
3385
3386 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3387 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3388
3389 // Both types need to be function types.
3390 if (!FromFunction || !ToFunction) {
3391 PDiag << ft_default;
3392 return;
3393 }
3394
3395 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3396 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3397 << FromFunction->getNumParams();
3398 return;
3399 }
3400
3401 // Handle different parameter types.
3402 unsigned ArgPos;
3403 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3404 PDiag << ft_parameter_mismatch << ArgPos + 1
3405 << ToFunction->getParamType(i: ArgPos)
3406 << FromFunction->getParamType(i: ArgPos);
3407 return;
3408 }
3409
3410 // Handle different return type.
3411 if (!Context.hasSameType(FromFunction->getReturnType(),
3412 ToFunction->getReturnType())) {
3413 PDiag << ft_return_type << ToFunction->getReturnType()
3414 << FromFunction->getReturnType();
3415 return;
3416 }
3417
3418 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3419 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3420 << FromFunction->getMethodQuals();
3421 return;
3422 }
3423
3424 // Handle exception specification differences on canonical type (in C++17
3425 // onwards).
3426 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3427 ->isNothrow() !=
3428 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3429 ->isNothrow()) {
3430 PDiag << ft_noexcept;
3431 return;
3432 }
3433
3434 // Unable to find a difference, so add no extra info.
3435 PDiag << ft_default;
3436}
3437
3438bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3439 ArrayRef<QualType> New, unsigned *ArgPos,
3440 bool Reversed) {
3441 assert(llvm::size(Old) == llvm::size(New) &&
3442 "Can't compare parameters of functions with different number of "
3443 "parameters!");
3444
3445 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3446 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3447 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3448
3449 // Ignore address spaces in pointee type. This is to disallow overloading
3450 // on __ptr32/__ptr64 address spaces.
3451 QualType OldType =
3452 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3453 QualType NewType =
3454 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3455
3456 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3457 if (ArgPos)
3458 *ArgPos = Idx;
3459 return false;
3460 }
3461 }
3462 return true;
3463}
3464
3465bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3466 const FunctionProtoType *NewType,
3467 unsigned *ArgPos, bool Reversed) {
3468 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3469 New: NewType->param_types(), ArgPos, Reversed);
3470}
3471
3472bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3473 const FunctionDecl *NewFunction,
3474 unsigned *ArgPos,
3475 bool Reversed) {
3476
3477 if (OldFunction->getNumNonObjectParams() !=
3478 NewFunction->getNumNonObjectParams())
3479 return false;
3480
3481 unsigned OldIgnore =
3482 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3483 unsigned NewIgnore =
3484 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3485
3486 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3487 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3488
3489 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3490 NewPT->param_types().slice(NewIgnore),
3491 ArgPos, Reversed);
3492}
3493
3494bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3495 CastKind &Kind,
3496 CXXCastPath& BasePath,
3497 bool IgnoreBaseAccess,
3498 bool Diagnose) {
3499 QualType FromType = From->getType();
3500 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3501
3502 Kind = CK_BitCast;
3503
3504 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3505 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3506 Expr::NPCK_ZeroExpression) {
3507 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3508 DiagRuntimeBehavior(From->getExprLoc(), From,
3509 PDiag(diag::warn_impcast_bool_to_null_pointer)
3510 << ToType << From->getSourceRange());
3511 else if (!isUnevaluatedContext())
3512 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3513 << ToType << From->getSourceRange();
3514 }
3515 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3516 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3517 QualType FromPointeeType = FromPtrType->getPointeeType(),
3518 ToPointeeType = ToPtrType->getPointeeType();
3519
3520 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3521 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3522 // We must have a derived-to-base conversion. Check an
3523 // ambiguous or inaccessible conversion.
3524 unsigned InaccessibleID = 0;
3525 unsigned AmbiguousID = 0;
3526 if (Diagnose) {
3527 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3528 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3529 }
3530 if (CheckDerivedToBaseConversion(
3531 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3532 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3533 &BasePath, IgnoreBaseAccess))
3534 return true;
3535
3536 // The conversion was successful.
3537 Kind = CK_DerivedToBase;
3538 }
3539
3540 if (Diagnose && !IsCStyleOrFunctionalCast &&
3541 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3542 assert(getLangOpts().MSVCCompat &&
3543 "this should only be possible with MSVCCompat!");
3544 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3545 << From->getSourceRange();
3546 }
3547 }
3548 } else if (const ObjCObjectPointerType *ToPtrType =
3549 ToType->getAs<ObjCObjectPointerType>()) {
3550 if (const ObjCObjectPointerType *FromPtrType =
3551 FromType->getAs<ObjCObjectPointerType>()) {
3552 // Objective-C++ conversions are always okay.
3553 // FIXME: We should have a different class of conversions for the
3554 // Objective-C++ implicit conversions.
3555 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3556 return false;
3557 } else if (FromType->isBlockPointerType()) {
3558 Kind = CK_BlockPointerToObjCPointerCast;
3559 } else {
3560 Kind = CK_CPointerToObjCPointerCast;
3561 }
3562 } else if (ToType->isBlockPointerType()) {
3563 if (!FromType->isBlockPointerType())
3564 Kind = CK_AnyPointerToBlockPointerCast;
3565 }
3566
3567 // We shouldn't fall into this case unless it's valid for other
3568 // reasons.
3569 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3570 Kind = CK_NullToPointer;
3571
3572 return false;
3573}
3574
3575bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3576 QualType ToType,
3577 bool InOverloadResolution,
3578 QualType &ConvertedType) {
3579 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3580 if (!ToTypePtr)
3581 return false;
3582
3583 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3584 if (From->isNullPointerConstant(Ctx&: Context,
3585 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3586 : Expr::NPC_ValueDependentIsNull)) {
3587 ConvertedType = ToType;
3588 return true;
3589 }
3590
3591 // Otherwise, both types have to be member pointers.
3592 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3593 if (!FromTypePtr)
3594 return false;
3595
3596 // A pointer to member of B can be converted to a pointer to member of D,
3597 // where D is derived from B (C++ 4.11p2).
3598 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3599 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3600
3601 if (!declaresSameEntity(FromClass, ToClass) &&
3602 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3603 ConvertedType = Context.getMemberPointerType(
3604 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3605 return true;
3606 }
3607
3608 return false;
3609}
3610
3611Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3612 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3613 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3614 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3615 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3616 if (!FromPtrType) {
3617 // This must be a null pointer to member pointer conversion
3618 Kind = CK_NullToMemberPointer;
3619 return MemberPointerConversionResult::Success;
3620 }
3621
3622 // Lock down the inheritance model right now in MS ABI, whether or not the
3623 // pointee types are the same.
3624 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3625 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3626 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3627 }
3628
3629 // T == T, modulo cv
3630 if (Direction == MemberPointerConversionDirection::Upcast &&
3631 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3632 T2: ToPtrType->getPointeeType()))
3633 return MemberPointerConversionResult::DifferentPointee;
3634
3635 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3636 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3637
3638 auto DiagCls = [](PartialDiagnostic &PD, NestedNameSpecifier *Qual,
3639 const CXXRecordDecl *Cls) {
3640 if (declaresSameEntity(Qual->getAsRecordDecl(), Cls))
3641 PD << Qual;
3642 else
3643 PD << QualType(Cls->getTypeForDecl(), 0);
3644 };
3645 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3646 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3647 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3648 return PD;
3649 };
3650
3651 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3652 if (Direction == MemberPointerConversionDirection::Upcast)
3653 std::swap(a&: Base, b&: Derived);
3654
3655 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3656 /*DetectVirtual=*/true);
3657 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3658 return MemberPointerConversionResult::NotDerived;
3659
3660 if (Paths.isAmbiguous(
3661 BaseType: Base->getTypeForDecl()->getCanonicalTypeUnqualified())) {
3662 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3663 PD << int(Direction);
3664 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3665 Diag(CheckLoc, PD);
3666 return MemberPointerConversionResult::Ambiguous;
3667 }
3668
3669 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3670 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3671 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3672 Diag(CheckLoc, PD);
3673 return MemberPointerConversionResult::Virtual;
3674 }
3675
3676 // Must be a base to derived member conversion.
3677 BuildBasePathArray(Paths, BasePath);
3678 Kind = Direction == MemberPointerConversionDirection::Upcast
3679 ? CK_DerivedToBaseMemberPointer
3680 : CK_BaseToDerivedMemberPointer;
3681
3682 if (!IgnoreBaseAccess)
3683 switch (CheckBaseClassAccess(
3684 CheckLoc, Base, Derived, Paths.front(),
3685 Direction == MemberPointerConversionDirection::Upcast
3686 ? diag::err_upcast_to_inaccessible_base
3687 : diag::err_downcast_from_inaccessible_base,
3688 [&](PartialDiagnostic &PD) {
3689 NestedNameSpecifier *BaseQual = FromPtrType->getQualifier(),
3690 *DerivedQual = ToPtrType->getQualifier();
3691 if (Direction == MemberPointerConversionDirection::Upcast)
3692 std::swap(BaseQual, DerivedQual);
3693 DiagCls(PD, DerivedQual, Derived);
3694 DiagCls(PD, BaseQual, Base);
3695 })) {
3696 case Sema::AR_accessible:
3697 case Sema::AR_delayed:
3698 case Sema::AR_dependent:
3699 // Optimistically assume that the delayed and dependent cases
3700 // will work out.
3701 break;
3702
3703 case Sema::AR_inaccessible:
3704 return MemberPointerConversionResult::Inaccessible;
3705 }
3706
3707 return MemberPointerConversionResult::Success;
3708}
3709
3710/// Determine whether the lifetime conversion between the two given
3711/// qualifiers sets is nontrivial.
3712static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3713 Qualifiers ToQuals) {
3714 // Converting anything to const __unsafe_unretained is trivial.
3715 if (ToQuals.hasConst() &&
3716 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3717 return false;
3718
3719 return true;
3720}
3721
3722/// Perform a single iteration of the loop for checking if a qualification
3723/// conversion is valid.
3724///
3725/// Specifically, check whether any change between the qualifiers of \p
3726/// FromType and \p ToType is permissible, given knowledge about whether every
3727/// outer layer is const-qualified.
3728static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3729 bool CStyle, bool IsTopLevel,
3730 bool &PreviousToQualsIncludeConst,
3731 bool &ObjCLifetimeConversion,
3732 const ASTContext &Ctx) {
3733 Qualifiers FromQuals = FromType.getQualifiers();
3734 Qualifiers ToQuals = ToType.getQualifiers();
3735
3736 // Ignore __unaligned qualifier.
3737 FromQuals.removeUnaligned();
3738
3739 // Objective-C ARC:
3740 // Check Objective-C lifetime conversions.
3741 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3742 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3743 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3744 ObjCLifetimeConversion = true;
3745 FromQuals.removeObjCLifetime();
3746 ToQuals.removeObjCLifetime();
3747 } else {
3748 // Qualification conversions cannot cast between different
3749 // Objective-C lifetime qualifiers.
3750 return false;
3751 }
3752 }
3753
3754 // Allow addition/removal of GC attributes but not changing GC attributes.
3755 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3756 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3757 FromQuals.removeObjCGCAttr();
3758 ToQuals.removeObjCGCAttr();
3759 }
3760
3761 // __ptrauth qualifiers must match exactly.
3762 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3763 return false;
3764
3765 // -- for every j > 0, if const is in cv 1,j then const is in cv
3766 // 2,j, and similarly for volatile.
3767 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3768 return false;
3769
3770 // If address spaces mismatch:
3771 // - in top level it is only valid to convert to addr space that is a
3772 // superset in all cases apart from C-style casts where we allow
3773 // conversions between overlapping address spaces.
3774 // - in non-top levels it is not a valid conversion.
3775 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3776 (!IsTopLevel ||
3777 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3778 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3779 return false;
3780
3781 // -- if the cv 1,j and cv 2,j are different, then const is in
3782 // every cv for 0 < k < j.
3783 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3784 !PreviousToQualsIncludeConst)
3785 return false;
3786
3787 // The following wording is from C++20, where the result of the conversion
3788 // is T3, not T2.
3789 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3790 // "array of unknown bound of"
3791 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3792 return false;
3793
3794 // -- if the resulting P3,i is different from P1,i [...], then const is
3795 // added to every cv 3_k for 0 < k < i.
3796 if (!CStyle && FromType->isConstantArrayType() &&
3797 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3798 return false;
3799
3800 // Keep track of whether all prior cv-qualifiers in the "to" type
3801 // include const.
3802 PreviousToQualsIncludeConst =
3803 PreviousToQualsIncludeConst && ToQuals.hasConst();
3804 return true;
3805}
3806
3807bool
3808Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3809 bool CStyle, bool &ObjCLifetimeConversion) {
3810 FromType = Context.getCanonicalType(T: FromType);
3811 ToType = Context.getCanonicalType(T: ToType);
3812 ObjCLifetimeConversion = false;
3813
3814 // If FromType and ToType are the same type, this is not a
3815 // qualification conversion.
3816 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3817 return false;
3818
3819 // (C++ 4.4p4):
3820 // A conversion can add cv-qualifiers at levels other than the first
3821 // in multi-level pointers, subject to the following rules: [...]
3822 bool PreviousToQualsIncludeConst = true;
3823 bool UnwrappedAnyPointer = false;
3824 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3825 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3826 IsTopLevel: !UnwrappedAnyPointer,
3827 PreviousToQualsIncludeConst,
3828 ObjCLifetimeConversion, Ctx: getASTContext()))
3829 return false;
3830 UnwrappedAnyPointer = true;
3831 }
3832
3833 // We are left with FromType and ToType being the pointee types
3834 // after unwrapping the original FromType and ToType the same number
3835 // of times. If we unwrapped any pointers, and if FromType and
3836 // ToType have the same unqualified type (since we checked
3837 // qualifiers above), then this is a qualification conversion.
3838 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3839}
3840
3841/// - Determine whether this is a conversion from a scalar type to an
3842/// atomic type.
3843///
3844/// If successful, updates \c SCS's second and third steps in the conversion
3845/// sequence to finish the conversion.
3846static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3847 bool InOverloadResolution,
3848 StandardConversionSequence &SCS,
3849 bool CStyle) {
3850 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3851 if (!ToAtomic)
3852 return false;
3853
3854 StandardConversionSequence InnerSCS;
3855 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3856 InOverloadResolution, SCS&: InnerSCS,
3857 CStyle, /*AllowObjCWritebackConversion=*/false))
3858 return false;
3859
3860 SCS.Second = InnerSCS.Second;
3861 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3862 SCS.Third = InnerSCS.Third;
3863 SCS.QualificationIncludesObjCLifetime
3864 = InnerSCS.QualificationIncludesObjCLifetime;
3865 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3866 return true;
3867}
3868
3869static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3870 CXXConstructorDecl *Constructor,
3871 QualType Type) {
3872 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3873 if (CtorType->getNumParams() > 0) {
3874 QualType FirstArg = CtorType->getParamType(0);
3875 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
3876 return true;
3877 }
3878 return false;
3879}
3880
3881static OverloadingResult
3882IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3883 CXXRecordDecl *To,
3884 UserDefinedConversionSequence &User,
3885 OverloadCandidateSet &CandidateSet,
3886 bool AllowExplicit) {
3887 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3888 for (auto *D : S.LookupConstructors(Class: To)) {
3889 auto Info = getConstructorInfo(ND: D);
3890 if (!Info)
3891 continue;
3892
3893 bool Usable = !Info.Constructor->isInvalidDecl() &&
3894 S.isInitListConstructor(Info.Constructor);
3895 if (Usable) {
3896 bool SuppressUserConversions = false;
3897 if (Info.ConstructorTmpl)
3898 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
3899 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
3900 CandidateSet, SuppressUserConversions,
3901 /*PartialOverloading*/ false,
3902 AllowExplicit);
3903 else
3904 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3905 CandidateSet, SuppressUserConversions,
3906 /*PartialOverloading*/ false, AllowExplicit);
3907 }
3908 }
3909
3910 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3911
3912 OverloadCandidateSet::iterator Best;
3913 switch (auto Result =
3914 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3915 case OR_Deleted:
3916 case OR_Success: {
3917 // Record the standard conversion we used and the conversion function.
3918 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
3919 QualType ThisType = Constructor->getFunctionObjectParameterType();
3920 // Initializer lists don't have conversions as such.
3921 User.Before.setAsIdentityConversion();
3922 User.HadMultipleCandidates = HadMultipleCandidates;
3923 User.ConversionFunction = Constructor;
3924 User.FoundConversionFunction = Best->FoundDecl;
3925 User.After.setAsIdentityConversion();
3926 User.After.setFromType(ThisType);
3927 User.After.setAllToTypes(ToType);
3928 return Result;
3929 }
3930
3931 case OR_No_Viable_Function:
3932 return OR_No_Viable_Function;
3933 case OR_Ambiguous:
3934 return OR_Ambiguous;
3935 }
3936
3937 llvm_unreachable("Invalid OverloadResult!");
3938}
3939
3940/// Determines whether there is a user-defined conversion sequence
3941/// (C++ [over.ics.user]) that converts expression From to the type
3942/// ToType. If such a conversion exists, User will contain the
3943/// user-defined conversion sequence that performs such a conversion
3944/// and this routine will return true. Otherwise, this routine returns
3945/// false and User is unspecified.
3946///
3947/// \param AllowExplicit true if the conversion should consider C++0x
3948/// "explicit" conversion functions as well as non-explicit conversion
3949/// functions (C++0x [class.conv.fct]p2).
3950///
3951/// \param AllowObjCConversionOnExplicit true if the conversion should
3952/// allow an extra Objective-C pointer conversion on uses of explicit
3953/// constructors. Requires \c AllowExplicit to also be set.
3954static OverloadingResult
3955IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3956 UserDefinedConversionSequence &User,
3957 OverloadCandidateSet &CandidateSet,
3958 AllowedExplicit AllowExplicit,
3959 bool AllowObjCConversionOnExplicit) {
3960 assert(AllowExplicit != AllowedExplicit::None ||
3961 !AllowObjCConversionOnExplicit);
3962 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3963
3964 // Whether we will only visit constructors.
3965 bool ConstructorsOnly = false;
3966
3967 // If the type we are conversion to is a class type, enumerate its
3968 // constructors.
3969 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3970 // C++ [over.match.ctor]p1:
3971 // When objects of class type are direct-initialized (8.5), or
3972 // copy-initialized from an expression of the same or a
3973 // derived class type (8.5), overload resolution selects the
3974 // constructor. [...] For copy-initialization, the candidate
3975 // functions are all the converting constructors (12.3.1) of
3976 // that class. The argument list is the expression-list within
3977 // the parentheses of the initializer.
3978 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
3979 (From->getType()->getAs<RecordType>() &&
3980 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3981 ConstructorsOnly = true;
3982
3983 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
3984 // We're not going to find any constructors.
3985 } else if (CXXRecordDecl *ToRecordDecl
3986 = dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
3987
3988 Expr **Args = &From;
3989 unsigned NumArgs = 1;
3990 bool ListInitializing = false;
3991 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
3992 // But first, see if there is an init-list-constructor that will work.
3993 OverloadingResult Result = IsInitializerListConstructorConversion(
3994 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
3995 AllowExplicit: AllowExplicit == AllowedExplicit::All);
3996 if (Result != OR_No_Viable_Function)
3997 return Result;
3998 // Never mind.
3999 CandidateSet.clear(
4000 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4001
4002 // If we're list-initializing, we pass the individual elements as
4003 // arguments, not the entire list.
4004 Args = InitList->getInits();
4005 NumArgs = InitList->getNumInits();
4006 ListInitializing = true;
4007 }
4008
4009 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4010 auto Info = getConstructorInfo(ND: D);
4011 if (!Info)
4012 continue;
4013
4014 bool Usable = !Info.Constructor->isInvalidDecl();
4015 if (!ListInitializing)
4016 Usable = Usable && Info.Constructor->isConvertingConstructor(
4017 /*AllowExplicit*/ true);
4018 if (Usable) {
4019 bool SuppressUserConversions = !ConstructorsOnly;
4020 // C++20 [over.best.ics.general]/4.5:
4021 // if the target is the first parameter of a constructor [of class
4022 // X] and the constructor [...] is a candidate by [...] the second
4023 // phase of [over.match.list] when the initializer list has exactly
4024 // one element that is itself an initializer list, [...] and the
4025 // conversion is to X or reference to cv X, user-defined conversion
4026 // sequences are not considered.
4027 if (SuppressUserConversions && ListInitializing) {
4028 SuppressUserConversions =
4029 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4030 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4031 Type: ToType);
4032 }
4033 if (Info.ConstructorTmpl)
4034 S.AddTemplateOverloadCandidate(
4035 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4036 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4037 CandidateSet, SuppressUserConversions,
4038 /*PartialOverloading*/ false,
4039 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4040 else
4041 // Allow one user-defined conversion when user specifies a
4042 // From->ToType conversion via an static cast (c-style, etc).
4043 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4044 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4045 SuppressUserConversions,
4046 /*PartialOverloading*/ false,
4047 AllowExplicit == AllowedExplicit::All);
4048 }
4049 }
4050 }
4051 }
4052
4053 // Enumerate conversion functions, if we're allowed to.
4054 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4055 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4056 // No conversion functions from incomplete types.
4057 } else if (const RecordType *FromRecordType =
4058 From->getType()->getAs<RecordType>()) {
4059 if (CXXRecordDecl *FromRecordDecl
4060 = dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4061 // Add all of the conversion functions as candidates.
4062 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4063 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4064 DeclAccessPair FoundDecl = I.getPair();
4065 NamedDecl *D = FoundDecl.getDecl();
4066 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4067 if (isa<UsingShadowDecl>(Val: D))
4068 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4069
4070 CXXConversionDecl *Conv;
4071 FunctionTemplateDecl *ConvTemplate;
4072 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4073 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4074 else
4075 Conv = cast<CXXConversionDecl>(Val: D);
4076
4077 if (ConvTemplate)
4078 S.AddTemplateConversionCandidate(
4079 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4080 CandidateSet, AllowObjCConversionOnExplicit,
4081 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4082 else
4083 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4084 CandidateSet, AllowObjCConversionOnExplicit,
4085 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4086 }
4087 }
4088 }
4089
4090 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4091
4092 OverloadCandidateSet::iterator Best;
4093 switch (auto Result =
4094 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4095 case OR_Success:
4096 case OR_Deleted:
4097 // Record the standard conversion we used and the conversion function.
4098 if (CXXConstructorDecl *Constructor
4099 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4100 // C++ [over.ics.user]p1:
4101 // If the user-defined conversion is specified by a
4102 // constructor (12.3.1), the initial standard conversion
4103 // sequence converts the source type to the type required by
4104 // the argument of the constructor.
4105 //
4106 if (isa<InitListExpr>(Val: From)) {
4107 // Initializer lists don't have conversions as such.
4108 User.Before.setAsIdentityConversion();
4109 User.Before.FromBracedInitList = true;
4110 } else {
4111 if (Best->Conversions[0].isEllipsis())
4112 User.EllipsisConversion = true;
4113 else {
4114 User.Before = Best->Conversions[0].Standard;
4115 User.EllipsisConversion = false;
4116 }
4117 }
4118 User.HadMultipleCandidates = HadMultipleCandidates;
4119 User.ConversionFunction = Constructor;
4120 User.FoundConversionFunction = Best->FoundDecl;
4121 User.After.setAsIdentityConversion();
4122 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4123 User.After.setAllToTypes(ToType);
4124 return Result;
4125 }
4126 if (CXXConversionDecl *Conversion
4127 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4128
4129 assert(Best->HasFinalConversion);
4130
4131 // C++ [over.ics.user]p1:
4132 //
4133 // [...] If the user-defined conversion is specified by a
4134 // conversion function (12.3.2), the initial standard
4135 // conversion sequence converts the source type to the
4136 // implicit object parameter of the conversion function.
4137 User.Before = Best->Conversions[0].Standard;
4138 User.HadMultipleCandidates = HadMultipleCandidates;
4139 User.ConversionFunction = Conversion;
4140 User.FoundConversionFunction = Best->FoundDecl;
4141 User.EllipsisConversion = false;
4142
4143 // C++ [over.ics.user]p2:
4144 // The second standard conversion sequence converts the
4145 // result of the user-defined conversion to the target type
4146 // for the sequence. Since an implicit conversion sequence
4147 // is an initialization, the special rules for
4148 // initialization by user-defined conversion apply when
4149 // selecting the best user-defined conversion for a
4150 // user-defined conversion sequence (see 13.3.3 and
4151 // 13.3.3.1).
4152 User.After = Best->FinalConversion;
4153 return Result;
4154 }
4155 llvm_unreachable("Not a constructor or conversion function?");
4156
4157 case OR_No_Viable_Function:
4158 return OR_No_Viable_Function;
4159
4160 case OR_Ambiguous:
4161 return OR_Ambiguous;
4162 }
4163
4164 llvm_unreachable("Invalid OverloadResult!");
4165}
4166
4167bool
4168Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4169 ImplicitConversionSequence ICS;
4170 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4171 OverloadCandidateSet::CSK_Normal);
4172 OverloadingResult OvResult =
4173 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4174 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4175
4176 if (!(OvResult == OR_Ambiguous ||
4177 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4178 return false;
4179
4180 auto Cands = CandidateSet.CompleteCandidates(
4181 S&: *this,
4182 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4183 Args: From);
4184 if (OvResult == OR_Ambiguous)
4185 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4186 << From->getType() << ToType << From->getSourceRange();
4187 else { // OR_No_Viable_Function && !CandidateSet.empty()
4188 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4189 diag::err_typecheck_nonviable_condition_incomplete,
4190 From->getType(), From->getSourceRange()))
4191 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4192 << false << From->getType() << From->getSourceRange() << ToType;
4193 }
4194
4195 CandidateSet.NoteCandidates(
4196 S&: *this, Args: From, Cands);
4197 return true;
4198}
4199
4200// Helper for compareConversionFunctions that gets the FunctionType that the
4201// conversion-operator return value 'points' to, or nullptr.
4202static const FunctionType *
4203getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4204 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4205 const PointerType *RetPtrTy =
4206 ConvFuncTy->getReturnType()->getAs<PointerType>();
4207
4208 if (!RetPtrTy)
4209 return nullptr;
4210
4211 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4212}
4213
4214/// Compare the user-defined conversion functions or constructors
4215/// of two user-defined conversion sequences to determine whether any ordering
4216/// is possible.
4217static ImplicitConversionSequence::CompareKind
4218compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4219 FunctionDecl *Function2) {
4220 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4221 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4222 if (!Conv1 || !Conv2)
4223 return ImplicitConversionSequence::Indistinguishable;
4224
4225 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4226 return ImplicitConversionSequence::Indistinguishable;
4227
4228 // Objective-C++:
4229 // If both conversion functions are implicitly-declared conversions from
4230 // a lambda closure type to a function pointer and a block pointer,
4231 // respectively, always prefer the conversion to a function pointer,
4232 // because the function pointer is more lightweight and is more likely
4233 // to keep code working.
4234 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4235 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4236 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4237 if (Block1 != Block2)
4238 return Block1 ? ImplicitConversionSequence::Worse
4239 : ImplicitConversionSequence::Better;
4240 }
4241
4242 // In order to support multiple calling conventions for the lambda conversion
4243 // operator (such as when the free and member function calling convention is
4244 // different), prefer the 'free' mechanism, followed by the calling-convention
4245 // of operator(). The latter is in place to support the MSVC-like solution of
4246 // defining ALL of the possible conversions in regards to calling-convention.
4247 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4248 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4249
4250 if (Conv1FuncRet && Conv2FuncRet &&
4251 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4252 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4253 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4254
4255 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4256 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4257
4258 CallingConv CallOpCC =
4259 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4260 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4261 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4262 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4263 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4264
4265 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4266 for (CallingConv CC : PrefOrder) {
4267 if (Conv1CC == CC)
4268 return ImplicitConversionSequence::Better;
4269 if (Conv2CC == CC)
4270 return ImplicitConversionSequence::Worse;
4271 }
4272 }
4273
4274 return ImplicitConversionSequence::Indistinguishable;
4275}
4276
4277static bool hasDeprecatedStringLiteralToCharPtrConversion(
4278 const ImplicitConversionSequence &ICS) {
4279 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4280 (ICS.isUserDefined() &&
4281 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4282}
4283
4284/// CompareImplicitConversionSequences - Compare two implicit
4285/// conversion sequences to determine whether one is better than the
4286/// other or if they are indistinguishable (C++ 13.3.3.2).
4287static ImplicitConversionSequence::CompareKind
4288CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4289 const ImplicitConversionSequence& ICS1,
4290 const ImplicitConversionSequence& ICS2)
4291{
4292 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4293 // conversion sequences (as defined in 13.3.3.1)
4294 // -- a standard conversion sequence (13.3.3.1.1) is a better
4295 // conversion sequence than a user-defined conversion sequence or
4296 // an ellipsis conversion sequence, and
4297 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4298 // conversion sequence than an ellipsis conversion sequence
4299 // (13.3.3.1.3).
4300 //
4301 // C++0x [over.best.ics]p10:
4302 // For the purpose of ranking implicit conversion sequences as
4303 // described in 13.3.3.2, the ambiguous conversion sequence is
4304 // treated as a user-defined sequence that is indistinguishable
4305 // from any other user-defined conversion sequence.
4306
4307 // String literal to 'char *' conversion has been deprecated in C++03. It has
4308 // been removed from C++11. We still accept this conversion, if it happens at
4309 // the best viable function. Otherwise, this conversion is considered worse
4310 // than ellipsis conversion. Consider this as an extension; this is not in the
4311 // standard. For example:
4312 //
4313 // int &f(...); // #1
4314 // void f(char*); // #2
4315 // void g() { int &r = f("foo"); }
4316 //
4317 // In C++03, we pick #2 as the best viable function.
4318 // In C++11, we pick #1 as the best viable function, because ellipsis
4319 // conversion is better than string-literal to char* conversion (since there
4320 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4321 // convert arguments, #2 would be the best viable function in C++11.
4322 // If the best viable function has this conversion, a warning will be issued
4323 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4324
4325 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4326 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4327 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4328 // Ill-formedness must not differ
4329 ICS1.isBad() == ICS2.isBad())
4330 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4331 ? ImplicitConversionSequence::Worse
4332 : ImplicitConversionSequence::Better;
4333
4334 if (ICS1.getKindRank() < ICS2.getKindRank())
4335 return ImplicitConversionSequence::Better;
4336 if (ICS2.getKindRank() < ICS1.getKindRank())
4337 return ImplicitConversionSequence::Worse;
4338
4339 // The following checks require both conversion sequences to be of
4340 // the same kind.
4341 if (ICS1.getKind() != ICS2.getKind())
4342 return ImplicitConversionSequence::Indistinguishable;
4343
4344 ImplicitConversionSequence::CompareKind Result =
4345 ImplicitConversionSequence::Indistinguishable;
4346
4347 // Two implicit conversion sequences of the same form are
4348 // indistinguishable conversion sequences unless one of the
4349 // following rules apply: (C++ 13.3.3.2p3):
4350
4351 // List-initialization sequence L1 is a better conversion sequence than
4352 // list-initialization sequence L2 if:
4353 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4354 // if not that,
4355 // — L1 and L2 convert to arrays of the same element type, and either the
4356 // number of elements n_1 initialized by L1 is less than the number of
4357 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4358 // an array of unknown bound and L1 does not,
4359 // even if one of the other rules in this paragraph would otherwise apply.
4360 if (!ICS1.isBad()) {
4361 bool StdInit1 = false, StdInit2 = false;
4362 if (ICS1.hasInitializerListContainerType())
4363 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4364 Element: nullptr);
4365 if (ICS2.hasInitializerListContainerType())
4366 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4367 Element: nullptr);
4368 if (StdInit1 != StdInit2)
4369 return StdInit1 ? ImplicitConversionSequence::Better
4370 : ImplicitConversionSequence::Worse;
4371
4372 if (ICS1.hasInitializerListContainerType() &&
4373 ICS2.hasInitializerListContainerType())
4374 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4375 T: ICS1.getInitializerListContainerType()))
4376 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4377 T: ICS2.getInitializerListContainerType())) {
4378 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4379 T2: CAT2->getElementType())) {
4380 // Both to arrays of the same element type
4381 if (CAT1->getSize() != CAT2->getSize())
4382 // Different sized, the smaller wins
4383 return CAT1->getSize().ult(RHS: CAT2->getSize())
4384 ? ImplicitConversionSequence::Better
4385 : ImplicitConversionSequence::Worse;
4386 if (ICS1.isInitializerListOfIncompleteArray() !=
4387 ICS2.isInitializerListOfIncompleteArray())
4388 // One is incomplete, it loses
4389 return ICS2.isInitializerListOfIncompleteArray()
4390 ? ImplicitConversionSequence::Better
4391 : ImplicitConversionSequence::Worse;
4392 }
4393 }
4394 }
4395
4396 if (ICS1.isStandard())
4397 // Standard conversion sequence S1 is a better conversion sequence than
4398 // standard conversion sequence S2 if [...]
4399 Result = CompareStandardConversionSequences(S, Loc,
4400 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4401 else if (ICS1.isUserDefined()) {
4402 // User-defined conversion sequence U1 is a better conversion
4403 // sequence than another user-defined conversion sequence U2 if
4404 // they contain the same user-defined conversion function or
4405 // constructor and if the second standard conversion sequence of
4406 // U1 is better than the second standard conversion sequence of
4407 // U2 (C++ 13.3.3.2p3).
4408 if (ICS1.UserDefined.ConversionFunction ==
4409 ICS2.UserDefined.ConversionFunction)
4410 Result = CompareStandardConversionSequences(S, Loc,
4411 SCS1: ICS1.UserDefined.After,
4412 SCS2: ICS2.UserDefined.After);
4413 else
4414 Result = compareConversionFunctions(S,
4415 Function1: ICS1.UserDefined.ConversionFunction,
4416 Function2: ICS2.UserDefined.ConversionFunction);
4417 }
4418
4419 return Result;
4420}
4421
4422// Per 13.3.3.2p3, compare the given standard conversion sequences to
4423// determine if one is a proper subset of the other.
4424static ImplicitConversionSequence::CompareKind
4425compareStandardConversionSubsets(ASTContext &Context,
4426 const StandardConversionSequence& SCS1,
4427 const StandardConversionSequence& SCS2) {
4428 ImplicitConversionSequence::CompareKind Result
4429 = ImplicitConversionSequence::Indistinguishable;
4430
4431 // the identity conversion sequence is considered to be a subsequence of
4432 // any non-identity conversion sequence
4433 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4434 return ImplicitConversionSequence::Better;
4435 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4436 return ImplicitConversionSequence::Worse;
4437
4438 if (SCS1.Second != SCS2.Second) {
4439 if (SCS1.Second == ICK_Identity)
4440 Result = ImplicitConversionSequence::Better;
4441 else if (SCS2.Second == ICK_Identity)
4442 Result = ImplicitConversionSequence::Worse;
4443 else
4444 return ImplicitConversionSequence::Indistinguishable;
4445 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4446 return ImplicitConversionSequence::Indistinguishable;
4447
4448 if (SCS1.Third == SCS2.Third) {
4449 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4450 : ImplicitConversionSequence::Indistinguishable;
4451 }
4452
4453 if (SCS1.Third == ICK_Identity)
4454 return Result == ImplicitConversionSequence::Worse
4455 ? ImplicitConversionSequence::Indistinguishable
4456 : ImplicitConversionSequence::Better;
4457
4458 if (SCS2.Third == ICK_Identity)
4459 return Result == ImplicitConversionSequence::Better
4460 ? ImplicitConversionSequence::Indistinguishable
4461 : ImplicitConversionSequence::Worse;
4462
4463 return ImplicitConversionSequence::Indistinguishable;
4464}
4465
4466/// Determine whether one of the given reference bindings is better
4467/// than the other based on what kind of bindings they are.
4468static bool
4469isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4470 const StandardConversionSequence &SCS2) {
4471 // C++0x [over.ics.rank]p3b4:
4472 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4473 // implicit object parameter of a non-static member function declared
4474 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4475 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4476 // lvalue reference to a function lvalue and S2 binds an rvalue
4477 // reference*.
4478 //
4479 // FIXME: Rvalue references. We're going rogue with the above edits,
4480 // because the semantics in the current C++0x working paper (N3225 at the
4481 // time of this writing) break the standard definition of std::forward
4482 // and std::reference_wrapper when dealing with references to functions.
4483 // Proposed wording changes submitted to CWG for consideration.
4484 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4485 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4486 return false;
4487
4488 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4489 SCS2.IsLvalueReference) ||
4490 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4491 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4492}
4493
4494enum class FixedEnumPromotion {
4495 None,
4496 ToUnderlyingType,
4497 ToPromotedUnderlyingType
4498};
4499
4500/// Returns kind of fixed enum promotion the \a SCS uses.
4501static FixedEnumPromotion
4502getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4503
4504 if (SCS.Second != ICK_Integral_Promotion)
4505 return FixedEnumPromotion::None;
4506
4507 QualType FromType = SCS.getFromType();
4508 if (!FromType->isEnumeralType())
4509 return FixedEnumPromotion::None;
4510
4511 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4512 if (!Enum->isFixed())
4513 return FixedEnumPromotion::None;
4514
4515 QualType UnderlyingType = Enum->getIntegerType();
4516 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4517 return FixedEnumPromotion::ToUnderlyingType;
4518
4519 return FixedEnumPromotion::ToPromotedUnderlyingType;
4520}
4521
4522/// CompareStandardConversionSequences - Compare two standard
4523/// conversion sequences to determine whether one is better than the
4524/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4525static ImplicitConversionSequence::CompareKind
4526CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4527 const StandardConversionSequence& SCS1,
4528 const StandardConversionSequence& SCS2)
4529{
4530 // Standard conversion sequence S1 is a better conversion sequence
4531 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4532
4533 // -- S1 is a proper subsequence of S2 (comparing the conversion
4534 // sequences in the canonical form defined by 13.3.3.1.1,
4535 // excluding any Lvalue Transformation; the identity conversion
4536 // sequence is considered to be a subsequence of any
4537 // non-identity conversion sequence) or, if not that,
4538 if (ImplicitConversionSequence::CompareKind CK
4539 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4540 return CK;
4541
4542 // -- the rank of S1 is better than the rank of S2 (by the rules
4543 // defined below), or, if not that,
4544 ImplicitConversionRank Rank1 = SCS1.getRank();
4545 ImplicitConversionRank Rank2 = SCS2.getRank();
4546 if (Rank1 < Rank2)
4547 return ImplicitConversionSequence::Better;
4548 else if (Rank2 < Rank1)
4549 return ImplicitConversionSequence::Worse;
4550
4551 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4552 // are indistinguishable unless one of the following rules
4553 // applies:
4554
4555 // A conversion that is not a conversion of a pointer, or
4556 // pointer to member, to bool is better than another conversion
4557 // that is such a conversion.
4558 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4559 return SCS2.isPointerConversionToBool()
4560 ? ImplicitConversionSequence::Better
4561 : ImplicitConversionSequence::Worse;
4562
4563 // C++14 [over.ics.rank]p4b2:
4564 // This is retroactively applied to C++11 by CWG 1601.
4565 //
4566 // A conversion that promotes an enumeration whose underlying type is fixed
4567 // to its underlying type is better than one that promotes to the promoted
4568 // underlying type, if the two are different.
4569 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4570 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4571 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4572 FEP1 != FEP2)
4573 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4574 ? ImplicitConversionSequence::Better
4575 : ImplicitConversionSequence::Worse;
4576
4577 // C++ [over.ics.rank]p4b2:
4578 //
4579 // If class B is derived directly or indirectly from class A,
4580 // conversion of B* to A* is better than conversion of B* to
4581 // void*, and conversion of A* to void* is better than conversion
4582 // of B* to void*.
4583 bool SCS1ConvertsToVoid
4584 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4585 bool SCS2ConvertsToVoid
4586 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4587 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4588 // Exactly one of the conversion sequences is a conversion to
4589 // a void pointer; it's the worse conversion.
4590 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4591 : ImplicitConversionSequence::Worse;
4592 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4593 // Neither conversion sequence converts to a void pointer; compare
4594 // their derived-to-base conversions.
4595 if (ImplicitConversionSequence::CompareKind DerivedCK
4596 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4597 return DerivedCK;
4598 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4599 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4600 // Both conversion sequences are conversions to void
4601 // pointers. Compare the source types to determine if there's an
4602 // inheritance relationship in their sources.
4603 QualType FromType1 = SCS1.getFromType();
4604 QualType FromType2 = SCS2.getFromType();
4605
4606 // Adjust the types we're converting from via the array-to-pointer
4607 // conversion, if we need to.
4608 if (SCS1.First == ICK_Array_To_Pointer)
4609 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4610 if (SCS2.First == ICK_Array_To_Pointer)
4611 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4612
4613 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4614 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4615
4616 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4617 return ImplicitConversionSequence::Better;
4618 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4619 return ImplicitConversionSequence::Worse;
4620
4621 // Objective-C++: If one interface is more specific than the
4622 // other, it is the better one.
4623 const ObjCObjectPointerType* FromObjCPtr1
4624 = FromType1->getAs<ObjCObjectPointerType>();
4625 const ObjCObjectPointerType* FromObjCPtr2
4626 = FromType2->getAs<ObjCObjectPointerType>();
4627 if (FromObjCPtr1 && FromObjCPtr2) {
4628 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4629 RHSOPT: FromObjCPtr2);
4630 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4631 RHSOPT: FromObjCPtr1);
4632 if (AssignLeft != AssignRight) {
4633 return AssignLeft? ImplicitConversionSequence::Better
4634 : ImplicitConversionSequence::Worse;
4635 }
4636 }
4637 }
4638
4639 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4640 // Check for a better reference binding based on the kind of bindings.
4641 if (isBetterReferenceBindingKind(SCS1, SCS2))
4642 return ImplicitConversionSequence::Better;
4643 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4644 return ImplicitConversionSequence::Worse;
4645 }
4646
4647 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4648 // bullet 3).
4649 if (ImplicitConversionSequence::CompareKind QualCK
4650 = CompareQualificationConversions(S, SCS1, SCS2))
4651 return QualCK;
4652
4653 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4654 // C++ [over.ics.rank]p3b4:
4655 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4656 // which the references refer are the same type except for
4657 // top-level cv-qualifiers, and the type to which the reference
4658 // initialized by S2 refers is more cv-qualified than the type
4659 // to which the reference initialized by S1 refers.
4660 QualType T1 = SCS1.getToType(Idx: 2);
4661 QualType T2 = SCS2.getToType(Idx: 2);
4662 T1 = S.Context.getCanonicalType(T: T1);
4663 T2 = S.Context.getCanonicalType(T: T2);
4664 Qualifiers T1Quals, T2Quals;
4665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4667 if (UnqualT1 == UnqualT2) {
4668 // Objective-C++ ARC: If the references refer to objects with different
4669 // lifetimes, prefer bindings that don't change lifetime.
4670 if (SCS1.ObjCLifetimeConversionBinding !=
4671 SCS2.ObjCLifetimeConversionBinding) {
4672 return SCS1.ObjCLifetimeConversionBinding
4673 ? ImplicitConversionSequence::Worse
4674 : ImplicitConversionSequence::Better;
4675 }
4676
4677 // If the type is an array type, promote the element qualifiers to the
4678 // type for comparison.
4679 if (isa<ArrayType>(Val: T1) && T1Quals)
4680 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4681 if (isa<ArrayType>(Val: T2) && T2Quals)
4682 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4683 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4684 return ImplicitConversionSequence::Better;
4685 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4686 return ImplicitConversionSequence::Worse;
4687 }
4688 }
4689
4690 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4691 // floating-to-integral conversion if the integral conversion
4692 // is between types of the same size.
4693 // For example:
4694 // void f(float);
4695 // void f(int);
4696 // int main {
4697 // long a;
4698 // f(a);
4699 // }
4700 // Here, MSVC will call f(int) instead of generating a compile error
4701 // as clang will do in standard mode.
4702 if (S.getLangOpts().MSVCCompat &&
4703 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4704 SCS1.Second == ICK_Integral_Conversion &&
4705 SCS2.Second == ICK_Floating_Integral &&
4706 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4707 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4708 return ImplicitConversionSequence::Better;
4709
4710 // Prefer a compatible vector conversion over a lax vector conversion
4711 // For example:
4712 //
4713 // typedef float __v4sf __attribute__((__vector_size__(16)));
4714 // void f(vector float);
4715 // void f(vector signed int);
4716 // int main() {
4717 // __v4sf a;
4718 // f(a);
4719 // }
4720 // Here, we'd like to choose f(vector float) and not
4721 // report an ambiguous call error
4722 if (SCS1.Second == ICK_Vector_Conversion &&
4723 SCS2.Second == ICK_Vector_Conversion) {
4724 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4725 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4726 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4727 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4728
4729 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4730 return SCS1IsCompatibleVectorConversion
4731 ? ImplicitConversionSequence::Better
4732 : ImplicitConversionSequence::Worse;
4733 }
4734
4735 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4736 SCS2.Second == ICK_SVE_Vector_Conversion) {
4737 bool SCS1IsCompatibleSVEVectorConversion =
4738 S.Context.areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4739 bool SCS2IsCompatibleSVEVectorConversion =
4740 S.Context.areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4741
4742 if (SCS1IsCompatibleSVEVectorConversion !=
4743 SCS2IsCompatibleSVEVectorConversion)
4744 return SCS1IsCompatibleSVEVectorConversion
4745 ? ImplicitConversionSequence::Better
4746 : ImplicitConversionSequence::Worse;
4747 }
4748
4749 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4750 SCS2.Second == ICK_RVV_Vector_Conversion) {
4751 bool SCS1IsCompatibleRVVVectorConversion =
4752 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4753 bool SCS2IsCompatibleRVVVectorConversion =
4754 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4755
4756 if (SCS1IsCompatibleRVVVectorConversion !=
4757 SCS2IsCompatibleRVVVectorConversion)
4758 return SCS1IsCompatibleRVVVectorConversion
4759 ? ImplicitConversionSequence::Better
4760 : ImplicitConversionSequence::Worse;
4761 }
4762 return ImplicitConversionSequence::Indistinguishable;
4763}
4764
4765/// CompareQualificationConversions - Compares two standard conversion
4766/// sequences to determine whether they can be ranked based on their
4767/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4768static ImplicitConversionSequence::CompareKind
4769CompareQualificationConversions(Sema &S,
4770 const StandardConversionSequence& SCS1,
4771 const StandardConversionSequence& SCS2) {
4772 // C++ [over.ics.rank]p3:
4773 // -- S1 and S2 differ only in their qualification conversion and
4774 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4775 // [C++98]
4776 // [...] and the cv-qualification signature of type T1 is a proper subset
4777 // of the cv-qualification signature of type T2, and S1 is not the
4778 // deprecated string literal array-to-pointer conversion (4.2).
4779 // [C++2a]
4780 // [...] where T1 can be converted to T2 by a qualification conversion.
4781 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4782 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4783 return ImplicitConversionSequence::Indistinguishable;
4784
4785 // FIXME: the example in the standard doesn't use a qualification
4786 // conversion (!)
4787 QualType T1 = SCS1.getToType(Idx: 2);
4788 QualType T2 = SCS2.getToType(Idx: 2);
4789 T1 = S.Context.getCanonicalType(T: T1);
4790 T2 = S.Context.getCanonicalType(T: T2);
4791 assert(!T1->isReferenceType() && !T2->isReferenceType());
4792 Qualifiers T1Quals, T2Quals;
4793 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4794 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4795
4796 // If the types are the same, we won't learn anything by unwrapping
4797 // them.
4798 if (UnqualT1 == UnqualT2)
4799 return ImplicitConversionSequence::Indistinguishable;
4800
4801 // Don't ever prefer a standard conversion sequence that uses the deprecated
4802 // string literal array to pointer conversion.
4803 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4804 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4805
4806 // Objective-C++ ARC:
4807 // Prefer qualification conversions not involving a change in lifetime
4808 // to qualification conversions that do change lifetime.
4809 if (SCS1.QualificationIncludesObjCLifetime &&
4810 !SCS2.QualificationIncludesObjCLifetime)
4811 CanPick1 = false;
4812 if (SCS2.QualificationIncludesObjCLifetime &&
4813 !SCS1.QualificationIncludesObjCLifetime)
4814 CanPick2 = false;
4815
4816 bool ObjCLifetimeConversion;
4817 if (CanPick1 &&
4818 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
4819 CanPick1 = false;
4820 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4821 // directions, so we can't short-cut this second check in general.
4822 if (CanPick2 &&
4823 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
4824 CanPick2 = false;
4825
4826 if (CanPick1 != CanPick2)
4827 return CanPick1 ? ImplicitConversionSequence::Better
4828 : ImplicitConversionSequence::Worse;
4829 return ImplicitConversionSequence::Indistinguishable;
4830}
4831
4832/// CompareDerivedToBaseConversions - Compares two standard conversion
4833/// sequences to determine whether they can be ranked based on their
4834/// various kinds of derived-to-base conversions (C++
4835/// [over.ics.rank]p4b3). As part of these checks, we also look at
4836/// conversions between Objective-C interface types.
4837static ImplicitConversionSequence::CompareKind
4838CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4839 const StandardConversionSequence& SCS1,
4840 const StandardConversionSequence& SCS2) {
4841 QualType FromType1 = SCS1.getFromType();
4842 QualType ToType1 = SCS1.getToType(Idx: 1);
4843 QualType FromType2 = SCS2.getFromType();
4844 QualType ToType2 = SCS2.getToType(Idx: 1);
4845
4846 // Adjust the types we're converting from via the array-to-pointer
4847 // conversion, if we need to.
4848 if (SCS1.First == ICK_Array_To_Pointer)
4849 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4850 if (SCS2.First == ICK_Array_To_Pointer)
4851 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4852
4853 // Canonicalize all of the types.
4854 FromType1 = S.Context.getCanonicalType(T: FromType1);
4855 ToType1 = S.Context.getCanonicalType(T: ToType1);
4856 FromType2 = S.Context.getCanonicalType(T: FromType2);
4857 ToType2 = S.Context.getCanonicalType(T: ToType2);
4858
4859 // C++ [over.ics.rank]p4b3:
4860 //
4861 // If class B is derived directly or indirectly from class A and
4862 // class C is derived directly or indirectly from B,
4863 //
4864 // Compare based on pointer conversions.
4865 if (SCS1.Second == ICK_Pointer_Conversion &&
4866 SCS2.Second == ICK_Pointer_Conversion &&
4867 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4868 FromType1->isPointerType() && FromType2->isPointerType() &&
4869 ToType1->isPointerType() && ToType2->isPointerType()) {
4870 QualType FromPointee1 =
4871 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4872 QualType ToPointee1 =
4873 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4874 QualType FromPointee2 =
4875 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4876 QualType ToPointee2 =
4877 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4878
4879 // -- conversion of C* to B* is better than conversion of C* to A*,
4880 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4881 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4882 return ImplicitConversionSequence::Better;
4883 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4884 return ImplicitConversionSequence::Worse;
4885 }
4886
4887 // -- conversion of B* to A* is better than conversion of C* to A*,
4888 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4889 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4890 return ImplicitConversionSequence::Better;
4891 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4892 return ImplicitConversionSequence::Worse;
4893 }
4894 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4895 SCS2.Second == ICK_Pointer_Conversion) {
4896 const ObjCObjectPointerType *FromPtr1
4897 = FromType1->getAs<ObjCObjectPointerType>();
4898 const ObjCObjectPointerType *FromPtr2
4899 = FromType2->getAs<ObjCObjectPointerType>();
4900 const ObjCObjectPointerType *ToPtr1
4901 = ToType1->getAs<ObjCObjectPointerType>();
4902 const ObjCObjectPointerType *ToPtr2
4903 = ToType2->getAs<ObjCObjectPointerType>();
4904
4905 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4906 // Apply the same conversion ranking rules for Objective-C pointer types
4907 // that we do for C++ pointers to class types. However, we employ the
4908 // Objective-C pseudo-subtyping relationship used for assignment of
4909 // Objective-C pointer types.
4910 bool FromAssignLeft
4911 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
4912 bool FromAssignRight
4913 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
4914 bool ToAssignLeft
4915 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
4916 bool ToAssignRight
4917 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
4918
4919 // A conversion to an a non-id object pointer type or qualified 'id'
4920 // type is better than a conversion to 'id'.
4921 if (ToPtr1->isObjCIdType() &&
4922 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4923 return ImplicitConversionSequence::Worse;
4924 if (ToPtr2->isObjCIdType() &&
4925 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4926 return ImplicitConversionSequence::Better;
4927
4928 // A conversion to a non-id object pointer type is better than a
4929 // conversion to a qualified 'id' type
4930 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4931 return ImplicitConversionSequence::Worse;
4932 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4933 return ImplicitConversionSequence::Better;
4934
4935 // A conversion to an a non-Class object pointer type or qualified 'Class'
4936 // type is better than a conversion to 'Class'.
4937 if (ToPtr1->isObjCClassType() &&
4938 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4939 return ImplicitConversionSequence::Worse;
4940 if (ToPtr2->isObjCClassType() &&
4941 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4942 return ImplicitConversionSequence::Better;
4943
4944 // A conversion to a non-Class object pointer type is better than a
4945 // conversion to a qualified 'Class' type.
4946 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4947 return ImplicitConversionSequence::Worse;
4948 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4949 return ImplicitConversionSequence::Better;
4950
4951 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4952 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
4953 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4954 (ToAssignLeft != ToAssignRight)) {
4955 if (FromPtr1->isSpecialized()) {
4956 // "conversion of B<A> * to B * is better than conversion of B * to
4957 // C *.
4958 bool IsFirstSame =
4959 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4960 bool IsSecondSame =
4961 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4962 if (IsFirstSame) {
4963 if (!IsSecondSame)
4964 return ImplicitConversionSequence::Better;
4965 } else if (IsSecondSame)
4966 return ImplicitConversionSequence::Worse;
4967 }
4968 return ToAssignLeft? ImplicitConversionSequence::Worse
4969 : ImplicitConversionSequence::Better;
4970 }
4971
4972 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4973 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
4974 (FromAssignLeft != FromAssignRight))
4975 return FromAssignLeft? ImplicitConversionSequence::Better
4976 : ImplicitConversionSequence::Worse;
4977 }
4978 }
4979
4980 // Ranking of member-pointer types.
4981 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4982 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4983 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4984 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4985 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4986 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4987 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4988 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4989 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4990 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4991 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4992 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4993 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4994 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
4995 return ImplicitConversionSequence::Worse;
4996 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
4997 return ImplicitConversionSequence::Better;
4998 }
4999 // conversion of B::* to C::* is better than conversion of A::* to C::*
5000 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5001 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5002 return ImplicitConversionSequence::Better;
5003 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5004 return ImplicitConversionSequence::Worse;
5005 }
5006 }
5007
5008 if (SCS1.Second == ICK_Derived_To_Base) {
5009 // -- conversion of C to B is better than conversion of C to A,
5010 // -- binding of an expression of type C to a reference of type
5011 // B& is better than binding an expression of type C to a
5012 // reference of type A&,
5013 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5014 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5015 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5016 return ImplicitConversionSequence::Better;
5017 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5018 return ImplicitConversionSequence::Worse;
5019 }
5020
5021 // -- conversion of B to A is better than conversion of C to A.
5022 // -- binding of an expression of type B to a reference of type
5023 // A& is better than binding an expression of type C to a
5024 // reference of type A&,
5025 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5026 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5027 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5028 return ImplicitConversionSequence::Better;
5029 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5030 return ImplicitConversionSequence::Worse;
5031 }
5032 }
5033
5034 return ImplicitConversionSequence::Indistinguishable;
5035}
5036
5037static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5038 if (!T.getQualifiers().hasUnaligned())
5039 return T;
5040
5041 Qualifiers Q;
5042 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5043 Q.removeUnaligned();
5044 return Ctx.getQualifiedType(T, Qs: Q);
5045}
5046
5047Sema::ReferenceCompareResult
5048Sema::CompareReferenceRelationship(SourceLocation Loc,
5049 QualType OrigT1, QualType OrigT2,
5050 ReferenceConversions *ConvOut) {
5051 assert(!OrigT1->isReferenceType() &&
5052 "T1 must be the pointee type of the reference type");
5053 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5054
5055 QualType T1 = Context.getCanonicalType(T: OrigT1);
5056 QualType T2 = Context.getCanonicalType(T: OrigT2);
5057 Qualifiers T1Quals, T2Quals;
5058 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5059 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5060
5061 ReferenceConversions ConvTmp;
5062 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5063 Conv = ReferenceConversions();
5064
5065 // C++2a [dcl.init.ref]p4:
5066 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5067 // reference-related to "cv2 T2" if T1 is similar to T2, or
5068 // T1 is a base class of T2.
5069 // "cv1 T1" is reference-compatible with "cv2 T2" if
5070 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5071 // "pointer to cv1 T1" via a standard conversion sequence.
5072
5073 // Check for standard conversions we can apply to pointers: derived-to-base
5074 // conversions, ObjC pointer conversions, and function pointer conversions.
5075 // (Qualification conversions are checked last.)
5076 if (UnqualT1 == UnqualT2) {
5077 // Nothing to do.
5078 } else if (isCompleteType(Loc, T: OrigT2) &&
5079 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5080 Conv |= ReferenceConversions::DerivedToBase;
5081 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5082 UnqualT2->isObjCObjectOrInterfaceType() &&
5083 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5084 Conv |= ReferenceConversions::ObjC;
5085 else if (UnqualT2->isFunctionType() &&
5086 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5087 Conv |= ReferenceConversions::Function;
5088 // No need to check qualifiers; function types don't have them.
5089 return Ref_Compatible;
5090 }
5091 bool ConvertedReferent = Conv != 0;
5092
5093 // We can have a qualification conversion. Compute whether the types are
5094 // similar at the same time.
5095 bool PreviousToQualsIncludeConst = true;
5096 bool TopLevel = true;
5097 do {
5098 if (T1 == T2)
5099 break;
5100
5101 // We will need a qualification conversion.
5102 Conv |= ReferenceConversions::Qualification;
5103
5104 // Track whether we performed a qualification conversion anywhere other
5105 // than the top level. This matters for ranking reference bindings in
5106 // overload resolution.
5107 if (!TopLevel)
5108 Conv |= ReferenceConversions::NestedQualification;
5109
5110 // MS compiler ignores __unaligned qualifier for references; do the same.
5111 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5112 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5113
5114 // If we find a qualifier mismatch, the types are not reference-compatible,
5115 // but are still be reference-related if they're similar.
5116 bool ObjCLifetimeConversion = false;
5117 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5118 PreviousToQualsIncludeConst,
5119 ObjCLifetimeConversion, Ctx: getASTContext()))
5120 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5121 ? Ref_Related
5122 : Ref_Incompatible;
5123
5124 // FIXME: Should we track this for any level other than the first?
5125 if (ObjCLifetimeConversion)
5126 Conv |= ReferenceConversions::ObjCLifetime;
5127
5128 TopLevel = false;
5129 } while (Context.UnwrapSimilarTypes(T1, T2));
5130
5131 // At this point, if the types are reference-related, we must either have the
5132 // same inner type (ignoring qualifiers), or must have already worked out how
5133 // to convert the referent.
5134 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5135 ? Ref_Compatible
5136 : Ref_Incompatible;
5137}
5138
5139/// Look for a user-defined conversion to a value reference-compatible
5140/// with DeclType. Return true if something definite is found.
5141static bool
5142FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5143 QualType DeclType, SourceLocation DeclLoc,
5144 Expr *Init, QualType T2, bool AllowRvalues,
5145 bool AllowExplicit) {
5146 assert(T2->isRecordType() && "Can only find conversions of record types.");
5147 auto *T2RecordDecl = cast<CXXRecordDecl>(Val: T2->castAs<RecordType>()->getDecl());
5148
5149 OverloadCandidateSet CandidateSet(
5150 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5151 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5152 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5153 NamedDecl *D = *I;
5154 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5155 if (isa<UsingShadowDecl>(Val: D))
5156 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5157
5158 FunctionTemplateDecl *ConvTemplate
5159 = dyn_cast<FunctionTemplateDecl>(Val: D);
5160 CXXConversionDecl *Conv;
5161 if (ConvTemplate)
5162 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5163 else
5164 Conv = cast<CXXConversionDecl>(Val: D);
5165
5166 if (AllowRvalues) {
5167 // If we are initializing an rvalue reference, don't permit conversion
5168 // functions that return lvalues.
5169 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5170 const ReferenceType *RefType
5171 = Conv->getConversionType()->getAs<LValueReferenceType>();
5172 if (RefType && !RefType->getPointeeType()->isFunctionType())
5173 continue;
5174 }
5175
5176 if (!ConvTemplate &&
5177 S.CompareReferenceRelationship(
5178 Loc: DeclLoc,
5179 OrigT1: Conv->getConversionType()
5180 .getNonReferenceType()
5181 .getUnqualifiedType(),
5182 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5183 Sema::Ref_Incompatible)
5184 continue;
5185 } else {
5186 // If the conversion function doesn't return a reference type,
5187 // it can't be considered for this conversion. An rvalue reference
5188 // is only acceptable if its referencee is a function type.
5189
5190 const ReferenceType *RefType =
5191 Conv->getConversionType()->getAs<ReferenceType>();
5192 if (!RefType ||
5193 (!RefType->isLValueReferenceType() &&
5194 !RefType->getPointeeType()->isFunctionType()))
5195 continue;
5196 }
5197
5198 if (ConvTemplate)
5199 S.AddTemplateConversionCandidate(
5200 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5201 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5202 else
5203 S.AddConversionCandidate(
5204 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5205 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5206 }
5207
5208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5209
5210 OverloadCandidateSet::iterator Best;
5211 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5212 case OR_Success:
5213
5214 assert(Best->HasFinalConversion);
5215
5216 // C++ [over.ics.ref]p1:
5217 //
5218 // [...] If the parameter binds directly to the result of
5219 // applying a conversion function to the argument
5220 // expression, the implicit conversion sequence is a
5221 // user-defined conversion sequence (13.3.3.1.2), with the
5222 // second standard conversion sequence either an identity
5223 // conversion or, if the conversion function returns an
5224 // entity of a type that is a derived class of the parameter
5225 // type, a derived-to-base Conversion.
5226 if (!Best->FinalConversion.DirectBinding)
5227 return false;
5228
5229 ICS.setUserDefined();
5230 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5231 ICS.UserDefined.After = Best->FinalConversion;
5232 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5233 ICS.UserDefined.ConversionFunction = Best->Function;
5234 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5235 ICS.UserDefined.EllipsisConversion = false;
5236 assert(ICS.UserDefined.After.ReferenceBinding &&
5237 ICS.UserDefined.After.DirectBinding &&
5238 "Expected a direct reference binding!");
5239 return true;
5240
5241 case OR_Ambiguous:
5242 ICS.setAmbiguous();
5243 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5244 Cand != CandidateSet.end(); ++Cand)
5245 if (Cand->Best)
5246 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5247 return true;
5248
5249 case OR_No_Viable_Function:
5250 case OR_Deleted:
5251 // There was no suitable conversion, or we found a deleted
5252 // conversion; continue with other checks.
5253 return false;
5254 }
5255
5256 llvm_unreachable("Invalid OverloadResult!");
5257}
5258
5259/// Compute an implicit conversion sequence for reference
5260/// initialization.
5261static ImplicitConversionSequence
5262TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5263 SourceLocation DeclLoc,
5264 bool SuppressUserConversions,
5265 bool AllowExplicit) {
5266 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5267
5268 // Most paths end in a failed conversion.
5269 ImplicitConversionSequence ICS;
5270 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5271
5272 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5273 QualType T2 = Init->getType();
5274
5275 // If the initializer is the address of an overloaded function, try
5276 // to resolve the overloaded function. If all goes well, T2 is the
5277 // type of the resulting function.
5278 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5279 DeclAccessPair Found;
5280 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5281 Complain: false, Found))
5282 T2 = Fn->getType();
5283 }
5284
5285 // Compute some basic properties of the types and the initializer.
5286 bool isRValRef = DeclType->isRValueReferenceType();
5287 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5288
5289 Sema::ReferenceConversions RefConv;
5290 Sema::ReferenceCompareResult RefRelationship =
5291 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5292
5293 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5294 ICS.setStandard();
5295 ICS.Standard.First = ICK_Identity;
5296 // FIXME: A reference binding can be a function conversion too. We should
5297 // consider that when ordering reference-to-function bindings.
5298 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5299 ? ICK_Derived_To_Base
5300 : (RefConv & Sema::ReferenceConversions::ObjC)
5301 ? ICK_Compatible_Conversion
5302 : ICK_Identity;
5303 ICS.Standard.Dimension = ICK_Identity;
5304 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5305 // a reference binding that performs a non-top-level qualification
5306 // conversion as a qualification conversion, not as an identity conversion.
5307 ICS.Standard.Third = (RefConv &
5308 Sema::ReferenceConversions::NestedQualification)
5309 ? ICK_Qualification
5310 : ICK_Identity;
5311 ICS.Standard.setFromType(T2);
5312 ICS.Standard.setToType(Idx: 0, T: T2);
5313 ICS.Standard.setToType(Idx: 1, T: T1);
5314 ICS.Standard.setToType(Idx: 2, T: T1);
5315 ICS.Standard.ReferenceBinding = true;
5316 ICS.Standard.DirectBinding = BindsDirectly;
5317 ICS.Standard.IsLvalueReference = !isRValRef;
5318 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5319 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5320 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5321 ICS.Standard.ObjCLifetimeConversionBinding =
5322 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5323 ICS.Standard.FromBracedInitList = false;
5324 ICS.Standard.CopyConstructor = nullptr;
5325 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5326 };
5327
5328 // C++0x [dcl.init.ref]p5:
5329 // A reference to type "cv1 T1" is initialized by an expression
5330 // of type "cv2 T2" as follows:
5331
5332 // -- If reference is an lvalue reference and the initializer expression
5333 if (!isRValRef) {
5334 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5335 // reference-compatible with "cv2 T2," or
5336 //
5337 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5338 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5339 // C++ [over.ics.ref]p1:
5340 // When a parameter of reference type binds directly (8.5.3)
5341 // to an argument expression, the implicit conversion sequence
5342 // is the identity conversion, unless the argument expression
5343 // has a type that is a derived class of the parameter type,
5344 // in which case the implicit conversion sequence is a
5345 // derived-to-base Conversion (13.3.3.1).
5346 SetAsReferenceBinding(/*BindsDirectly=*/true);
5347
5348 // Nothing more to do: the inaccessibility/ambiguity check for
5349 // derived-to-base conversions is suppressed when we're
5350 // computing the implicit conversion sequence (C++
5351 // [over.best.ics]p2).
5352 return ICS;
5353 }
5354
5355 // -- has a class type (i.e., T2 is a class type), where T1 is
5356 // not reference-related to T2, and can be implicitly
5357 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5358 // is reference-compatible with "cv3 T3" 92) (this
5359 // conversion is selected by enumerating the applicable
5360 // conversion functions (13.3.1.6) and choosing the best
5361 // one through overload resolution (13.3)),
5362 if (!SuppressUserConversions && T2->isRecordType() &&
5363 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5364 RefRelationship == Sema::Ref_Incompatible) {
5365 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5366 Init, T2, /*AllowRvalues=*/false,
5367 AllowExplicit))
5368 return ICS;
5369 }
5370 }
5371
5372 // -- Otherwise, the reference shall be an lvalue reference to a
5373 // non-volatile const type (i.e., cv1 shall be const), or the reference
5374 // shall be an rvalue reference.
5375 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5376 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5377 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5378 return ICS;
5379 }
5380
5381 // -- If the initializer expression
5382 //
5383 // -- is an xvalue, class prvalue, array prvalue or function
5384 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5385 if (RefRelationship == Sema::Ref_Compatible &&
5386 (InitCategory.isXValue() ||
5387 (InitCategory.isPRValue() &&
5388 (T2->isRecordType() || T2->isArrayType())) ||
5389 (InitCategory.isLValue() && T2->isFunctionType()))) {
5390 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5391 // binding unless we're binding to a class prvalue.
5392 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5393 // allow the use of rvalue references in C++98/03 for the benefit of
5394 // standard library implementors; therefore, we need the xvalue check here.
5395 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5396 !(InitCategory.isPRValue() || T2->isRecordType()));
5397 return ICS;
5398 }
5399
5400 // -- has a class type (i.e., T2 is a class type), where T1 is not
5401 // reference-related to T2, and can be implicitly converted to
5402 // an xvalue, class prvalue, or function lvalue of type
5403 // "cv3 T3", where "cv1 T1" is reference-compatible with
5404 // "cv3 T3",
5405 //
5406 // then the reference is bound to the value of the initializer
5407 // expression in the first case and to the result of the conversion
5408 // in the second case (or, in either case, to an appropriate base
5409 // class subobject).
5410 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5411 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5412 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5413 Init, T2, /*AllowRvalues=*/true,
5414 AllowExplicit)) {
5415 // In the second case, if the reference is an rvalue reference
5416 // and the second standard conversion sequence of the
5417 // user-defined conversion sequence includes an lvalue-to-rvalue
5418 // conversion, the program is ill-formed.
5419 if (ICS.isUserDefined() && isRValRef &&
5420 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5421 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5422
5423 return ICS;
5424 }
5425
5426 // A temporary of function type cannot be created; don't even try.
5427 if (T1->isFunctionType())
5428 return ICS;
5429
5430 // -- Otherwise, a temporary of type "cv1 T1" is created and
5431 // initialized from the initializer expression using the
5432 // rules for a non-reference copy initialization (8.5). The
5433 // reference is then bound to the temporary. If T1 is
5434 // reference-related to T2, cv1 must be the same
5435 // cv-qualification as, or greater cv-qualification than,
5436 // cv2; otherwise, the program is ill-formed.
5437 if (RefRelationship == Sema::Ref_Related) {
5438 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5439 // we would be reference-compatible or reference-compatible with
5440 // added qualification. But that wasn't the case, so the reference
5441 // initialization fails.
5442 //
5443 // Note that we only want to check address spaces and cvr-qualifiers here.
5444 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5445 Qualifiers T1Quals = T1.getQualifiers();
5446 Qualifiers T2Quals = T2.getQualifiers();
5447 T1Quals.removeObjCGCAttr();
5448 T1Quals.removeObjCLifetime();
5449 T2Quals.removeObjCGCAttr();
5450 T2Quals.removeObjCLifetime();
5451 // MS compiler ignores __unaligned qualifier for references; do the same.
5452 T1Quals.removeUnaligned();
5453 T2Quals.removeUnaligned();
5454 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5455 return ICS;
5456 }
5457
5458 // If at least one of the types is a class type, the types are not
5459 // related, and we aren't allowed any user conversions, the
5460 // reference binding fails. This case is important for breaking
5461 // recursion, since TryImplicitConversion below will attempt to
5462 // create a temporary through the use of a copy constructor.
5463 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5464 (T1->isRecordType() || T2->isRecordType()))
5465 return ICS;
5466
5467 // If T1 is reference-related to T2 and the reference is an rvalue
5468 // reference, the initializer expression shall not be an lvalue.
5469 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5470 Init->Classify(Ctx&: S.Context).isLValue()) {
5471 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5472 return ICS;
5473 }
5474
5475 // C++ [over.ics.ref]p2:
5476 // When a parameter of reference type is not bound directly to
5477 // an argument expression, the conversion sequence is the one
5478 // required to convert the argument expression to the
5479 // underlying type of the reference according to
5480 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5481 // to copy-initializing a temporary of the underlying type with
5482 // the argument expression. Any difference in top-level
5483 // cv-qualification is subsumed by the initialization itself
5484 // and does not constitute a conversion.
5485 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5486 AllowExplicit: AllowedExplicit::None,
5487 /*InOverloadResolution=*/false,
5488 /*CStyle=*/false,
5489 /*AllowObjCWritebackConversion=*/false,
5490 /*AllowObjCConversionOnExplicit=*/false);
5491
5492 // Of course, that's still a reference binding.
5493 if (ICS.isStandard()) {
5494 ICS.Standard.ReferenceBinding = true;
5495 ICS.Standard.IsLvalueReference = !isRValRef;
5496 ICS.Standard.BindsToFunctionLvalue = false;
5497 ICS.Standard.BindsToRvalue = true;
5498 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5499 ICS.Standard.ObjCLifetimeConversionBinding = false;
5500 } else if (ICS.isUserDefined()) {
5501 const ReferenceType *LValRefType =
5502 ICS.UserDefined.ConversionFunction->getReturnType()
5503 ->getAs<LValueReferenceType>();
5504
5505 // C++ [over.ics.ref]p3:
5506 // Except for an implicit object parameter, for which see 13.3.1, a
5507 // standard conversion sequence cannot be formed if it requires [...]
5508 // binding an rvalue reference to an lvalue other than a function
5509 // lvalue.
5510 // Note that the function case is not possible here.
5511 if (isRValRef && LValRefType) {
5512 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5513 return ICS;
5514 }
5515
5516 ICS.UserDefined.After.ReferenceBinding = true;
5517 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5518 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5519 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5520 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5521 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5522 ICS.UserDefined.After.FromBracedInitList = false;
5523 }
5524
5525 return ICS;
5526}
5527
5528static ImplicitConversionSequence
5529TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5530 bool SuppressUserConversions,
5531 bool InOverloadResolution,
5532 bool AllowObjCWritebackConversion,
5533 bool AllowExplicit = false);
5534
5535/// TryListConversion - Try to copy-initialize a value of type ToType from the
5536/// initializer list From.
5537static ImplicitConversionSequence
5538TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5539 bool SuppressUserConversions,
5540 bool InOverloadResolution,
5541 bool AllowObjCWritebackConversion) {
5542 // C++11 [over.ics.list]p1:
5543 // When an argument is an initializer list, it is not an expression and
5544 // special rules apply for converting it to a parameter type.
5545
5546 ImplicitConversionSequence Result;
5547 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5548
5549 // We need a complete type for what follows. With one C++20 exception,
5550 // incomplete types can never be initialized from init lists.
5551 QualType InitTy = ToType;
5552 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5553 if (AT && S.getLangOpts().CPlusPlus20)
5554 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5555 // C++20 allows list initialization of an incomplete array type.
5556 InitTy = IAT->getElementType();
5557 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5558 return Result;
5559
5560 // C++20 [over.ics.list]/2:
5561 // If the initializer list is a designated-initializer-list, a conversion
5562 // is only possible if the parameter has an aggregate type
5563 //
5564 // FIXME: The exception for reference initialization here is not part of the
5565 // language rules, but follow other compilers in adding it as a tentative DR
5566 // resolution.
5567 bool IsDesignatedInit = From->hasDesignatedInit();
5568 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5569 IsDesignatedInit)
5570 return Result;
5571
5572 // Per DR1467 and DR2137:
5573 // If the parameter type is an aggregate class X and the initializer list
5574 // has a single element of type cv U, where U is X or a class derived from
5575 // X, the implicit conversion sequence is the one required to convert the
5576 // element to the parameter type.
5577 //
5578 // Otherwise, if the parameter type is a character array [... ]
5579 // and the initializer list has a single element that is an
5580 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5581 // implicit conversion sequence is the identity conversion.
5582 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5583 if (ToType->isRecordType() && ToType->isAggregateType()) {
5584 QualType InitType = From->getInit(Init: 0)->getType();
5585 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5586 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5587 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5588 SuppressUserConversions,
5589 InOverloadResolution,
5590 AllowObjCWritebackConversion);
5591 }
5592
5593 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5594 InitializedEntity Entity =
5595 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5596 /*Consumed=*/false);
5597 if (S.CanPerformCopyInitialization(Entity, From)) {
5598 Result.setStandard();
5599 Result.Standard.setAsIdentityConversion();
5600 Result.Standard.setFromType(ToType);
5601 Result.Standard.setAllToTypes(ToType);
5602 return Result;
5603 }
5604 }
5605 }
5606
5607 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5608 // C++11 [over.ics.list]p2:
5609 // If the parameter type is std::initializer_list<X> or "array of X" and
5610 // all the elements can be implicitly converted to X, the implicit
5611 // conversion sequence is the worst conversion necessary to convert an
5612 // element of the list to X.
5613 //
5614 // C++14 [over.ics.list]p3:
5615 // Otherwise, if the parameter type is "array of N X", if the initializer
5616 // list has exactly N elements or if it has fewer than N elements and X is
5617 // default-constructible, and if all the elements of the initializer list
5618 // can be implicitly converted to X, the implicit conversion sequence is
5619 // the worst conversion necessary to convert an element of the list to X.
5620 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5621 unsigned e = From->getNumInits();
5622 ImplicitConversionSequence DfltElt;
5623 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5624 ToType: QualType());
5625 QualType ContTy = ToType;
5626 bool IsUnbounded = false;
5627 if (AT) {
5628 InitTy = AT->getElementType();
5629 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5630 if (CT->getSize().ult(RHS: e)) {
5631 // Too many inits, fatally bad
5632 Result.setBad(BadConversionSequence::too_many_initializers, From,
5633 ToType);
5634 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5635 return Result;
5636 }
5637 if (CT->getSize().ugt(RHS: e)) {
5638 // Need an init from empty {}, is there one?
5639 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5640 From->getEndLoc());
5641 EmptyList.setType(S.Context.VoidTy);
5642 DfltElt = TryListConversion(
5643 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5644 InOverloadResolution, AllowObjCWritebackConversion);
5645 if (DfltElt.isBad()) {
5646 // No {} init, fatally bad
5647 Result.setBad(BadConversionSequence::too_few_initializers, From,
5648 ToType);
5649 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5650 return Result;
5651 }
5652 }
5653 } else {
5654 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5655 IsUnbounded = true;
5656 if (!e) {
5657 // Cannot convert to zero-sized.
5658 Result.setBad(BadConversionSequence::too_few_initializers, From,
5659 ToType);
5660 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5661 return Result;
5662 }
5663 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5664 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5665 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5666 }
5667 }
5668
5669 Result.setStandard();
5670 Result.Standard.setAsIdentityConversion();
5671 Result.Standard.setFromType(InitTy);
5672 Result.Standard.setAllToTypes(InitTy);
5673 for (unsigned i = 0; i < e; ++i) {
5674 Expr *Init = From->getInit(Init: i);
5675 ImplicitConversionSequence ICS = TryCopyInitialization(
5676 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5677 AllowObjCWritebackConversion);
5678
5679 // Keep the worse conversion seen so far.
5680 // FIXME: Sequences are not totally ordered, so 'worse' can be
5681 // ambiguous. CWG has been informed.
5682 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5683 ICS2: Result) ==
5684 ImplicitConversionSequence::Worse) {
5685 Result = ICS;
5686 // Bail as soon as we find something unconvertible.
5687 if (Result.isBad()) {
5688 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5689 return Result;
5690 }
5691 }
5692 }
5693
5694 // If we needed any implicit {} initialization, compare that now.
5695 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5696 // has been informed that this might not be the best thing.
5697 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5698 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5699 ImplicitConversionSequence::Worse)
5700 Result = DfltElt;
5701 // Record the type being initialized so that we may compare sequences
5702 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5703 return Result;
5704 }
5705
5706 // C++14 [over.ics.list]p4:
5707 // C++11 [over.ics.list]p3:
5708 // Otherwise, if the parameter is a non-aggregate class X and overload
5709 // resolution chooses a single best constructor [...] the implicit
5710 // conversion sequence is a user-defined conversion sequence. If multiple
5711 // constructors are viable but none is better than the others, the
5712 // implicit conversion sequence is a user-defined conversion sequence.
5713 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5714 // This function can deal with initializer lists.
5715 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5716 AllowedExplicit::None,
5717 InOverloadResolution, /*CStyle=*/false,
5718 AllowObjCWritebackConversion,
5719 /*AllowObjCConversionOnExplicit=*/false);
5720 }
5721
5722 // C++14 [over.ics.list]p5:
5723 // C++11 [over.ics.list]p4:
5724 // Otherwise, if the parameter has an aggregate type which can be
5725 // initialized from the initializer list [...] the implicit conversion
5726 // sequence is a user-defined conversion sequence.
5727 if (ToType->isAggregateType()) {
5728 // Type is an aggregate, argument is an init list. At this point it comes
5729 // down to checking whether the initialization works.
5730 // FIXME: Find out whether this parameter is consumed or not.
5731 InitializedEntity Entity =
5732 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5733 /*Consumed=*/false);
5734 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5735 From)) {
5736 Result.setUserDefined();
5737 Result.UserDefined.Before.setAsIdentityConversion();
5738 // Initializer lists don't have a type.
5739 Result.UserDefined.Before.setFromType(QualType());
5740 Result.UserDefined.Before.setAllToTypes(QualType());
5741
5742 Result.UserDefined.After.setAsIdentityConversion();
5743 Result.UserDefined.After.setFromType(ToType);
5744 Result.UserDefined.After.setAllToTypes(ToType);
5745 Result.UserDefined.ConversionFunction = nullptr;
5746 }
5747 return Result;
5748 }
5749
5750 // C++14 [over.ics.list]p6:
5751 // C++11 [over.ics.list]p5:
5752 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5753 if (ToType->isReferenceType()) {
5754 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5755 // mention initializer lists in any way. So we go by what list-
5756 // initialization would do and try to extrapolate from that.
5757
5758 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5759
5760 // If the initializer list has a single element that is reference-related
5761 // to the parameter type, we initialize the reference from that.
5762 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5763 Expr *Init = From->getInit(Init: 0);
5764
5765 QualType T2 = Init->getType();
5766
5767 // If the initializer is the address of an overloaded function, try
5768 // to resolve the overloaded function. If all goes well, T2 is the
5769 // type of the resulting function.
5770 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5771 DeclAccessPair Found;
5772 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5773 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5774 T2 = Fn->getType();
5775 }
5776
5777 // Compute some basic properties of the types and the initializer.
5778 Sema::ReferenceCompareResult RefRelationship =
5779 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5780
5781 if (RefRelationship >= Sema::Ref_Related) {
5782 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5783 SuppressUserConversions,
5784 /*AllowExplicit=*/false);
5785 }
5786 }
5787
5788 // Otherwise, we bind the reference to a temporary created from the
5789 // initializer list.
5790 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5791 InOverloadResolution,
5792 AllowObjCWritebackConversion);
5793 if (Result.isFailure())
5794 return Result;
5795 assert(!Result.isEllipsis() &&
5796 "Sub-initialization cannot result in ellipsis conversion.");
5797
5798 // Can we even bind to a temporary?
5799 if (ToType->isRValueReferenceType() ||
5800 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5801 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5802 Result.UserDefined.After;
5803 SCS.ReferenceBinding = true;
5804 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5805 SCS.BindsToRvalue = true;
5806 SCS.BindsToFunctionLvalue = false;
5807 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5808 SCS.ObjCLifetimeConversionBinding = false;
5809 SCS.FromBracedInitList = false;
5810
5811 } else
5812 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5813 From, ToType);
5814 return Result;
5815 }
5816
5817 // C++14 [over.ics.list]p7:
5818 // C++11 [over.ics.list]p6:
5819 // Otherwise, if the parameter type is not a class:
5820 if (!ToType->isRecordType()) {
5821 // - if the initializer list has one element that is not itself an
5822 // initializer list, the implicit conversion sequence is the one
5823 // required to convert the element to the parameter type.
5824 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5825 // single integer.
5826 unsigned NumInits = From->getNumInits();
5827 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
5828 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
5829 Result = TryCopyInitialization(
5830 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
5831 InOverloadResolution, AllowObjCWritebackConversion);
5832 if (Result.isStandard())
5833 Result.Standard.FromBracedInitList = true;
5834 }
5835 // - if the initializer list has no elements, the implicit conversion
5836 // sequence is the identity conversion.
5837 else if (NumInits == 0) {
5838 Result.setStandard();
5839 Result.Standard.setAsIdentityConversion();
5840 Result.Standard.setFromType(ToType);
5841 Result.Standard.setAllToTypes(ToType);
5842 }
5843 return Result;
5844 }
5845
5846 // C++14 [over.ics.list]p8:
5847 // C++11 [over.ics.list]p7:
5848 // In all cases other than those enumerated above, no conversion is possible
5849 return Result;
5850}
5851
5852/// TryCopyInitialization - Try to copy-initialize a value of type
5853/// ToType from the expression From. Return the implicit conversion
5854/// sequence required to pass this argument, which may be a bad
5855/// conversion sequence (meaning that the argument cannot be passed to
5856/// a parameter of this type). If @p SuppressUserConversions, then we
5857/// do not permit any user-defined conversion sequences.
5858static ImplicitConversionSequence
5859TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5860 bool SuppressUserConversions,
5861 bool InOverloadResolution,
5862 bool AllowObjCWritebackConversion,
5863 bool AllowExplicit) {
5864 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
5865 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
5866 InOverloadResolution,AllowObjCWritebackConversion);
5867
5868 if (ToType->isReferenceType())
5869 return TryReferenceInit(S, From, ToType,
5870 /*FIXME:*/ From->getBeginLoc(),
5871 SuppressUserConversions, AllowExplicit);
5872
5873 return TryImplicitConversion(S, From, ToType,
5874 SuppressUserConversions,
5875 AllowExplicit: AllowedExplicit::None,
5876 InOverloadResolution,
5877 /*CStyle=*/false,
5878 AllowObjCWritebackConversion,
5879 /*AllowObjCConversionOnExplicit=*/false);
5880}
5881
5882static bool TryCopyInitialization(const CanQualType FromQTy,
5883 const CanQualType ToQTy,
5884 Sema &S,
5885 SourceLocation Loc,
5886 ExprValueKind FromVK) {
5887 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5888 ImplicitConversionSequence ICS =
5889 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5890
5891 return !ICS.isBad();
5892}
5893
5894/// TryObjectArgumentInitialization - Try to initialize the object
5895/// parameter of the given member function (@c Method) from the
5896/// expression @p From.
5897static ImplicitConversionSequence TryObjectArgumentInitialization(
5898 Sema &S, SourceLocation Loc, QualType FromType,
5899 Expr::Classification FromClassification, CXXMethodDecl *Method,
5900 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5901 QualType ExplicitParameterType = QualType(),
5902 bool SuppressUserConversion = false) {
5903
5904 // We need to have an object of class type.
5905 if (const auto *PT = FromType->getAs<PointerType>()) {
5906 FromType = PT->getPointeeType();
5907
5908 // When we had a pointer, it's implicitly dereferenced, so we
5909 // better have an lvalue.
5910 assert(FromClassification.isLValue());
5911 }
5912
5913 auto ValueKindFromClassification = [](Expr::Classification C) {
5914 if (C.isPRValue())
5915 return clang::VK_PRValue;
5916 if (C.isXValue())
5917 return VK_XValue;
5918 return clang::VK_LValue;
5919 };
5920
5921 if (Method->isExplicitObjectMemberFunction()) {
5922 if (ExplicitParameterType.isNull())
5923 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5924 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5925 ValueKindFromClassification(FromClassification));
5926 ImplicitConversionSequence ICS = TryCopyInitialization(
5927 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5928 /*InOverloadResolution=*/true, false);
5929 if (ICS.isBad())
5930 ICS.Bad.FromExpr = nullptr;
5931 return ICS;
5932 }
5933
5934 assert(FromType->isRecordType());
5935
5936 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5937 // C++98 [class.dtor]p2:
5938 // A destructor can be invoked for a const, volatile or const volatile
5939 // object.
5940 // C++98 [over.match.funcs]p4:
5941 // For static member functions, the implicit object parameter is considered
5942 // to match any object (since if the function is selected, the object is
5943 // discarded).
5944 Qualifiers Quals = Method->getMethodQualifiers();
5945 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
5946 Quals.addConst();
5947 Quals.addVolatile();
5948 }
5949
5950 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
5951
5952 // Set up the conversion sequence as a "bad" conversion, to allow us
5953 // to exit early.
5954 ImplicitConversionSequence ICS;
5955
5956 // C++0x [over.match.funcs]p4:
5957 // For non-static member functions, the type of the implicit object
5958 // parameter is
5959 //
5960 // - "lvalue reference to cv X" for functions declared without a
5961 // ref-qualifier or with the & ref-qualifier
5962 // - "rvalue reference to cv X" for functions declared with the &&
5963 // ref-qualifier
5964 //
5965 // where X is the class of which the function is a member and cv is the
5966 // cv-qualification on the member function declaration.
5967 //
5968 // However, when finding an implicit conversion sequence for the argument, we
5969 // are not allowed to perform user-defined conversions
5970 // (C++ [over.match.funcs]p5). We perform a simplified version of
5971 // reference binding here, that allows class rvalues to bind to
5972 // non-constant references.
5973
5974 // First check the qualifiers.
5975 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
5976 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5977 if (ImplicitParamType.getCVRQualifiers() !=
5978 FromTypeCanon.getLocalCVRQualifiers() &&
5979 !ImplicitParamType.isAtLeastAsQualifiedAs(
5980 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
5981 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5982 FromType, ToType: ImplicitParamType);
5983 return ICS;
5984 }
5985
5986 if (FromTypeCanon.hasAddressSpace()) {
5987 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5988 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5989 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
5990 Ctx: S.getASTContext())) {
5991 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
5992 FromType, ToType: ImplicitParamType);
5993 return ICS;
5994 }
5995 }
5996
5997 // Check that we have either the same type or a derived type. It
5998 // affects the conversion rank.
5999 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6000 ImplicitConversionKind SecondKind;
6001 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6002 SecondKind = ICK_Identity;
6003 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6004 SecondKind = ICK_Derived_To_Base;
6005 } else if (!Method->isExplicitObjectMemberFunction()) {
6006 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6007 FromType, ToType: ImplicitParamType);
6008 return ICS;
6009 }
6010
6011 // Check the ref-qualifier.
6012 switch (Method->getRefQualifier()) {
6013 case RQ_None:
6014 // Do nothing; we don't care about lvalueness or rvalueness.
6015 break;
6016
6017 case RQ_LValue:
6018 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6019 // non-const lvalue reference cannot bind to an rvalue
6020 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6021 ToType: ImplicitParamType);
6022 return ICS;
6023 }
6024 break;
6025
6026 case RQ_RValue:
6027 if (!FromClassification.isRValue()) {
6028 // rvalue reference cannot bind to an lvalue
6029 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6030 ToType: ImplicitParamType);
6031 return ICS;
6032 }
6033 break;
6034 }
6035
6036 // Success. Mark this as a reference binding.
6037 ICS.setStandard();
6038 ICS.Standard.setAsIdentityConversion();
6039 ICS.Standard.Second = SecondKind;
6040 ICS.Standard.setFromType(FromType);
6041 ICS.Standard.setAllToTypes(ImplicitParamType);
6042 ICS.Standard.ReferenceBinding = true;
6043 ICS.Standard.DirectBinding = true;
6044 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6045 ICS.Standard.BindsToFunctionLvalue = false;
6046 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6047 ICS.Standard.FromBracedInitList = false;
6048 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6049 = (Method->getRefQualifier() == RQ_None);
6050 return ICS;
6051}
6052
6053/// PerformObjectArgumentInitialization - Perform initialization of
6054/// the implicit object parameter for the given Method with the given
6055/// expression.
6056ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6057 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
6058 CXXMethodDecl *Method) {
6059 QualType FromRecordType, DestType;
6060 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6061
6062 Expr::Classification FromClassification;
6063 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6064 FromRecordType = PT->getPointeeType();
6065 DestType = Method->getThisType();
6066 FromClassification = Expr::Classification::makeSimpleLValue();
6067 } else {
6068 FromRecordType = From->getType();
6069 DestType = ImplicitParamRecordType;
6070 FromClassification = From->Classify(Ctx&: Context);
6071
6072 // CWG2813 [expr.call]p6:
6073 // If the function is an implicit object member function, the object
6074 // expression of the class member access shall be a glvalue [...]
6075 if (From->isPRValue()) {
6076 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6077 BoundToLvalueReference: Method->getRefQualifier() !=
6078 RefQualifierKind::RQ_RValue);
6079 }
6080 }
6081
6082 // Note that we always use the true parent context when performing
6083 // the actual argument initialization.
6084 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6085 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6086 Method->getParent());
6087 if (ICS.isBad()) {
6088 switch (ICS.Bad.Kind) {
6089 case BadConversionSequence::bad_qualifiers: {
6090 Qualifiers FromQs = FromRecordType.getQualifiers();
6091 Qualifiers ToQs = DestType.getQualifiers();
6092 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6093 if (CVR) {
6094 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6095 << Method->getDeclName() << FromRecordType << (CVR - 1)
6096 << From->getSourceRange();
6097 Diag(Method->getLocation(), diag::note_previous_decl)
6098 << Method->getDeclName();
6099 return ExprError();
6100 }
6101 break;
6102 }
6103
6104 case BadConversionSequence::lvalue_ref_to_rvalue:
6105 case BadConversionSequence::rvalue_ref_to_lvalue: {
6106 bool IsRValueQualified =
6107 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6108 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6109 << Method->getDeclName() << FromClassification.isRValue()
6110 << IsRValueQualified;
6111 Diag(Method->getLocation(), diag::note_previous_decl)
6112 << Method->getDeclName();
6113 return ExprError();
6114 }
6115
6116 case BadConversionSequence::no_conversion:
6117 case BadConversionSequence::unrelated_class:
6118 break;
6119
6120 case BadConversionSequence::too_few_initializers:
6121 case BadConversionSequence::too_many_initializers:
6122 llvm_unreachable("Lists are not objects");
6123 }
6124
6125 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6126 << ImplicitParamRecordType << FromRecordType
6127 << From->getSourceRange();
6128 }
6129
6130 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6131 ExprResult FromRes =
6132 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6133 if (FromRes.isInvalid())
6134 return ExprError();
6135 From = FromRes.get();
6136 }
6137
6138 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6139 CastKind CK;
6140 QualType PteeTy = DestType->getPointeeType();
6141 LangAS DestAS =
6142 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6143 if (FromRecordType.getAddressSpace() != DestAS)
6144 CK = CK_AddressSpaceConversion;
6145 else
6146 CK = CK_NoOp;
6147 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6148 }
6149 return From;
6150}
6151
6152/// TryContextuallyConvertToBool - Attempt to contextually convert the
6153/// expression From to bool (C++0x [conv]p3).
6154static ImplicitConversionSequence
6155TryContextuallyConvertToBool(Sema &S, Expr *From) {
6156 // C++ [dcl.init]/17.8:
6157 // - Otherwise, if the initialization is direct-initialization, the source
6158 // type is std::nullptr_t, and the destination type is bool, the initial
6159 // value of the object being initialized is false.
6160 if (From->getType()->isNullPtrType())
6161 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6162 DestType: S.Context.BoolTy,
6163 NeedLValToRVal: From->isGLValue());
6164
6165 // All other direct-initialization of bool is equivalent to an implicit
6166 // conversion to bool in which explicit conversions are permitted.
6167 return TryImplicitConversion(S, From, S.Context.BoolTy,
6168 /*SuppressUserConversions=*/false,
6169 AllowedExplicit::Conversions,
6170 /*InOverloadResolution=*/false,
6171 /*CStyle=*/false,
6172 /*AllowObjCWritebackConversion=*/false,
6173 /*AllowObjCConversionOnExplicit=*/false);
6174}
6175
6176ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6177 if (checkPlaceholderForOverload(S&: *this, E&: From))
6178 return ExprError();
6179
6180 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6181 if (!ICS.isBad())
6182 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6183 AssignmentAction::Converting);
6184
6185 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6186 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6187 << From->getType() << From->getSourceRange();
6188 return ExprError();
6189}
6190
6191/// Check that the specified conversion is permitted in a converted constant
6192/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6193/// is acceptable.
6194static bool CheckConvertedConstantConversions(Sema &S,
6195 StandardConversionSequence &SCS) {
6196 // Since we know that the target type is an integral or unscoped enumeration
6197 // type, most conversion kinds are impossible. All possible First and Third
6198 // conversions are fine.
6199 switch (SCS.Second) {
6200 case ICK_Identity:
6201 case ICK_Integral_Promotion:
6202 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6203 case ICK_Zero_Queue_Conversion:
6204 return true;
6205
6206 case ICK_Boolean_Conversion:
6207 // Conversion from an integral or unscoped enumeration type to bool is
6208 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6209 // conversion, so we allow it in a converted constant expression.
6210 //
6211 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6212 // a lot of popular code. We should at least add a warning for this
6213 // (non-conforming) extension.
6214 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6215 SCS.getToType(Idx: 2)->isBooleanType();
6216
6217 case ICK_Pointer_Conversion:
6218 case ICK_Pointer_Member:
6219 // C++1z: null pointer conversions and null member pointer conversions are
6220 // only permitted if the source type is std::nullptr_t.
6221 return SCS.getFromType()->isNullPtrType();
6222
6223 case ICK_Floating_Promotion:
6224 case ICK_Complex_Promotion:
6225 case ICK_Floating_Conversion:
6226 case ICK_Complex_Conversion:
6227 case ICK_Floating_Integral:
6228 case ICK_Compatible_Conversion:
6229 case ICK_Derived_To_Base:
6230 case ICK_Vector_Conversion:
6231 case ICK_SVE_Vector_Conversion:
6232 case ICK_RVV_Vector_Conversion:
6233 case ICK_HLSL_Vector_Splat:
6234 case ICK_Vector_Splat:
6235 case ICK_Complex_Real:
6236 case ICK_Block_Pointer_Conversion:
6237 case ICK_TransparentUnionConversion:
6238 case ICK_Writeback_Conversion:
6239 case ICK_Zero_Event_Conversion:
6240 case ICK_C_Only_Conversion:
6241 case ICK_Incompatible_Pointer_Conversion:
6242 case ICK_Fixed_Point_Conversion:
6243 case ICK_HLSL_Vector_Truncation:
6244 return false;
6245
6246 case ICK_Lvalue_To_Rvalue:
6247 case ICK_Array_To_Pointer:
6248 case ICK_Function_To_Pointer:
6249 case ICK_HLSL_Array_RValue:
6250 llvm_unreachable("found a first conversion kind in Second");
6251
6252 case ICK_Function_Conversion:
6253 case ICK_Qualification:
6254 llvm_unreachable("found a third conversion kind in Second");
6255
6256 case ICK_Num_Conversion_Kinds:
6257 break;
6258 }
6259
6260 llvm_unreachable("unknown conversion kind");
6261}
6262
6263/// BuildConvertedConstantExpression - Check that the expression From is a
6264/// converted constant expression of type T, perform the conversion but
6265/// does not evaluate the expression
6266static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6267 QualType T, CCEKind CCE,
6268 NamedDecl *Dest,
6269 APValue &PreNarrowingValue) {
6270 assert((S.getLangOpts().CPlusPlus11 || CCE == CCEKind::TempArgStrict) &&
6271 "converted constant expression outside C++11 or TTP matching");
6272
6273 if (checkPlaceholderForOverload(S, E&: From))
6274 return ExprError();
6275
6276 // C++1z [expr.const]p3:
6277 // A converted constant expression of type T is an expression,
6278 // implicitly converted to type T, where the converted
6279 // expression is a constant expression and the implicit conversion
6280 // sequence contains only [... list of conversions ...].
6281 ImplicitConversionSequence ICS =
6282 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6283 ? TryContextuallyConvertToBool(S, From)
6284 : TryCopyInitialization(S, From, ToType: T,
6285 /*SuppressUserConversions=*/false,
6286 /*InOverloadResolution=*/false,
6287 /*AllowObjCWritebackConversion=*/false,
6288 /*AllowExplicit=*/false);
6289 StandardConversionSequence *SCS = nullptr;
6290 switch (ICS.getKind()) {
6291 case ImplicitConversionSequence::StandardConversion:
6292 SCS = &ICS.Standard;
6293 break;
6294 case ImplicitConversionSequence::UserDefinedConversion:
6295 if (T->isRecordType())
6296 SCS = &ICS.UserDefined.Before;
6297 else
6298 SCS = &ICS.UserDefined.After;
6299 break;
6300 case ImplicitConversionSequence::AmbiguousConversion:
6301 case ImplicitConversionSequence::BadConversion:
6302 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6303 return S.Diag(From->getBeginLoc(),
6304 diag::err_typecheck_converted_constant_expression)
6305 << From->getType() << From->getSourceRange() << T;
6306 return ExprError();
6307
6308 case ImplicitConversionSequence::EllipsisConversion:
6309 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6310 llvm_unreachable("bad conversion in converted constant expression");
6311 }
6312
6313 // Check that we would only use permitted conversions.
6314 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6315 return S.Diag(From->getBeginLoc(),
6316 diag::err_typecheck_converted_constant_expression_disallowed)
6317 << From->getType() << From->getSourceRange() << T;
6318 }
6319 // [...] and where the reference binding (if any) binds directly.
6320 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6321 return S.Diag(From->getBeginLoc(),
6322 diag::err_typecheck_converted_constant_expression_indirect)
6323 << From->getType() << From->getSourceRange() << T;
6324 }
6325 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6326 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6327 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6328 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6329 // case explicitly.
6330 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6331 return S.Diag(From->getBeginLoc(),
6332 diag::err_reference_bind_to_bitfield_in_cce)
6333 << From->getSourceRange();
6334 }
6335
6336 // Usually we can simply apply the ImplicitConversionSequence we formed
6337 // earlier, but that's not guaranteed to work when initializing an object of
6338 // class type.
6339 ExprResult Result;
6340 bool IsTemplateArgument =
6341 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6342 if (T->isRecordType()) {
6343 assert(IsTemplateArgument &&
6344 "unexpected class type converted constant expr");
6345 Result = S.PerformCopyInitialization(
6346 Entity: InitializedEntity::InitializeTemplateParameter(
6347 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6348 EqualLoc: SourceLocation(), Init: From);
6349 } else {
6350 Result =
6351 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6352 }
6353 if (Result.isInvalid())
6354 return Result;
6355
6356 // C++2a [intro.execution]p5:
6357 // A full-expression is [...] a constant-expression [...]
6358 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6359 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6360 IsTemplateArgument);
6361 if (Result.isInvalid())
6362 return Result;
6363
6364 // Check for a narrowing implicit conversion.
6365 bool ReturnPreNarrowingValue = false;
6366 QualType PreNarrowingType;
6367 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6368 ConstantType&: PreNarrowingType)) {
6369 case NK_Variable_Narrowing:
6370 // Implicit conversion to a narrower type, and the value is not a constant
6371 // expression. We'll diagnose this in a moment.
6372 case NK_Not_Narrowing:
6373 break;
6374
6375 case NK_Constant_Narrowing:
6376 if (CCE == CCEKind::ArrayBound &&
6377 PreNarrowingType->isIntegralOrEnumerationType() &&
6378 PreNarrowingValue.isInt()) {
6379 // Don't diagnose array bound narrowing here; we produce more precise
6380 // errors by allowing the un-narrowed value through.
6381 ReturnPreNarrowingValue = true;
6382 break;
6383 }
6384 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6385 << CCE << /*Constant*/ 1
6386 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6387 break;
6388
6389 case NK_Dependent_Narrowing:
6390 // Implicit conversion to a narrower type, but the expression is
6391 // value-dependent so we can't tell whether it's actually narrowing.
6392 // For matching the parameters of a TTP, the conversion is ill-formed
6393 // if it may narrow.
6394 if (CCE != CCEKind::TempArgStrict)
6395 break;
6396 [[fallthrough]];
6397 case NK_Type_Narrowing:
6398 // FIXME: It would be better to diagnose that the expression is not a
6399 // constant expression.
6400 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6401 << CCE << /*Constant*/ 0 << From->getType() << T;
6402 break;
6403 }
6404 if (!ReturnPreNarrowingValue)
6405 PreNarrowingValue = {};
6406
6407 return Result;
6408}
6409
6410/// CheckConvertedConstantExpression - Check that the expression From is a
6411/// converted constant expression of type T, perform the conversion and produce
6412/// the converted expression, per C++11 [expr.const]p3.
6413static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6414 QualType T, APValue &Value,
6415 CCEKind CCE, bool RequireInt,
6416 NamedDecl *Dest) {
6417
6418 APValue PreNarrowingValue;
6419 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6420 PreNarrowingValue);
6421 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6422 Value = APValue();
6423 return Result;
6424 }
6425 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6426 RequireInt, PreNarrowingValue);
6427}
6428
6429ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6430 CCEKind CCE,
6431 NamedDecl *Dest) {
6432 APValue PreNarrowingValue;
6433 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6434 PreNarrowingValue);
6435}
6436
6437ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6438 APValue &Value, CCEKind CCE,
6439 NamedDecl *Dest) {
6440 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6441 Dest);
6442}
6443
6444ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6445 llvm::APSInt &Value,
6446 CCEKind CCE) {
6447 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6448
6449 APValue V;
6450 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6451 /*Dest=*/nullptr);
6452 if (!R.isInvalid() && !R.get()->isValueDependent())
6453 Value = V.getInt();
6454 return R;
6455}
6456
6457ExprResult
6458Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6459 CCEKind CCE, bool RequireInt,
6460 const APValue &PreNarrowingValue) {
6461
6462 ExprResult Result = E;
6463 // Check the expression is a constant expression.
6464 SmallVector<PartialDiagnosticAt, 8> Notes;
6465 Expr::EvalResult Eval;
6466 Eval.Diag = &Notes;
6467
6468 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6469
6470 ConstantExprKind Kind;
6471 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6472 Kind = ConstantExprKind::ClassTemplateArgument;
6473 else if (CCE == CCEKind::TemplateArg)
6474 Kind = ConstantExprKind::NonClassTemplateArgument;
6475 else
6476 Kind = ConstantExprKind::Normal;
6477
6478 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6479 (RequireInt && !Eval.Val.isInt())) {
6480 // The expression can't be folded, so we can't keep it at this position in
6481 // the AST.
6482 Result = ExprError();
6483 } else {
6484 Value = Eval.Val;
6485
6486 if (Notes.empty()) {
6487 // It's a constant expression.
6488 Expr *E = Result.get();
6489 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6490 // We expect a ConstantExpr to have a value associated with it
6491 // by this point.
6492 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6493 "ConstantExpr has no value associated with it");
6494 (void)CE;
6495 } else {
6496 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6497 }
6498 if (!PreNarrowingValue.isAbsent())
6499 Value = std::move(PreNarrowingValue);
6500 return E;
6501 }
6502 }
6503
6504 // It's not a constant expression. Produce an appropriate diagnostic.
6505 if (Notes.size() == 1 &&
6506 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6507 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6508 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6509 diag::note_constexpr_invalid_template_arg) {
6510 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6511 for (unsigned I = 0; I < Notes.size(); ++I)
6512 Diag(Notes[I].first, Notes[I].second);
6513 } else {
6514 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6515 << CCE << E->getSourceRange();
6516 for (unsigned I = 0; I < Notes.size(); ++I)
6517 Diag(Notes[I].first, Notes[I].second);
6518 }
6519 return ExprError();
6520}
6521
6522/// dropPointerConversions - If the given standard conversion sequence
6523/// involves any pointer conversions, remove them. This may change
6524/// the result type of the conversion sequence.
6525static void dropPointerConversion(StandardConversionSequence &SCS) {
6526 if (SCS.Second == ICK_Pointer_Conversion) {
6527 SCS.Second = ICK_Identity;
6528 SCS.Dimension = ICK_Identity;
6529 SCS.Third = ICK_Identity;
6530 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6531 }
6532}
6533
6534/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6535/// convert the expression From to an Objective-C pointer type.
6536static ImplicitConversionSequence
6537TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6538 // Do an implicit conversion to 'id'.
6539 QualType Ty = S.Context.getObjCIdType();
6540 ImplicitConversionSequence ICS
6541 = TryImplicitConversion(S, From, ToType: Ty,
6542 // FIXME: Are these flags correct?
6543 /*SuppressUserConversions=*/false,
6544 AllowExplicit: AllowedExplicit::Conversions,
6545 /*InOverloadResolution=*/false,
6546 /*CStyle=*/false,
6547 /*AllowObjCWritebackConversion=*/false,
6548 /*AllowObjCConversionOnExplicit=*/true);
6549
6550 // Strip off any final conversions to 'id'.
6551 switch (ICS.getKind()) {
6552 case ImplicitConversionSequence::BadConversion:
6553 case ImplicitConversionSequence::AmbiguousConversion:
6554 case ImplicitConversionSequence::EllipsisConversion:
6555 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6556 break;
6557
6558 case ImplicitConversionSequence::UserDefinedConversion:
6559 dropPointerConversion(SCS&: ICS.UserDefined.After);
6560 break;
6561
6562 case ImplicitConversionSequence::StandardConversion:
6563 dropPointerConversion(SCS&: ICS.Standard);
6564 break;
6565 }
6566
6567 return ICS;
6568}
6569
6570ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6571 if (checkPlaceholderForOverload(S&: *this, E&: From))
6572 return ExprError();
6573
6574 QualType Ty = Context.getObjCIdType();
6575 ImplicitConversionSequence ICS =
6576 TryContextuallyConvertToObjCPointer(S&: *this, From);
6577 if (!ICS.isBad())
6578 return PerformImplicitConversion(From, ToType: Ty, ICS,
6579 Action: AssignmentAction::Converting);
6580 return ExprResult();
6581}
6582
6583static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6584 const Expr *Base = nullptr;
6585 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6586 "expected a member expression");
6587
6588 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6589 M && !M->isImplicitAccess())
6590 Base = M->getBase();
6591 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6592 M && !M->isImplicitAccess())
6593 Base = M->getBase();
6594
6595 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6596
6597 if (T->isPointerType())
6598 T = T->getPointeeType();
6599
6600 return T;
6601}
6602
6603static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6604 const FunctionDecl *Fun) {
6605 QualType ObjType = Obj->getType();
6606 if (ObjType->isPointerType()) {
6607 ObjType = ObjType->getPointeeType();
6608 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6609 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6610 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6611 }
6612 return Obj;
6613}
6614
6615ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6616 FunctionDecl *Fun) {
6617 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6618 return S.PerformCopyInitialization(
6619 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6620 EqualLoc: Obj->getExprLoc(), Init: Obj);
6621}
6622
6623static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6624 Expr *Object, MultiExprArg &Args,
6625 SmallVectorImpl<Expr *> &NewArgs) {
6626 assert(Method->isExplicitObjectMemberFunction() &&
6627 "Method is not an explicit member function");
6628 assert(NewArgs.empty() && "NewArgs should be empty");
6629
6630 NewArgs.reserve(N: Args.size() + 1);
6631 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6632 NewArgs.push_back(Elt: This);
6633 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6634 Args = NewArgs;
6635 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6636 Method, CallLoc: Object->getBeginLoc());
6637}
6638
6639/// Determine whether the provided type is an integral type, or an enumeration
6640/// type of a permitted flavor.
6641bool Sema::ICEConvertDiagnoser::match(QualType T) {
6642 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6643 : T->isIntegralOrUnscopedEnumerationType();
6644}
6645
6646static ExprResult
6647diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6648 Sema::ContextualImplicitConverter &Converter,
6649 QualType T, UnresolvedSetImpl &ViableConversions) {
6650
6651 if (Converter.Suppress)
6652 return ExprError();
6653
6654 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6655 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6656 CXXConversionDecl *Conv =
6657 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6658 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6659 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6660 }
6661 return From;
6662}
6663
6664static bool
6665diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6666 Sema::ContextualImplicitConverter &Converter,
6667 QualType T, bool HadMultipleCandidates,
6668 UnresolvedSetImpl &ExplicitConversions) {
6669 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6670 DeclAccessPair Found = ExplicitConversions[0];
6671 CXXConversionDecl *Conversion =
6672 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6673
6674 // The user probably meant to invoke the given explicit
6675 // conversion; use it.
6676 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6677 std::string TypeStr;
6678 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6679
6680 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6681 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6682 Code: "static_cast<" + TypeStr + ">(")
6683 << FixItHint::CreateInsertion(
6684 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6685 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6686
6687 // If we aren't in a SFINAE context, build a call to the
6688 // explicit conversion function.
6689 if (SemaRef.isSFINAEContext())
6690 return true;
6691
6692 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6693 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6694 HadMultipleCandidates);
6695 if (Result.isInvalid())
6696 return true;
6697
6698 // Replace the conversion with a RecoveryExpr, so we don't try to
6699 // instantiate it later, but can further diagnose here.
6700 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6701 SubExprs: From, T: Result.get()->getType());
6702 if (Result.isInvalid())
6703 return true;
6704 From = Result.get();
6705 }
6706 return false;
6707}
6708
6709static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6710 Sema::ContextualImplicitConverter &Converter,
6711 QualType T, bool HadMultipleCandidates,
6712 DeclAccessPair &Found) {
6713 CXXConversionDecl *Conversion =
6714 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6715 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6716
6717 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6718 if (!Converter.SuppressConversion) {
6719 if (SemaRef.isSFINAEContext())
6720 return true;
6721
6722 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6723 << From->getSourceRange();
6724 }
6725
6726 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6727 HadMultipleCandidates);
6728 if (Result.isInvalid())
6729 return true;
6730 // Record usage of conversion in an implicit cast.
6731 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6732 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6733 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6734 FPO: SemaRef.CurFPFeatureOverrides());
6735 return false;
6736}
6737
6738static ExprResult finishContextualImplicitConversion(
6739 Sema &SemaRef, SourceLocation Loc, Expr *From,
6740 Sema::ContextualImplicitConverter &Converter) {
6741 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6742 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6743 << From->getSourceRange();
6744
6745 return SemaRef.DefaultLvalueConversion(E: From);
6746}
6747
6748static void
6749collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6750 UnresolvedSetImpl &ViableConversions,
6751 OverloadCandidateSet &CandidateSet) {
6752 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6753 NamedDecl *D = FoundDecl.getDecl();
6754 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6755 if (isa<UsingShadowDecl>(Val: D))
6756 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6757
6758 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6759 SemaRef.AddTemplateConversionCandidate(
6760 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6761 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6762 continue;
6763 }
6764 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6765 SemaRef.AddConversionCandidate(
6766 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6767 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6768 }
6769}
6770
6771/// Attempt to convert the given expression to a type which is accepted
6772/// by the given converter.
6773///
6774/// This routine will attempt to convert an expression of class type to a
6775/// type accepted by the specified converter. In C++11 and before, the class
6776/// must have a single non-explicit conversion function converting to a matching
6777/// type. In C++1y, there can be multiple such conversion functions, but only
6778/// one target type.
6779///
6780/// \param Loc The source location of the construct that requires the
6781/// conversion.
6782///
6783/// \param From The expression we're converting from.
6784///
6785/// \param Converter Used to control and diagnose the conversion process.
6786///
6787/// \returns The expression, converted to an integral or enumeration type if
6788/// successful.
6789ExprResult Sema::PerformContextualImplicitConversion(
6790 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6791 // We can't perform any more checking for type-dependent expressions.
6792 if (From->isTypeDependent())
6793 return From;
6794
6795 // Process placeholders immediately.
6796 if (From->hasPlaceholderType()) {
6797 ExprResult result = CheckPlaceholderExpr(E: From);
6798 if (result.isInvalid())
6799 return result;
6800 From = result.get();
6801 }
6802
6803 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6804 ExprResult Converted = DefaultLvalueConversion(E: From);
6805 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6806 // If the expression already has a matching type, we're golden.
6807 if (Converter.match(T))
6808 return Converted;
6809
6810 // FIXME: Check for missing '()' if T is a function type?
6811
6812 // We can only perform contextual implicit conversions on objects of class
6813 // type.
6814 const RecordType *RecordTy = T->getAs<RecordType>();
6815 if (!RecordTy || !getLangOpts().CPlusPlus) {
6816 if (!Converter.Suppress)
6817 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
6818 return From;
6819 }
6820
6821 // We must have a complete class type.
6822 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6823 ContextualImplicitConverter &Converter;
6824 Expr *From;
6825
6826 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6827 : Converter(Converter), From(From) {}
6828
6829 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6830 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6831 }
6832 } IncompleteDiagnoser(Converter, From);
6833
6834 if (Converter.Suppress ? !isCompleteType(Loc, T)
6835 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
6836 return From;
6837
6838 // Look for a conversion to an integral or enumeration type.
6839 UnresolvedSet<4>
6840 ViableConversions; // These are *potentially* viable in C++1y.
6841 UnresolvedSet<4> ExplicitConversions;
6842 const auto &Conversions =
6843 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getVisibleConversionFunctions();
6844
6845 bool HadMultipleCandidates =
6846 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
6847
6848 // To check that there is only one target type, in C++1y:
6849 QualType ToType;
6850 bool HasUniqueTargetType = true;
6851
6852 // Collect explicit or viable (potentially in C++1y) conversions.
6853 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6854 NamedDecl *D = (*I)->getUnderlyingDecl();
6855 CXXConversionDecl *Conversion;
6856 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6857 if (ConvTemplate) {
6858 if (getLangOpts().CPlusPlus14)
6859 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6860 else
6861 continue; // C++11 does not consider conversion operator templates(?).
6862 } else
6863 Conversion = cast<CXXConversionDecl>(Val: D);
6864
6865 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6866 "Conversion operator templates are considered potentially "
6867 "viable in C++1y");
6868
6869 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6870 if (Converter.match(T: CurToType) || ConvTemplate) {
6871
6872 if (Conversion->isExplicit()) {
6873 // FIXME: For C++1y, do we need this restriction?
6874 // cf. diagnoseNoViableConversion()
6875 if (!ConvTemplate)
6876 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6877 } else {
6878 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6879 if (ToType.isNull())
6880 ToType = CurToType.getUnqualifiedType();
6881 else if (HasUniqueTargetType &&
6882 (CurToType.getUnqualifiedType() != ToType))
6883 HasUniqueTargetType = false;
6884 }
6885 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
6886 }
6887 }
6888 }
6889
6890 if (getLangOpts().CPlusPlus14) {
6891 // C++1y [conv]p6:
6892 // ... An expression e of class type E appearing in such a context
6893 // is said to be contextually implicitly converted to a specified
6894 // type T and is well-formed if and only if e can be implicitly
6895 // converted to a type T that is determined as follows: E is searched
6896 // for conversion functions whose return type is cv T or reference to
6897 // cv T such that T is allowed by the context. There shall be
6898 // exactly one such T.
6899
6900 // If no unique T is found:
6901 if (ToType.isNull()) {
6902 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6903 HadMultipleCandidates,
6904 ExplicitConversions))
6905 return ExprError();
6906 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6907 }
6908
6909 // If more than one unique Ts are found:
6910 if (!HasUniqueTargetType)
6911 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6912 ViableConversions);
6913
6914 // If one unique T is found:
6915 // First, build a candidate set from the previously recorded
6916 // potentially viable conversions.
6917 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6918 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
6919 CandidateSet);
6920
6921 // Then, perform overload resolution over the candidate set.
6922 OverloadCandidateSet::iterator Best;
6923 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
6924 case OR_Success: {
6925 // Apply this conversion.
6926 DeclAccessPair Found =
6927 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6928 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6929 HadMultipleCandidates, Found))
6930 return ExprError();
6931 break;
6932 }
6933 case OR_Ambiguous:
6934 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6935 ViableConversions);
6936 case OR_No_Viable_Function:
6937 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6938 HadMultipleCandidates,
6939 ExplicitConversions))
6940 return ExprError();
6941 [[fallthrough]];
6942 case OR_Deleted:
6943 // We'll complain below about a non-integral condition type.
6944 break;
6945 }
6946 } else {
6947 switch (ViableConversions.size()) {
6948 case 0: {
6949 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
6950 HadMultipleCandidates,
6951 ExplicitConversions))
6952 return ExprError();
6953
6954 // We'll complain below about a non-integral condition type.
6955 break;
6956 }
6957 case 1: {
6958 // Apply this conversion.
6959 DeclAccessPair Found = ViableConversions[0];
6960 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
6961 HadMultipleCandidates, Found))
6962 return ExprError();
6963 break;
6964 }
6965 default:
6966 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
6967 ViableConversions);
6968 }
6969 }
6970
6971 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
6972}
6973
6974/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6975/// an acceptable non-member overloaded operator for a call whose
6976/// arguments have types T1 (and, if non-empty, T2). This routine
6977/// implements the check in C++ [over.match.oper]p3b2 concerning
6978/// enumeration types.
6979static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6980 FunctionDecl *Fn,
6981 ArrayRef<Expr *> Args) {
6982 QualType T1 = Args[0]->getType();
6983 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6984
6985 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6986 return true;
6987
6988 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6989 return true;
6990
6991 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6992 if (Proto->getNumParams() < 1)
6993 return false;
6994
6995 if (T1->isEnumeralType()) {
6996 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6997 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
6998 return true;
6999 }
7000
7001 if (Proto->getNumParams() < 2)
7002 return false;
7003
7004 if (!T2.isNull() && T2->isEnumeralType()) {
7005 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7006 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7007 return true;
7008 }
7009
7010 return false;
7011}
7012
7013static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7014 if (FD->isTargetMultiVersionDefault())
7015 return false;
7016
7017 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7018 return FD->isTargetMultiVersion();
7019
7020 if (!FD->isMultiVersion())
7021 return false;
7022
7023 // Among multiple target versions consider either the default,
7024 // or the first non-default in the absence of default version.
7025 unsigned SeenAt = 0;
7026 unsigned I = 0;
7027 bool HasDefault = false;
7028 FD->getASTContext().forEachMultiversionedFunctionVersion(
7029 FD, [&](const FunctionDecl *CurFD) {
7030 if (FD == CurFD)
7031 SeenAt = I;
7032 else if (CurFD->isTargetMultiVersionDefault())
7033 HasDefault = true;
7034 ++I;
7035 });
7036 return HasDefault || SeenAt != 0;
7037}
7038
7039void Sema::AddOverloadCandidate(
7040 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7041 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7042 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7043 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7044 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7045 bool StrictPackMatch) {
7046 const FunctionProtoType *Proto
7047 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7048 assert(Proto && "Functions without a prototype cannot be overloaded");
7049 assert(!Function->getDescribedFunctionTemplate() &&
7050 "Use AddTemplateOverloadCandidate for function templates");
7051
7052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7053 if (!isa<CXXConstructorDecl>(Val: Method)) {
7054 // If we get here, it's because we're calling a member function
7055 // that is named without a member access expression (e.g.,
7056 // "this->f") that was either written explicitly or created
7057 // implicitly. This can happen with a qualified call to a member
7058 // function, e.g., X::f(). We use an empty type for the implied
7059 // object argument (C++ [over.call.func]p3), and the acting context
7060 // is irrelevant.
7061 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7062 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7063 CandidateSet, SuppressUserConversions,
7064 PartialOverloading, EarlyConversions, PO,
7065 StrictPackMatch);
7066 return;
7067 }
7068 // We treat a constructor like a non-member function, since its object
7069 // argument doesn't participate in overload resolution.
7070 }
7071
7072 if (!CandidateSet.isNewCandidate(Function, PO))
7073 return;
7074
7075 // C++11 [class.copy]p11: [DR1402]
7076 // A defaulted move constructor that is defined as deleted is ignored by
7077 // overload resolution.
7078 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7079 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7080 Constructor->isMoveConstructor())
7081 return;
7082
7083 // Overload resolution is always an unevaluated context.
7084 EnterExpressionEvaluationContext Unevaluated(
7085 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7086
7087 // C++ [over.match.oper]p3:
7088 // if no operand has a class type, only those non-member functions in the
7089 // lookup set that have a first parameter of type T1 or "reference to
7090 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7091 // is a right operand) a second parameter of type T2 or "reference to
7092 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7093 // candidate functions.
7094 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7095 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7096 return;
7097
7098 // Add this candidate
7099 OverloadCandidate &Candidate =
7100 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7101 Candidate.FoundDecl = FoundDecl;
7102 Candidate.Function = Function;
7103 Candidate.Viable = true;
7104 Candidate.RewriteKind =
7105 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7106 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7107 Candidate.ExplicitCallArguments = Args.size();
7108 Candidate.StrictPackMatch = StrictPackMatch;
7109
7110 // Explicit functions are not actually candidates at all if we're not
7111 // allowing them in this context, but keep them around so we can point
7112 // to them in diagnostics.
7113 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7114 Candidate.Viable = false;
7115 Candidate.FailureKind = ovl_fail_explicit;
7116 return;
7117 }
7118
7119 // Functions with internal linkage are only viable in the same module unit.
7120 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7121 /// FIXME: Currently, the semantics of linkage in clang is slightly
7122 /// different from the semantics in C++ spec. In C++ spec, only names
7123 /// have linkage. So that all entities of the same should share one
7124 /// linkage. But in clang, different entities of the same could have
7125 /// different linkage.
7126 const NamedDecl *ND = Function;
7127 bool IsImplicitlyInstantiated = false;
7128 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7129 ND = SpecInfo->getTemplate();
7130 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7131 TSK_ImplicitInstantiation;
7132 }
7133
7134 /// Don't remove inline functions with internal linkage from the overload
7135 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7136 /// However:
7137 /// - Inline functions with internal linkage are a common pattern in
7138 /// headers to avoid ODR issues.
7139 /// - The global module is meant to be a transition mechanism for C and C++
7140 /// headers, and the current rules as written work against that goal.
7141 const bool IsInlineFunctionInGMF =
7142 Function->isFromGlobalModule() &&
7143 (IsImplicitlyInstantiated || Function->isInlined());
7144
7145 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7146 Candidate.Viable = false;
7147 Candidate.FailureKind = ovl_fail_module_mismatched;
7148 return;
7149 }
7150 }
7151
7152 if (isNonViableMultiVersionOverload(FD: Function)) {
7153 Candidate.Viable = false;
7154 Candidate.FailureKind = ovl_non_default_multiversion_function;
7155 return;
7156 }
7157
7158 if (Constructor) {
7159 // C++ [class.copy]p3:
7160 // A member function template is never instantiated to perform the copy
7161 // of a class object to an object of its class type.
7162 QualType ClassType = Context.getTypeDeclType(Decl: Constructor->getParent());
7163 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7164 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7165 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7166 ClassType))) {
7167 Candidate.Viable = false;
7168 Candidate.FailureKind = ovl_fail_illegal_constructor;
7169 return;
7170 }
7171
7172 // C++ [over.match.funcs]p8: (proposed DR resolution)
7173 // A constructor inherited from class type C that has a first parameter
7174 // of type "reference to P" (including such a constructor instantiated
7175 // from a template) is excluded from the set of candidate functions when
7176 // constructing an object of type cv D if the argument list has exactly
7177 // one argument and D is reference-related to P and P is reference-related
7178 // to C.
7179 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7180 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7181 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7182 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7183 QualType C = Context.getRecordType(Decl: Constructor->getParent());
7184 QualType D = Context.getRecordType(Shadow->getParent());
7185 SourceLocation Loc = Args.front()->getExprLoc();
7186 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7187 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7188 Candidate.Viable = false;
7189 Candidate.FailureKind = ovl_fail_inhctor_slice;
7190 return;
7191 }
7192 }
7193
7194 // Check that the constructor is capable of constructing an object in the
7195 // destination address space.
7196 if (!Qualifiers::isAddressSpaceSupersetOf(
7197 Constructor->getMethodQualifiers().getAddressSpace(),
7198 CandidateSet.getDestAS(), getASTContext())) {
7199 Candidate.Viable = false;
7200 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7201 }
7202 }
7203
7204 unsigned NumParams = Proto->getNumParams();
7205
7206 // (C++ 13.3.2p2): A candidate function having fewer than m
7207 // parameters is viable only if it has an ellipsis in its parameter
7208 // list (8.3.5).
7209 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7210 !Proto->isVariadic() &&
7211 shouldEnforceArgLimit(PartialOverloading, Function)) {
7212 Candidate.Viable = false;
7213 Candidate.FailureKind = ovl_fail_too_many_arguments;
7214 return;
7215 }
7216
7217 // (C++ 13.3.2p2): A candidate function having more than m parameters
7218 // is viable only if the (m+1)st parameter has a default argument
7219 // (8.3.6). For the purposes of overload resolution, the
7220 // parameter list is truncated on the right, so that there are
7221 // exactly m parameters.
7222 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7223 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7224 !PartialOverloading) {
7225 // Not enough arguments.
7226 Candidate.Viable = false;
7227 Candidate.FailureKind = ovl_fail_too_few_arguments;
7228 return;
7229 }
7230
7231 // (CUDA B.1): Check for invalid calls between targets.
7232 if (getLangOpts().CUDA) {
7233 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7234 // Skip the check for callers that are implicit members, because in this
7235 // case we may not yet know what the member's target is; the target is
7236 // inferred for the member automatically, based on the bases and fields of
7237 // the class.
7238 if (!(Caller && Caller->isImplicit()) &&
7239 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7240 Candidate.Viable = false;
7241 Candidate.FailureKind = ovl_fail_bad_target;
7242 return;
7243 }
7244 }
7245
7246 if (Function->getTrailingRequiresClause()) {
7247 ConstraintSatisfaction Satisfaction;
7248 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7249 /*ForOverloadResolution*/ true) ||
7250 !Satisfaction.IsSatisfied) {
7251 Candidate.Viable = false;
7252 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7253 return;
7254 }
7255 }
7256
7257 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7258 // Determine the implicit conversion sequences for each of the
7259 // arguments.
7260 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7261 unsigned ConvIdx =
7262 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7263 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7264 // We already formed a conversion sequence for this parameter during
7265 // template argument deduction.
7266 } else if (ArgIdx < NumParams) {
7267 // (C++ 13.3.2p3): for F to be a viable function, there shall
7268 // exist for each argument an implicit conversion sequence
7269 // (13.3.3.1) that converts that argument to the corresponding
7270 // parameter of F.
7271 QualType ParamType = Proto->getParamType(i: ArgIdx);
7272 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7273 if (ParamABI == ParameterABI::HLSLOut ||
7274 ParamABI == ParameterABI::HLSLInOut)
7275 ParamType = ParamType.getNonReferenceType();
7276 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7277 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7278 /*InOverloadResolution=*/true,
7279 /*AllowObjCWritebackConversion=*/
7280 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7281 if (Candidate.Conversions[ConvIdx].isBad()) {
7282 Candidate.Viable = false;
7283 Candidate.FailureKind = ovl_fail_bad_conversion;
7284 return;
7285 }
7286 } else {
7287 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7288 // argument for which there is no corresponding parameter is
7289 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7290 Candidate.Conversions[ConvIdx].setEllipsis();
7291 }
7292 }
7293
7294 if (EnableIfAttr *FailedAttr =
7295 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7296 Candidate.Viable = false;
7297 Candidate.FailureKind = ovl_fail_enable_if;
7298 Candidate.DeductionFailure.Data = FailedAttr;
7299 return;
7300 }
7301}
7302
7303ObjCMethodDecl *
7304Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7305 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7306 if (Methods.size() <= 1)
7307 return nullptr;
7308
7309 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7310 bool Match = true;
7311 ObjCMethodDecl *Method = Methods[b];
7312 unsigned NumNamedArgs = Sel.getNumArgs();
7313 // Method might have more arguments than selector indicates. This is due
7314 // to addition of c-style arguments in method.
7315 if (Method->param_size() > NumNamedArgs)
7316 NumNamedArgs = Method->param_size();
7317 if (Args.size() < NumNamedArgs)
7318 continue;
7319
7320 for (unsigned i = 0; i < NumNamedArgs; i++) {
7321 // We can't do any type-checking on a type-dependent argument.
7322 if (Args[i]->isTypeDependent()) {
7323 Match = false;
7324 break;
7325 }
7326
7327 ParmVarDecl *param = Method->parameters()[i];
7328 Expr *argExpr = Args[i];
7329 assert(argExpr && "SelectBestMethod(): missing expression");
7330
7331 // Strip the unbridged-cast placeholder expression off unless it's
7332 // a consumed argument.
7333 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7334 !param->hasAttr<CFConsumedAttr>())
7335 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7336
7337 // If the parameter is __unknown_anytype, move on to the next method.
7338 if (param->getType() == Context.UnknownAnyTy) {
7339 Match = false;
7340 break;
7341 }
7342
7343 ImplicitConversionSequence ConversionState
7344 = TryCopyInitialization(*this, argExpr, param->getType(),
7345 /*SuppressUserConversions*/false,
7346 /*InOverloadResolution=*/true,
7347 /*AllowObjCWritebackConversion=*/
7348 getLangOpts().ObjCAutoRefCount,
7349 /*AllowExplicit*/false);
7350 // This function looks for a reasonably-exact match, so we consider
7351 // incompatible pointer conversions to be a failure here.
7352 if (ConversionState.isBad() ||
7353 (ConversionState.isStandard() &&
7354 ConversionState.Standard.Second ==
7355 ICK_Incompatible_Pointer_Conversion)) {
7356 Match = false;
7357 break;
7358 }
7359 }
7360 // Promote additional arguments to variadic methods.
7361 if (Match && Method->isVariadic()) {
7362 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7363 if (Args[i]->isTypeDependent()) {
7364 Match = false;
7365 break;
7366 }
7367 ExprResult Arg = DefaultVariadicArgumentPromotion(
7368 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7369 if (Arg.isInvalid()) {
7370 Match = false;
7371 break;
7372 }
7373 }
7374 } else {
7375 // Check for extra arguments to non-variadic methods.
7376 if (Args.size() != NumNamedArgs)
7377 Match = false;
7378 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7379 // Special case when selectors have no argument. In this case, select
7380 // one with the most general result type of 'id'.
7381 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7382 QualType ReturnT = Methods[b]->getReturnType();
7383 if (ReturnT->isObjCIdType())
7384 return Methods[b];
7385 }
7386 }
7387 }
7388
7389 if (Match)
7390 return Method;
7391 }
7392 return nullptr;
7393}
7394
7395static bool convertArgsForAvailabilityChecks(
7396 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7397 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7398 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7399 if (ThisArg) {
7400 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7401 assert(!isa<CXXConstructorDecl>(Method) &&
7402 "Shouldn't have `this` for ctors!");
7403 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7404 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7405 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7406 if (R.isInvalid())
7407 return false;
7408 ConvertedThis = R.get();
7409 } else {
7410 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7411 (void)MD;
7412 assert((MissingImplicitThis || MD->isStatic() ||
7413 isa<CXXConstructorDecl>(MD)) &&
7414 "Expected `this` for non-ctor instance methods");
7415 }
7416 ConvertedThis = nullptr;
7417 }
7418
7419 // Ignore any variadic arguments. Converting them is pointless, since the
7420 // user can't refer to them in the function condition.
7421 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7422
7423 // Convert the arguments.
7424 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7425 ExprResult R;
7426 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7427 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7428 EqualLoc: SourceLocation(), Init: Args[I]);
7429
7430 if (R.isInvalid())
7431 return false;
7432
7433 ConvertedArgs.push_back(Elt: R.get());
7434 }
7435
7436 if (Trap.hasErrorOccurred())
7437 return false;
7438
7439 // Push default arguments if needed.
7440 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7441 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7442 ParmVarDecl *P = Function->getParamDecl(i);
7443 if (!P->hasDefaultArg())
7444 return false;
7445 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7446 if (R.isInvalid())
7447 return false;
7448 ConvertedArgs.push_back(Elt: R.get());
7449 }
7450
7451 if (Trap.hasErrorOccurred())
7452 return false;
7453 }
7454 return true;
7455}
7456
7457EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7458 SourceLocation CallLoc,
7459 ArrayRef<Expr *> Args,
7460 bool MissingImplicitThis) {
7461 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7462 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7463 return nullptr;
7464
7465 SFINAETrap Trap(*this);
7466 SmallVector<Expr *, 16> ConvertedArgs;
7467 // FIXME: We should look into making enable_if late-parsed.
7468 Expr *DiscardedThis;
7469 if (!convertArgsForAvailabilityChecks(
7470 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7471 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7472 return *EnableIfAttrs.begin();
7473
7474 for (auto *EIA : EnableIfAttrs) {
7475 APValue Result;
7476 // FIXME: This doesn't consider value-dependent cases, because doing so is
7477 // very difficult. Ideally, we should handle them more gracefully.
7478 if (EIA->getCond()->isValueDependent() ||
7479 !EIA->getCond()->EvaluateWithSubstitution(
7480 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7481 return EIA;
7482
7483 if (!Result.isInt() || !Result.getInt().getBoolValue())
7484 return EIA;
7485 }
7486 return nullptr;
7487}
7488
7489template <typename CheckFn>
7490static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7491 bool ArgDependent, SourceLocation Loc,
7492 CheckFn &&IsSuccessful) {
7493 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7494 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7495 if (ArgDependent == DIA->getArgDependent())
7496 Attrs.push_back(DIA);
7497 }
7498
7499 // Common case: No diagnose_if attributes, so we can quit early.
7500 if (Attrs.empty())
7501 return false;
7502
7503 auto WarningBegin = std::stable_partition(
7504 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7505 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7506 DIA->getWarningGroup().empty();
7507 });
7508
7509 // Note that diagnose_if attributes are late-parsed, so they appear in the
7510 // correct order (unlike enable_if attributes).
7511 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7512 IsSuccessful);
7513 if (ErrAttr != WarningBegin) {
7514 const DiagnoseIfAttr *DIA = *ErrAttr;
7515 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7516 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7517 << DIA->getParent() << DIA->getCond()->getSourceRange();
7518 return true;
7519 }
7520
7521 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7522 switch (Sev) {
7523 case DiagnoseIfAttr::DS_warning:
7524 return diag::Severity::Warning;
7525 case DiagnoseIfAttr::DS_error:
7526 return diag::Severity::Error;
7527 }
7528 llvm_unreachable("Fully covered switch above!");
7529 };
7530
7531 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7532 if (IsSuccessful(DIA)) {
7533 if (DIA->getWarningGroup().empty() &&
7534 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7535 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7536 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7537 << DIA->getParent() << DIA->getCond()->getSourceRange();
7538 } else {
7539 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7540 DIA->getWarningGroup());
7541 assert(DiagGroup);
7542 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7543 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7544 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7545 S.Diag(Loc, DiagID) << DIA->getMessage();
7546 }
7547 }
7548
7549 return false;
7550}
7551
7552bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7553 const Expr *ThisArg,
7554 ArrayRef<const Expr *> Args,
7555 SourceLocation Loc) {
7556 return diagnoseDiagnoseIfAttrsWith(
7557 *this, Function, /*ArgDependent=*/true, Loc,
7558 [&](const DiagnoseIfAttr *DIA) {
7559 APValue Result;
7560 // It's sane to use the same Args for any redecl of this function, since
7561 // EvaluateWithSubstitution only cares about the position of each
7562 // argument in the arg list, not the ParmVarDecl* it maps to.
7563 if (!DIA->getCond()->EvaluateWithSubstitution(
7564 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7565 return false;
7566 return Result.isInt() && Result.getInt().getBoolValue();
7567 });
7568}
7569
7570bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7571 SourceLocation Loc) {
7572 return diagnoseDiagnoseIfAttrsWith(
7573 S&: *this, ND, /*ArgDependent=*/false, Loc,
7574 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7575 bool Result;
7576 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7577 Result;
7578 });
7579}
7580
7581void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7582 ArrayRef<Expr *> Args,
7583 OverloadCandidateSet &CandidateSet,
7584 TemplateArgumentListInfo *ExplicitTemplateArgs,
7585 bool SuppressUserConversions,
7586 bool PartialOverloading,
7587 bool FirstArgumentIsBase) {
7588 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7589 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7590 ArrayRef<Expr *> FunctionArgs = Args;
7591
7592 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7593 FunctionDecl *FD =
7594 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7595
7596 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7597 QualType ObjectType;
7598 Expr::Classification ObjectClassification;
7599 if (Args.size() > 0) {
7600 if (Expr *E = Args[0]) {
7601 // Use the explicit base to restrict the lookup:
7602 ObjectType = E->getType();
7603 // Pointers in the object arguments are implicitly dereferenced, so we
7604 // always classify them as l-values.
7605 if (!ObjectType.isNull() && ObjectType->isPointerType())
7606 ObjectClassification = Expr::Classification::makeSimpleLValue();
7607 else
7608 ObjectClassification = E->Classify(Ctx&: Context);
7609 } // .. else there is an implicit base.
7610 FunctionArgs = Args.slice(N: 1);
7611 }
7612 if (FunTmpl) {
7613 AddMethodTemplateCandidate(
7614 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7615 ActingContext: cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7616 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7617 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7618 PartialOverloading);
7619 } else {
7620 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7621 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7622 ObjectClassification, Args: FunctionArgs, CandidateSet,
7623 SuppressUserConversions, PartialOverloading);
7624 }
7625 } else {
7626 // This branch handles both standalone functions and static methods.
7627
7628 // Slice the first argument (which is the base) when we access
7629 // static method as non-static.
7630 if (Args.size() > 0 &&
7631 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7632 !isa<CXXConstructorDecl>(Val: FD)))) {
7633 assert(cast<CXXMethodDecl>(FD)->isStatic());
7634 FunctionArgs = Args.slice(N: 1);
7635 }
7636 if (FunTmpl) {
7637 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7638 ExplicitTemplateArgs, Args: FunctionArgs,
7639 CandidateSet, SuppressUserConversions,
7640 PartialOverloading);
7641 } else {
7642 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7643 SuppressUserConversions, PartialOverloading);
7644 }
7645 }
7646 }
7647}
7648
7649void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7650 Expr::Classification ObjectClassification,
7651 ArrayRef<Expr *> Args,
7652 OverloadCandidateSet &CandidateSet,
7653 bool SuppressUserConversions,
7654 OverloadCandidateParamOrder PO) {
7655 NamedDecl *Decl = FoundDecl.getDecl();
7656 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7657
7658 if (isa<UsingShadowDecl>(Val: Decl))
7659 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7660
7661 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7662 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7663 "Expected a member function template");
7664 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7665 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7666 ObjectClassification, Args, CandidateSet,
7667 SuppressUserConversions, PartialOverloading: false, PO);
7668 } else {
7669 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7670 ObjectType, ObjectClassification, Args, CandidateSet,
7671 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7672 }
7673}
7674
7675void Sema::AddMethodCandidate(
7676 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7677 CXXRecordDecl *ActingContext, QualType ObjectType,
7678 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7679 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7680 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7681 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7682 const FunctionProtoType *Proto
7683 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7684 assert(Proto && "Methods without a prototype cannot be overloaded");
7685 assert(!isa<CXXConstructorDecl>(Method) &&
7686 "Use AddOverloadCandidate for constructors");
7687
7688 if (!CandidateSet.isNewCandidate(Method, PO))
7689 return;
7690
7691 // C++11 [class.copy]p23: [DR1402]
7692 // A defaulted move assignment operator that is defined as deleted is
7693 // ignored by overload resolution.
7694 if (Method->isDefaulted() && Method->isDeleted() &&
7695 Method->isMoveAssignmentOperator())
7696 return;
7697
7698 // Overload resolution is always an unevaluated context.
7699 EnterExpressionEvaluationContext Unevaluated(
7700 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7701
7702 // Add this candidate
7703 OverloadCandidate &Candidate =
7704 CandidateSet.addCandidate(NumConversions: Args.size() + 1, Conversions: EarlyConversions);
7705 Candidate.FoundDecl = FoundDecl;
7706 Candidate.Function = Method;
7707 Candidate.RewriteKind =
7708 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7709 Candidate.TookAddressOfOverload =
7710 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7711 Candidate.ExplicitCallArguments = Args.size();
7712 Candidate.StrictPackMatch = StrictPackMatch;
7713
7714 bool IgnoreExplicitObject =
7715 (Method->isExplicitObjectMemberFunction() &&
7716 CandidateSet.getKind() ==
7717 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7718 bool ImplicitObjectMethodTreatedAsStatic =
7719 CandidateSet.getKind() ==
7720 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7721 Method->isImplicitObjectMemberFunction();
7722
7723 unsigned ExplicitOffset =
7724 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7725
7726 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7727 int(ImplicitObjectMethodTreatedAsStatic);
7728
7729 // (C++ 13.3.2p2): A candidate function having fewer than m
7730 // parameters is viable only if it has an ellipsis in its parameter
7731 // list (8.3.5).
7732 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7733 !Proto->isVariadic() &&
7734 shouldEnforceArgLimit(PartialOverloading, Method)) {
7735 Candidate.Viable = false;
7736 Candidate.FailureKind = ovl_fail_too_many_arguments;
7737 return;
7738 }
7739
7740 // (C++ 13.3.2p2): A candidate function having more than m parameters
7741 // is viable only if the (m+1)st parameter has a default argument
7742 // (8.3.6). For the purposes of overload resolution, the
7743 // parameter list is truncated on the right, so that there are
7744 // exactly m parameters.
7745 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7746 ExplicitOffset +
7747 int(ImplicitObjectMethodTreatedAsStatic);
7748
7749 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7750 // Not enough arguments.
7751 Candidate.Viable = false;
7752 Candidate.FailureKind = ovl_fail_too_few_arguments;
7753 return;
7754 }
7755
7756 Candidate.Viable = true;
7757
7758 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7759 if (ObjectType.isNull())
7760 Candidate.IgnoreObjectArgument = true;
7761 else if (Method->isStatic()) {
7762 // [over.best.ics.general]p8
7763 // When the parameter is the implicit object parameter of a static member
7764 // function, the implicit conversion sequence is a standard conversion
7765 // sequence that is neither better nor worse than any other standard
7766 // conversion sequence.
7767 //
7768 // This is a rule that was introduced in C++23 to support static lambdas. We
7769 // apply it retroactively because we want to support static lambdas as an
7770 // extension and it doesn't hurt previous code.
7771 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7772 } else {
7773 // Determine the implicit conversion sequence for the object
7774 // parameter.
7775 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7776 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7777 Method, ActingContext, /*InOverloadResolution=*/true);
7778 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7779 Candidate.Viable = false;
7780 Candidate.FailureKind = ovl_fail_bad_conversion;
7781 return;
7782 }
7783 }
7784
7785 // (CUDA B.1): Check for invalid calls between targets.
7786 if (getLangOpts().CUDA)
7787 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7788 Method)) {
7789 Candidate.Viable = false;
7790 Candidate.FailureKind = ovl_fail_bad_target;
7791 return;
7792 }
7793
7794 if (Method->getTrailingRequiresClause()) {
7795 ConstraintSatisfaction Satisfaction;
7796 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7797 /*ForOverloadResolution*/ true) ||
7798 !Satisfaction.IsSatisfied) {
7799 Candidate.Viable = false;
7800 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7801 return;
7802 }
7803 }
7804
7805 // Determine the implicit conversion sequences for each of the
7806 // arguments.
7807 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7808 unsigned ConvIdx =
7809 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7810 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7811 // We already formed a conversion sequence for this parameter during
7812 // template argument deduction.
7813 } else if (ArgIdx < NumParams) {
7814 // (C++ 13.3.2p3): for F to be a viable function, there shall
7815 // exist for each argument an implicit conversion sequence
7816 // (13.3.3.1) that converts that argument to the corresponding
7817 // parameter of F.
7818 QualType ParamType;
7819 if (ImplicitObjectMethodTreatedAsStatic) {
7820 ParamType = ArgIdx == 0
7821 ? Method->getFunctionObjectParameterReferenceType()
7822 : Proto->getParamType(i: ArgIdx - 1);
7823 } else {
7824 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
7825 }
7826 Candidate.Conversions[ConvIdx]
7827 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
7828 SuppressUserConversions,
7829 /*InOverloadResolution=*/true,
7830 /*AllowObjCWritebackConversion=*/
7831 getLangOpts().ObjCAutoRefCount);
7832 if (Candidate.Conversions[ConvIdx].isBad()) {
7833 Candidate.Viable = false;
7834 Candidate.FailureKind = ovl_fail_bad_conversion;
7835 return;
7836 }
7837 } else {
7838 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7839 // argument for which there is no corresponding parameter is
7840 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7841 Candidate.Conversions[ConvIdx].setEllipsis();
7842 }
7843 }
7844
7845 if (EnableIfAttr *FailedAttr =
7846 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7847 Candidate.Viable = false;
7848 Candidate.FailureKind = ovl_fail_enable_if;
7849 Candidate.DeductionFailure.Data = FailedAttr;
7850 return;
7851 }
7852
7853 if (isNonViableMultiVersionOverload(Method)) {
7854 Candidate.Viable = false;
7855 Candidate.FailureKind = ovl_non_default_multiversion_function;
7856 }
7857}
7858
7859static void AddMethodTemplateCandidateImmediately(
7860 Sema &S, OverloadCandidateSet &CandidateSet,
7861 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7862 CXXRecordDecl *ActingContext,
7863 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7864 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7865 bool SuppressUserConversions, bool PartialOverloading,
7866 OverloadCandidateParamOrder PO) {
7867
7868 // C++ [over.match.funcs]p7:
7869 // In each case where a candidate is a function template, candidate
7870 // function template specializations are generated using template argument
7871 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7872 // candidate functions in the usual way.113) A given name can refer to one
7873 // or more function templates and also to a set of overloaded non-template
7874 // functions. In such a case, the candidate functions generated from each
7875 // function template are combined with the set of non-template candidate
7876 // functions.
7877 TemplateDeductionInfo Info(CandidateSet.getLocation());
7878 FunctionDecl *Specialization = nullptr;
7879 ConversionSequenceList Conversions;
7880 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7881 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7882 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7883 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7884 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
7885 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
7886 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
7887 bool OnlyInitializeNonUserDefinedConversions) {
7888 return S.CheckNonDependentConversions(
7889 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7890 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
7891 SuppressUserConversions,
7892 OnlyInitializeNonUserDefinedConversions),
7893 ActingContext, ObjectType, ObjectClassification, PO);
7894 });
7895 Result != TemplateDeductionResult::Success) {
7896 OverloadCandidate &Candidate =
7897 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
7898 Candidate.FoundDecl = FoundDecl;
7899 Candidate.Function = MethodTmpl->getTemplatedDecl();
7900 Candidate.Viable = false;
7901 Candidate.RewriteKind =
7902 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
7903 Candidate.IsSurrogate = false;
7904 Candidate.IgnoreObjectArgument =
7905 cast<CXXMethodDecl>(Val: Candidate.Function)->isStatic() ||
7906 ObjectType.isNull();
7907 Candidate.ExplicitCallArguments = Args.size();
7908 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7909 Candidate.FailureKind = ovl_fail_bad_conversion;
7910 else {
7911 Candidate.FailureKind = ovl_fail_bad_deduction;
7912 Candidate.DeductionFailure =
7913 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
7914 }
7915 return;
7916 }
7917
7918 // Add the function template specialization produced by template argument
7919 // deduction as a candidate.
7920 assert(Specialization && "Missing member function template specialization?");
7921 assert(isa<CXXMethodDecl>(Specialization) &&
7922 "Specialization is not a member function?");
7923 S.AddMethodCandidate(
7924 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
7925 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7926 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
7927}
7928
7929void Sema::AddMethodTemplateCandidate(
7930 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7931 CXXRecordDecl *ActingContext,
7932 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7933 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7934 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7935 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7936 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7937 return;
7938
7939 if (ExplicitTemplateArgs ||
7940 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts())) {
7941 AddMethodTemplateCandidateImmediately(
7942 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7943 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7944 SuppressUserConversions, PartialOverloading, PO);
7945 return;
7946 }
7947
7948 CandidateSet.AddDeferredMethodTemplateCandidate(
7949 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7950 Args, SuppressUserConversions, PartialOverloading, PO);
7951}
7952
7953/// Determine whether a given function template has a simple explicit specifier
7954/// or a non-value-dependent explicit-specification that evaluates to true.
7955static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7956 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
7957}
7958
7959static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
7960 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
7961 ExplicitSpecKind::Unresolved;
7962}
7963
7964static void AddTemplateOverloadCandidateImmediately(
7965 Sema &S, OverloadCandidateSet &CandidateSet,
7966 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7967 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7968 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7969 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
7970 bool AggregateCandidateDeduction) {
7971
7972 // If the function template has a non-dependent explicit specification,
7973 // exclude it now if appropriate; we are not permitted to perform deduction
7974 // and substitution in this case.
7975 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
7976 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7977 Candidate.FoundDecl = FoundDecl;
7978 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7979 Candidate.Viable = false;
7980 Candidate.FailureKind = ovl_fail_explicit;
7981 return;
7982 }
7983
7984 // C++ [over.match.funcs]p7:
7985 // In each case where a candidate is a function template, candidate
7986 // function template specializations are generated using template argument
7987 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7988 // candidate functions in the usual way.113) A given name can refer to one
7989 // or more function templates and also to a set of overloaded non-template
7990 // functions. In such a case, the candidate functions generated from each
7991 // function template are combined with the set of non-template candidate
7992 // functions.
7993 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7994 FunctionTemplate->getTemplateDepth());
7995 FunctionDecl *Specialization = nullptr;
7996 ConversionSequenceList Conversions;
7997 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7998 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7999 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8000 /*PartialOrdering=*/false,
8001 /*ObjectType=*/QualType(),
8002 /*ObjectClassification=*/Expr::Classification(),
8003 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8004 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8005 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8006 bool OnlyInitializeNonUserDefinedConversions) {
8007 return S.CheckNonDependentConversions(
8008 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8009 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8010 SuppressUserConversions,
8011 OnlyInitializeNonUserDefinedConversions),
8012 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8013 });
8014 Result != TemplateDeductionResult::Success) {
8015 OverloadCandidate &Candidate =
8016 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8017 Candidate.FoundDecl = FoundDecl;
8018 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8019 Candidate.Viable = false;
8020 Candidate.RewriteKind =
8021 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8022 Candidate.IsSurrogate = false;
8023 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8024 // Ignore the object argument if there is one, since we don't have an object
8025 // type.
8026 Candidate.IgnoreObjectArgument =
8027 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8028 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8029 Candidate.ExplicitCallArguments = Args.size();
8030 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8031 Candidate.FailureKind = ovl_fail_bad_conversion;
8032 else {
8033 Candidate.FailureKind = ovl_fail_bad_deduction;
8034 Candidate.DeductionFailure =
8035 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8036 }
8037 return;
8038 }
8039
8040 // Add the function template specialization produced by template argument
8041 // deduction as a candidate.
8042 assert(Specialization && "Missing function template specialization?");
8043 S.AddOverloadCandidate(
8044 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8045 PartialOverloading, AllowExplicit,
8046 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8047 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8048 StrictPackMatch: Info.hasStrictPackMatch());
8049}
8050
8051void Sema::AddTemplateOverloadCandidate(
8052 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8053 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8054 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8055 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8056 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8057 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8058 return;
8059
8060 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8061
8062 if (ExplicitTemplateArgs ||
8063 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8064 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8065 DependentExplicitSpecifier)) {
8066
8067 AddTemplateOverloadCandidateImmediately(
8068 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8069 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8070 IsADLCandidate, PO, AggregateCandidateDeduction);
8071
8072 if (DependentExplicitSpecifier)
8073 CandidateSet.DisableResolutionByPerfectCandidate();
8074 return;
8075 }
8076
8077 CandidateSet.AddDeferredTemplateCandidate(
8078 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8079 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8080 AggregateCandidateDeduction);
8081}
8082
8083bool Sema::CheckNonDependentConversions(
8084 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8085 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8086 ConversionSequenceList &Conversions,
8087 CheckNonDependentConversionsFlag UserConversionFlag,
8088 CXXRecordDecl *ActingContext, QualType ObjectType,
8089 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8090 // FIXME: The cases in which we allow explicit conversions for constructor
8091 // arguments never consider calling a constructor template. It's not clear
8092 // that is correct.
8093 const bool AllowExplicit = false;
8094
8095 auto *FD = FunctionTemplate->getTemplatedDecl();
8096 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8097 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Val: Method);
8098 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8099
8100 if (Conversions.empty())
8101 Conversions =
8102 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8103
8104 // Overload resolution is always an unevaluated context.
8105 EnterExpressionEvaluationContext Unevaluated(
8106 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8107
8108 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8109 // require that, but this check should never result in a hard error, and
8110 // overload resolution is permitted to sidestep instantiations.
8111 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8112 !ObjectType.isNull()) {
8113 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8114 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8115 !ParamTypes[0]->isDependentType()) {
8116 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8117 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8118 Method, ActingContext, /*InOverloadResolution=*/true,
8119 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8120 : QualType());
8121 if (Conversions[ConvIdx].isBad())
8122 return true;
8123 }
8124 }
8125
8126 // A speculative workaround for self-dependent constraint bugs that manifest
8127 // after CWG2369.
8128 // FIXME: Add references to the standard once P3606 is adopted.
8129 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8130 QualType ArgType) {
8131 ParamType = ParamType.getNonReferenceType();
8132 ArgType = ArgType.getNonReferenceType();
8133 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8134 if (PointerConv) {
8135 ParamType = ParamType->getPointeeType();
8136 ArgType = ArgType->getPointeeType();
8137 }
8138
8139 if (auto *RT = ParamType->getAs<RecordType>())
8140 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl());
8141 RD && RD->hasDefinition()) {
8142 if (llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8143 auto Info = getConstructorInfo(ND);
8144 if (!Info)
8145 return false;
8146 CXXConstructorDecl *Ctor = Info.Constructor;
8147 /// isConvertingConstructor takes copy/move constructors into
8148 /// account!
8149 return !Ctor->isCopyOrMoveConstructor() &&
8150 Ctor->isConvertingConstructor(
8151 /*AllowExplicit=*/true);
8152 }))
8153 return true;
8154 }
8155
8156 if (auto *RT = ArgType->getAs<RecordType>())
8157 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl());
8158 RD && RD->hasDefinition() &&
8159 !RD->getVisibleConversionFunctions().empty()) {
8160 return true;
8161 }
8162
8163 return false;
8164 };
8165
8166 unsigned Offset =
8167 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
8168
8169 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8170 I != N; ++I) {
8171 QualType ParamType = ParamTypes[I + Offset];
8172 if (!ParamType->isDependentType()) {
8173 unsigned ConvIdx;
8174 if (PO == OverloadCandidateParamOrder::Reversed) {
8175 ConvIdx = Args.size() - 1 - I;
8176 assert(Args.size() + ThisConversions == 2 &&
8177 "number of args (including 'this') must be exactly 2 for "
8178 "reversed order");
8179 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8180 // would also be 0. 'this' got ConvIdx = 1 previously.
8181 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8182 } else {
8183 // For members, 'this' got ConvIdx = 0 previously.
8184 ConvIdx = ThisConversions + I;
8185 }
8186 if (Conversions[ConvIdx].isInitialized())
8187 continue;
8188 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8189 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8190 continue;
8191 Conversions[ConvIdx] = TryCopyInitialization(
8192 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8193 /*InOverloadResolution=*/true,
8194 /*AllowObjCWritebackConversion=*/
8195 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8196 if (Conversions[ConvIdx].isBad())
8197 return true;
8198 }
8199 }
8200
8201 return false;
8202}
8203
8204/// Determine whether this is an allowable conversion from the result
8205/// of an explicit conversion operator to the expected type, per C++
8206/// [over.match.conv]p1 and [over.match.ref]p1.
8207///
8208/// \param ConvType The return type of the conversion function.
8209///
8210/// \param ToType The type we are converting to.
8211///
8212/// \param AllowObjCPointerConversion Allow a conversion from one
8213/// Objective-C pointer to another.
8214///
8215/// \returns true if the conversion is allowable, false otherwise.
8216static bool isAllowableExplicitConversion(Sema &S,
8217 QualType ConvType, QualType ToType,
8218 bool AllowObjCPointerConversion) {
8219 QualType ToNonRefType = ToType.getNonReferenceType();
8220
8221 // Easy case: the types are the same.
8222 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8223 return true;
8224
8225 // Allow qualification conversions.
8226 bool ObjCLifetimeConversion;
8227 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8228 ObjCLifetimeConversion))
8229 return true;
8230
8231 // If we're not allowed to consider Objective-C pointer conversions,
8232 // we're done.
8233 if (!AllowObjCPointerConversion)
8234 return false;
8235
8236 // Is this an Objective-C pointer conversion?
8237 bool IncompatibleObjC = false;
8238 QualType ConvertedType;
8239 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8240 IncompatibleObjC);
8241}
8242
8243void Sema::AddConversionCandidate(
8244 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8245 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8246 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8247 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8248 assert(!Conversion->getDescribedFunctionTemplate() &&
8249 "Conversion function templates use AddTemplateConversionCandidate");
8250 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8251 if (!CandidateSet.isNewCandidate(Conversion))
8252 return;
8253
8254 // If the conversion function has an undeduced return type, trigger its
8255 // deduction now.
8256 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8257 if (DeduceReturnType(Conversion, From->getExprLoc()))
8258 return;
8259 ConvType = Conversion->getConversionType().getNonReferenceType();
8260 }
8261
8262 // If we don't allow any conversion of the result type, ignore conversion
8263 // functions that don't convert to exactly (possibly cv-qualified) T.
8264 if (!AllowResultConversion &&
8265 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8266 return;
8267
8268 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8269 // operator is only a candidate if its return type is the target type or
8270 // can be converted to the target type with a qualification conversion.
8271 //
8272 // FIXME: Include such functions in the candidate list and explain why we
8273 // can't select them.
8274 if (Conversion->isExplicit() &&
8275 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8276 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8277 return;
8278
8279 // Overload resolution is always an unevaluated context.
8280 EnterExpressionEvaluationContext Unevaluated(
8281 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8282
8283 // Add this candidate
8284 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8285 Candidate.FoundDecl = FoundDecl;
8286 Candidate.Function = Conversion;
8287 Candidate.FinalConversion.setAsIdentityConversion();
8288 Candidate.FinalConversion.setFromType(ConvType);
8289 Candidate.FinalConversion.setAllToTypes(ToType);
8290 Candidate.HasFinalConversion = true;
8291 Candidate.Viable = true;
8292 Candidate.ExplicitCallArguments = 1;
8293 Candidate.StrictPackMatch = StrictPackMatch;
8294
8295 // Explicit functions are not actually candidates at all if we're not
8296 // allowing them in this context, but keep them around so we can point
8297 // to them in diagnostics.
8298 if (!AllowExplicit && Conversion->isExplicit()) {
8299 Candidate.Viable = false;
8300 Candidate.FailureKind = ovl_fail_explicit;
8301 return;
8302 }
8303
8304 // C++ [over.match.funcs]p4:
8305 // For conversion functions, the function is considered to be a member of
8306 // the class of the implicit implied object argument for the purpose of
8307 // defining the type of the implicit object parameter.
8308 //
8309 // Determine the implicit conversion sequence for the implicit
8310 // object parameter.
8311 QualType ObjectType = From->getType();
8312 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8313 ObjectType = FromPtrType->getPointeeType();
8314 const auto *ConversionContext =
8315 cast<CXXRecordDecl>(Val: ObjectType->castAs<RecordType>()->getDecl());
8316
8317 // C++23 [over.best.ics.general]
8318 // However, if the target is [...]
8319 // - the object parameter of a user-defined conversion function
8320 // [...] user-defined conversion sequences are not considered.
8321 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8322 *this, CandidateSet.getLocation(), From->getType(),
8323 From->Classify(Ctx&: Context), Conversion, ConversionContext,
8324 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8325 /*SuppressUserConversion*/ true);
8326
8327 if (Candidate.Conversions[0].isBad()) {
8328 Candidate.Viable = false;
8329 Candidate.FailureKind = ovl_fail_bad_conversion;
8330 return;
8331 }
8332
8333 if (Conversion->getTrailingRequiresClause()) {
8334 ConstraintSatisfaction Satisfaction;
8335 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8336 !Satisfaction.IsSatisfied) {
8337 Candidate.Viable = false;
8338 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8339 return;
8340 }
8341 }
8342
8343 // We won't go through a user-defined type conversion function to convert a
8344 // derived to base as such conversions are given Conversion Rank. They only
8345 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8346 QualType FromCanon
8347 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8348 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8349 if (FromCanon == ToCanon ||
8350 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8351 Candidate.Viable = false;
8352 Candidate.FailureKind = ovl_fail_trivial_conversion;
8353 return;
8354 }
8355
8356 // To determine what the conversion from the result of calling the
8357 // conversion function to the type we're eventually trying to
8358 // convert to (ToType), we need to synthesize a call to the
8359 // conversion function and attempt copy initialization from it. This
8360 // makes sure that we get the right semantics with respect to
8361 // lvalues/rvalues and the type. Fortunately, we can allocate this
8362 // call on the stack and we don't need its arguments to be
8363 // well-formed.
8364 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8365 VK_LValue, From->getBeginLoc());
8366 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8367 Context.getPointerType(Conversion->getType()),
8368 CK_FunctionToPointerDecay, &ConversionRef,
8369 VK_PRValue, FPOptionsOverride());
8370
8371 QualType ConversionType = Conversion->getConversionType();
8372 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8373 Candidate.Viable = false;
8374 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8375 return;
8376 }
8377
8378 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8379
8380 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8381
8382 // Introduce a temporary expression with the right type and value category
8383 // that we can use for deduction purposes.
8384 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8385
8386 ImplicitConversionSequence ICS =
8387 TryCopyInitialization(*this, &FakeCall, ToType,
8388 /*SuppressUserConversions=*/true,
8389 /*InOverloadResolution=*/false,
8390 /*AllowObjCWritebackConversion=*/false);
8391
8392 switch (ICS.getKind()) {
8393 case ImplicitConversionSequence::StandardConversion:
8394 Candidate.FinalConversion = ICS.Standard;
8395 Candidate.HasFinalConversion = true;
8396
8397 // C++ [over.ics.user]p3:
8398 // If the user-defined conversion is specified by a specialization of a
8399 // conversion function template, the second standard conversion sequence
8400 // shall have exact match rank.
8401 if (Conversion->getPrimaryTemplate() &&
8402 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8403 Candidate.Viable = false;
8404 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8405 return;
8406 }
8407
8408 // C++0x [dcl.init.ref]p5:
8409 // In the second case, if the reference is an rvalue reference and
8410 // the second standard conversion sequence of the user-defined
8411 // conversion sequence includes an lvalue-to-rvalue conversion, the
8412 // program is ill-formed.
8413 if (ToType->isRValueReferenceType() &&
8414 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8415 Candidate.Viable = false;
8416 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8417 return;
8418 }
8419 break;
8420
8421 case ImplicitConversionSequence::BadConversion:
8422 Candidate.Viable = false;
8423 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8424 return;
8425
8426 default:
8427 llvm_unreachable(
8428 "Can only end up with a standard conversion sequence or failure");
8429 }
8430
8431 if (EnableIfAttr *FailedAttr =
8432 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8433 Candidate.Viable = false;
8434 Candidate.FailureKind = ovl_fail_enable_if;
8435 Candidate.DeductionFailure.Data = FailedAttr;
8436 return;
8437 }
8438
8439 if (isNonViableMultiVersionOverload(Conversion)) {
8440 Candidate.Viable = false;
8441 Candidate.FailureKind = ovl_non_default_multiversion_function;
8442 }
8443}
8444
8445static void AddTemplateConversionCandidateImmediately(
8446 Sema &S, OverloadCandidateSet &CandidateSet,
8447 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8448 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8449 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8450 bool AllowResultConversion) {
8451
8452 // If the function template has a non-dependent explicit specification,
8453 // exclude it now if appropriate; we are not permitted to perform deduction
8454 // and substitution in this case.
8455 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8456 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8457 Candidate.FoundDecl = FoundDecl;
8458 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8459 Candidate.Viable = false;
8460 Candidate.FailureKind = ovl_fail_explicit;
8461 return;
8462 }
8463
8464 QualType ObjectType = From->getType();
8465 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8466
8467 TemplateDeductionInfo Info(CandidateSet.getLocation());
8468 CXXConversionDecl *Specialization = nullptr;
8469 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8470 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8471 Specialization, Info);
8472 Result != TemplateDeductionResult::Success) {
8473 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8474 Candidate.FoundDecl = FoundDecl;
8475 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8476 Candidate.Viable = false;
8477 Candidate.FailureKind = ovl_fail_bad_deduction;
8478 Candidate.ExplicitCallArguments = 1;
8479 Candidate.DeductionFailure =
8480 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8481 return;
8482 }
8483
8484 // Add the conversion function template specialization produced by
8485 // template argument deduction as a candidate.
8486 assert(Specialization && "Missing function template specialization?");
8487 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8488 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8489 AllowExplicit, AllowResultConversion,
8490 StrictPackMatch: Info.hasStrictPackMatch());
8491}
8492
8493void Sema::AddTemplateConversionCandidate(
8494 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8495 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8496 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8497 bool AllowExplicit, bool AllowResultConversion) {
8498 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8499 "Only conversion function templates permitted here");
8500
8501 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8502 return;
8503
8504 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8505 CandidateSet.getKind() ==
8506 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8507 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8508 AddTemplateConversionCandidateImmediately(
8509 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8510 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8511 AllowResultConversion);
8512
8513 CandidateSet.DisableResolutionByPerfectCandidate();
8514 return;
8515 }
8516
8517 CandidateSet.AddDeferredConversionTemplateCandidate(
8518 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8519 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8520}
8521
8522void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8523 DeclAccessPair FoundDecl,
8524 CXXRecordDecl *ActingContext,
8525 const FunctionProtoType *Proto,
8526 Expr *Object,
8527 ArrayRef<Expr *> Args,
8528 OverloadCandidateSet& CandidateSet) {
8529 if (!CandidateSet.isNewCandidate(Conversion))
8530 return;
8531
8532 // Overload resolution is always an unevaluated context.
8533 EnterExpressionEvaluationContext Unevaluated(
8534 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8535
8536 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8537 Candidate.FoundDecl = FoundDecl;
8538 Candidate.Function = nullptr;
8539 Candidate.Surrogate = Conversion;
8540 Candidate.IsSurrogate = true;
8541 Candidate.Viable = true;
8542 Candidate.ExplicitCallArguments = Args.size();
8543
8544 // Determine the implicit conversion sequence for the implicit
8545 // object parameter.
8546 ImplicitConversionSequence ObjectInit;
8547 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8548 ObjectInit = TryCopyInitialization(*this, Object,
8549 Conversion->getParamDecl(0)->getType(),
8550 /*SuppressUserConversions=*/false,
8551 /*InOverloadResolution=*/true, false);
8552 } else {
8553 ObjectInit = TryObjectArgumentInitialization(
8554 *this, CandidateSet.getLocation(), Object->getType(),
8555 Object->Classify(Ctx&: Context), Conversion, ActingContext);
8556 }
8557
8558 if (ObjectInit.isBad()) {
8559 Candidate.Viable = false;
8560 Candidate.FailureKind = ovl_fail_bad_conversion;
8561 Candidate.Conversions[0] = ObjectInit;
8562 return;
8563 }
8564
8565 // The first conversion is actually a user-defined conversion whose
8566 // first conversion is ObjectInit's standard conversion (which is
8567 // effectively a reference binding). Record it as such.
8568 Candidate.Conversions[0].setUserDefined();
8569 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8570 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8571 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8572 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8573 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8574 Candidate.Conversions[0].UserDefined.After
8575 = Candidate.Conversions[0].UserDefined.Before;
8576 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8577
8578 // Find the
8579 unsigned NumParams = Proto->getNumParams();
8580
8581 // (C++ 13.3.2p2): A candidate function having fewer than m
8582 // parameters is viable only if it has an ellipsis in its parameter
8583 // list (8.3.5).
8584 if (Args.size() > NumParams && !Proto->isVariadic()) {
8585 Candidate.Viable = false;
8586 Candidate.FailureKind = ovl_fail_too_many_arguments;
8587 return;
8588 }
8589
8590 // Function types don't have any default arguments, so just check if
8591 // we have enough arguments.
8592 if (Args.size() < NumParams) {
8593 // Not enough arguments.
8594 Candidate.Viable = false;
8595 Candidate.FailureKind = ovl_fail_too_few_arguments;
8596 return;
8597 }
8598
8599 // Determine the implicit conversion sequences for each of the
8600 // arguments.
8601 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8602 if (ArgIdx < NumParams) {
8603 // (C++ 13.3.2p3): for F to be a viable function, there shall
8604 // exist for each argument an implicit conversion sequence
8605 // (13.3.3.1) that converts that argument to the corresponding
8606 // parameter of F.
8607 QualType ParamType = Proto->getParamType(i: ArgIdx);
8608 Candidate.Conversions[ArgIdx + 1]
8609 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8610 /*SuppressUserConversions=*/false,
8611 /*InOverloadResolution=*/false,
8612 /*AllowObjCWritebackConversion=*/
8613 getLangOpts().ObjCAutoRefCount);
8614 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8615 Candidate.Viable = false;
8616 Candidate.FailureKind = ovl_fail_bad_conversion;
8617 return;
8618 }
8619 } else {
8620 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8621 // argument for which there is no corresponding parameter is
8622 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8623 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8624 }
8625 }
8626
8627 if (Conversion->getTrailingRequiresClause()) {
8628 ConstraintSatisfaction Satisfaction;
8629 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8630 /*ForOverloadResolution*/ true) ||
8631 !Satisfaction.IsSatisfied) {
8632 Candidate.Viable = false;
8633 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8634 return;
8635 }
8636 }
8637
8638 if (EnableIfAttr *FailedAttr =
8639 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8640 Candidate.Viable = false;
8641 Candidate.FailureKind = ovl_fail_enable_if;
8642 Candidate.DeductionFailure.Data = FailedAttr;
8643 return;
8644 }
8645}
8646
8647void Sema::AddNonMemberOperatorCandidates(
8648 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8649 OverloadCandidateSet &CandidateSet,
8650 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8651 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8652 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8653 ArrayRef<Expr *> FunctionArgs = Args;
8654
8655 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8656 FunctionDecl *FD =
8657 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8658
8659 // Don't consider rewritten functions if we're not rewriting.
8660 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8661 continue;
8662
8663 assert(!isa<CXXMethodDecl>(FD) &&
8664 "unqualified operator lookup found a member function");
8665
8666 if (FunTmpl) {
8667 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8668 Args: FunctionArgs, CandidateSet);
8669 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8670
8671 // As template candidates are not deduced immediately,
8672 // persist the array in the overload set.
8673 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8674 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8675 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8676 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8677 IsADLCandidate: ADLCallKind::NotADL,
8678 PO: OverloadCandidateParamOrder::Reversed);
8679 }
8680 } else {
8681 if (ExplicitTemplateArgs)
8682 continue;
8683 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8684 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8685 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8686 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8687 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8688 PO: OverloadCandidateParamOrder::Reversed);
8689 }
8690 }
8691}
8692
8693void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8694 SourceLocation OpLoc,
8695 ArrayRef<Expr *> Args,
8696 OverloadCandidateSet &CandidateSet,
8697 OverloadCandidateParamOrder PO) {
8698 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8699
8700 // C++ [over.match.oper]p3:
8701 // For a unary operator @ with an operand of a type whose
8702 // cv-unqualified version is T1, and for a binary operator @ with
8703 // a left operand of a type whose cv-unqualified version is T1 and
8704 // a right operand of a type whose cv-unqualified version is T2,
8705 // three sets of candidate functions, designated member
8706 // candidates, non-member candidates and built-in candidates, are
8707 // constructed as follows:
8708 QualType T1 = Args[0]->getType();
8709
8710 // -- If T1 is a complete class type or a class currently being
8711 // defined, the set of member candidates is the result of the
8712 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8713 // the set of member candidates is empty.
8714 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8715 // Complete the type if it can be completed.
8716 if (!isCompleteType(Loc: OpLoc, T: T1) && !T1Rec->isBeingDefined())
8717 return;
8718 // If the type is neither complete nor being defined, bail out now.
8719 if (!T1Rec->getDecl()->getDefinition())
8720 return;
8721
8722 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8723 LookupQualifiedName(Operators, T1Rec->getDecl());
8724 Operators.suppressAccessDiagnostics();
8725
8726 for (LookupResult::iterator Oper = Operators.begin(),
8727 OperEnd = Operators.end();
8728 Oper != OperEnd; ++Oper) {
8729 if (Oper->getAsFunction() &&
8730 PO == OverloadCandidateParamOrder::Reversed &&
8731 !CandidateSet.getRewriteInfo().shouldAddReversed(
8732 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8733 continue;
8734 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8735 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8736 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8737 }
8738 }
8739}
8740
8741void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8742 OverloadCandidateSet& CandidateSet,
8743 bool IsAssignmentOperator,
8744 unsigned NumContextualBoolArguments) {
8745 // Overload resolution is always an unevaluated context.
8746 EnterExpressionEvaluationContext Unevaluated(
8747 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8748
8749 // Add this candidate
8750 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8751 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8752 Candidate.Function = nullptr;
8753 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8754
8755 // Determine the implicit conversion sequences for each of the
8756 // arguments.
8757 Candidate.Viable = true;
8758 Candidate.ExplicitCallArguments = Args.size();
8759 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8760 // C++ [over.match.oper]p4:
8761 // For the built-in assignment operators, conversions of the
8762 // left operand are restricted as follows:
8763 // -- no temporaries are introduced to hold the left operand, and
8764 // -- no user-defined conversions are applied to the left
8765 // operand to achieve a type match with the left-most
8766 // parameter of a built-in candidate.
8767 //
8768 // We block these conversions by turning off user-defined
8769 // conversions, since that is the only way that initialization of
8770 // a reference to a non-class type can occur from something that
8771 // is not of the same type.
8772 if (ArgIdx < NumContextualBoolArguments) {
8773 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8774 "Contextual conversion to bool requires bool type");
8775 Candidate.Conversions[ArgIdx]
8776 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
8777 } else {
8778 Candidate.Conversions[ArgIdx]
8779 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
8780 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
8781 /*InOverloadResolution=*/false,
8782 /*AllowObjCWritebackConversion=*/
8783 getLangOpts().ObjCAutoRefCount);
8784 }
8785 if (Candidate.Conversions[ArgIdx].isBad()) {
8786 Candidate.Viable = false;
8787 Candidate.FailureKind = ovl_fail_bad_conversion;
8788 break;
8789 }
8790 }
8791}
8792
8793namespace {
8794
8795/// BuiltinCandidateTypeSet - A set of types that will be used for the
8796/// candidate operator functions for built-in operators (C++
8797/// [over.built]). The types are separated into pointer types and
8798/// enumeration types.
8799class BuiltinCandidateTypeSet {
8800 /// TypeSet - A set of types.
8801 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8802
8803 /// PointerTypes - The set of pointer types that will be used in the
8804 /// built-in candidates.
8805 TypeSet PointerTypes;
8806
8807 /// MemberPointerTypes - The set of member pointer types that will be
8808 /// used in the built-in candidates.
8809 TypeSet MemberPointerTypes;
8810
8811 /// EnumerationTypes - The set of enumeration types that will be
8812 /// used in the built-in candidates.
8813 TypeSet EnumerationTypes;
8814
8815 /// The set of vector types that will be used in the built-in
8816 /// candidates.
8817 TypeSet VectorTypes;
8818
8819 /// The set of matrix types that will be used in the built-in
8820 /// candidates.
8821 TypeSet MatrixTypes;
8822
8823 /// The set of _BitInt types that will be used in the built-in candidates.
8824 TypeSet BitIntTypes;
8825
8826 /// A flag indicating non-record types are viable candidates
8827 bool HasNonRecordTypes;
8828
8829 /// A flag indicating whether either arithmetic or enumeration types
8830 /// were present in the candidate set.
8831 bool HasArithmeticOrEnumeralTypes;
8832
8833 /// A flag indicating whether the nullptr type was present in the
8834 /// candidate set.
8835 bool HasNullPtrType;
8836
8837 /// Sema - The semantic analysis instance where we are building the
8838 /// candidate type set.
8839 Sema &SemaRef;
8840
8841 /// Context - The AST context in which we will build the type sets.
8842 ASTContext &Context;
8843
8844 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8845 const Qualifiers &VisibleQuals);
8846 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8847
8848public:
8849 /// iterator - Iterates through the types that are part of the set.
8850 typedef TypeSet::iterator iterator;
8851
8852 BuiltinCandidateTypeSet(Sema &SemaRef)
8853 : HasNonRecordTypes(false),
8854 HasArithmeticOrEnumeralTypes(false),
8855 HasNullPtrType(false),
8856 SemaRef(SemaRef),
8857 Context(SemaRef.Context) { }
8858
8859 void AddTypesConvertedFrom(QualType Ty,
8860 SourceLocation Loc,
8861 bool AllowUserConversions,
8862 bool AllowExplicitConversions,
8863 const Qualifiers &VisibleTypeConversionsQuals);
8864
8865 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8866 llvm::iterator_range<iterator> member_pointer_types() {
8867 return MemberPointerTypes;
8868 }
8869 llvm::iterator_range<iterator> enumeration_types() {
8870 return EnumerationTypes;
8871 }
8872 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8873 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8874 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8875
8876 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
8877 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8878 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8879 bool hasNullPtrType() const { return HasNullPtrType; }
8880};
8881
8882} // end anonymous namespace
8883
8884/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8885/// the set of pointer types along with any more-qualified variants of
8886/// that type. For example, if @p Ty is "int const *", this routine
8887/// will add "int const *", "int const volatile *", "int const
8888/// restrict *", and "int const volatile restrict *" to the set of
8889/// pointer types. Returns true if the add of @p Ty itself succeeded,
8890/// false otherwise.
8891///
8892/// FIXME: what to do about extended qualifiers?
8893bool
8894BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8895 const Qualifiers &VisibleQuals) {
8896
8897 // Insert this type.
8898 if (!PointerTypes.insert(X: Ty))
8899 return false;
8900
8901 QualType PointeeTy;
8902 const PointerType *PointerTy = Ty->getAs<PointerType>();
8903 bool buildObjCPtr = false;
8904 if (!PointerTy) {
8905 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8906 PointeeTy = PTy->getPointeeType();
8907 buildObjCPtr = true;
8908 } else {
8909 PointeeTy = PointerTy->getPointeeType();
8910 }
8911
8912 // Don't add qualified variants of arrays. For one, they're not allowed
8913 // (the qualifier would sink to the element type), and for another, the
8914 // only overload situation where it matters is subscript or pointer +- int,
8915 // and those shouldn't have qualifier variants anyway.
8916 if (PointeeTy->isArrayType())
8917 return true;
8918
8919 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8920 bool hasVolatile = VisibleQuals.hasVolatile();
8921 bool hasRestrict = VisibleQuals.hasRestrict();
8922
8923 // Iterate through all strict supersets of BaseCVR.
8924 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8925 if ((CVR | BaseCVR) != CVR) continue;
8926 // Skip over volatile if no volatile found anywhere in the types.
8927 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8928
8929 // Skip over restrict if no restrict found anywhere in the types, or if
8930 // the type cannot be restrict-qualified.
8931 if ((CVR & Qualifiers::Restrict) &&
8932 (!hasRestrict ||
8933 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8934 continue;
8935
8936 // Build qualified pointee type.
8937 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8938
8939 // Build qualified pointer type.
8940 QualType QPointerTy;
8941 if (!buildObjCPtr)
8942 QPointerTy = Context.getPointerType(T: QPointeeTy);
8943 else
8944 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
8945
8946 // Insert qualified pointer type.
8947 PointerTypes.insert(X: QPointerTy);
8948 }
8949
8950 return true;
8951}
8952
8953/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8954/// to the set of pointer types along with any more-qualified variants of
8955/// that type. For example, if @p Ty is "int const *", this routine
8956/// will add "int const *", "int const volatile *", "int const
8957/// restrict *", and "int const volatile restrict *" to the set of
8958/// pointer types. Returns true if the add of @p Ty itself succeeded,
8959/// false otherwise.
8960///
8961/// FIXME: what to do about extended qualifiers?
8962bool
8963BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8964 QualType Ty) {
8965 // Insert this type.
8966 if (!MemberPointerTypes.insert(X: Ty))
8967 return false;
8968
8969 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8970 assert(PointerTy && "type was not a member pointer type!");
8971
8972 QualType PointeeTy = PointerTy->getPointeeType();
8973 // Don't add qualified variants of arrays. For one, they're not allowed
8974 // (the qualifier would sink to the element type), and for another, the
8975 // only overload situation where it matters is subscript or pointer +- int,
8976 // and those shouldn't have qualifier variants anyway.
8977 if (PointeeTy->isArrayType())
8978 return true;
8979 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
8980
8981 // Iterate through all strict supersets of the pointee type's CVR
8982 // qualifiers.
8983 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8984 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8985 if ((CVR | BaseCVR) != CVR) continue;
8986
8987 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
8988 MemberPointerTypes.insert(
8989 X: Context.getMemberPointerType(T: QPointeeTy, /*Qualifier=*/nullptr, Cls));
8990 }
8991
8992 return true;
8993}
8994
8995/// AddTypesConvertedFrom - Add each of the types to which the type @p
8996/// Ty can be implicit converted to the given set of @p Types. We're
8997/// primarily interested in pointer types and enumeration types. We also
8998/// take member pointer types, for the conditional operator.
8999/// AllowUserConversions is true if we should look at the conversion
9000/// functions of a class type, and AllowExplicitConversions if we
9001/// should also include the explicit conversion functions of a class
9002/// type.
9003void
9004BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9005 SourceLocation Loc,
9006 bool AllowUserConversions,
9007 bool AllowExplicitConversions,
9008 const Qualifiers &VisibleQuals) {
9009 // Only deal with canonical types.
9010 Ty = Context.getCanonicalType(T: Ty);
9011
9012 // Look through reference types; they aren't part of the type of an
9013 // expression for the purposes of conversions.
9014 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9015 Ty = RefTy->getPointeeType();
9016
9017 // If we're dealing with an array type, decay to the pointer.
9018 if (Ty->isArrayType())
9019 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9020
9021 // Otherwise, we don't care about qualifiers on the type.
9022 Ty = Ty.getLocalUnqualifiedType();
9023
9024 // Flag if we ever add a non-record type.
9025 const RecordType *TyRec = Ty->getAs<RecordType>();
9026 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
9027
9028 // Flag if we encounter an arithmetic type.
9029 HasArithmeticOrEnumeralTypes =
9030 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9031
9032 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9033 PointerTypes.insert(X: Ty);
9034 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9035 // Insert our type, and its more-qualified variants, into the set
9036 // of types.
9037 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9038 return;
9039 } else if (Ty->isMemberPointerType()) {
9040 // Member pointers are far easier, since the pointee can't be converted.
9041 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9042 return;
9043 } else if (Ty->isEnumeralType()) {
9044 HasArithmeticOrEnumeralTypes = true;
9045 EnumerationTypes.insert(X: Ty);
9046 } else if (Ty->isBitIntType()) {
9047 HasArithmeticOrEnumeralTypes = true;
9048 BitIntTypes.insert(X: Ty);
9049 } else if (Ty->isVectorType()) {
9050 // We treat vector types as arithmetic types in many contexts as an
9051 // extension.
9052 HasArithmeticOrEnumeralTypes = true;
9053 VectorTypes.insert(X: Ty);
9054 } else if (Ty->isMatrixType()) {
9055 // Similar to vector types, we treat vector types as arithmetic types in
9056 // many contexts as an extension.
9057 HasArithmeticOrEnumeralTypes = true;
9058 MatrixTypes.insert(X: Ty);
9059 } else if (Ty->isNullPtrType()) {
9060 HasNullPtrType = true;
9061 } else if (AllowUserConversions && TyRec) {
9062 // No conversion functions in incomplete types.
9063 if (!SemaRef.isCompleteType(Loc, T: Ty))
9064 return;
9065
9066 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: TyRec->getDecl());
9067 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9068 if (isa<UsingShadowDecl>(Val: D))
9069 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9070
9071 // Skip conversion function templates; they don't tell us anything
9072 // about which builtin types we can convert to.
9073 if (isa<FunctionTemplateDecl>(Val: D))
9074 continue;
9075
9076 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9077 if (AllowExplicitConversions || !Conv->isExplicit()) {
9078 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9079 VisibleQuals);
9080 }
9081 }
9082 }
9083}
9084/// Helper function for adjusting address spaces for the pointer or reference
9085/// operands of builtin operators depending on the argument.
9086static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9087 Expr *Arg) {
9088 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9089}
9090
9091/// Helper function for AddBuiltinOperatorCandidates() that adds
9092/// the volatile- and non-volatile-qualified assignment operators for the
9093/// given type to the candidate set.
9094static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9095 QualType T,
9096 ArrayRef<Expr *> Args,
9097 OverloadCandidateSet &CandidateSet) {
9098 QualType ParamTypes[2];
9099
9100 // T& operator=(T&, T)
9101 ParamTypes[0] = S.Context.getLValueReferenceType(
9102 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9103 ParamTypes[1] = T;
9104 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9105 /*IsAssignmentOperator=*/true);
9106
9107 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9108 // volatile T& operator=(volatile T&, T)
9109 ParamTypes[0] = S.Context.getLValueReferenceType(
9110 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9111 Arg: Args[0]));
9112 ParamTypes[1] = T;
9113 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9114 /*IsAssignmentOperator=*/true);
9115 }
9116}
9117
9118/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9119/// if any, found in visible type conversion functions found in ArgExpr's type.
9120static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9121 Qualifiers VRQuals;
9122 CXXRecordDecl *ClassDecl;
9123 if (const MemberPointerType *RHSMPType =
9124 ArgExpr->getType()->getAs<MemberPointerType>())
9125 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9126 else
9127 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9128 if (!ClassDecl) {
9129 // Just to be safe, assume the worst case.
9130 VRQuals.addVolatile();
9131 VRQuals.addRestrict();
9132 return VRQuals;
9133 }
9134 if (!ClassDecl->hasDefinition())
9135 return VRQuals;
9136
9137 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9138 if (isa<UsingShadowDecl>(Val: D))
9139 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9140 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9141 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9142 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9143 CanTy = ResTypeRef->getPointeeType();
9144 // Need to go down the pointer/mempointer chain and add qualifiers
9145 // as see them.
9146 bool done = false;
9147 while (!done) {
9148 if (CanTy.isRestrictQualified())
9149 VRQuals.addRestrict();
9150 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9151 CanTy = ResTypePtr->getPointeeType();
9152 else if (const MemberPointerType *ResTypeMPtr =
9153 CanTy->getAs<MemberPointerType>())
9154 CanTy = ResTypeMPtr->getPointeeType();
9155 else
9156 done = true;
9157 if (CanTy.isVolatileQualified())
9158 VRQuals.addVolatile();
9159 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9160 return VRQuals;
9161 }
9162 }
9163 }
9164 return VRQuals;
9165}
9166
9167// Note: We're currently only handling qualifiers that are meaningful for the
9168// LHS of compound assignment overloading.
9169static void forAllQualifierCombinationsImpl(
9170 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9171 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9172 // _Atomic
9173 if (Available.hasAtomic()) {
9174 Available.removeAtomic();
9175 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9176 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9177 return;
9178 }
9179
9180 // volatile
9181 if (Available.hasVolatile()) {
9182 Available.removeVolatile();
9183 assert(!Applied.hasVolatile());
9184 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9185 Callback);
9186 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9187 return;
9188 }
9189
9190 Callback(Applied);
9191}
9192
9193static void forAllQualifierCombinations(
9194 QualifiersAndAtomic Quals,
9195 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9196 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9197 Callback);
9198}
9199
9200static QualType makeQualifiedLValueReferenceType(QualType Base,
9201 QualifiersAndAtomic Quals,
9202 Sema &S) {
9203 if (Quals.hasAtomic())
9204 Base = S.Context.getAtomicType(T: Base);
9205 if (Quals.hasVolatile())
9206 Base = S.Context.getVolatileType(T: Base);
9207 return S.Context.getLValueReferenceType(T: Base);
9208}
9209
9210namespace {
9211
9212/// Helper class to manage the addition of builtin operator overload
9213/// candidates. It provides shared state and utility methods used throughout
9214/// the process, as well as a helper method to add each group of builtin
9215/// operator overloads from the standard to a candidate set.
9216class BuiltinOperatorOverloadBuilder {
9217 // Common instance state available to all overload candidate addition methods.
9218 Sema &S;
9219 ArrayRef<Expr *> Args;
9220 QualifiersAndAtomic VisibleTypeConversionsQuals;
9221 bool HasArithmeticOrEnumeralCandidateType;
9222 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9223 OverloadCandidateSet &CandidateSet;
9224
9225 static constexpr int ArithmeticTypesCap = 26;
9226 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9227
9228 // Define some indices used to iterate over the arithmetic types in
9229 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9230 // types are that preserved by promotion (C++ [over.built]p2).
9231 unsigned FirstIntegralType,
9232 LastIntegralType;
9233 unsigned FirstPromotedIntegralType,
9234 LastPromotedIntegralType;
9235 unsigned FirstPromotedArithmeticType,
9236 LastPromotedArithmeticType;
9237 unsigned NumArithmeticTypes;
9238
9239 void InitArithmeticTypes() {
9240 // Start of promoted types.
9241 FirstPromotedArithmeticType = 0;
9242 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9243 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9244 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9245 if (S.Context.getTargetInfo().hasFloat128Type())
9246 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9247 if (S.Context.getTargetInfo().hasIbm128Type())
9248 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9249
9250 // Start of integral types.
9251 FirstIntegralType = ArithmeticTypes.size();
9252 FirstPromotedIntegralType = ArithmeticTypes.size();
9253 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9254 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9255 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9256 if (S.Context.getTargetInfo().hasInt128Type() ||
9257 (S.Context.getAuxTargetInfo() &&
9258 S.Context.getAuxTargetInfo()->hasInt128Type()))
9259 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9260 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9261 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9262 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9263 if (S.Context.getTargetInfo().hasInt128Type() ||
9264 (S.Context.getAuxTargetInfo() &&
9265 S.Context.getAuxTargetInfo()->hasInt128Type()))
9266 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9267
9268 /// We add candidates for the unique, unqualified _BitInt types present in
9269 /// the candidate type set. The candidate set already handled ensuring the
9270 /// type is unqualified and canonical, but because we're adding from N
9271 /// different sets, we need to do some extra work to unique things. Insert
9272 /// the candidates into a unique set, then move from that set into the list
9273 /// of arithmetic types.
9274 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9275 llvm::for_each(Range&: CandidateTypes, F: [&BitIntCandidates](
9276 BuiltinCandidateTypeSet &Candidate) {
9277 for (QualType BitTy : Candidate.bitint_types())
9278 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9279 });
9280 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9281 LastPromotedIntegralType = ArithmeticTypes.size();
9282 LastPromotedArithmeticType = ArithmeticTypes.size();
9283 // End of promoted types.
9284
9285 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9286 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9287 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9288 if (S.Context.getLangOpts().Char8)
9289 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9290 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9291 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9292 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9293 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9294 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9295 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9296 LastIntegralType = ArithmeticTypes.size();
9297 NumArithmeticTypes = ArithmeticTypes.size();
9298 // End of integral types.
9299 // FIXME: What about complex? What about half?
9300
9301 // We don't know for sure how many bit-precise candidates were involved, so
9302 // we subtract those from the total when testing whether we're under the
9303 // cap or not.
9304 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9305 ArithmeticTypesCap &&
9306 "Enough inline storage for all arithmetic types.");
9307 }
9308
9309 /// Helper method to factor out the common pattern of adding overloads
9310 /// for '++' and '--' builtin operators.
9311 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9312 bool HasVolatile,
9313 bool HasRestrict) {
9314 QualType ParamTypes[2] = {
9315 S.Context.getLValueReferenceType(T: CandidateTy),
9316 S.Context.IntTy
9317 };
9318
9319 // Non-volatile version.
9320 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9321
9322 // Use a heuristic to reduce number of builtin candidates in the set:
9323 // add volatile version only if there are conversions to a volatile type.
9324 if (HasVolatile) {
9325 ParamTypes[0] =
9326 S.Context.getLValueReferenceType(
9327 T: S.Context.getVolatileType(T: CandidateTy));
9328 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9329 }
9330
9331 // Add restrict version only if there are conversions to a restrict type
9332 // and our candidate type is a non-restrict-qualified pointer.
9333 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9334 !CandidateTy.isRestrictQualified()) {
9335 ParamTypes[0]
9336 = S.Context.getLValueReferenceType(
9337 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9338 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9339
9340 if (HasVolatile) {
9341 ParamTypes[0]
9342 = S.Context.getLValueReferenceType(
9343 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9344 CVR: (Qualifiers::Volatile |
9345 Qualifiers::Restrict)));
9346 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9347 }
9348 }
9349
9350 }
9351
9352 /// Helper to add an overload candidate for a binary builtin with types \p L
9353 /// and \p R.
9354 void AddCandidate(QualType L, QualType R) {
9355 QualType LandR[2] = {L, R};
9356 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9357 }
9358
9359public:
9360 BuiltinOperatorOverloadBuilder(
9361 Sema &S, ArrayRef<Expr *> Args,
9362 QualifiersAndAtomic VisibleTypeConversionsQuals,
9363 bool HasArithmeticOrEnumeralCandidateType,
9364 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9365 OverloadCandidateSet &CandidateSet)
9366 : S(S), Args(Args),
9367 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9368 HasArithmeticOrEnumeralCandidateType(
9369 HasArithmeticOrEnumeralCandidateType),
9370 CandidateTypes(CandidateTypes),
9371 CandidateSet(CandidateSet) {
9372
9373 InitArithmeticTypes();
9374 }
9375
9376 // Increment is deprecated for bool since C++17.
9377 //
9378 // C++ [over.built]p3:
9379 //
9380 // For every pair (T, VQ), where T is an arithmetic type other
9381 // than bool, and VQ is either volatile or empty, there exist
9382 // candidate operator functions of the form
9383 //
9384 // VQ T& operator++(VQ T&);
9385 // T operator++(VQ T&, int);
9386 //
9387 // C++ [over.built]p4:
9388 //
9389 // For every pair (T, VQ), where T is an arithmetic type other
9390 // than bool, and VQ is either volatile or empty, there exist
9391 // candidate operator functions of the form
9392 //
9393 // VQ T& operator--(VQ T&);
9394 // T operator--(VQ T&, int);
9395 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9396 if (!HasArithmeticOrEnumeralCandidateType)
9397 return;
9398
9399 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9400 const auto TypeOfT = ArithmeticTypes[Arith];
9401 if (TypeOfT == S.Context.BoolTy) {
9402 if (Op == OO_MinusMinus)
9403 continue;
9404 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9405 continue;
9406 }
9407 addPlusPlusMinusMinusStyleOverloads(
9408 CandidateTy: TypeOfT,
9409 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9410 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9411 }
9412 }
9413
9414 // C++ [over.built]p5:
9415 //
9416 // For every pair (T, VQ), where T is a cv-qualified or
9417 // cv-unqualified object type, and VQ is either volatile or
9418 // empty, there exist candidate operator functions of the form
9419 //
9420 // T*VQ& operator++(T*VQ&);
9421 // T*VQ& operator--(T*VQ&);
9422 // T* operator++(T*VQ&, int);
9423 // T* operator--(T*VQ&, int);
9424 void addPlusPlusMinusMinusPointerOverloads() {
9425 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9426 // Skip pointer types that aren't pointers to object types.
9427 if (!PtrTy->getPointeeType()->isObjectType())
9428 continue;
9429
9430 addPlusPlusMinusMinusStyleOverloads(
9431 CandidateTy: PtrTy,
9432 HasVolatile: (!PtrTy.isVolatileQualified() &&
9433 VisibleTypeConversionsQuals.hasVolatile()),
9434 HasRestrict: (!PtrTy.isRestrictQualified() &&
9435 VisibleTypeConversionsQuals.hasRestrict()));
9436 }
9437 }
9438
9439 // C++ [over.built]p6:
9440 // For every cv-qualified or cv-unqualified object type T, there
9441 // exist candidate operator functions of the form
9442 //
9443 // T& operator*(T*);
9444 //
9445 // C++ [over.built]p7:
9446 // For every function type T that does not have cv-qualifiers or a
9447 // ref-qualifier, there exist candidate operator functions of the form
9448 // T& operator*(T*);
9449 void addUnaryStarPointerOverloads() {
9450 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9451 QualType PointeeTy = ParamTy->getPointeeType();
9452 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9453 continue;
9454
9455 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9456 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9457 continue;
9458
9459 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9460 }
9461 }
9462
9463 // C++ [over.built]p9:
9464 // For every promoted arithmetic type T, there exist candidate
9465 // operator functions of the form
9466 //
9467 // T operator+(T);
9468 // T operator-(T);
9469 void addUnaryPlusOrMinusArithmeticOverloads() {
9470 if (!HasArithmeticOrEnumeralCandidateType)
9471 return;
9472
9473 for (unsigned Arith = FirstPromotedArithmeticType;
9474 Arith < LastPromotedArithmeticType; ++Arith) {
9475 QualType ArithTy = ArithmeticTypes[Arith];
9476 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9477 }
9478
9479 // Extension: We also add these operators for vector types.
9480 for (QualType VecTy : CandidateTypes[0].vector_types())
9481 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9482 }
9483
9484 // C++ [over.built]p8:
9485 // For every type T, there exist candidate operator functions of
9486 // the form
9487 //
9488 // T* operator+(T*);
9489 void addUnaryPlusPointerOverloads() {
9490 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9491 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9492 }
9493
9494 // C++ [over.built]p10:
9495 // For every promoted integral type T, there exist candidate
9496 // operator functions of the form
9497 //
9498 // T operator~(T);
9499 void addUnaryTildePromotedIntegralOverloads() {
9500 if (!HasArithmeticOrEnumeralCandidateType)
9501 return;
9502
9503 for (unsigned Int = FirstPromotedIntegralType;
9504 Int < LastPromotedIntegralType; ++Int) {
9505 QualType IntTy = ArithmeticTypes[Int];
9506 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9507 }
9508
9509 // Extension: We also add this operator for vector types.
9510 for (QualType VecTy : CandidateTypes[0].vector_types())
9511 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9512 }
9513
9514 // C++ [over.match.oper]p16:
9515 // For every pointer to member type T or type std::nullptr_t, there
9516 // exist candidate operator functions of the form
9517 //
9518 // bool operator==(T,T);
9519 // bool operator!=(T,T);
9520 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9521 /// Set of (canonical) types that we've already handled.
9522 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9523
9524 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9525 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9526 // Don't add the same builtin candidate twice.
9527 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9528 continue;
9529
9530 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9531 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9532 }
9533
9534 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9535 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9536 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9537 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9538 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9539 }
9540 }
9541 }
9542 }
9543
9544 // C++ [over.built]p15:
9545 //
9546 // For every T, where T is an enumeration type or a pointer type,
9547 // there exist candidate operator functions of the form
9548 //
9549 // bool operator<(T, T);
9550 // bool operator>(T, T);
9551 // bool operator<=(T, T);
9552 // bool operator>=(T, T);
9553 // bool operator==(T, T);
9554 // bool operator!=(T, T);
9555 // R operator<=>(T, T)
9556 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9557 // C++ [over.match.oper]p3:
9558 // [...]the built-in candidates include all of the candidate operator
9559 // functions defined in 13.6 that, compared to the given operator, [...]
9560 // do not have the same parameter-type-list as any non-template non-member
9561 // candidate.
9562 //
9563 // Note that in practice, this only affects enumeration types because there
9564 // aren't any built-in candidates of record type, and a user-defined operator
9565 // must have an operand of record or enumeration type. Also, the only other
9566 // overloaded operator with enumeration arguments, operator=,
9567 // cannot be overloaded for enumeration types, so this is the only place
9568 // where we must suppress candidates like this.
9569 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9570 UserDefinedBinaryOperators;
9571
9572 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9573 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9574 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9575 CEnd = CandidateSet.end();
9576 C != CEnd; ++C) {
9577 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9578 continue;
9579
9580 if (C->Function->isFunctionTemplateSpecialization())
9581 continue;
9582
9583 // We interpret "same parameter-type-list" as applying to the
9584 // "synthesized candidate, with the order of the two parameters
9585 // reversed", not to the original function.
9586 bool Reversed = C->isReversed();
9587 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9588 ->getType()
9589 .getUnqualifiedType();
9590 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9591 ->getType()
9592 .getUnqualifiedType();
9593
9594 // Skip if either parameter isn't of enumeral type.
9595 if (!FirstParamType->isEnumeralType() ||
9596 !SecondParamType->isEnumeralType())
9597 continue;
9598
9599 // Add this operator to the set of known user-defined operators.
9600 UserDefinedBinaryOperators.insert(
9601 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9602 y: S.Context.getCanonicalType(T: SecondParamType)));
9603 }
9604 }
9605 }
9606
9607 /// Set of (canonical) types that we've already handled.
9608 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9609
9610 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9611 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9612 // Don't add the same builtin candidate twice.
9613 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9614 continue;
9615 if (IsSpaceship && PtrTy->isFunctionPointerType())
9616 continue;
9617
9618 QualType ParamTypes[2] = {PtrTy, PtrTy};
9619 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9620 }
9621 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9622 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9623
9624 // Don't add the same builtin candidate twice, or if a user defined
9625 // candidate exists.
9626 if (!AddedTypes.insert(Ptr: CanonType).second ||
9627 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9628 y&: CanonType)))
9629 continue;
9630 QualType ParamTypes[2] = {EnumTy, EnumTy};
9631 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9632 }
9633 }
9634 }
9635
9636 // C++ [over.built]p13:
9637 //
9638 // For every cv-qualified or cv-unqualified object type T
9639 // there exist candidate operator functions of the form
9640 //
9641 // T* operator+(T*, ptrdiff_t);
9642 // T& operator[](T*, ptrdiff_t); [BELOW]
9643 // T* operator-(T*, ptrdiff_t);
9644 // T* operator+(ptrdiff_t, T*);
9645 // T& operator[](ptrdiff_t, T*); [BELOW]
9646 //
9647 // C++ [over.built]p14:
9648 //
9649 // For every T, where T is a pointer to object type, there
9650 // exist candidate operator functions of the form
9651 //
9652 // ptrdiff_t operator-(T, T);
9653 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9654 /// Set of (canonical) types that we've already handled.
9655 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9656
9657 for (int Arg = 0; Arg < 2; ++Arg) {
9658 QualType AsymmetricParamTypes[2] = {
9659 S.Context.getPointerDiffType(),
9660 S.Context.getPointerDiffType(),
9661 };
9662 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9663 QualType PointeeTy = PtrTy->getPointeeType();
9664 if (!PointeeTy->isObjectType())
9665 continue;
9666
9667 AsymmetricParamTypes[Arg] = PtrTy;
9668 if (Arg == 0 || Op == OO_Plus) {
9669 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9670 // T* operator+(ptrdiff_t, T*);
9671 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9672 }
9673 if (Op == OO_Minus) {
9674 // ptrdiff_t operator-(T, T);
9675 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9676 continue;
9677
9678 QualType ParamTypes[2] = {PtrTy, PtrTy};
9679 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9680 }
9681 }
9682 }
9683 }
9684
9685 // C++ [over.built]p12:
9686 //
9687 // For every pair of promoted arithmetic types L and R, there
9688 // exist candidate operator functions of the form
9689 //
9690 // LR operator*(L, R);
9691 // LR operator/(L, R);
9692 // LR operator+(L, R);
9693 // LR operator-(L, R);
9694 // bool operator<(L, R);
9695 // bool operator>(L, R);
9696 // bool operator<=(L, R);
9697 // bool operator>=(L, R);
9698 // bool operator==(L, R);
9699 // bool operator!=(L, R);
9700 //
9701 // where LR is the result of the usual arithmetic conversions
9702 // between types L and R.
9703 //
9704 // C++ [over.built]p24:
9705 //
9706 // For every pair of promoted arithmetic types L and R, there exist
9707 // candidate operator functions of the form
9708 //
9709 // LR operator?(bool, L, R);
9710 //
9711 // where LR is the result of the usual arithmetic conversions
9712 // between types L and R.
9713 // Our candidates ignore the first parameter.
9714 void addGenericBinaryArithmeticOverloads() {
9715 if (!HasArithmeticOrEnumeralCandidateType)
9716 return;
9717
9718 for (unsigned Left = FirstPromotedArithmeticType;
9719 Left < LastPromotedArithmeticType; ++Left) {
9720 for (unsigned Right = FirstPromotedArithmeticType;
9721 Right < LastPromotedArithmeticType; ++Right) {
9722 QualType LandR[2] = { ArithmeticTypes[Left],
9723 ArithmeticTypes[Right] };
9724 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9725 }
9726 }
9727
9728 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9729 // conditional operator for vector types.
9730 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9731 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9732 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9733 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9734 }
9735 }
9736
9737 /// Add binary operator overloads for each candidate matrix type M1, M2:
9738 /// * (M1, M1) -> M1
9739 /// * (M1, M1.getElementType()) -> M1
9740 /// * (M2.getElementType(), M2) -> M2
9741 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9742 void addMatrixBinaryArithmeticOverloads() {
9743 if (!HasArithmeticOrEnumeralCandidateType)
9744 return;
9745
9746 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9747 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9748 AddCandidate(L: M1, R: M1);
9749 }
9750
9751 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9752 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9753 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9754 AddCandidate(L: M2, R: M2);
9755 }
9756 }
9757
9758 // C++2a [over.built]p14:
9759 //
9760 // For every integral type T there exists a candidate operator function
9761 // of the form
9762 //
9763 // std::strong_ordering operator<=>(T, T)
9764 //
9765 // C++2a [over.built]p15:
9766 //
9767 // For every pair of floating-point types L and R, there exists a candidate
9768 // operator function of the form
9769 //
9770 // std::partial_ordering operator<=>(L, R);
9771 //
9772 // FIXME: The current specification for integral types doesn't play nice with
9773 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9774 // comparisons. Under the current spec this can lead to ambiguity during
9775 // overload resolution. For example:
9776 //
9777 // enum A : int {a};
9778 // auto x = (a <=> (long)42);
9779 //
9780 // error: call is ambiguous for arguments 'A' and 'long'.
9781 // note: candidate operator<=>(int, int)
9782 // note: candidate operator<=>(long, long)
9783 //
9784 // To avoid this error, this function deviates from the specification and adds
9785 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9786 // arithmetic types (the same as the generic relational overloads).
9787 //
9788 // For now this function acts as a placeholder.
9789 void addThreeWayArithmeticOverloads() {
9790 addGenericBinaryArithmeticOverloads();
9791 }
9792
9793 // C++ [over.built]p17:
9794 //
9795 // For every pair of promoted integral types L and R, there
9796 // exist candidate operator functions of the form
9797 //
9798 // LR operator%(L, R);
9799 // LR operator&(L, R);
9800 // LR operator^(L, R);
9801 // LR operator|(L, R);
9802 // L operator<<(L, R);
9803 // L operator>>(L, R);
9804 //
9805 // where LR is the result of the usual arithmetic conversions
9806 // between types L and R.
9807 void addBinaryBitwiseArithmeticOverloads() {
9808 if (!HasArithmeticOrEnumeralCandidateType)
9809 return;
9810
9811 for (unsigned Left = FirstPromotedIntegralType;
9812 Left < LastPromotedIntegralType; ++Left) {
9813 for (unsigned Right = FirstPromotedIntegralType;
9814 Right < LastPromotedIntegralType; ++Right) {
9815 QualType LandR[2] = { ArithmeticTypes[Left],
9816 ArithmeticTypes[Right] };
9817 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9818 }
9819 }
9820 }
9821
9822 // C++ [over.built]p20:
9823 //
9824 // For every pair (T, VQ), where T is an enumeration or
9825 // pointer to member type and VQ is either volatile or
9826 // empty, there exist candidate operator functions of the form
9827 //
9828 // VQ T& operator=(VQ T&, T);
9829 void addAssignmentMemberPointerOrEnumeralOverloads() {
9830 /// Set of (canonical) types that we've already handled.
9831 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9832
9833 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9834 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9835 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
9836 continue;
9837
9838 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
9839 }
9840
9841 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9842 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9843 continue;
9844
9845 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
9846 }
9847 }
9848 }
9849
9850 // C++ [over.built]p19:
9851 //
9852 // For every pair (T, VQ), where T is any type and VQ is either
9853 // volatile or empty, there exist candidate operator functions
9854 // of the form
9855 //
9856 // T*VQ& operator=(T*VQ&, T*);
9857 //
9858 // C++ [over.built]p21:
9859 //
9860 // For every pair (T, VQ), where T is a cv-qualified or
9861 // cv-unqualified object type and VQ is either volatile or
9862 // empty, there exist candidate operator functions of the form
9863 //
9864 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9865 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9866 void addAssignmentPointerOverloads(bool isEqualOp) {
9867 /// Set of (canonical) types that we've already handled.
9868 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9869
9870 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9871 // If this is operator=, keep track of the builtin candidates we added.
9872 if (isEqualOp)
9873 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
9874 else if (!PtrTy->getPointeeType()->isObjectType())
9875 continue;
9876
9877 // non-volatile version
9878 QualType ParamTypes[2] = {
9879 S.Context.getLValueReferenceType(T: PtrTy),
9880 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9881 };
9882 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9883 /*IsAssignmentOperator=*/ isEqualOp);
9884
9885 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9886 VisibleTypeConversionsQuals.hasVolatile();
9887 if (NeedVolatile) {
9888 // volatile version
9889 ParamTypes[0] =
9890 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
9891 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9892 /*IsAssignmentOperator=*/isEqualOp);
9893 }
9894
9895 if (!PtrTy.isRestrictQualified() &&
9896 VisibleTypeConversionsQuals.hasRestrict()) {
9897 // restrict version
9898 ParamTypes[0] =
9899 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
9900 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9901 /*IsAssignmentOperator=*/isEqualOp);
9902
9903 if (NeedVolatile) {
9904 // volatile restrict version
9905 ParamTypes[0] =
9906 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9907 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9908 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9909 /*IsAssignmentOperator=*/isEqualOp);
9910 }
9911 }
9912 }
9913
9914 if (isEqualOp) {
9915 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9916 // Make sure we don't add the same candidate twice.
9917 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9918 continue;
9919
9920 QualType ParamTypes[2] = {
9921 S.Context.getLValueReferenceType(T: PtrTy),
9922 PtrTy,
9923 };
9924
9925 // non-volatile version
9926 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9927 /*IsAssignmentOperator=*/true);
9928
9929 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9930 VisibleTypeConversionsQuals.hasVolatile();
9931 if (NeedVolatile) {
9932 // volatile version
9933 ParamTypes[0] = S.Context.getLValueReferenceType(
9934 T: S.Context.getVolatileType(T: PtrTy));
9935 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9936 /*IsAssignmentOperator=*/true);
9937 }
9938
9939 if (!PtrTy.isRestrictQualified() &&
9940 VisibleTypeConversionsQuals.hasRestrict()) {
9941 // restrict version
9942 ParamTypes[0] = S.Context.getLValueReferenceType(
9943 T: S.Context.getRestrictType(T: PtrTy));
9944 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9945 /*IsAssignmentOperator=*/true);
9946
9947 if (NeedVolatile) {
9948 // volatile restrict version
9949 ParamTypes[0] =
9950 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
9951 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
9952 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9953 /*IsAssignmentOperator=*/true);
9954 }
9955 }
9956 }
9957 }
9958 }
9959
9960 // C++ [over.built]p18:
9961 //
9962 // For every triple (L, VQ, R), where L is an arithmetic type,
9963 // VQ is either volatile or empty, and R is a promoted
9964 // arithmetic type, there exist candidate operator functions of
9965 // the form
9966 //
9967 // VQ L& operator=(VQ L&, R);
9968 // VQ L& operator*=(VQ L&, R);
9969 // VQ L& operator/=(VQ L&, R);
9970 // VQ L& operator+=(VQ L&, R);
9971 // VQ L& operator-=(VQ L&, R);
9972 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9973 if (!HasArithmeticOrEnumeralCandidateType)
9974 return;
9975
9976 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9977 for (unsigned Right = FirstPromotedArithmeticType;
9978 Right < LastPromotedArithmeticType; ++Right) {
9979 QualType ParamTypes[2];
9980 ParamTypes[1] = ArithmeticTypes[Right];
9981 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9982 S, T: ArithmeticTypes[Left], Arg: Args[0]);
9983
9984 forAllQualifierCombinations(
9985 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
9986 ParamTypes[0] =
9987 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
9988 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9989 /*IsAssignmentOperator=*/isEqualOp);
9990 });
9991 }
9992 }
9993
9994 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9995 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9996 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9997 QualType ParamTypes[2];
9998 ParamTypes[1] = Vec2Ty;
9999 // Add this built-in operator as a candidate (VQ is empty).
10000 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10001 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10002 /*IsAssignmentOperator=*/isEqualOp);
10003
10004 // Add this built-in operator as a candidate (VQ is 'volatile').
10005 if (VisibleTypeConversionsQuals.hasVolatile()) {
10006 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10007 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10008 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10009 /*IsAssignmentOperator=*/isEqualOp);
10010 }
10011 }
10012 }
10013
10014 // C++ [over.built]p22:
10015 //
10016 // For every triple (L, VQ, R), where L is an integral type, VQ
10017 // is either volatile or empty, and R is a promoted integral
10018 // type, there exist candidate operator functions of the form
10019 //
10020 // VQ L& operator%=(VQ L&, R);
10021 // VQ L& operator<<=(VQ L&, R);
10022 // VQ L& operator>>=(VQ L&, R);
10023 // VQ L& operator&=(VQ L&, R);
10024 // VQ L& operator^=(VQ L&, R);
10025 // VQ L& operator|=(VQ L&, R);
10026 void addAssignmentIntegralOverloads() {
10027 if (!HasArithmeticOrEnumeralCandidateType)
10028 return;
10029
10030 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10031 for (unsigned Right = FirstPromotedIntegralType;
10032 Right < LastPromotedIntegralType; ++Right) {
10033 QualType ParamTypes[2];
10034 ParamTypes[1] = ArithmeticTypes[Right];
10035 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10036 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10037
10038 forAllQualifierCombinations(
10039 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10040 ParamTypes[0] =
10041 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10042 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10043 });
10044 }
10045 }
10046 }
10047
10048 // C++ [over.operator]p23:
10049 //
10050 // There also exist candidate operator functions of the form
10051 //
10052 // bool operator!(bool);
10053 // bool operator&&(bool, bool);
10054 // bool operator||(bool, bool);
10055 void addExclaimOverload() {
10056 QualType ParamTy = S.Context.BoolTy;
10057 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10058 /*IsAssignmentOperator=*/false,
10059 /*NumContextualBoolArguments=*/1);
10060 }
10061 void addAmpAmpOrPipePipeOverload() {
10062 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10063 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10064 /*IsAssignmentOperator=*/false,
10065 /*NumContextualBoolArguments=*/2);
10066 }
10067
10068 // C++ [over.built]p13:
10069 //
10070 // For every cv-qualified or cv-unqualified object type T there
10071 // exist candidate operator functions of the form
10072 //
10073 // T* operator+(T*, ptrdiff_t); [ABOVE]
10074 // T& operator[](T*, ptrdiff_t);
10075 // T* operator-(T*, ptrdiff_t); [ABOVE]
10076 // T* operator+(ptrdiff_t, T*); [ABOVE]
10077 // T& operator[](ptrdiff_t, T*);
10078 void addSubscriptOverloads() {
10079 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10080 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10081 QualType PointeeType = PtrTy->getPointeeType();
10082 if (!PointeeType->isObjectType())
10083 continue;
10084
10085 // T& operator[](T*, ptrdiff_t)
10086 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10087 }
10088
10089 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10090 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10091 QualType PointeeType = PtrTy->getPointeeType();
10092 if (!PointeeType->isObjectType())
10093 continue;
10094
10095 // T& operator[](ptrdiff_t, T*)
10096 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10097 }
10098 }
10099
10100 // C++ [over.built]p11:
10101 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10102 // C1 is the same type as C2 or is a derived class of C2, T is an object
10103 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10104 // there exist candidate operator functions of the form
10105 //
10106 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10107 //
10108 // where CV12 is the union of CV1 and CV2.
10109 void addArrowStarOverloads() {
10110 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10111 QualType C1Ty = PtrTy;
10112 QualType C1;
10113 QualifierCollector Q1;
10114 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10115 if (!isa<RecordType>(Val: C1))
10116 continue;
10117 // heuristic to reduce number of builtin candidates in the set.
10118 // Add volatile/restrict version only if there are conversions to a
10119 // volatile/restrict type.
10120 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10121 continue;
10122 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10123 continue;
10124 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10125 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10126 CXXRecordDecl *D1 = C1->getAsCXXRecordDecl(),
10127 *D2 = mptr->getMostRecentCXXRecordDecl();
10128 if (!declaresSameEntity(D1, D2) &&
10129 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10130 break;
10131 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10132 // build CV12 T&
10133 QualType T = mptr->getPointeeType();
10134 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10135 T.isVolatileQualified())
10136 continue;
10137 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10138 T.isRestrictQualified())
10139 continue;
10140 T = Q1.apply(Context: S.Context, QT: T);
10141 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10142 }
10143 }
10144 }
10145
10146 // Note that we don't consider the first argument, since it has been
10147 // contextually converted to bool long ago. The candidates below are
10148 // therefore added as binary.
10149 //
10150 // C++ [over.built]p25:
10151 // For every type T, where T is a pointer, pointer-to-member, or scoped
10152 // enumeration type, there exist candidate operator functions of the form
10153 //
10154 // T operator?(bool, T, T);
10155 //
10156 void addConditionalOperatorOverloads() {
10157 /// Set of (canonical) types that we've already handled.
10158 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10159
10160 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10161 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10162 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10163 continue;
10164
10165 QualType ParamTypes[2] = {PtrTy, PtrTy};
10166 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10167 }
10168
10169 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10170 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10171 continue;
10172
10173 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10174 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10175 }
10176
10177 if (S.getLangOpts().CPlusPlus11) {
10178 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10179 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
10180 continue;
10181
10182 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10183 continue;
10184
10185 QualType ParamTypes[2] = {EnumTy, EnumTy};
10186 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10187 }
10188 }
10189 }
10190 }
10191};
10192
10193} // end anonymous namespace
10194
10195void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10196 SourceLocation OpLoc,
10197 ArrayRef<Expr *> Args,
10198 OverloadCandidateSet &CandidateSet) {
10199 // Find all of the types that the arguments can convert to, but only
10200 // if the operator we're looking at has built-in operator candidates
10201 // that make use of these types. Also record whether we encounter non-record
10202 // candidate types or either arithmetic or enumeral candidate types.
10203 QualifiersAndAtomic VisibleTypeConversionsQuals;
10204 VisibleTypeConversionsQuals.addConst();
10205 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10206 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10207 if (Args[ArgIdx]->getType()->isAtomicType())
10208 VisibleTypeConversionsQuals.addAtomic();
10209 }
10210
10211 bool HasNonRecordCandidateType = false;
10212 bool HasArithmeticOrEnumeralCandidateType = false;
10213 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10214 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10215 CandidateTypes.emplace_back(Args&: *this);
10216 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10217 Loc: OpLoc,
10218 AllowUserConversions: true,
10219 AllowExplicitConversions: (Op == OO_Exclaim ||
10220 Op == OO_AmpAmp ||
10221 Op == OO_PipePipe),
10222 VisibleQuals: VisibleTypeConversionsQuals);
10223 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10224 CandidateTypes[ArgIdx].hasNonRecordTypes();
10225 HasArithmeticOrEnumeralCandidateType =
10226 HasArithmeticOrEnumeralCandidateType ||
10227 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10228 }
10229
10230 // Exit early when no non-record types have been added to the candidate set
10231 // for any of the arguments to the operator.
10232 //
10233 // We can't exit early for !, ||, or &&, since there we have always have
10234 // 'bool' overloads.
10235 if (!HasNonRecordCandidateType &&
10236 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10237 return;
10238
10239 // Setup an object to manage the common state for building overloads.
10240 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10241 VisibleTypeConversionsQuals,
10242 HasArithmeticOrEnumeralCandidateType,
10243 CandidateTypes, CandidateSet);
10244
10245 // Dispatch over the operation to add in only those overloads which apply.
10246 switch (Op) {
10247 case OO_None:
10248 case NUM_OVERLOADED_OPERATORS:
10249 llvm_unreachable("Expected an overloaded operator");
10250
10251 case OO_New:
10252 case OO_Delete:
10253 case OO_Array_New:
10254 case OO_Array_Delete:
10255 case OO_Call:
10256 llvm_unreachable(
10257 "Special operators don't use AddBuiltinOperatorCandidates");
10258
10259 case OO_Comma:
10260 case OO_Arrow:
10261 case OO_Coawait:
10262 // C++ [over.match.oper]p3:
10263 // -- For the operator ',', the unary operator '&', the
10264 // operator '->', or the operator 'co_await', the
10265 // built-in candidates set is empty.
10266 break;
10267
10268 case OO_Plus: // '+' is either unary or binary
10269 if (Args.size() == 1)
10270 OpBuilder.addUnaryPlusPointerOverloads();
10271 [[fallthrough]];
10272
10273 case OO_Minus: // '-' is either unary or binary
10274 if (Args.size() == 1) {
10275 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10276 } else {
10277 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10278 OpBuilder.addGenericBinaryArithmeticOverloads();
10279 OpBuilder.addMatrixBinaryArithmeticOverloads();
10280 }
10281 break;
10282
10283 case OO_Star: // '*' is either unary or binary
10284 if (Args.size() == 1)
10285 OpBuilder.addUnaryStarPointerOverloads();
10286 else {
10287 OpBuilder.addGenericBinaryArithmeticOverloads();
10288 OpBuilder.addMatrixBinaryArithmeticOverloads();
10289 }
10290 break;
10291
10292 case OO_Slash:
10293 OpBuilder.addGenericBinaryArithmeticOverloads();
10294 break;
10295
10296 case OO_PlusPlus:
10297 case OO_MinusMinus:
10298 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10299 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10300 break;
10301
10302 case OO_EqualEqual:
10303 case OO_ExclaimEqual:
10304 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10305 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10306 OpBuilder.addGenericBinaryArithmeticOverloads();
10307 break;
10308
10309 case OO_Less:
10310 case OO_Greater:
10311 case OO_LessEqual:
10312 case OO_GreaterEqual:
10313 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10314 OpBuilder.addGenericBinaryArithmeticOverloads();
10315 break;
10316
10317 case OO_Spaceship:
10318 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10319 OpBuilder.addThreeWayArithmeticOverloads();
10320 break;
10321
10322 case OO_Percent:
10323 case OO_Caret:
10324 case OO_Pipe:
10325 case OO_LessLess:
10326 case OO_GreaterGreater:
10327 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10328 break;
10329
10330 case OO_Amp: // '&' is either unary or binary
10331 if (Args.size() == 1)
10332 // C++ [over.match.oper]p3:
10333 // -- For the operator ',', the unary operator '&', or the
10334 // operator '->', the built-in candidates set is empty.
10335 break;
10336
10337 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10338 break;
10339
10340 case OO_Tilde:
10341 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10342 break;
10343
10344 case OO_Equal:
10345 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10346 [[fallthrough]];
10347
10348 case OO_PlusEqual:
10349 case OO_MinusEqual:
10350 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10351 [[fallthrough]];
10352
10353 case OO_StarEqual:
10354 case OO_SlashEqual:
10355 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10356 break;
10357
10358 case OO_PercentEqual:
10359 case OO_LessLessEqual:
10360 case OO_GreaterGreaterEqual:
10361 case OO_AmpEqual:
10362 case OO_CaretEqual:
10363 case OO_PipeEqual:
10364 OpBuilder.addAssignmentIntegralOverloads();
10365 break;
10366
10367 case OO_Exclaim:
10368 OpBuilder.addExclaimOverload();
10369 break;
10370
10371 case OO_AmpAmp:
10372 case OO_PipePipe:
10373 OpBuilder.addAmpAmpOrPipePipeOverload();
10374 break;
10375
10376 case OO_Subscript:
10377 if (Args.size() == 2)
10378 OpBuilder.addSubscriptOverloads();
10379 break;
10380
10381 case OO_ArrowStar:
10382 OpBuilder.addArrowStarOverloads();
10383 break;
10384
10385 case OO_Conditional:
10386 OpBuilder.addConditionalOperatorOverloads();
10387 OpBuilder.addGenericBinaryArithmeticOverloads();
10388 break;
10389 }
10390}
10391
10392void
10393Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10394 SourceLocation Loc,
10395 ArrayRef<Expr *> Args,
10396 TemplateArgumentListInfo *ExplicitTemplateArgs,
10397 OverloadCandidateSet& CandidateSet,
10398 bool PartialOverloading) {
10399 ADLResult Fns;
10400
10401 // FIXME: This approach for uniquing ADL results (and removing
10402 // redundant candidates from the set) relies on pointer-equality,
10403 // which means we need to key off the canonical decl. However,
10404 // always going back to the canonical decl might not get us the
10405 // right set of default arguments. What default arguments are
10406 // we supposed to consider on ADL candidates, anyway?
10407
10408 // FIXME: Pass in the explicit template arguments?
10409 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10410
10411 ArrayRef<Expr *> ReversedArgs;
10412
10413 // Erase all of the candidates we already knew about.
10414 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10415 CandEnd = CandidateSet.end();
10416 Cand != CandEnd; ++Cand)
10417 if (Cand->Function) {
10418 FunctionDecl *Fn = Cand->Function;
10419 Fns.erase(Fn);
10420 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10421 Fns.erase(FunTmpl);
10422 }
10423
10424 // For each of the ADL candidates we found, add it to the overload
10425 // set.
10426 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10427 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10428
10429 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10430 if (ExplicitTemplateArgs)
10431 continue;
10432
10433 AddOverloadCandidate(
10434 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10435 PartialOverloading, /*AllowExplicit=*/true,
10436 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10437 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10438 AddOverloadCandidate(
10439 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10440 /*SuppressUserConversions=*/false, PartialOverloading,
10441 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10442 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10443 }
10444 } else {
10445 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10446 AddTemplateOverloadCandidate(
10447 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10448 /*SuppressUserConversions=*/false, PartialOverloading,
10449 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10450 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10451 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10452
10453 // As template candidates are not deduced immediately,
10454 // persist the array in the overload set.
10455 if (ReversedArgs.empty())
10456 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10457
10458 AddTemplateOverloadCandidate(
10459 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10460 /*SuppressUserConversions=*/false, PartialOverloading,
10461 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10462 PO: OverloadCandidateParamOrder::Reversed);
10463 }
10464 }
10465 }
10466}
10467
10468namespace {
10469enum class Comparison { Equal, Better, Worse };
10470}
10471
10472/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10473/// overload resolution.
10474///
10475/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10476/// Cand1's first N enable_if attributes have precisely the same conditions as
10477/// Cand2's first N enable_if attributes (where N = the number of enable_if
10478/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10479///
10480/// Note that you can have a pair of candidates such that Cand1's enable_if
10481/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10482/// worse than Cand1's.
10483static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10484 const FunctionDecl *Cand2) {
10485 // Common case: One (or both) decls don't have enable_if attrs.
10486 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10487 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10488 if (!Cand1Attr || !Cand2Attr) {
10489 if (Cand1Attr == Cand2Attr)
10490 return Comparison::Equal;
10491 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10492 }
10493
10494 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10495 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10496
10497 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10498 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10499 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10500 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10501
10502 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10503 // has fewer enable_if attributes than Cand2, and vice versa.
10504 if (!Cand1A)
10505 return Comparison::Worse;
10506 if (!Cand2A)
10507 return Comparison::Better;
10508
10509 Cand1ID.clear();
10510 Cand2ID.clear();
10511
10512 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10513 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10514 if (Cand1ID != Cand2ID)
10515 return Comparison::Worse;
10516 }
10517
10518 return Comparison::Equal;
10519}
10520
10521static Comparison
10522isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10523 const OverloadCandidate &Cand2) {
10524 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10525 !Cand2.Function->isMultiVersion())
10526 return Comparison::Equal;
10527
10528 // If both are invalid, they are equal. If one of them is invalid, the other
10529 // is better.
10530 if (Cand1.Function->isInvalidDecl()) {
10531 if (Cand2.Function->isInvalidDecl())
10532 return Comparison::Equal;
10533 return Comparison::Worse;
10534 }
10535 if (Cand2.Function->isInvalidDecl())
10536 return Comparison::Better;
10537
10538 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10539 // cpu_dispatch, else arbitrarily based on the identifiers.
10540 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10541 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10542 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10543 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10544
10545 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10546 return Comparison::Equal;
10547
10548 if (Cand1CPUDisp && !Cand2CPUDisp)
10549 return Comparison::Better;
10550 if (Cand2CPUDisp && !Cand1CPUDisp)
10551 return Comparison::Worse;
10552
10553 if (Cand1CPUSpec && Cand2CPUSpec) {
10554 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10555 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10556 ? Comparison::Better
10557 : Comparison::Worse;
10558
10559 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10560 FirstDiff = std::mismatch(
10561 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10562 Cand2CPUSpec->cpus_begin(),
10563 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10564 return LHS->getName() == RHS->getName();
10565 });
10566
10567 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10568 "Two different cpu-specific versions should not have the same "
10569 "identifier list, otherwise they'd be the same decl!");
10570 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10571 ? Comparison::Better
10572 : Comparison::Worse;
10573 }
10574 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10575}
10576
10577/// Compute the type of the implicit object parameter for the given function,
10578/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10579/// null QualType if there is a 'matches anything' implicit object parameter.
10580static std::optional<QualType>
10581getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10582 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10583 return std::nullopt;
10584
10585 auto *M = cast<CXXMethodDecl>(Val: F);
10586 // Static member functions' object parameters match all types.
10587 if (M->isStatic())
10588 return QualType();
10589 return M->getFunctionObjectParameterReferenceType();
10590}
10591
10592// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10593// represent the same entity.
10594static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10595 const FunctionDecl *F2) {
10596 if (declaresSameEntity(F1, F2))
10597 return true;
10598 auto PT1 = F1->getPrimaryTemplate();
10599 auto PT2 = F2->getPrimaryTemplate();
10600 if (PT1 && PT2) {
10601 if (declaresSameEntity(PT1, PT2) ||
10602 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10603 PT2->getInstantiatedFromMemberTemplate()))
10604 return true;
10605 }
10606 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10607 // different functions with same params). Consider removing this (as no test
10608 // fail w/o it).
10609 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10610 if (First) {
10611 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10612 return *T;
10613 }
10614 assert(I < F->getNumParams());
10615 return F->getParamDecl(I++)->getType();
10616 };
10617
10618 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10619 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10620
10621 if (F1NumParams != F2NumParams)
10622 return false;
10623
10624 unsigned I1 = 0, I2 = 0;
10625 for (unsigned I = 0; I != F1NumParams; ++I) {
10626 QualType T1 = NextParam(F1, I1, I == 0);
10627 QualType T2 = NextParam(F2, I2, I == 0);
10628 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10629 if (!Context.hasSameUnqualifiedType(T1, T2))
10630 return false;
10631 }
10632 return true;
10633}
10634
10635/// We're allowed to use constraints partial ordering only if the candidates
10636/// have the same parameter types:
10637/// [over.match.best.general]p2.6
10638/// F1 and F2 are non-template functions with the same
10639/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10640static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10641 FunctionDecl *Fn2,
10642 bool IsFn1Reversed,
10643 bool IsFn2Reversed) {
10644 assert(Fn1 && Fn2);
10645 if (Fn1->isVariadic() != Fn2->isVariadic())
10646 return false;
10647
10648 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10649 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10650 return false;
10651
10652 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10653 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10654 if (Mem1 && Mem2) {
10655 // if they are member functions, both are direct members of the same class,
10656 // and
10657 if (Mem1->getParent() != Mem2->getParent())
10658 return false;
10659 // if both are non-static member functions, they have the same types for
10660 // their object parameters
10661 if (Mem1->isInstance() && Mem2->isInstance() &&
10662 !S.getASTContext().hasSameType(
10663 T1: Mem1->getFunctionObjectParameterReferenceType(),
10664 T2: Mem1->getFunctionObjectParameterReferenceType()))
10665 return false;
10666 }
10667 return true;
10668}
10669
10670static FunctionDecl *
10671getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10672 bool IsFn1Reversed, bool IsFn2Reversed) {
10673 if (!Fn1 || !Fn2)
10674 return nullptr;
10675
10676 // C++ [temp.constr.order]:
10677 // A non-template function F1 is more partial-ordering-constrained than a
10678 // non-template function F2 if:
10679 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10680 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10681
10682 if (Cand1IsSpecialization || Cand2IsSpecialization)
10683 return nullptr;
10684
10685 // - they have the same non-object-parameter-type-lists, and [...]
10686 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10687 IsFn2Reversed))
10688 return nullptr;
10689
10690 // - the declaration of F1 is more constrained than the declaration of F2.
10691 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10692}
10693
10694/// isBetterOverloadCandidate - Determines whether the first overload
10695/// candidate is a better candidate than the second (C++ 13.3.3p1).
10696bool clang::isBetterOverloadCandidate(
10697 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10698 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10699 bool PartialOverloading) {
10700 // Define viable functions to be better candidates than non-viable
10701 // functions.
10702 if (!Cand2.Viable)
10703 return Cand1.Viable;
10704 else if (!Cand1.Viable)
10705 return false;
10706
10707 // [CUDA] A function with 'never' preference is marked not viable, therefore
10708 // is never shown up here. The worst preference shown up here is 'wrong side',
10709 // e.g. an H function called by a HD function in device compilation. This is
10710 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10711 // function which is called only by an H function. A deferred diagnostic will
10712 // be triggered if it is emitted. However a wrong-sided function is still
10713 // a viable candidate here.
10714 //
10715 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10716 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10717 // can be emitted, Cand1 is not better than Cand2. This rule should have
10718 // precedence over other rules.
10719 //
10720 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10721 // other rules should be used to determine which is better. This is because
10722 // host/device based overloading resolution is mostly for determining
10723 // viability of a function. If two functions are both viable, other factors
10724 // should take precedence in preference, e.g. the standard-defined preferences
10725 // like argument conversion ranks or enable_if partial-ordering. The
10726 // preference for pass-object-size parameters is probably most similar to a
10727 // type-based-overloading decision and so should take priority.
10728 //
10729 // If other rules cannot determine which is better, CUDA preference will be
10730 // used again to determine which is better.
10731 //
10732 // TODO: Currently IdentifyPreference does not return correct values
10733 // for functions called in global variable initializers due to missing
10734 // correct context about device/host. Therefore we can only enforce this
10735 // rule when there is a caller. We should enforce this rule for functions
10736 // in global variable initializers once proper context is added.
10737 //
10738 // TODO: We can only enable the hostness based overloading resolution when
10739 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10740 // overloading resolution diagnostics.
10741 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10742 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10743 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10744 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10745 bool IsCand1ImplicitHD =
10746 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10747 bool IsCand2ImplicitHD =
10748 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10749 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10750 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10751 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10752 // The implicit HD function may be a function in a system header which
10753 // is forced by pragma. In device compilation, if we prefer HD candidates
10754 // over wrong-sided candidates, overloading resolution may change, which
10755 // may result in non-deferrable diagnostics. As a workaround, we let
10756 // implicit HD candidates take equal preference as wrong-sided candidates.
10757 // This will preserve the overloading resolution.
10758 // TODO: We still need special handling of implicit HD functions since
10759 // they may incur other diagnostics to be deferred. We should make all
10760 // host/device related diagnostics deferrable and remove special handling
10761 // of implicit HD functions.
10762 auto EmitThreshold =
10763 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10764 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10765 ? SemaCUDA::CFP_Never
10766 : SemaCUDA::CFP_WrongSide;
10767 auto Cand1Emittable = P1 > EmitThreshold;
10768 auto Cand2Emittable = P2 > EmitThreshold;
10769 if (Cand1Emittable && !Cand2Emittable)
10770 return true;
10771 if (!Cand1Emittable && Cand2Emittable)
10772 return false;
10773 }
10774 }
10775
10776 // C++ [over.match.best]p1: (Changed in C++23)
10777 //
10778 // -- if F is a static member function, ICS1(F) is defined such
10779 // that ICS1(F) is neither better nor worse than ICS1(G) for
10780 // any function G, and, symmetrically, ICS1(G) is neither
10781 // better nor worse than ICS1(F).
10782 unsigned StartArg = 0;
10783 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10784 StartArg = 1;
10785
10786 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10787 // We don't allow incompatible pointer conversions in C++.
10788 if (!S.getLangOpts().CPlusPlus)
10789 return ICS.isStandard() &&
10790 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10791
10792 // The only ill-formed conversion we allow in C++ is the string literal to
10793 // char* conversion, which is only considered ill-formed after C++11.
10794 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10795 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10796 };
10797
10798 // Define functions that don't require ill-formed conversions for a given
10799 // argument to be better candidates than functions that do.
10800 unsigned NumArgs = Cand1.Conversions.size();
10801 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10802 bool HasBetterConversion = false;
10803 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10804 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10805 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10806 if (Cand1Bad != Cand2Bad) {
10807 if (Cand1Bad)
10808 return false;
10809 HasBetterConversion = true;
10810 }
10811 }
10812
10813 if (HasBetterConversion)
10814 return true;
10815
10816 // C++ [over.match.best]p1:
10817 // A viable function F1 is defined to be a better function than another
10818 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10819 // conversion sequence than ICSi(F2), and then...
10820 bool HasWorseConversion = false;
10821 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10822 switch (CompareImplicitConversionSequences(S, Loc,
10823 ICS1: Cand1.Conversions[ArgIdx],
10824 ICS2: Cand2.Conversions[ArgIdx])) {
10825 case ImplicitConversionSequence::Better:
10826 // Cand1 has a better conversion sequence.
10827 HasBetterConversion = true;
10828 break;
10829
10830 case ImplicitConversionSequence::Worse:
10831 if (Cand1.Function && Cand2.Function &&
10832 Cand1.isReversed() != Cand2.isReversed() &&
10833 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
10834 // Work around large-scale breakage caused by considering reversed
10835 // forms of operator== in C++20:
10836 //
10837 // When comparing a function against a reversed function, if we have a
10838 // better conversion for one argument and a worse conversion for the
10839 // other, the implicit conversion sequences are treated as being equally
10840 // good.
10841 //
10842 // This prevents a comparison function from being considered ambiguous
10843 // with a reversed form that is written in the same way.
10844 //
10845 // We diagnose this as an extension from CreateOverloadedBinOp.
10846 HasWorseConversion = true;
10847 break;
10848 }
10849
10850 // Cand1 can't be better than Cand2.
10851 return false;
10852
10853 case ImplicitConversionSequence::Indistinguishable:
10854 // Do nothing.
10855 break;
10856 }
10857 }
10858
10859 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10860 // ICSj(F2), or, if not that,
10861 if (HasBetterConversion && !HasWorseConversion)
10862 return true;
10863
10864 // -- the context is an initialization by user-defined conversion
10865 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10866 // from the return type of F1 to the destination type (i.e.,
10867 // the type of the entity being initialized) is a better
10868 // conversion sequence than the standard conversion sequence
10869 // from the return type of F2 to the destination type.
10870 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10871 Cand1.Function && Cand2.Function &&
10872 isa<CXXConversionDecl>(Val: Cand1.Function) &&
10873 isa<CXXConversionDecl>(Val: Cand2.Function)) {
10874
10875 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10876 // First check whether we prefer one of the conversion functions over the
10877 // other. This only distinguishes the results in non-standard, extension
10878 // cases such as the conversion from a lambda closure type to a function
10879 // pointer or block.
10880 ImplicitConversionSequence::CompareKind Result =
10881 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
10882 if (Result == ImplicitConversionSequence::Indistinguishable)
10883 Result = CompareStandardConversionSequences(S, Loc,
10884 SCS1: Cand1.FinalConversion,
10885 SCS2: Cand2.FinalConversion);
10886
10887 if (Result != ImplicitConversionSequence::Indistinguishable)
10888 return Result == ImplicitConversionSequence::Better;
10889
10890 // FIXME: Compare kind of reference binding if conversion functions
10891 // convert to a reference type used in direct reference binding, per
10892 // C++14 [over.match.best]p1 section 2 bullet 3.
10893 }
10894
10895 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10896 // as combined with the resolution to CWG issue 243.
10897 //
10898 // When the context is initialization by constructor ([over.match.ctor] or
10899 // either phase of [over.match.list]), a constructor is preferred over
10900 // a conversion function.
10901 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10902 Cand1.Function && Cand2.Function &&
10903 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
10904 isa<CXXConstructorDecl>(Val: Cand2.Function))
10905 return isa<CXXConstructorDecl>(Val: Cand1.Function);
10906
10907 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10908 return Cand2.StrictPackMatch;
10909
10910 // -- F1 is a non-template function and F2 is a function template
10911 // specialization, or, if not that,
10912 bool Cand1IsSpecialization = Cand1.Function &&
10913 Cand1.Function->getPrimaryTemplate();
10914 bool Cand2IsSpecialization = Cand2.Function &&
10915 Cand2.Function->getPrimaryTemplate();
10916 if (Cand1IsSpecialization != Cand2IsSpecialization)
10917 return Cand2IsSpecialization;
10918
10919 // -- F1 and F2 are function template specializations, and the function
10920 // template for F1 is more specialized than the template for F2
10921 // according to the partial ordering rules described in 14.5.5.2, or,
10922 // if not that,
10923 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10924 const auto *Obj1Context =
10925 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10926 const auto *Obj2Context =
10927 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10928 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10929 FT1: Cand1.Function->getPrimaryTemplate(),
10930 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
10931 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
10932 : TPOC_Call,
10933 NumCallArguments1: Cand1.ExplicitCallArguments,
10934 RawObj1Ty: Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10935 : QualType{},
10936 RawObj2Ty: Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10937 : QualType{},
10938 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10939 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10940 }
10941 }
10942
10943 // -— F1 and F2 are non-template functions and F1 is more
10944 // partial-ordering-constrained than F2 [...],
10945 if (FunctionDecl *F = getMorePartialOrderingConstrained(
10946 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
10947 IsFn2Reversed: Cand2.isReversed());
10948 F && F == Cand1.Function)
10949 return true;
10950
10951 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10952 // class B of D, and for all arguments the corresponding parameters of
10953 // F1 and F2 have the same type.
10954 // FIXME: Implement the "all parameters have the same type" check.
10955 bool Cand1IsInherited =
10956 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
10957 bool Cand2IsInherited =
10958 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
10959 if (Cand1IsInherited != Cand2IsInherited)
10960 return Cand2IsInherited;
10961 else if (Cand1IsInherited) {
10962 assert(Cand2IsInherited);
10963 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10964 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10965 if (Cand1Class->isDerivedFrom(Cand2Class))
10966 return true;
10967 if (Cand2Class->isDerivedFrom(Cand1Class))
10968 return false;
10969 // Inherited from sibling base classes: still ambiguous.
10970 }
10971
10972 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10973 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10974 // with reversed order of parameters and F1 is not
10975 //
10976 // We rank reversed + different operator as worse than just reversed, but
10977 // that comparison can never happen, because we only consider reversing for
10978 // the maximally-rewritten operator (== or <=>).
10979 if (Cand1.RewriteKind != Cand2.RewriteKind)
10980 return Cand1.RewriteKind < Cand2.RewriteKind;
10981
10982 // Check C++17 tie-breakers for deduction guides.
10983 {
10984 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
10985 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
10986 if (Guide1 && Guide2) {
10987 // -- F1 is generated from a deduction-guide and F2 is not
10988 if (Guide1->isImplicit() != Guide2->isImplicit())
10989 return Guide2->isImplicit();
10990
10991 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10992 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10993 return true;
10994 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10995 return false;
10996
10997 // --F1 is generated from a non-template constructor and F2 is generated
10998 // from a constructor template
10999 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11000 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11001 if (Constructor1 && Constructor2) {
11002 bool isC1Templated = Constructor1->getTemplatedKind() !=
11003 FunctionDecl::TemplatedKind::TK_NonTemplate;
11004 bool isC2Templated = Constructor2->getTemplatedKind() !=
11005 FunctionDecl::TemplatedKind::TK_NonTemplate;
11006 if (isC1Templated != isC2Templated)
11007 return isC2Templated;
11008 }
11009 }
11010 }
11011
11012 // Check for enable_if value-based overload resolution.
11013 if (Cand1.Function && Cand2.Function) {
11014 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11015 if (Cmp != Comparison::Equal)
11016 return Cmp == Comparison::Better;
11017 }
11018
11019 bool HasPS1 = Cand1.Function != nullptr &&
11020 functionHasPassObjectSizeParams(FD: Cand1.Function);
11021 bool HasPS2 = Cand2.Function != nullptr &&
11022 functionHasPassObjectSizeParams(FD: Cand2.Function);
11023 if (HasPS1 != HasPS2 && HasPS1)
11024 return true;
11025
11026 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11027 if (MV == Comparison::Better)
11028 return true;
11029 if (MV == Comparison::Worse)
11030 return false;
11031
11032 // If other rules cannot determine which is better, CUDA preference is used
11033 // to determine which is better.
11034 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11035 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11036 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11037 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11038 }
11039
11040 // General member function overloading is handled above, so this only handles
11041 // constructors with address spaces.
11042 // This only handles address spaces since C++ has no other
11043 // qualifier that can be used with constructors.
11044 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11045 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11046 if (CD1 && CD2) {
11047 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11048 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11049 if (AS1 != AS2) {
11050 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11051 return true;
11052 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11053 return false;
11054 }
11055 }
11056
11057 return false;
11058}
11059
11060/// Determine whether two declarations are "equivalent" for the purposes of
11061/// name lookup and overload resolution. This applies when the same internal/no
11062/// linkage entity is defined by two modules (probably by textually including
11063/// the same header). In such a case, we don't consider the declarations to
11064/// declare the same entity, but we also don't want lookups with both
11065/// declarations visible to be ambiguous in some cases (this happens when using
11066/// a modularized libstdc++).
11067bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11068 const NamedDecl *B) {
11069 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11070 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11071 if (!VA || !VB)
11072 return false;
11073
11074 // The declarations must be declaring the same name as an internal linkage
11075 // entity in different modules.
11076 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11077 VB->getDeclContext()->getRedeclContext()) ||
11078 getOwningModule(VA) == getOwningModule(VB) ||
11079 VA->isExternallyVisible() || VB->isExternallyVisible())
11080 return false;
11081
11082 // Check that the declarations appear to be equivalent.
11083 //
11084 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11085 // For constants and functions, we should check the initializer or body is
11086 // the same. For non-constant variables, we shouldn't allow it at all.
11087 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11088 return true;
11089
11090 // Enum constants within unnamed enumerations will have different types, but
11091 // may still be similar enough to be interchangeable for our purposes.
11092 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11093 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11094 // Only handle anonymous enums. If the enumerations were named and
11095 // equivalent, they would have been merged to the same type.
11096 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11097 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11098 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11099 !Context.hasSameType(EnumA->getIntegerType(),
11100 EnumB->getIntegerType()))
11101 return false;
11102 // Allow this only if the value is the same for both enumerators.
11103 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11104 }
11105 }
11106
11107 // Nothing else is sufficiently similar.
11108 return false;
11109}
11110
11111void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11112 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11113 assert(D && "Unknown declaration");
11114 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11115
11116 Module *M = getOwningModule(D);
11117 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11118 << !M << (M ? M->getFullModuleName() : "");
11119
11120 for (auto *E : Equiv) {
11121 Module *M = getOwningModule(E);
11122 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11123 << !M << (M ? M->getFullModuleName() : "");
11124 }
11125}
11126
11127bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11128 return FailureKind == ovl_fail_bad_deduction &&
11129 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11130 TemplateDeductionResult::ConstraintsNotSatisfied &&
11131 static_cast<CNSInfo *>(DeductionFailure.Data)
11132 ->Satisfaction.ContainsErrors;
11133}
11134
11135void OverloadCandidateSet::AddDeferredTemplateCandidate(
11136 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11137 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11138 bool PartialOverloading, bool AllowExplicit,
11139 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11140 bool AggregateCandidateDeduction) {
11141
11142 auto *C =
11143 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11144
11145 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11146 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11147 /*AllowObjCConversionOnExplicit=*/false,
11148 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11149 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11150 .FunctionTemplate: FunctionTemplate,
11151 .FoundDecl: FoundDecl,
11152 .Args: Args,
11153 .IsADLCandidate: IsADLCandidate,
11154 .PO: PO};
11155
11156 HasDeferredTemplateConstructors |=
11157 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11158}
11159
11160void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11161 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11162 CXXRecordDecl *ActingContext, QualType ObjectType,
11163 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11164 bool SuppressUserConversions, bool PartialOverloading,
11165 OverloadCandidateParamOrder PO) {
11166
11167 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11168
11169 auto *C =
11170 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11171
11172 C = new (C) DeferredMethodTemplateOverloadCandidate{
11173 {nullptr, DeferredFunctionTemplateOverloadCandidate::Method,
11174 /*AllowObjCConversionOnExplicit=*/false,
11175 /*AllowResultConversion=*/false,
11176 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11177 /*AggregateCandidateDeduction=*/false},
11178 MethodTmpl,
11179 FoundDecl,
11180 Args,
11181 ActingContext,
11182 ObjectClassification,
11183 ObjectType,
11184 PO};
11185}
11186
11187void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11188 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11189 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11190 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11191 bool AllowResultConversion) {
11192
11193 auto *C =
11194 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11195
11196 C = new (C) DeferredConversionTemplateOverloadCandidate{
11197 {nullptr, DeferredFunctionTemplateOverloadCandidate::Conversion,
11198 AllowObjCConversionOnExplicit, AllowResultConversion,
11199 /*AllowExplicit=*/false,
11200 /*SuppressUserConversions=*/false,
11201 /*PartialOverloading*/ false,
11202 /*AggregateCandidateDeduction=*/false},
11203 FunctionTemplate,
11204 FoundDecl,
11205 ActingContext,
11206 From,
11207 ToType};
11208}
11209
11210static void
11211AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11212 DeferredMethodTemplateOverloadCandidate &C) {
11213
11214 AddMethodTemplateCandidateImmediately(
11215 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11216 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11217 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11218}
11219
11220static void
11221AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11222 DeferredFunctionTemplateOverloadCandidate &C) {
11223 AddTemplateOverloadCandidateImmediately(
11224 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11225 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11226 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11227 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11228}
11229
11230static void
11231AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11232 DeferredConversionTemplateOverloadCandidate &C) {
11233 return AddTemplateConversionCandidateImmediately(
11234 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11235 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11236 C.AllowResultConversion);
11237}
11238
11239void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11240 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11241 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11242 while (Cand) {
11243 switch (Cand->Kind) {
11244 case DeferredTemplateOverloadCandidate::Function:
11245 AddTemplateOverloadCandidate(
11246 S, CandidateSet&: *this,
11247 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11248 break;
11249 case DeferredTemplateOverloadCandidate::Method:
11250 AddTemplateOverloadCandidate(
11251 S, CandidateSet&: *this,
11252 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11253 break;
11254 case DeferredTemplateOverloadCandidate::Conversion:
11255 AddTemplateOverloadCandidate(
11256 S, CandidateSet&: *this,
11257 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11258 break;
11259 }
11260 Cand = Cand->Next;
11261 }
11262 FirstDeferredCandidate = nullptr;
11263 DeferredCandidatesCount = 0;
11264}
11265
11266OverloadingResult
11267OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11268 Best->Best = true;
11269 if (Best->Function && Best->Function->isDeleted())
11270 return OR_Deleted;
11271 return OR_Success;
11272}
11273
11274void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11275 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11276 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11277 // are accepted by both clang and NVCC. However, during a particular
11278 // compilation mode only one call variant is viable. We need to
11279 // exclude non-viable overload candidates from consideration based
11280 // only on their host/device attributes. Specifically, if one
11281 // candidate call is WrongSide and the other is SameSide, we ignore
11282 // the WrongSide candidate.
11283 // We only need to remove wrong-sided candidates here if
11284 // -fgpu-exclude-wrong-side-overloads is off. When
11285 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11286 // uniformly in isBetterOverloadCandidate.
11287 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11288 return;
11289 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11290
11291 bool ContainsSameSideCandidate =
11292 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11293 // Check viable function only.
11294 return Cand->Viable && Cand->Function &&
11295 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11296 SemaCUDA::CFP_SameSide;
11297 });
11298
11299 if (!ContainsSameSideCandidate)
11300 return;
11301
11302 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11303 // Check viable function only to avoid unnecessary data copying/moving.
11304 return Cand->Viable && Cand->Function &&
11305 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11306 SemaCUDA::CFP_WrongSide;
11307 };
11308 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11309}
11310
11311/// Computes the best viable function (C++ 13.3.3)
11312/// within an overload candidate set.
11313///
11314/// \param Loc The location of the function name (or operator symbol) for
11315/// which overload resolution occurs.
11316///
11317/// \param Best If overload resolution was successful or found a deleted
11318/// function, \p Best points to the candidate function found.
11319///
11320/// \returns The result of overload resolution.
11321OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11322 SourceLocation Loc,
11323 iterator &Best) {
11324
11325 assert(shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11326 DeferredCandidatesCount == 0 &&
11327 "Unexpected deferred template candidates");
11328
11329 bool TwoPhaseResolution =
11330 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11331
11332 if (TwoPhaseResolution) {
11333
11334 PerfectViableFunction(S, Loc, Best);
11335 if (Best != end())
11336 return ResultForBestCandidate(Best);
11337 }
11338
11339 InjectNonDeducedTemplateCandidates(S);
11340 return BestViableFunctionImpl(S, Loc, Best);
11341}
11342
11343void OverloadCandidateSet::PerfectViableFunction(
11344 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11345
11346 Best = end();
11347 for (auto It = Candidates.begin(); It != Candidates.end(); ++It) {
11348
11349 if (!It->isPerfectMatch(Ctx: S.getASTContext()))
11350 continue;
11351
11352 // We found a suitable conversion function
11353 // but if there is a template constructor in the target class
11354 // we might prefer that instead.
11355 if (HasDeferredTemplateConstructors &&
11356 isa_and_nonnull<CXXConversionDecl>(Val: It->Function)) {
11357 Best = end();
11358 break;
11359 }
11360
11361 if (Best == end()) {
11362 Best = It;
11363 continue;
11364 }
11365 if (Best->Function && It->Function) {
11366 FunctionDecl *D =
11367 S.getMoreConstrainedFunction(FD1: Best->Function, FD2: It->Function);
11368 if (D == nullptr) {
11369 Best = end();
11370 break;
11371 }
11372 if (D == It->Function)
11373 Best = It;
11374 continue;
11375 }
11376 // ambiguous
11377 Best = end();
11378 break;
11379 }
11380}
11381
11382OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11383 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11384
11385 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11386 Candidates.reserve(N: this->Candidates.size());
11387 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11388 result: std::back_inserter(x&: Candidates),
11389 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11390
11391 if (S.getLangOpts().CUDA)
11392 CudaExcludeWrongSideCandidates(S, Candidates);
11393
11394 Best = end();
11395 for (auto *Cand : Candidates) {
11396 Cand->Best = false;
11397 if (Cand->Viable) {
11398 if (Best == end() ||
11399 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11400 Best = Cand;
11401 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11402 // This candidate has constraint that we were unable to evaluate because
11403 // it referenced an expression that contained an error. Rather than fall
11404 // back onto a potentially unintended candidate (made worse by
11405 // subsuming constraints), treat this as 'no viable candidate'.
11406 Best = end();
11407 return OR_No_Viable_Function;
11408 }
11409 }
11410
11411 // If we didn't find any viable functions, abort.
11412 if (Best == end())
11413 return OR_No_Viable_Function;
11414
11415 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11416 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11417 PendingBest.push_back(Elt: &*Best);
11418 Best->Best = true;
11419
11420 // Make sure that this function is better than every other viable
11421 // function. If not, we have an ambiguity.
11422 while (!PendingBest.empty()) {
11423 auto *Curr = PendingBest.pop_back_val();
11424 for (auto *Cand : Candidates) {
11425 if (Cand->Viable && !Cand->Best &&
11426 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11427 PendingBest.push_back(Elt: Cand);
11428 Cand->Best = true;
11429
11430 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
11431 Curr->Function))
11432 EquivalentCands.push_back(Cand->Function);
11433 else
11434 Best = end();
11435 }
11436 }
11437 }
11438
11439 if (Best == end())
11440 return OR_Ambiguous;
11441
11442 OverloadingResult R = ResultForBestCandidate(Best);
11443
11444 if (!EquivalentCands.empty())
11445 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
11446 EquivalentCands);
11447 return R;
11448}
11449
11450namespace {
11451
11452enum OverloadCandidateKind {
11453 oc_function,
11454 oc_method,
11455 oc_reversed_binary_operator,
11456 oc_constructor,
11457 oc_implicit_default_constructor,
11458 oc_implicit_copy_constructor,
11459 oc_implicit_move_constructor,
11460 oc_implicit_copy_assignment,
11461 oc_implicit_move_assignment,
11462 oc_implicit_equality_comparison,
11463 oc_inherited_constructor
11464};
11465
11466enum OverloadCandidateSelect {
11467 ocs_non_template,
11468 ocs_template,
11469 ocs_described_template,
11470};
11471
11472static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11473ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11474 const FunctionDecl *Fn,
11475 OverloadCandidateRewriteKind CRK,
11476 std::string &Description) {
11477
11478 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11479 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11480 isTemplate = true;
11481 Description = S.getTemplateArgumentBindingsText(
11482 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11483 }
11484
11485 OverloadCandidateSelect Select = [&]() {
11486 if (!Description.empty())
11487 return ocs_described_template;
11488 return isTemplate ? ocs_template : ocs_non_template;
11489 }();
11490
11491 OverloadCandidateKind Kind = [&]() {
11492 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11493 return oc_implicit_equality_comparison;
11494
11495 if (CRK & CRK_Reversed)
11496 return oc_reversed_binary_operator;
11497
11498 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11499 if (!Ctor->isImplicit()) {
11500 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11501 return oc_inherited_constructor;
11502 else
11503 return oc_constructor;
11504 }
11505
11506 if (Ctor->isDefaultConstructor())
11507 return oc_implicit_default_constructor;
11508
11509 if (Ctor->isMoveConstructor())
11510 return oc_implicit_move_constructor;
11511
11512 assert(Ctor->isCopyConstructor() &&
11513 "unexpected sort of implicit constructor");
11514 return oc_implicit_copy_constructor;
11515 }
11516
11517 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11518 // This actually gets spelled 'candidate function' for now, but
11519 // it doesn't hurt to split it out.
11520 if (!Meth->isImplicit())
11521 return oc_method;
11522
11523 if (Meth->isMoveAssignmentOperator())
11524 return oc_implicit_move_assignment;
11525
11526 if (Meth->isCopyAssignmentOperator())
11527 return oc_implicit_copy_assignment;
11528
11529 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11530 return oc_method;
11531 }
11532
11533 return oc_function;
11534 }();
11535
11536 return std::make_pair(x&: Kind, y&: Select);
11537}
11538
11539void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11540 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11541 // set.
11542 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11543 S.Diag(FoundDecl->getLocation(),
11544 diag::note_ovl_candidate_inherited_constructor)
11545 << Shadow->getNominatedBaseClass();
11546}
11547
11548} // end anonymous namespace
11549
11550static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11551 const FunctionDecl *FD) {
11552 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11553 bool AlwaysTrue;
11554 if (EnableIf->getCond()->isValueDependent() ||
11555 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11556 return false;
11557 if (!AlwaysTrue)
11558 return false;
11559 }
11560 return true;
11561}
11562
11563/// Returns true if we can take the address of the function.
11564///
11565/// \param Complain - If true, we'll emit a diagnostic
11566/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11567/// we in overload resolution?
11568/// \param Loc - The location of the statement we're complaining about. Ignored
11569/// if we're not complaining, or if we're in overload resolution.
11570static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11571 bool Complain,
11572 bool InOverloadResolution,
11573 SourceLocation Loc) {
11574 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11575 if (Complain) {
11576 if (InOverloadResolution)
11577 S.Diag(FD->getBeginLoc(),
11578 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11579 else
11580 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11581 }
11582 return false;
11583 }
11584
11585 if (FD->getTrailingRequiresClause()) {
11586 ConstraintSatisfaction Satisfaction;
11587 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11588 return false;
11589 if (!Satisfaction.IsSatisfied) {
11590 if (Complain) {
11591 if (InOverloadResolution) {
11592 SmallString<128> TemplateArgString;
11593 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11594 TemplateArgString += " ";
11595 TemplateArgString += S.getTemplateArgumentBindingsText(
11596 FunTmpl->getTemplateParameters(),
11597 *FD->getTemplateSpecializationArgs());
11598 }
11599
11600 S.Diag(FD->getBeginLoc(),
11601 diag::note_ovl_candidate_unsatisfied_constraints)
11602 << TemplateArgString;
11603 } else
11604 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11605 << FD;
11606 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11607 }
11608 return false;
11609 }
11610 }
11611
11612 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11613 return P->hasAttr<PassObjectSizeAttr>();
11614 });
11615 if (I == FD->param_end())
11616 return true;
11617
11618 if (Complain) {
11619 // Add one to ParamNo because it's user-facing
11620 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11621 if (InOverloadResolution)
11622 S.Diag(FD->getLocation(),
11623 diag::note_ovl_candidate_has_pass_object_size_params)
11624 << ParamNo;
11625 else
11626 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11627 << FD << ParamNo;
11628 }
11629 return false;
11630}
11631
11632static bool checkAddressOfCandidateIsAvailable(Sema &S,
11633 const FunctionDecl *FD) {
11634 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11635 /*InOverloadResolution=*/true,
11636 /*Loc=*/SourceLocation());
11637}
11638
11639bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11640 bool Complain,
11641 SourceLocation Loc) {
11642 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11643 /*InOverloadResolution=*/false,
11644 Loc);
11645}
11646
11647// Don't print candidates other than the one that matches the calling
11648// convention of the call operator, since that is guaranteed to exist.
11649static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11650 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11651
11652 if (!ConvD)
11653 return false;
11654 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11655 if (!RD->isLambda())
11656 return false;
11657
11658 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11659 CallingConv CallOpCC =
11660 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11661 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11662 CallingConv ConvToCC =
11663 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11664
11665 return ConvToCC != CallOpCC;
11666}
11667
11668// Notes the location of an overload candidate.
11669void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11670 OverloadCandidateRewriteKind RewriteKind,
11671 QualType DestType, bool TakingAddress) {
11672 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11673 return;
11674 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11675 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11676 return;
11677 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11678 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11679 return;
11680 if (shouldSkipNotingLambdaConversionDecl(Fn))
11681 return;
11682
11683 std::string FnDesc;
11684 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11685 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11686 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11687 << (unsigned)KSPair.first << (unsigned)KSPair.second
11688 << Fn << FnDesc;
11689
11690 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11691 Diag(Fn->getLocation(), PD);
11692 MaybeEmitInheritedConstructorNote(*this, Found);
11693}
11694
11695static void
11696MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11697 // Perhaps the ambiguity was caused by two atomic constraints that are
11698 // 'identical' but not equivalent:
11699 //
11700 // void foo() requires (sizeof(T) > 4) { } // #1
11701 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11702 //
11703 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11704 // #2 to subsume #1, but these constraint are not considered equivalent
11705 // according to the subsumption rules because they are not the same
11706 // source-level construct. This behavior is quite confusing and we should try
11707 // to help the user figure out what happened.
11708
11709 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11710 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11711 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11712 if (!I->Function)
11713 continue;
11714 SmallVector<AssociatedConstraint, 3> AC;
11715 if (auto *Template = I->Function->getPrimaryTemplate())
11716 Template->getAssociatedConstraints(AC);
11717 else
11718 I->Function->getAssociatedConstraints(ACs&: AC);
11719 if (AC.empty())
11720 continue;
11721 if (FirstCand == nullptr) {
11722 FirstCand = I->Function;
11723 FirstAC = AC;
11724 } else if (SecondCand == nullptr) {
11725 SecondCand = I->Function;
11726 SecondAC = AC;
11727 } else {
11728 // We have more than one pair of constrained functions - this check is
11729 // expensive and we'd rather not try to diagnose it.
11730 return;
11731 }
11732 }
11733 if (!SecondCand)
11734 return;
11735 // The diagnostic can only happen if there are associated constraints on
11736 // both sides (there needs to be some identical atomic constraint).
11737 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11738 SecondCand, SecondAC))
11739 // Just show the user one diagnostic, they'll probably figure it out
11740 // from here.
11741 return;
11742}
11743
11744// Notes the location of all overload candidates designated through
11745// OverloadedExpr
11746void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11747 bool TakingAddress) {
11748 assert(OverloadedExpr->getType() == Context.OverloadTy);
11749
11750 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11751 OverloadExpr *OvlExpr = Ovl.Expression;
11752
11753 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11754 IEnd = OvlExpr->decls_end();
11755 I != IEnd; ++I) {
11756 if (FunctionTemplateDecl *FunTmpl =
11757 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11758 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11759 TakingAddress);
11760 } else if (FunctionDecl *Fun
11761 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11762 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11763 }
11764 }
11765}
11766
11767/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11768/// "lead" diagnostic; it will be given two arguments, the source and
11769/// target types of the conversion.
11770void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11771 Sema &S,
11772 SourceLocation CaretLoc,
11773 const PartialDiagnostic &PDiag) const {
11774 S.Diag(CaretLoc, PDiag)
11775 << Ambiguous.getFromType() << Ambiguous.getToType();
11776 unsigned CandsShown = 0;
11777 AmbiguousConversionSequence::const_iterator I, E;
11778 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11779 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11780 break;
11781 ++CandsShown;
11782 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11783 }
11784 S.Diags.overloadCandidatesShown(N: CandsShown);
11785 if (I != E)
11786 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11787}
11788
11789static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11790 unsigned I, bool TakingCandidateAddress) {
11791 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11792 assert(Conv.isBad());
11793 assert(Cand->Function && "for now, candidate must be a function");
11794 FunctionDecl *Fn = Cand->Function;
11795
11796 // There's a conversion slot for the object argument if this is a
11797 // non-constructor method. Note that 'I' corresponds the
11798 // conversion-slot index.
11799 bool isObjectArgument = false;
11800 if (isa<CXXMethodDecl>(Val: Fn) && !isa<CXXConstructorDecl>(Val: Fn)) {
11801 if (I == 0)
11802 isObjectArgument = true;
11803 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11804 I--;
11805 }
11806
11807 std::string FnDesc;
11808 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11809 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
11810 Description&: FnDesc);
11811
11812 Expr *FromExpr = Conv.Bad.FromExpr;
11813 QualType FromTy = Conv.Bad.getFromType();
11814 QualType ToTy = Conv.Bad.getToType();
11815 SourceRange ToParamRange;
11816
11817 // FIXME: In presence of parameter packs we can't determine parameter range
11818 // reliably, as we don't have access to instantiation.
11819 bool HasParamPack =
11820 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
11821 return Parm->isParameterPack();
11822 });
11823 if (!isObjectArgument && !HasParamPack)
11824 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
11825
11826 if (FromTy == S.Context.OverloadTy) {
11827 assert(FromExpr && "overload set argument came from implicit argument?");
11828 Expr *E = FromExpr->IgnoreParens();
11829 if (isa<UnaryOperator>(Val: E))
11830 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
11831 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
11832
11833 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11834 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11835 << ToParamRange << ToTy << Name << I + 1;
11836 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11837 return;
11838 }
11839
11840 // Do some hand-waving analysis to see if the non-viability is due
11841 // to a qualifier mismatch.
11842 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
11843 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
11844 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11845 CToTy = RT->getPointeeType();
11846 else {
11847 // TODO: detect and diagnose the full richness of const mismatches.
11848 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11849 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11850 CFromTy = FromPT->getPointeeType();
11851 CToTy = ToPT->getPointeeType();
11852 }
11853 }
11854
11855 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11856 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
11857 Qualifiers FromQs = CFromTy.getQualifiers();
11858 Qualifiers ToQs = CToTy.getQualifiers();
11859
11860 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11861 if (isObjectArgument)
11862 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11863 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11864 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11865 else
11866 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11867 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11868 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11869 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11870 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11871 return;
11872 }
11873
11874 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11876 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11877 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11878 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11879 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11880 return;
11881 }
11882
11883 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11884 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11885 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11886 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11887 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11888 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11889 return;
11890 }
11891
11892 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
11893 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11894 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11895 << FromTy << !!FromQs.getPointerAuth()
11896 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11897 << ToQs.getPointerAuth().getAsString() << I + 1
11898 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11899 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11900 return;
11901 }
11902
11903 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11904 assert(CVR && "expected qualifiers mismatch");
11905
11906 if (isObjectArgument) {
11907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11908 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11909 << FromTy << (CVR - 1);
11910 } else {
11911 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11912 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11913 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11914 }
11915 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11916 return;
11917 }
11918
11919 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11920 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11922 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11923 << (unsigned)isObjectArgument << I + 1
11924 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11925 << ToParamRange;
11926 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11927 return;
11928 }
11929
11930 // Special diagnostic for failure to convert an initializer list, since
11931 // telling the user that it has type void is not useful.
11932 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
11933 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11934 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11935 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11936 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11937 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11938 ? 2
11939 : 0);
11940 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11941 return;
11942 }
11943
11944 // Diagnose references or pointers to incomplete types differently,
11945 // since it's far from impossible that the incompleteness triggered
11946 // the failure.
11947 QualType TempFromTy = FromTy.getNonReferenceType();
11948 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11949 TempFromTy = PTy->getPointeeType();
11950 if (TempFromTy->isIncompleteType()) {
11951 // Emit the generic diagnostic and, optionally, add the hints to it.
11952 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11953 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11954 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11955 << (unsigned)(Cand->Fix.Kind);
11956
11957 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11958 return;
11959 }
11960
11961 // Diagnose base -> derived pointer conversions.
11962 unsigned BaseToDerivedConversion = 0;
11963 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11964 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11965 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11966 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
11967 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11968 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11969 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
11970 Base: FromPtrTy->getPointeeType()))
11971 BaseToDerivedConversion = 1;
11972 }
11973 } else if (const ObjCObjectPointerType *FromPtrTy
11974 = FromTy->getAs<ObjCObjectPointerType>()) {
11975 if (const ObjCObjectPointerType *ToPtrTy
11976 = ToTy->getAs<ObjCObjectPointerType>())
11977 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11978 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11979 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11980 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
11981 FromIface->isSuperClassOf(I: ToIface))
11982 BaseToDerivedConversion = 2;
11983 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11984 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
11985 Ctx: S.getASTContext()) &&
11986 !FromTy->isIncompleteType() &&
11987 !ToRefTy->getPointeeType()->isIncompleteType() &&
11988 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
11989 BaseToDerivedConversion = 3;
11990 }
11991 }
11992
11993 if (BaseToDerivedConversion) {
11994 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11995 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11996 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11997 << I + 1;
11998 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11999 return;
12000 }
12001
12002 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12003 isa<PointerType>(Val: CToTy)) {
12004 Qualifiers FromQs = CFromTy.getQualifiers();
12005 Qualifiers ToQs = CToTy.getQualifiers();
12006 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12008 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12009 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12010 << I + 1;
12011 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12012 return;
12013 }
12014 }
12015
12016 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12017 return;
12018
12019 // Emit the generic diagnostic and, optionally, add the hints to it.
12020 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12021 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12022 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12023 << (unsigned)(Cand->Fix.Kind);
12024
12025 // Check that location of Fn is not in system header.
12026 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12027 // If we can fix the conversion, suggest the FixIts.
12028 for (const FixItHint &HI : Cand->Fix.Hints)
12029 FDiag << HI;
12030 }
12031
12032 S.Diag(Fn->getLocation(), FDiag);
12033
12034 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12035}
12036
12037/// Additional arity mismatch diagnosis specific to a function overload
12038/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12039/// over a candidate in any candidate set.
12040static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12041 unsigned NumArgs, bool IsAddressOf = false) {
12042 assert(Cand->Function && "Candidate is required to be a function.");
12043 FunctionDecl *Fn = Cand->Function;
12044 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12045 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12046
12047 // With invalid overloaded operators, it's possible that we think we
12048 // have an arity mismatch when in fact it looks like we have the
12049 // right number of arguments, because only overloaded operators have
12050 // the weird behavior of overloading member and non-member functions.
12051 // Just don't report anything.
12052 if (Fn->isInvalidDecl() &&
12053 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12054 return true;
12055
12056 if (NumArgs < MinParams) {
12057 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12058 (Cand->FailureKind == ovl_fail_bad_deduction &&
12059 Cand->DeductionFailure.getResult() ==
12060 TemplateDeductionResult::TooFewArguments));
12061 } else {
12062 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12063 (Cand->FailureKind == ovl_fail_bad_deduction &&
12064 Cand->DeductionFailure.getResult() ==
12065 TemplateDeductionResult::TooManyArguments));
12066 }
12067
12068 return false;
12069}
12070
12071/// General arity mismatch diagnosis over a candidate in a candidate set.
12072static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12073 unsigned NumFormalArgs,
12074 bool IsAddressOf = false) {
12075 assert(isa<FunctionDecl>(D) &&
12076 "The templated declaration should at least be a function"
12077 " when diagnosing bad template argument deduction due to too many"
12078 " or too few arguments");
12079
12080 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12081
12082 // TODO: treat calls to a missing default constructor as a special case
12083 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12084 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12085 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12086
12087 // at least / at most / exactly
12088 bool HasExplicitObjectParam =
12089 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12090
12091 unsigned ParamCount =
12092 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12093 unsigned mode, modeCount;
12094
12095 if (NumFormalArgs < MinParams) {
12096 if (MinParams != ParamCount || FnTy->isVariadic() ||
12097 FnTy->isTemplateVariadic())
12098 mode = 0; // "at least"
12099 else
12100 mode = 2; // "exactly"
12101 modeCount = MinParams;
12102 } else {
12103 if (MinParams != ParamCount)
12104 mode = 1; // "at most"
12105 else
12106 mode = 2; // "exactly"
12107 modeCount = ParamCount;
12108 }
12109
12110 std::string Description;
12111 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12112 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12113
12114 if (modeCount == 1 && !IsAddressOf &&
12115 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12117 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12118 << Description << mode
12119 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12120 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12121 else
12122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12123 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12124 << Description << mode << modeCount << NumFormalArgs
12125 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12126
12127 MaybeEmitInheritedConstructorNote(S, Found);
12128}
12129
12130/// Arity mismatch diagnosis specific to a function overload candidate.
12131static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12132 unsigned NumFormalArgs) {
12133 assert(Cand->Function && "Candidate must be a function");
12134 FunctionDecl *Fn = Cand->Function;
12135 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12136 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12137 Cand->TookAddressOfOverload);
12138}
12139
12140static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12141 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12142 return TD;
12143 llvm_unreachable("Unsupported: Getting the described template declaration"
12144 " for bad deduction diagnosis");
12145}
12146
12147/// Diagnose a failed template-argument deduction.
12148static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12149 DeductionFailureInfo &DeductionFailure,
12150 unsigned NumArgs,
12151 bool TakingCandidateAddress) {
12152 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12153 NamedDecl *ParamD;
12154 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12155 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12156 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12157 switch (DeductionFailure.getResult()) {
12158 case TemplateDeductionResult::Success:
12159 llvm_unreachable(
12160 "TemplateDeductionResult::Success while diagnosing bad deduction");
12161 case TemplateDeductionResult::NonDependentConversionFailure:
12162 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12163 "while diagnosing bad deduction");
12164 case TemplateDeductionResult::Invalid:
12165 case TemplateDeductionResult::AlreadyDiagnosed:
12166 return;
12167
12168 case TemplateDeductionResult::Incomplete: {
12169 assert(ParamD && "no parameter found for incomplete deduction result");
12170 S.Diag(Templated->getLocation(),
12171 diag::note_ovl_candidate_incomplete_deduction)
12172 << ParamD->getDeclName();
12173 MaybeEmitInheritedConstructorNote(S, Found);
12174 return;
12175 }
12176
12177 case TemplateDeductionResult::IncompletePack: {
12178 assert(ParamD && "no parameter found for incomplete deduction result");
12179 S.Diag(Templated->getLocation(),
12180 diag::note_ovl_candidate_incomplete_deduction_pack)
12181 << ParamD->getDeclName()
12182 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12183 << *DeductionFailure.getFirstArg();
12184 MaybeEmitInheritedConstructorNote(S, Found);
12185 return;
12186 }
12187
12188 case TemplateDeductionResult::Underqualified: {
12189 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12190 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12191
12192 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12193
12194 // Param will have been canonicalized, but it should just be a
12195 // qualified version of ParamD, so move the qualifiers to that.
12196 QualifierCollector Qs;
12197 Qs.strip(type: Param);
12198 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12199 assert(S.Context.hasSameType(Param, NonCanonParam));
12200
12201 // Arg has also been canonicalized, but there's nothing we can do
12202 // about that. It also doesn't matter as much, because it won't
12203 // have any template parameters in it (because deduction isn't
12204 // done on dependent types).
12205 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12206
12207 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12208 << ParamD->getDeclName() << Arg << NonCanonParam;
12209 MaybeEmitInheritedConstructorNote(S, Found);
12210 return;
12211 }
12212
12213 case TemplateDeductionResult::Inconsistent: {
12214 assert(ParamD && "no parameter found for inconsistent deduction result");
12215 int which = 0;
12216 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12217 which = 0;
12218 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12219 // Deduction might have failed because we deduced arguments of two
12220 // different types for a non-type template parameter.
12221 // FIXME: Use a different TDK value for this.
12222 QualType T1 =
12223 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12224 QualType T2 =
12225 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12226 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12227 S.Diag(Templated->getLocation(),
12228 diag::note_ovl_candidate_inconsistent_deduction_types)
12229 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12230 << *DeductionFailure.getSecondArg() << T2;
12231 MaybeEmitInheritedConstructorNote(S, Found);
12232 return;
12233 }
12234
12235 which = 1;
12236 } else {
12237 which = 2;
12238 }
12239
12240 // Tweak the diagnostic if the problem is that we deduced packs of
12241 // different arities. We'll print the actual packs anyway in case that
12242 // includes additional useful information.
12243 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12244 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12245 DeductionFailure.getFirstArg()->pack_size() !=
12246 DeductionFailure.getSecondArg()->pack_size()) {
12247 which = 3;
12248 }
12249
12250 S.Diag(Templated->getLocation(),
12251 diag::note_ovl_candidate_inconsistent_deduction)
12252 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12253 << *DeductionFailure.getSecondArg();
12254 MaybeEmitInheritedConstructorNote(S, Found);
12255 return;
12256 }
12257
12258 case TemplateDeductionResult::InvalidExplicitArguments:
12259 assert(ParamD && "no parameter found for invalid explicit arguments");
12260 if (ParamD->getDeclName())
12261 S.Diag(Templated->getLocation(),
12262 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12263 << ParamD->getDeclName();
12264 else {
12265 int index = 0;
12266 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
12267 index = TTP->getIndex();
12268 else if (NonTypeTemplateParmDecl *NTTP
12269 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
12270 index = NTTP->getIndex();
12271 else
12272 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
12273 S.Diag(Templated->getLocation(),
12274 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12275 << (index + 1);
12276 }
12277 MaybeEmitInheritedConstructorNote(S, Found);
12278 return;
12279
12280 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12281 // Format the template argument list into the argument string.
12282 SmallString<128> TemplateArgString;
12283 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12284 TemplateArgString = " ";
12285 TemplateArgString += S.getTemplateArgumentBindingsText(
12286 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12287 if (TemplateArgString.size() == 1)
12288 TemplateArgString.clear();
12289 S.Diag(Templated->getLocation(),
12290 diag::note_ovl_candidate_unsatisfied_constraints)
12291 << TemplateArgString;
12292
12293 S.DiagnoseUnsatisfiedConstraint(
12294 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12295 return;
12296 }
12297 case TemplateDeductionResult::TooManyArguments:
12298 case TemplateDeductionResult::TooFewArguments:
12299 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs);
12300 return;
12301
12302 case TemplateDeductionResult::InstantiationDepth:
12303 S.Diag(Templated->getLocation(),
12304 diag::note_ovl_candidate_instantiation_depth);
12305 MaybeEmitInheritedConstructorNote(S, Found);
12306 return;
12307
12308 case TemplateDeductionResult::SubstitutionFailure: {
12309 // Format the template argument list into the argument string.
12310 SmallString<128> TemplateArgString;
12311 if (TemplateArgumentList *Args =
12312 DeductionFailure.getTemplateArgumentList()) {
12313 TemplateArgString = " ";
12314 TemplateArgString += S.getTemplateArgumentBindingsText(
12315 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12316 if (TemplateArgString.size() == 1)
12317 TemplateArgString.clear();
12318 }
12319
12320 // If this candidate was disabled by enable_if, say so.
12321 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12322 if (PDiag && PDiag->second.getDiagID() ==
12323 diag::err_typename_nested_not_found_enable_if) {
12324 // FIXME: Use the source range of the condition, and the fully-qualified
12325 // name of the enable_if template. These are both present in PDiag.
12326 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12327 << "'enable_if'" << TemplateArgString;
12328 return;
12329 }
12330
12331 // We found a specific requirement that disabled the enable_if.
12332 if (PDiag && PDiag->second.getDiagID() ==
12333 diag::err_typename_nested_not_found_requirement) {
12334 S.Diag(Templated->getLocation(),
12335 diag::note_ovl_candidate_disabled_by_requirement)
12336 << PDiag->second.getStringArg(0) << TemplateArgString;
12337 return;
12338 }
12339
12340 // Format the SFINAE diagnostic into the argument string.
12341 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12342 // formatted message in another diagnostic.
12343 SmallString<128> SFINAEArgString;
12344 SourceRange R;
12345 if (PDiag) {
12346 SFINAEArgString = ": ";
12347 R = SourceRange(PDiag->first, PDiag->first);
12348 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12349 }
12350
12351 S.Diag(Templated->getLocation(),
12352 diag::note_ovl_candidate_substitution_failure)
12353 << TemplateArgString << SFINAEArgString << R;
12354 MaybeEmitInheritedConstructorNote(S, Found);
12355 return;
12356 }
12357
12358 case TemplateDeductionResult::DeducedMismatch:
12359 case TemplateDeductionResult::DeducedMismatchNested: {
12360 // Format the template argument list into the argument string.
12361 SmallString<128> TemplateArgString;
12362 if (TemplateArgumentList *Args =
12363 DeductionFailure.getTemplateArgumentList()) {
12364 TemplateArgString = " ";
12365 TemplateArgString += S.getTemplateArgumentBindingsText(
12366 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12367 if (TemplateArgString.size() == 1)
12368 TemplateArgString.clear();
12369 }
12370
12371 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12372 << (*DeductionFailure.getCallArgIndex() + 1)
12373 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12374 << TemplateArgString
12375 << (DeductionFailure.getResult() ==
12376 TemplateDeductionResult::DeducedMismatchNested);
12377 break;
12378 }
12379
12380 case TemplateDeductionResult::NonDeducedMismatch: {
12381 // FIXME: Provide a source location to indicate what we couldn't match.
12382 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12383 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12384 if (FirstTA.getKind() == TemplateArgument::Template &&
12385 SecondTA.getKind() == TemplateArgument::Template) {
12386 TemplateName FirstTN = FirstTA.getAsTemplate();
12387 TemplateName SecondTN = SecondTA.getAsTemplate();
12388 if (FirstTN.getKind() == TemplateName::Template &&
12389 SecondTN.getKind() == TemplateName::Template) {
12390 if (FirstTN.getAsTemplateDecl()->getName() ==
12391 SecondTN.getAsTemplateDecl()->getName()) {
12392 // FIXME: This fixes a bad diagnostic where both templates are named
12393 // the same. This particular case is a bit difficult since:
12394 // 1) It is passed as a string to the diagnostic printer.
12395 // 2) The diagnostic printer only attempts to find a better
12396 // name for types, not decls.
12397 // Ideally, this should folded into the diagnostic printer.
12398 S.Diag(Templated->getLocation(),
12399 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12400 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12401 return;
12402 }
12403 }
12404 }
12405
12406 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12407 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12408 return;
12409
12410 // FIXME: For generic lambda parameters, check if the function is a lambda
12411 // call operator, and if so, emit a prettier and more informative
12412 // diagnostic that mentions 'auto' and lambda in addition to
12413 // (or instead of?) the canonical template type parameters.
12414 S.Diag(Templated->getLocation(),
12415 diag::note_ovl_candidate_non_deduced_mismatch)
12416 << FirstTA << SecondTA;
12417 return;
12418 }
12419 // TODO: diagnose these individually, then kill off
12420 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12421 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12422 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12423 MaybeEmitInheritedConstructorNote(S, Found);
12424 return;
12425 case TemplateDeductionResult::CUDATargetMismatch:
12426 S.Diag(Templated->getLocation(),
12427 diag::note_cuda_ovl_candidate_target_mismatch);
12428 return;
12429 }
12430}
12431
12432/// Diagnose a failed template-argument deduction, for function calls.
12433static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12434 unsigned NumArgs,
12435 bool TakingCandidateAddress) {
12436 assert(Cand->Function && "Candidate must be a function");
12437 FunctionDecl *Fn = Cand->Function;
12438 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12439 if (TDK == TemplateDeductionResult::TooFewArguments ||
12440 TDK == TemplateDeductionResult::TooManyArguments) {
12441 if (CheckArityMismatch(S, Cand, NumArgs))
12442 return;
12443 }
12444 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12445 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12446}
12447
12448/// CUDA: diagnose an invalid call across targets.
12449static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12450 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12451 assert(Cand->Function && "Candidate must be a Function.");
12452 FunctionDecl *Callee = Cand->Function;
12453
12454 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12455 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12456
12457 std::string FnDesc;
12458 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12459 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12460 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12461
12462 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12463 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12464 << FnDesc /* Ignored */
12465 << CalleeTarget << CallerTarget;
12466
12467 // This could be an implicit constructor for which we could not infer the
12468 // target due to a collsion. Diagnose that case.
12469 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12470 if (Meth != nullptr && Meth->isImplicit()) {
12471 CXXRecordDecl *ParentClass = Meth->getParent();
12472 CXXSpecialMemberKind CSM;
12473
12474 switch (FnKindPair.first) {
12475 default:
12476 return;
12477 case oc_implicit_default_constructor:
12478 CSM = CXXSpecialMemberKind::DefaultConstructor;
12479 break;
12480 case oc_implicit_copy_constructor:
12481 CSM = CXXSpecialMemberKind::CopyConstructor;
12482 break;
12483 case oc_implicit_move_constructor:
12484 CSM = CXXSpecialMemberKind::MoveConstructor;
12485 break;
12486 case oc_implicit_copy_assignment:
12487 CSM = CXXSpecialMemberKind::CopyAssignment;
12488 break;
12489 case oc_implicit_move_assignment:
12490 CSM = CXXSpecialMemberKind::MoveAssignment;
12491 break;
12492 };
12493
12494 bool ConstRHS = false;
12495 if (Meth->getNumParams()) {
12496 if (const ReferenceType *RT =
12497 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12498 ConstRHS = RT->getPointeeType().isConstQualified();
12499 }
12500 }
12501
12502 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12503 /* ConstRHS */ ConstRHS,
12504 /* Diagnose */ true);
12505 }
12506}
12507
12508static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12509 assert(Cand->Function && "Candidate must be a function");
12510 FunctionDecl *Callee = Cand->Function;
12511 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12512
12513 S.Diag(Callee->getLocation(),
12514 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12515 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12516}
12517
12518static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12519 assert(Cand->Function && "Candidate must be a function");
12520 FunctionDecl *Fn = Cand->Function;
12521 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12522 assert(ES.isExplicit() && "not an explicit candidate");
12523
12524 unsigned Kind;
12525 switch (Fn->getDeclKind()) {
12526 case Decl::Kind::CXXConstructor:
12527 Kind = 0;
12528 break;
12529 case Decl::Kind::CXXConversion:
12530 Kind = 1;
12531 break;
12532 case Decl::Kind::CXXDeductionGuide:
12533 Kind = Fn->isImplicit() ? 0 : 2;
12534 break;
12535 default:
12536 llvm_unreachable("invalid Decl");
12537 }
12538
12539 // Note the location of the first (in-class) declaration; a redeclaration
12540 // (particularly an out-of-class definition) will typically lack the
12541 // 'explicit' specifier.
12542 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12543 FunctionDecl *First = Fn->getFirstDecl();
12544 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12545 First = Pattern->getFirstDecl();
12546
12547 S.Diag(First->getLocation(),
12548 diag::note_ovl_candidate_explicit)
12549 << Kind << (ES.getExpr() ? 1 : 0)
12550 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12551}
12552
12553static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12554 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12555 if (!DG)
12556 return;
12557 TemplateDecl *OriginTemplate =
12558 DG->getDeclName().getCXXDeductionGuideTemplate();
12559 // We want to always print synthesized deduction guides for type aliases.
12560 // They would retain the explicit bit of the corresponding constructor.
12561 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12562 return;
12563 std::string FunctionProto;
12564 llvm::raw_string_ostream OS(FunctionProto);
12565 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12566 if (!Template) {
12567 // This also could be an instantiation. Find out the primary template.
12568 FunctionDecl *Pattern =
12569 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12570 if (!Pattern) {
12571 // The implicit deduction guide is built on an explicit non-template
12572 // deduction guide. Currently, this might be the case only for type
12573 // aliases.
12574 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12575 // gets merged.
12576 assert(OriginTemplate->isTypeAlias() &&
12577 "Non-template implicit deduction guides are only possible for "
12578 "type aliases");
12579 DG->print(OS);
12580 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12581 << FunctionProto;
12582 return;
12583 }
12584 Template = Pattern->getDescribedFunctionTemplate();
12585 assert(Template && "Cannot find the associated function template of "
12586 "CXXDeductionGuideDecl?");
12587 }
12588 Template->print(OS);
12589 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12590 << FunctionProto;
12591}
12592
12593/// Generates a 'note' diagnostic for an overload candidate. We've
12594/// already generated a primary error at the call site.
12595///
12596/// It really does need to be a single diagnostic with its caret
12597/// pointed at the candidate declaration. Yes, this creates some
12598/// major challenges of technical writing. Yes, this makes pointing
12599/// out problems with specific arguments quite awkward. It's still
12600/// better than generating twenty screens of text for every failed
12601/// overload.
12602///
12603/// It would be great to be able to express per-candidate problems
12604/// more richly for those diagnostic clients that cared, but we'd
12605/// still have to be just as careful with the default diagnostics.
12606/// \param CtorDestAS Addr space of object being constructed (for ctor
12607/// candidates only).
12608static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12609 unsigned NumArgs,
12610 bool TakingCandidateAddress,
12611 LangAS CtorDestAS = LangAS::Default) {
12612 assert(Cand->Function && "Candidate must be a function");
12613 FunctionDecl *Fn = Cand->Function;
12614 if (shouldSkipNotingLambdaConversionDecl(Fn))
12615 return;
12616
12617 // There is no physical candidate declaration to point to for OpenCL builtins.
12618 // Except for failed conversions, the notes are identical for each candidate,
12619 // so do not generate such notes.
12620 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12621 Cand->FailureKind != ovl_fail_bad_conversion)
12622 return;
12623
12624 // Skip implicit member functions when trying to resolve
12625 // the address of a an overload set for a function pointer.
12626 if (Cand->TookAddressOfOverload &&
12627 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12628 return;
12629
12630 // Note deleted candidates, but only if they're viable.
12631 if (Cand->Viable) {
12632 if (Fn->isDeleted()) {
12633 std::string FnDesc;
12634 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12635 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12636 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12637
12638 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12639 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12640 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12641 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12642 return;
12643 }
12644
12645 // We don't really have anything else to say about viable candidates.
12646 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12647 return;
12648 }
12649
12650 // If this is a synthesized deduction guide we're deducing against, add a note
12651 // for it. These deduction guides are not explicitly spelled in the source
12652 // code, so simply printing a deduction failure note mentioning synthesized
12653 // template parameters or pointing to the header of the surrounding RecordDecl
12654 // would be confusing.
12655 //
12656 // We prefer adding such notes at the end of the deduction failure because
12657 // duplicate code snippets appearing in the diagnostic would likely become
12658 // noisy.
12659 auto _ = llvm::make_scope_exit(F: [&] { NoteImplicitDeductionGuide(S, Fn); });
12660
12661 switch (Cand->FailureKind) {
12662 case ovl_fail_too_many_arguments:
12663 case ovl_fail_too_few_arguments:
12664 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12665
12666 case ovl_fail_bad_deduction:
12667 return DiagnoseBadDeduction(S, Cand, NumArgs,
12668 TakingCandidateAddress);
12669
12670 case ovl_fail_illegal_constructor: {
12671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12672 << (Fn->getPrimaryTemplate() ? 1 : 0);
12673 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12674 return;
12675 }
12676
12677 case ovl_fail_object_addrspace_mismatch: {
12678 Qualifiers QualsForPrinting;
12679 QualsForPrinting.setAddressSpace(CtorDestAS);
12680 S.Diag(Fn->getLocation(),
12681 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12682 << QualsForPrinting;
12683 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12684 return;
12685 }
12686
12687 case ovl_fail_trivial_conversion:
12688 case ovl_fail_bad_final_conversion:
12689 case ovl_fail_final_conversion_not_exact:
12690 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12691
12692 case ovl_fail_bad_conversion: {
12693 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12694 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12695 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12696 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12697
12698 // FIXME: this currently happens when we're called from SemaInit
12699 // when user-conversion overload fails. Figure out how to handle
12700 // those conditions and diagnose them well.
12701 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12702 }
12703
12704 case ovl_fail_bad_target:
12705 return DiagnoseBadTarget(S, Cand);
12706
12707 case ovl_fail_enable_if:
12708 return DiagnoseFailedEnableIfAttr(S, Cand);
12709
12710 case ovl_fail_explicit:
12711 return DiagnoseFailedExplicitSpec(S, Cand);
12712
12713 case ovl_fail_inhctor_slice:
12714 // It's generally not interesting to note copy/move constructors here.
12715 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12716 return;
12717 S.Diag(Fn->getLocation(),
12718 diag::note_ovl_candidate_inherited_constructor_slice)
12719 << (Fn->getPrimaryTemplate() ? 1 : 0)
12720 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12721 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12722 return;
12723
12724 case ovl_fail_addr_not_available: {
12725 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12726 (void)Available;
12727 assert(!Available);
12728 break;
12729 }
12730 case ovl_non_default_multiversion_function:
12731 // Do nothing, these should simply be ignored.
12732 break;
12733
12734 case ovl_fail_constraints_not_satisfied: {
12735 std::string FnDesc;
12736 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12737 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12738 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12739
12740 S.Diag(Fn->getLocation(),
12741 diag::note_ovl_candidate_constraints_not_satisfied)
12742 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12743 << FnDesc /* Ignored */;
12744 ConstraintSatisfaction Satisfaction;
12745 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction))
12746 break;
12747 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12748 }
12749 }
12750}
12751
12752static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12753 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
12754 return;
12755
12756 // Desugar the type of the surrogate down to a function type,
12757 // retaining as many typedefs as possible while still showing
12758 // the function type (and, therefore, its parameter types).
12759 QualType FnType = Cand->Surrogate->getConversionType();
12760 bool isLValueReference = false;
12761 bool isRValueReference = false;
12762 bool isPointer = false;
12763 if (const LValueReferenceType *FnTypeRef =
12764 FnType->getAs<LValueReferenceType>()) {
12765 FnType = FnTypeRef->getPointeeType();
12766 isLValueReference = true;
12767 } else if (const RValueReferenceType *FnTypeRef =
12768 FnType->getAs<RValueReferenceType>()) {
12769 FnType = FnTypeRef->getPointeeType();
12770 isRValueReference = true;
12771 }
12772 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12773 FnType = FnTypePtr->getPointeeType();
12774 isPointer = true;
12775 }
12776 // Desugar down to a function type.
12777 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12778 // Reconstruct the pointer/reference as appropriate.
12779 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12780 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12781 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12782
12783 if (!Cand->Viable &&
12784 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12785 S.Diag(Cand->Surrogate->getLocation(),
12786 diag::note_ovl_surrogate_constraints_not_satisfied)
12787 << Cand->Surrogate;
12788 ConstraintSatisfaction Satisfaction;
12789 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12790 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12791 } else {
12792 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12793 << FnType;
12794 }
12795}
12796
12797static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12798 SourceLocation OpLoc,
12799 OverloadCandidate *Cand) {
12800 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12801 std::string TypeStr("operator");
12802 TypeStr += Opc;
12803 TypeStr += "(";
12804 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12805 if (Cand->Conversions.size() == 1) {
12806 TypeStr += ")";
12807 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12808 } else {
12809 TypeStr += ", ";
12810 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12811 TypeStr += ")";
12812 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12813 }
12814}
12815
12816static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12817 OverloadCandidate *Cand) {
12818 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12819 if (ICS.isBad()) break; // all meaningless after first invalid
12820 if (!ICS.isAmbiguous()) continue;
12821
12822 ICS.DiagnoseAmbiguousConversion(
12823 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12824 }
12825}
12826
12827static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12828 if (Cand->Function)
12829 return Cand->Function->getLocation();
12830 if (Cand->IsSurrogate)
12831 return Cand->Surrogate->getLocation();
12832 return SourceLocation();
12833}
12834
12835static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12836 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12837 case TemplateDeductionResult::Success:
12838 case TemplateDeductionResult::NonDependentConversionFailure:
12839 case TemplateDeductionResult::AlreadyDiagnosed:
12840 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12841
12842 case TemplateDeductionResult::Invalid:
12843 case TemplateDeductionResult::Incomplete:
12844 case TemplateDeductionResult::IncompletePack:
12845 return 1;
12846
12847 case TemplateDeductionResult::Underqualified:
12848 case TemplateDeductionResult::Inconsistent:
12849 return 2;
12850
12851 case TemplateDeductionResult::SubstitutionFailure:
12852 case TemplateDeductionResult::DeducedMismatch:
12853 case TemplateDeductionResult::ConstraintsNotSatisfied:
12854 case TemplateDeductionResult::DeducedMismatchNested:
12855 case TemplateDeductionResult::NonDeducedMismatch:
12856 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12857 case TemplateDeductionResult::CUDATargetMismatch:
12858 return 3;
12859
12860 case TemplateDeductionResult::InstantiationDepth:
12861 return 4;
12862
12863 case TemplateDeductionResult::InvalidExplicitArguments:
12864 return 5;
12865
12866 case TemplateDeductionResult::TooManyArguments:
12867 case TemplateDeductionResult::TooFewArguments:
12868 return 6;
12869 }
12870 llvm_unreachable("Unhandled deduction result");
12871}
12872
12873namespace {
12874
12875struct CompareOverloadCandidatesForDisplay {
12876 Sema &S;
12877 SourceLocation Loc;
12878 size_t NumArgs;
12879 OverloadCandidateSet::CandidateSetKind CSK;
12880
12881 CompareOverloadCandidatesForDisplay(
12882 Sema &S, SourceLocation Loc, size_t NArgs,
12883 OverloadCandidateSet::CandidateSetKind CSK)
12884 : S(S), NumArgs(NArgs), CSK(CSK) {}
12885
12886 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12887 // If there are too many or too few arguments, that's the high-order bit we
12888 // want to sort by, even if the immediate failure kind was something else.
12889 if (C->FailureKind == ovl_fail_too_many_arguments ||
12890 C->FailureKind == ovl_fail_too_few_arguments)
12891 return static_cast<OverloadFailureKind>(C->FailureKind);
12892
12893 if (C->Function) {
12894 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12895 return ovl_fail_too_many_arguments;
12896 if (NumArgs < C->Function->getMinRequiredArguments())
12897 return ovl_fail_too_few_arguments;
12898 }
12899
12900 return static_cast<OverloadFailureKind>(C->FailureKind);
12901 }
12902
12903 bool operator()(const OverloadCandidate *L,
12904 const OverloadCandidate *R) {
12905 // Fast-path this check.
12906 if (L == R) return false;
12907
12908 // Order first by viability.
12909 if (L->Viable) {
12910 if (!R->Viable) return true;
12911
12912 if (int Ord = CompareConversions(L: *L, R: *R))
12913 return Ord < 0;
12914 // Use other tie breakers.
12915 } else if (R->Viable)
12916 return false;
12917
12918 assert(L->Viable == R->Viable);
12919
12920 // Criteria by which we can sort non-viable candidates:
12921 if (!L->Viable) {
12922 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
12923 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
12924
12925 // 1. Arity mismatches come after other candidates.
12926 if (LFailureKind == ovl_fail_too_many_arguments ||
12927 LFailureKind == ovl_fail_too_few_arguments) {
12928 if (RFailureKind == ovl_fail_too_many_arguments ||
12929 RFailureKind == ovl_fail_too_few_arguments) {
12930 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
12931 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
12932 if (LDist == RDist) {
12933 if (LFailureKind == RFailureKind)
12934 // Sort non-surrogates before surrogates.
12935 return !L->IsSurrogate && R->IsSurrogate;
12936 // Sort candidates requiring fewer parameters than there were
12937 // arguments given after candidates requiring more parameters
12938 // than there were arguments given.
12939 return LFailureKind == ovl_fail_too_many_arguments;
12940 }
12941 return LDist < RDist;
12942 }
12943 return false;
12944 }
12945 if (RFailureKind == ovl_fail_too_many_arguments ||
12946 RFailureKind == ovl_fail_too_few_arguments)
12947 return true;
12948
12949 // 2. Bad conversions come first and are ordered by the number
12950 // of bad conversions and quality of good conversions.
12951 if (LFailureKind == ovl_fail_bad_conversion) {
12952 if (RFailureKind != ovl_fail_bad_conversion)
12953 return true;
12954
12955 // The conversion that can be fixed with a smaller number of changes,
12956 // comes first.
12957 unsigned numLFixes = L->Fix.NumConversionsFixed;
12958 unsigned numRFixes = R->Fix.NumConversionsFixed;
12959 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12960 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12961 if (numLFixes != numRFixes) {
12962 return numLFixes < numRFixes;
12963 }
12964
12965 // If there's any ordering between the defined conversions...
12966 if (int Ord = CompareConversions(L: *L, R: *R))
12967 return Ord < 0;
12968 } else if (RFailureKind == ovl_fail_bad_conversion)
12969 return false;
12970
12971 if (LFailureKind == ovl_fail_bad_deduction) {
12972 if (RFailureKind != ovl_fail_bad_deduction)
12973 return true;
12974
12975 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12976 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
12977 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
12978 if (LRank != RRank)
12979 return LRank < RRank;
12980 }
12981 } else if (RFailureKind == ovl_fail_bad_deduction)
12982 return false;
12983
12984 // TODO: others?
12985 }
12986
12987 // Sort everything else by location.
12988 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
12989 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
12990
12991 // Put candidates without locations (e.g. builtins) at the end.
12992 if (LLoc.isValid() && RLoc.isValid())
12993 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
12994 if (LLoc.isValid() && !RLoc.isValid())
12995 return true;
12996 if (RLoc.isValid() && !LLoc.isValid())
12997 return false;
12998 assert(!LLoc.isValid() && !RLoc.isValid());
12999 // For builtins and other functions without locations, fallback to the order
13000 // in which they were added into the candidate set.
13001 return L < R;
13002 }
13003
13004private:
13005 struct ConversionSignals {
13006 unsigned KindRank = 0;
13007 ImplicitConversionRank Rank = ICR_Exact_Match;
13008
13009 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13010 ConversionSignals Sig;
13011 Sig.KindRank = Seq.getKindRank();
13012 if (Seq.isStandard())
13013 Sig.Rank = Seq.Standard.getRank();
13014 else if (Seq.isUserDefined())
13015 Sig.Rank = Seq.UserDefined.After.getRank();
13016 // We intend StaticObjectArgumentConversion to compare the same as
13017 // StandardConversion with ICR_ExactMatch rank.
13018 return Sig;
13019 }
13020
13021 static ConversionSignals ForObjectArgument() {
13022 // We intend StaticObjectArgumentConversion to compare the same as
13023 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13024 return {};
13025 }
13026 };
13027
13028 // Returns -1 if conversions in L are considered better.
13029 // 0 if they are considered indistinguishable.
13030 // 1 if conversions in R are better.
13031 int CompareConversions(const OverloadCandidate &L,
13032 const OverloadCandidate &R) {
13033 // We cannot use `isBetterOverloadCandidate` because it is defined
13034 // according to the C++ standard and provides a partial order, but we need
13035 // a total order as this function is used in sort.
13036 assert(L.Conversions.size() == R.Conversions.size());
13037 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13038 auto LS = L.IgnoreObjectArgument && I == 0
13039 ? ConversionSignals::ForObjectArgument()
13040 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13041 auto RS = R.IgnoreObjectArgument
13042 ? ConversionSignals::ForObjectArgument()
13043 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13044 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13045 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13046 ? -1
13047 : 1;
13048 }
13049 // FIXME: find a way to compare templates for being more or less
13050 // specialized that provides a strict weak ordering.
13051 return 0;
13052 }
13053};
13054}
13055
13056/// CompleteNonViableCandidate - Normally, overload resolution only
13057/// computes up to the first bad conversion. Produces the FixIt set if
13058/// possible.
13059static void
13060CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13061 ArrayRef<Expr *> Args,
13062 OverloadCandidateSet::CandidateSetKind CSK) {
13063 assert(!Cand->Viable);
13064
13065 // Don't do anything on failures other than bad conversion.
13066 if (Cand->FailureKind != ovl_fail_bad_conversion)
13067 return;
13068
13069 // We only want the FixIts if all the arguments can be corrected.
13070 bool Unfixable = false;
13071 // Use a implicit copy initialization to check conversion fixes.
13072 Cand->Fix.setConversionChecker(TryCopyInitialization);
13073
13074 // Attempt to fix the bad conversion.
13075 unsigned ConvCount = Cand->Conversions.size();
13076 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
13077 ++ConvIdx) {
13078 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13079 if (Cand->Conversions[ConvIdx].isInitialized() &&
13080 Cand->Conversions[ConvIdx].isBad()) {
13081 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13082 break;
13083 }
13084 }
13085
13086 // FIXME: this should probably be preserved from the overload
13087 // operation somehow.
13088 bool SuppressUserConversions = false;
13089
13090 unsigned ConvIdx = 0;
13091 unsigned ArgIdx = 0;
13092 ArrayRef<QualType> ParamTypes;
13093 bool Reversed = Cand->isReversed();
13094
13095 if (Cand->IsSurrogate) {
13096 QualType ConvType
13097 = Cand->Surrogate->getConversionType().getNonReferenceType();
13098 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13099 ConvType = ConvPtrType->getPointeeType();
13100 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13101 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13102 ConvIdx = 1;
13103 } else if (Cand->Function) {
13104 ParamTypes =
13105 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13106 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13107 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed) {
13108 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13109 ConvIdx = 1;
13110 if (CSK == OverloadCandidateSet::CSK_Operator &&
13111 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13112 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13113 OO_Subscript)
13114 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13115 ArgIdx = 1;
13116 }
13117 } else {
13118 // Builtin operator.
13119 assert(ConvCount <= 3);
13120 ParamTypes = Cand->BuiltinParamTypes;
13121 }
13122
13123 // Fill in the rest of the conversions.
13124 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13125 ConvIdx != ConvCount;
13126 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13127 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
13128 if (Cand->Conversions[ConvIdx].isInitialized()) {
13129 // We've already checked this conversion.
13130 } else if (ParamIdx < ParamTypes.size()) {
13131 if (ParamTypes[ParamIdx]->isDependentType())
13132 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13133 Args[ArgIdx]->getType());
13134 else {
13135 Cand->Conversions[ConvIdx] =
13136 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13137 SuppressUserConversions,
13138 /*InOverloadResolution=*/true,
13139 /*AllowObjCWritebackConversion=*/
13140 S.getLangOpts().ObjCAutoRefCount);
13141 // Store the FixIt in the candidate if it exists.
13142 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13143 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13144 }
13145 } else
13146 Cand->Conversions[ConvIdx].setEllipsis();
13147 }
13148}
13149
13150SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13151 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13152 SourceLocation OpLoc,
13153 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13154
13155 InjectNonDeducedTemplateCandidates(S);
13156
13157 // Sort the candidates by viability and position. Sorting directly would
13158 // be prohibitive, so we make a set of pointers and sort those.
13159 SmallVector<OverloadCandidate*, 32> Cands;
13160 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13161 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13162 Cand != LastCand; ++Cand) {
13163 if (!Filter(*Cand))
13164 continue;
13165 switch (OCD) {
13166 case OCD_AllCandidates:
13167 if (!Cand->Viable) {
13168 if (!Cand->Function && !Cand->IsSurrogate) {
13169 // This a non-viable builtin candidate. We do not, in general,
13170 // want to list every possible builtin candidate.
13171 continue;
13172 }
13173 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13174 }
13175 break;
13176
13177 case OCD_ViableCandidates:
13178 if (!Cand->Viable)
13179 continue;
13180 break;
13181
13182 case OCD_AmbiguousCandidates:
13183 if (!Cand->Best)
13184 continue;
13185 break;
13186 }
13187
13188 Cands.push_back(Elt: Cand);
13189 }
13190
13191 llvm::stable_sort(
13192 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13193
13194 return Cands;
13195}
13196
13197bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13198 SourceLocation OpLoc) {
13199 bool DeferHint = false;
13200 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13201 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13202 // host device candidates.
13203 auto WrongSidedCands =
13204 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13205 return (Cand.Viable == false &&
13206 Cand.FailureKind == ovl_fail_bad_target) ||
13207 (Cand.Function &&
13208 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13209 Cand.Function->template hasAttr<CUDADeviceAttr>());
13210 });
13211 DeferHint = !WrongSidedCands.empty();
13212 }
13213 return DeferHint;
13214}
13215
13216/// When overload resolution fails, prints diagnostic messages containing the
13217/// candidates in the candidate set.
13218void OverloadCandidateSet::NoteCandidates(
13219 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13220 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13221 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13222
13223 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13224
13225 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13226
13227 // In WebAssembly we don't want to emit further diagnostics if a table is
13228 // passed as an argument to a function.
13229 bool NoteCands = true;
13230 for (const Expr *Arg : Args) {
13231 if (Arg->getType()->isWebAssemblyTableType())
13232 NoteCands = false;
13233 }
13234
13235 if (NoteCands)
13236 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13237
13238 if (OCD == OCD_AmbiguousCandidates)
13239 MaybeDiagnoseAmbiguousConstraints(S,
13240 Cands: {Candidates.begin(), Candidates.end()});
13241}
13242
13243void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13244 ArrayRef<OverloadCandidate *> Cands,
13245 StringRef Opc, SourceLocation OpLoc) {
13246 bool ReportedAmbiguousConversions = false;
13247
13248 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13249 unsigned CandsShown = 0;
13250 auto I = Cands.begin(), E = Cands.end();
13251 for (; I != E; ++I) {
13252 OverloadCandidate *Cand = *I;
13253
13254 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13255 ShowOverloads == Ovl_Best) {
13256 break;
13257 }
13258 ++CandsShown;
13259
13260 if (Cand->Function)
13261 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13262 /*TakingCandidateAddress=*/false, CtorDestAS: DestAS);
13263 else if (Cand->IsSurrogate)
13264 NoteSurrogateCandidate(S, Cand);
13265 else {
13266 assert(Cand->Viable &&
13267 "Non-viable built-in candidates are not added to Cands.");
13268 // Generally we only see ambiguities including viable builtin
13269 // operators if overload resolution got screwed up by an
13270 // ambiguous user-defined conversion.
13271 //
13272 // FIXME: It's quite possible for different conversions to see
13273 // different ambiguities, though.
13274 if (!ReportedAmbiguousConversions) {
13275 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13276 ReportedAmbiguousConversions = true;
13277 }
13278
13279 // If this is a viable builtin, print it.
13280 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13281 }
13282 }
13283
13284 // Inform S.Diags that we've shown an overload set with N elements. This may
13285 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13286 S.Diags.overloadCandidatesShown(N: CandsShown);
13287
13288 if (I != E)
13289 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13290 shouldDeferDiags(S, Args, OpLoc))
13291 << int(E - I);
13292}
13293
13294static SourceLocation
13295GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13296 return Cand->Specialization ? Cand->Specialization->getLocation()
13297 : SourceLocation();
13298}
13299
13300namespace {
13301struct CompareTemplateSpecCandidatesForDisplay {
13302 Sema &S;
13303 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13304
13305 bool operator()(const TemplateSpecCandidate *L,
13306 const TemplateSpecCandidate *R) {
13307 // Fast-path this check.
13308 if (L == R)
13309 return false;
13310
13311 // Assuming that both candidates are not matches...
13312
13313 // Sort by the ranking of deduction failures.
13314 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13315 return RankDeductionFailure(DFI: L->DeductionFailure) <
13316 RankDeductionFailure(DFI: R->DeductionFailure);
13317
13318 // Sort everything else by location.
13319 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13320 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13321
13322 // Put candidates without locations (e.g. builtins) at the end.
13323 if (LLoc.isInvalid())
13324 return false;
13325 if (RLoc.isInvalid())
13326 return true;
13327
13328 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13329 }
13330};
13331}
13332
13333/// Diagnose a template argument deduction failure.
13334/// We are treating these failures as overload failures due to bad
13335/// deductions.
13336void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13337 bool ForTakingAddress) {
13338 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13339 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13340}
13341
13342void TemplateSpecCandidateSet::destroyCandidates() {
13343 for (iterator i = begin(), e = end(); i != e; ++i) {
13344 i->DeductionFailure.Destroy();
13345 }
13346}
13347
13348void TemplateSpecCandidateSet::clear() {
13349 destroyCandidates();
13350 Candidates.clear();
13351}
13352
13353/// NoteCandidates - When no template specialization match is found, prints
13354/// diagnostic messages containing the non-matching specializations that form
13355/// the candidate set.
13356/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13357/// OCD == OCD_AllCandidates and Cand->Viable == false.
13358void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13359 // Sort the candidates by position (assuming no candidate is a match).
13360 // Sorting directly would be prohibitive, so we make a set of pointers
13361 // and sort those.
13362 SmallVector<TemplateSpecCandidate *, 32> Cands;
13363 Cands.reserve(N: size());
13364 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13365 if (Cand->Specialization)
13366 Cands.push_back(Elt: Cand);
13367 // Otherwise, this is a non-matching builtin candidate. We do not,
13368 // in general, want to list every possible builtin candidate.
13369 }
13370
13371 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13372
13373 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13374 // for generalization purposes (?).
13375 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13376
13377 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13378 unsigned CandsShown = 0;
13379 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13380 TemplateSpecCandidate *Cand = *I;
13381
13382 // Set an arbitrary limit on the number of candidates we'll spam
13383 // the user with. FIXME: This limit should depend on details of the
13384 // candidate list.
13385 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13386 break;
13387 ++CandsShown;
13388
13389 assert(Cand->Specialization &&
13390 "Non-matching built-in candidates are not added to Cands.");
13391 Cand->NoteDeductionFailure(S, ForTakingAddress);
13392 }
13393
13394 if (I != E)
13395 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13396}
13397
13398// [PossiblyAFunctionType] --> [Return]
13399// NonFunctionType --> NonFunctionType
13400// R (A) --> R(A)
13401// R (*)(A) --> R (A)
13402// R (&)(A) --> R (A)
13403// R (S::*)(A) --> R (A)
13404QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13405 QualType Ret = PossiblyAFunctionType;
13406 if (const PointerType *ToTypePtr =
13407 PossiblyAFunctionType->getAs<PointerType>())
13408 Ret = ToTypePtr->getPointeeType();
13409 else if (const ReferenceType *ToTypeRef =
13410 PossiblyAFunctionType->getAs<ReferenceType>())
13411 Ret = ToTypeRef->getPointeeType();
13412 else if (const MemberPointerType *MemTypePtr =
13413 PossiblyAFunctionType->getAs<MemberPointerType>())
13414 Ret = MemTypePtr->getPointeeType();
13415 Ret =
13416 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13417 return Ret;
13418}
13419
13420static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13421 bool Complain = true) {
13422 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13423 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13424 return true;
13425
13426 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13427 if (S.getLangOpts().CPlusPlus17 &&
13428 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13429 !S.ResolveExceptionSpec(Loc, FPT: FPT))
13430 return true;
13431
13432 return false;
13433}
13434
13435namespace {
13436// A helper class to help with address of function resolution
13437// - allows us to avoid passing around all those ugly parameters
13438class AddressOfFunctionResolver {
13439 Sema& S;
13440 Expr* SourceExpr;
13441 const QualType& TargetType;
13442 QualType TargetFunctionType; // Extracted function type from target type
13443
13444 bool Complain;
13445 //DeclAccessPair& ResultFunctionAccessPair;
13446 ASTContext& Context;
13447
13448 bool TargetTypeIsNonStaticMemberFunction;
13449 bool FoundNonTemplateFunction;
13450 bool StaticMemberFunctionFromBoundPointer;
13451 bool HasComplained;
13452
13453 OverloadExpr::FindResult OvlExprInfo;
13454 OverloadExpr *OvlExpr;
13455 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13456 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13457 TemplateSpecCandidateSet FailedCandidates;
13458
13459public:
13460 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13461 const QualType &TargetType, bool Complain)
13462 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13463 Complain(Complain), Context(S.getASTContext()),
13464 TargetTypeIsNonStaticMemberFunction(
13465 !!TargetType->getAs<MemberPointerType>()),
13466 FoundNonTemplateFunction(false),
13467 StaticMemberFunctionFromBoundPointer(false),
13468 HasComplained(false),
13469 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13470 OvlExpr(OvlExprInfo.Expression),
13471 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13472 ExtractUnqualifiedFunctionTypeFromTargetType();
13473
13474 if (TargetFunctionType->isFunctionType()) {
13475 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13476 if (!UME->isImplicitAccess() &&
13477 !S.ResolveSingleFunctionTemplateSpecialization(UME))
13478 StaticMemberFunctionFromBoundPointer = true;
13479 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13480 DeclAccessPair dap;
13481 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13482 ovl: OvlExpr, Complain: false, Found: &dap)) {
13483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13484 if (!Method->isStatic()) {
13485 // If the target type is a non-function type and the function found
13486 // is a non-static member function, pretend as if that was the
13487 // target, it's the only possible type to end up with.
13488 TargetTypeIsNonStaticMemberFunction = true;
13489
13490 // And skip adding the function if its not in the proper form.
13491 // We'll diagnose this due to an empty set of functions.
13492 if (!OvlExprInfo.HasFormOfMemberPointer)
13493 return;
13494 }
13495
13496 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13497 }
13498 return;
13499 }
13500
13501 if (OvlExpr->hasExplicitTemplateArgs())
13502 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13503
13504 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13505 // C++ [over.over]p4:
13506 // If more than one function is selected, [...]
13507 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13508 if (FoundNonTemplateFunction) {
13509 EliminateAllTemplateMatches();
13510 EliminateLessPartialOrderingConstrainedMatches();
13511 } else
13512 EliminateAllExceptMostSpecializedTemplate();
13513 }
13514 }
13515
13516 if (S.getLangOpts().CUDA && Matches.size() > 1)
13517 EliminateSuboptimalCudaMatches();
13518 }
13519
13520 bool hasComplained() const { return HasComplained; }
13521
13522private:
13523 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13524 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13525 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13526 }
13527
13528 /// \return true if A is considered a better overload candidate for the
13529 /// desired type than B.
13530 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13531 // If A doesn't have exactly the correct type, we don't want to classify it
13532 // as "better" than anything else. This way, the user is required to
13533 // disambiguate for us if there are multiple candidates and no exact match.
13534 return candidateHasExactlyCorrectType(FD: A) &&
13535 (!candidateHasExactlyCorrectType(FD: B) ||
13536 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13537 }
13538
13539 /// \return true if we were able to eliminate all but one overload candidate,
13540 /// false otherwise.
13541 bool eliminiateSuboptimalOverloadCandidates() {
13542 // Same algorithm as overload resolution -- one pass to pick the "best",
13543 // another pass to be sure that nothing is better than the best.
13544 auto Best = Matches.begin();
13545 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13546 if (isBetterCandidate(A: I->second, B: Best->second))
13547 Best = I;
13548
13549 const FunctionDecl *BestFn = Best->second;
13550 auto IsBestOrInferiorToBest = [this, BestFn](
13551 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13552 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13553 };
13554
13555 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13556 // option, so we can potentially give the user a better error
13557 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13558 return false;
13559 Matches[0] = *Best;
13560 Matches.resize(N: 1);
13561 return true;
13562 }
13563
13564 bool isTargetTypeAFunction() const {
13565 return TargetFunctionType->isFunctionType();
13566 }
13567
13568 // [ToType] [Return]
13569
13570 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13571 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13572 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13573 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13574 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13575 }
13576
13577 // return true if any matching specializations were found
13578 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13579 const DeclAccessPair& CurAccessFunPair) {
13580 if (CXXMethodDecl *Method
13581 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13582 // Skip non-static function templates when converting to pointer, and
13583 // static when converting to member pointer.
13584 bool CanConvertToFunctionPointer =
13585 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13586 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13587 return false;
13588 }
13589 else if (TargetTypeIsNonStaticMemberFunction)
13590 return false;
13591
13592 // C++ [over.over]p2:
13593 // If the name is a function template, template argument deduction is
13594 // done (14.8.2.2), and if the argument deduction succeeds, the
13595 // resulting template argument list is used to generate a single
13596 // function template specialization, which is added to the set of
13597 // overloaded functions considered.
13598 FunctionDecl *Specialization = nullptr;
13599 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13600 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13601 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13602 Specialization, Info, /*IsAddressOfFunction*/ true);
13603 Result != TemplateDeductionResult::Success) {
13604 // Make a note of the failed deduction for diagnostics.
13605 FailedCandidates.addCandidate()
13606 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13607 MakeDeductionFailureInfo(Context, TDK: Result, Info));
13608 return false;
13609 }
13610
13611 // Template argument deduction ensures that we have an exact match or
13612 // compatible pointer-to-function arguments that would be adjusted by ICS.
13613 // This function template specicalization works.
13614 assert(S.isSameOrCompatibleFunctionType(
13615 Context.getCanonicalType(Specialization->getType()),
13616 Context.getCanonicalType(TargetFunctionType)));
13617
13618 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13619 return false;
13620
13621 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13622 return true;
13623 }
13624
13625 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13626 const DeclAccessPair& CurAccessFunPair) {
13627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13628 // Skip non-static functions when converting to pointer, and static
13629 // when converting to member pointer.
13630 bool CanConvertToFunctionPointer =
13631 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13632 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13633 return false;
13634 }
13635 else if (TargetTypeIsNonStaticMemberFunction)
13636 return false;
13637
13638 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13639 if (S.getLangOpts().CUDA) {
13640 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13641 if (!(Caller && Caller->isImplicit()) &&
13642 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13643 return false;
13644 }
13645 if (FunDecl->isMultiVersion()) {
13646 const auto *TA = FunDecl->getAttr<TargetAttr>();
13647 if (TA && !TA->isDefaultVersion())
13648 return false;
13649 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13650 if (TVA && !TVA->isDefaultVersion())
13651 return false;
13652 }
13653
13654 // If any candidate has a placeholder return type, trigger its deduction
13655 // now.
13656 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13657 Complain)) {
13658 HasComplained |= Complain;
13659 return false;
13660 }
13661
13662 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13663 return false;
13664
13665 // If we're in C, we need to support types that aren't exactly identical.
13666 if (!S.getLangOpts().CPlusPlus ||
13667 candidateHasExactlyCorrectType(FD: FunDecl)) {
13668 Matches.push_back(Elt: std::make_pair(
13669 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13670 FoundNonTemplateFunction = true;
13671 return true;
13672 }
13673 }
13674
13675 return false;
13676 }
13677
13678 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13679 bool Ret = false;
13680
13681 // If the overload expression doesn't have the form of a pointer to
13682 // member, don't try to convert it to a pointer-to-member type.
13683 if (IsInvalidFormOfPointerToMemberFunction())
13684 return false;
13685
13686 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13687 E = OvlExpr->decls_end();
13688 I != E; ++I) {
13689 // Look through any using declarations to find the underlying function.
13690 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13691
13692 // C++ [over.over]p3:
13693 // Non-member functions and static member functions match
13694 // targets of type "pointer-to-function" or "reference-to-function."
13695 // Nonstatic member functions match targets of
13696 // type "pointer-to-member-function."
13697 // Note that according to DR 247, the containing class does not matter.
13698 if (FunctionTemplateDecl *FunctionTemplate
13699 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13700 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13701 Ret = true;
13702 }
13703 // If we have explicit template arguments supplied, skip non-templates.
13704 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13705 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13706 Ret = true;
13707 }
13708 assert(Ret || Matches.empty());
13709 return Ret;
13710 }
13711
13712 void EliminateAllExceptMostSpecializedTemplate() {
13713 // [...] and any given function template specialization F1 is
13714 // eliminated if the set contains a second function template
13715 // specialization whose function template is more specialized
13716 // than the function template of F1 according to the partial
13717 // ordering rules of 14.5.5.2.
13718
13719 // The algorithm specified above is quadratic. We instead use a
13720 // two-pass algorithm (similar to the one used to identify the
13721 // best viable function in an overload set) that identifies the
13722 // best function template (if it exists).
13723
13724 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13725 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13726 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13727
13728 // TODO: It looks like FailedCandidates does not serve much purpose
13729 // here, since the no_viable diagnostic has index 0.
13730 UnresolvedSetIterator Result = S.getMostSpecialized(
13731 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13732 SourceExpr->getBeginLoc(), S.PDiag(),
13733 S.PDiag(diag::err_addr_ovl_ambiguous)
13734 << Matches[0].second->getDeclName(),
13735 S.PDiag(diag::note_ovl_candidate)
13736 << (unsigned)oc_function << (unsigned)ocs_described_template,
13737 Complain, TargetFunctionType);
13738
13739 if (Result != MatchesCopy.end()) {
13740 // Make it the first and only element
13741 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13742 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13743 Matches.resize(N: 1);
13744 } else
13745 HasComplained |= Complain;
13746 }
13747
13748 void EliminateAllTemplateMatches() {
13749 // [...] any function template specializations in the set are
13750 // eliminated if the set also contains a non-template function, [...]
13751 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13752 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13753 ++I;
13754 else {
13755 Matches[I] = Matches[--N];
13756 Matches.resize(N);
13757 }
13758 }
13759 }
13760
13761 void EliminateLessPartialOrderingConstrainedMatches() {
13762 // C++ [over.over]p5:
13763 // [...] Any given non-template function F0 is eliminated if the set
13764 // contains a second non-template function that is more
13765 // partial-ordering-constrained than F0. [...]
13766 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13767 "Call EliminateAllTemplateMatches() first");
13768 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13769 Results.push_back(Elt: Matches[0]);
13770 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13771 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13772 FunctionDecl *F = getMorePartialOrderingConstrained(
13773 S, Fn1: Matches[I].second, Fn2: Results[0].second,
13774 /*IsFn1Reversed=*/false,
13775 /*IsFn2Reversed=*/false);
13776 if (!F) {
13777 Results.push_back(Elt: Matches[I]);
13778 continue;
13779 }
13780 if (F == Matches[I].second) {
13781 Results.clear();
13782 Results.push_back(Elt: Matches[I]);
13783 }
13784 }
13785 std::swap(LHS&: Matches, RHS&: Results);
13786 }
13787
13788 void EliminateSuboptimalCudaMatches() {
13789 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
13790 Matches);
13791 }
13792
13793public:
13794 void ComplainNoMatchesFound() const {
13795 assert(Matches.empty());
13796 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13797 << OvlExpr->getName() << TargetFunctionType
13798 << OvlExpr->getSourceRange();
13799 if (FailedCandidates.empty())
13800 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13801 /*TakingAddress=*/true);
13802 else {
13803 // We have some deduction failure messages. Use them to diagnose
13804 // the function templates, and diagnose the non-template candidates
13805 // normally.
13806 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13807 IEnd = OvlExpr->decls_end();
13808 I != IEnd; ++I)
13809 if (FunctionDecl *Fun =
13810 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13811 if (!functionHasPassObjectSizeParams(Fun))
13812 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13813 /*TakingAddress=*/true);
13814 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13815 }
13816 }
13817
13818 bool IsInvalidFormOfPointerToMemberFunction() const {
13819 return TargetTypeIsNonStaticMemberFunction &&
13820 !OvlExprInfo.HasFormOfMemberPointer;
13821 }
13822
13823 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13824 // TODO: Should we condition this on whether any functions might
13825 // have matched, or is it more appropriate to do that in callers?
13826 // TODO: a fixit wouldn't hurt.
13827 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13828 << TargetType << OvlExpr->getSourceRange();
13829 }
13830
13831 bool IsStaticMemberFunctionFromBoundPointer() const {
13832 return StaticMemberFunctionFromBoundPointer;
13833 }
13834
13835 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13836 S.Diag(OvlExpr->getBeginLoc(),
13837 diag::err_invalid_form_pointer_member_function)
13838 << OvlExpr->getSourceRange();
13839 }
13840
13841 void ComplainOfInvalidConversion() const {
13842 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13843 << OvlExpr->getName() << TargetType;
13844 }
13845
13846 void ComplainMultipleMatchesFound() const {
13847 assert(Matches.size() > 1);
13848 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13849 << OvlExpr->getName() << OvlExpr->getSourceRange();
13850 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13851 /*TakingAddress=*/true);
13852 }
13853
13854 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13855
13856 int getNumMatches() const { return Matches.size(); }
13857
13858 FunctionDecl* getMatchingFunctionDecl() const {
13859 if (Matches.size() != 1) return nullptr;
13860 return Matches[0].second;
13861 }
13862
13863 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13864 if (Matches.size() != 1) return nullptr;
13865 return &Matches[0].first;
13866 }
13867};
13868}
13869
13870FunctionDecl *
13871Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13872 QualType TargetType,
13873 bool Complain,
13874 DeclAccessPair &FoundResult,
13875 bool *pHadMultipleCandidates) {
13876 assert(AddressOfExpr->getType() == Context.OverloadTy);
13877
13878 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13879 Complain);
13880 int NumMatches = Resolver.getNumMatches();
13881 FunctionDecl *Fn = nullptr;
13882 bool ShouldComplain = Complain && !Resolver.hasComplained();
13883 if (NumMatches == 0 && ShouldComplain) {
13884 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13885 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13886 else
13887 Resolver.ComplainNoMatchesFound();
13888 }
13889 else if (NumMatches > 1 && ShouldComplain)
13890 Resolver.ComplainMultipleMatchesFound();
13891 else if (NumMatches == 1) {
13892 Fn = Resolver.getMatchingFunctionDecl();
13893 assert(Fn);
13894 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13895 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT: FPT);
13896 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13897 if (Complain) {
13898 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13899 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13900 else
13901 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
13902 }
13903 }
13904
13905 if (pHadMultipleCandidates)
13906 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13907 return Fn;
13908}
13909
13910FunctionDecl *
13911Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13912 OverloadExpr::FindResult R = OverloadExpr::find(E);
13913 OverloadExpr *Ovl = R.Expression;
13914 bool IsResultAmbiguous = false;
13915 FunctionDecl *Result = nullptr;
13916 DeclAccessPair DAP;
13917 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13918
13919 // Return positive for better, negative for worse, 0 for equal preference.
13920 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13921 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13922 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
13923 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
13924 };
13925
13926 // Don't use the AddressOfResolver because we're specifically looking for
13927 // cases where we have one overload candidate that lacks
13928 // enable_if/pass_object_size/...
13929 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13930 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
13931 if (!FD)
13932 return nullptr;
13933
13934 if (!checkAddressOfFunctionIsAvailable(Function: FD))
13935 continue;
13936
13937 // If we found a better result, update Result.
13938 auto FoundBetter = [&]() {
13939 IsResultAmbiguous = false;
13940 DAP = I.getPair();
13941 Result = FD;
13942 };
13943
13944 // We have more than one result - see if it is more
13945 // partial-ordering-constrained than the previous one.
13946 if (Result) {
13947 // Check CUDA preference first. If the candidates have differennt CUDA
13948 // preference, choose the one with higher CUDA preference. Otherwise,
13949 // choose the one with more constraints.
13950 if (getLangOpts().CUDA) {
13951 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13952 // FD has different preference than Result.
13953 if (PreferenceByCUDA != 0) {
13954 // FD is more preferable than Result.
13955 if (PreferenceByCUDA > 0)
13956 FoundBetter();
13957 continue;
13958 }
13959 }
13960 // FD has the same CUDA preference than Result. Continue to check
13961 // constraints.
13962
13963 // C++ [over.over]p5:
13964 // [...] Any given non-template function F0 is eliminated if the set
13965 // contains a second non-template function that is more
13966 // partial-ordering-constrained than F0 [...]
13967 FunctionDecl *MoreConstrained =
13968 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
13969 /*IsFn1Reversed=*/false,
13970 /*IsFn2Reversed=*/false);
13971 if (MoreConstrained != FD) {
13972 if (!MoreConstrained) {
13973 IsResultAmbiguous = true;
13974 AmbiguousDecls.push_back(Elt: FD);
13975 }
13976 continue;
13977 }
13978 // FD is more constrained - replace Result with it.
13979 }
13980 FoundBetter();
13981 }
13982
13983 if (IsResultAmbiguous)
13984 return nullptr;
13985
13986 if (Result) {
13987 // We skipped over some ambiguous declarations which might be ambiguous with
13988 // the selected result.
13989 for (FunctionDecl *Skipped : AmbiguousDecls) {
13990 // If skipped candidate has different CUDA preference than the result,
13991 // there is no ambiguity. Otherwise check whether they have different
13992 // constraints.
13993 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13994 continue;
13995 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
13996 return nullptr;
13997 }
13998 Pair = DAP;
13999 }
14000 return Result;
14001}
14002
14003bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14004 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14005 Expr *E = SrcExpr.get();
14006 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14007
14008 DeclAccessPair DAP;
14009 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14010 if (!Found || Found->isCPUDispatchMultiVersion() ||
14011 Found->isCPUSpecificMultiVersion())
14012 return false;
14013
14014 // Emitting multiple diagnostics for a function that is both inaccessible and
14015 // unavailable is consistent with our behavior elsewhere. So, always check
14016 // for both.
14017 DiagnoseUseOfDecl(Found, E->getExprLoc());
14018 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14019 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14020 if (Res.isInvalid())
14021 return false;
14022 Expr *Fixed = Res.get();
14023 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14024 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14025 else
14026 SrcExpr = Fixed;
14027 return true;
14028}
14029
14030FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14031 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14032 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14033 // C++ [over.over]p1:
14034 // [...] [Note: any redundant set of parentheses surrounding the
14035 // overloaded function name is ignored (5.1). ]
14036 // C++ [over.over]p1:
14037 // [...] The overloaded function name can be preceded by the &
14038 // operator.
14039
14040 // If we didn't actually find any template-ids, we're done.
14041 if (!ovl->hasExplicitTemplateArgs())
14042 return nullptr;
14043
14044 TemplateArgumentListInfo ExplicitTemplateArgs;
14045 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14046
14047 // Look through all of the overloaded functions, searching for one
14048 // whose type matches exactly.
14049 FunctionDecl *Matched = nullptr;
14050 for (UnresolvedSetIterator I = ovl->decls_begin(),
14051 E = ovl->decls_end(); I != E; ++I) {
14052 // C++0x [temp.arg.explicit]p3:
14053 // [...] In contexts where deduction is done and fails, or in contexts
14054 // where deduction is not done, if a template argument list is
14055 // specified and it, along with any default template arguments,
14056 // identifies a single function template specialization, then the
14057 // template-id is an lvalue for the function template specialization.
14058 FunctionTemplateDecl *FunctionTemplate
14059 = cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14060
14061 // C++ [over.over]p2:
14062 // If the name is a function template, template argument deduction is
14063 // done (14.8.2.2), and if the argument deduction succeeds, the
14064 // resulting template argument list is used to generate a single
14065 // function template specialization, which is added to the set of
14066 // overloaded functions considered.
14067 FunctionDecl *Specialization = nullptr;
14068 TemplateDeductionInfo Info(ovl->getNameLoc());
14069 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14070 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14071 /*IsAddressOfFunction*/ true);
14072 Result != TemplateDeductionResult::Success) {
14073 // Make a note of the failed deduction for diagnostics.
14074 if (FailedTSC)
14075 FailedTSC->addCandidate().set(
14076 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14077 MakeDeductionFailureInfo(Context, TDK: Result, Info));
14078 continue;
14079 }
14080
14081 assert(Specialization && "no specialization and no error?");
14082
14083 // C++ [temp.deduct.call]p6:
14084 // [...] If all successful deductions yield the same deduced A, that
14085 // deduced A is the result of deduction; otherwise, the parameter is
14086 // treated as a non-deduced context.
14087 if (Matched) {
14088 if (ForTypeDeduction &&
14089 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14090 Arg: Specialization->getType()))
14091 continue;
14092 // Multiple matches; we can't resolve to a single declaration.
14093 if (Complain) {
14094 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14095 << ovl->getName();
14096 NoteAllOverloadCandidates(ovl);
14097 }
14098 return nullptr;
14099 }
14100
14101 Matched = Specialization;
14102 if (FoundResult) *FoundResult = I.getPair();
14103 }
14104
14105 if (Matched &&
14106 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14107 return nullptr;
14108
14109 return Matched;
14110}
14111
14112bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14113 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14114 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14115 unsigned DiagIDForComplaining) {
14116 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14117
14118 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14119
14120 DeclAccessPair found;
14121 ExprResult SingleFunctionExpression;
14122 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14123 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14124 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14125 SrcExpr = ExprError();
14126 return true;
14127 }
14128
14129 // It is only correct to resolve to an instance method if we're
14130 // resolving a form that's permitted to be a pointer to member.
14131 // Otherwise we'll end up making a bound member expression, which
14132 // is illegal in all the contexts we resolve like this.
14133 if (!ovl.HasFormOfMemberPointer &&
14134 isa<CXXMethodDecl>(Val: fn) &&
14135 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14136 if (!complain) return false;
14137
14138 Diag(ovl.Expression->getExprLoc(),
14139 diag::err_bound_member_function)
14140 << 0 << ovl.Expression->getSourceRange();
14141
14142 // TODO: I believe we only end up here if there's a mix of
14143 // static and non-static candidates (otherwise the expression
14144 // would have 'bound member' type, not 'overload' type).
14145 // Ideally we would note which candidate was chosen and why
14146 // the static candidates were rejected.
14147 SrcExpr = ExprError();
14148 return true;
14149 }
14150
14151 // Fix the expression to refer to 'fn'.
14152 SingleFunctionExpression =
14153 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14154
14155 // If desired, do function-to-pointer decay.
14156 if (doFunctionPointerConversion) {
14157 SingleFunctionExpression =
14158 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14159 if (SingleFunctionExpression.isInvalid()) {
14160 SrcExpr = ExprError();
14161 return true;
14162 }
14163 }
14164 }
14165
14166 if (!SingleFunctionExpression.isUsable()) {
14167 if (complain) {
14168 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14169 << ovl.Expression->getName()
14170 << DestTypeForComplaining
14171 << OpRangeForComplaining
14172 << ovl.Expression->getQualifierLoc().getSourceRange();
14173 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14174
14175 SrcExpr = ExprError();
14176 return true;
14177 }
14178
14179 return false;
14180 }
14181
14182 SrcExpr = SingleFunctionExpression;
14183 return true;
14184}
14185
14186/// Add a single candidate to the overload set.
14187static void AddOverloadedCallCandidate(Sema &S,
14188 DeclAccessPair FoundDecl,
14189 TemplateArgumentListInfo *ExplicitTemplateArgs,
14190 ArrayRef<Expr *> Args,
14191 OverloadCandidateSet &CandidateSet,
14192 bool PartialOverloading,
14193 bool KnownValid) {
14194 NamedDecl *Callee = FoundDecl.getDecl();
14195 if (isa<UsingShadowDecl>(Val: Callee))
14196 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14197
14198 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14199 if (ExplicitTemplateArgs) {
14200 assert(!KnownValid && "Explicit template arguments?");
14201 return;
14202 }
14203 // Prevent ill-formed function decls to be added as overload candidates.
14204 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14205 return;
14206
14207 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14208 /*SuppressUserConversions=*/false,
14209 PartialOverloading);
14210 return;
14211 }
14212
14213 if (FunctionTemplateDecl *FuncTemplate
14214 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14215 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14216 ExplicitTemplateArgs, Args, CandidateSet,
14217 /*SuppressUserConversions=*/false,
14218 PartialOverloading);
14219 return;
14220 }
14221
14222 assert(!KnownValid && "unhandled case in overloaded call candidate");
14223}
14224
14225void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14226 ArrayRef<Expr *> Args,
14227 OverloadCandidateSet &CandidateSet,
14228 bool PartialOverloading) {
14229
14230#ifndef NDEBUG
14231 // Verify that ArgumentDependentLookup is consistent with the rules
14232 // in C++0x [basic.lookup.argdep]p3:
14233 //
14234 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14235 // and let Y be the lookup set produced by argument dependent
14236 // lookup (defined as follows). If X contains
14237 //
14238 // -- a declaration of a class member, or
14239 //
14240 // -- a block-scope function declaration that is not a
14241 // using-declaration, or
14242 //
14243 // -- a declaration that is neither a function or a function
14244 // template
14245 //
14246 // then Y is empty.
14247
14248 if (ULE->requiresADL()) {
14249 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14250 E = ULE->decls_end(); I != E; ++I) {
14251 assert(!(*I)->getDeclContext()->isRecord());
14252 assert(isa<UsingShadowDecl>(*I) ||
14253 !(*I)->getDeclContext()->isFunctionOrMethod());
14254 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14255 }
14256 }
14257#endif
14258
14259 // It would be nice to avoid this copy.
14260 TemplateArgumentListInfo TABuffer;
14261 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14262 if (ULE->hasExplicitTemplateArgs()) {
14263 ULE->copyTemplateArgumentsInto(TABuffer);
14264 ExplicitTemplateArgs = &TABuffer;
14265 }
14266
14267 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14268 E = ULE->decls_end(); I != E; ++I)
14269 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14270 CandidateSet, PartialOverloading,
14271 /*KnownValid*/ true);
14272
14273 if (ULE->requiresADL())
14274 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14275 Args, ExplicitTemplateArgs,
14276 CandidateSet, PartialOverloading);
14277}
14278
14279void Sema::AddOverloadedCallCandidates(
14280 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14281 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14282 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14283 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14284 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14285}
14286
14287/// Determine whether a declaration with the specified name could be moved into
14288/// a different namespace.
14289static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14290 switch (Name.getCXXOverloadedOperator()) {
14291 case OO_New: case OO_Array_New:
14292 case OO_Delete: case OO_Array_Delete:
14293 return false;
14294
14295 default:
14296 return true;
14297 }
14298}
14299
14300/// Attempt to recover from an ill-formed use of a non-dependent name in a
14301/// template, where the non-dependent name was declared after the template
14302/// was defined. This is common in code written for a compilers which do not
14303/// correctly implement two-stage name lookup.
14304///
14305/// Returns true if a viable candidate was found and a diagnostic was issued.
14306static bool DiagnoseTwoPhaseLookup(
14307 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14308 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14309 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14310 CXXRecordDecl **FoundInClass = nullptr) {
14311 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14312 return false;
14313
14314 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14315 if (DC->isTransparentContext())
14316 continue;
14317
14318 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14319
14320 if (!R.empty()) {
14321 R.suppressDiagnostics();
14322
14323 OverloadCandidateSet Candidates(FnLoc, CSK);
14324 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14325 CandidateSet&: Candidates);
14326
14327 OverloadCandidateSet::iterator Best;
14328 OverloadingResult OR =
14329 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14330
14331 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14332 // We either found non-function declarations or a best viable function
14333 // at class scope. A class-scope lookup result disables ADL. Don't
14334 // look past this, but let the caller know that we found something that
14335 // either is, or might be, usable in this class.
14336 if (FoundInClass) {
14337 *FoundInClass = RD;
14338 if (OR == OR_Success) {
14339 R.clear();
14340 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14341 R.resolveKind();
14342 }
14343 }
14344 return false;
14345 }
14346
14347 if (OR != OR_Success) {
14348 // There wasn't a unique best function or function template.
14349 return false;
14350 }
14351
14352 // Find the namespaces where ADL would have looked, and suggest
14353 // declaring the function there instead.
14354 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14355 Sema::AssociatedClassSet AssociatedClasses;
14356 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14357 AssociatedNamespaces,
14358 AssociatedClasses);
14359 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14360 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14361 DeclContext *Std = SemaRef.getStdNamespace();
14362 for (Sema::AssociatedNamespaceSet::iterator
14363 it = AssociatedNamespaces.begin(),
14364 end = AssociatedNamespaces.end(); it != end; ++it) {
14365 // Never suggest declaring a function within namespace 'std'.
14366 if (Std && Std->Encloses(DC: *it))
14367 continue;
14368
14369 // Never suggest declaring a function within a namespace with a
14370 // reserved name, like __gnu_cxx.
14371 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14372 if (NS &&
14373 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14374 continue;
14375
14376 SuggestedNamespaces.insert(X: *it);
14377 }
14378 }
14379
14380 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14381 << R.getLookupName();
14382 if (SuggestedNamespaces.empty()) {
14383 SemaRef.Diag(Best->Function->getLocation(),
14384 diag::note_not_found_by_two_phase_lookup)
14385 << R.getLookupName() << 0;
14386 } else if (SuggestedNamespaces.size() == 1) {
14387 SemaRef.Diag(Best->Function->getLocation(),
14388 diag::note_not_found_by_two_phase_lookup)
14389 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14390 } else {
14391 // FIXME: It would be useful to list the associated namespaces here,
14392 // but the diagnostics infrastructure doesn't provide a way to produce
14393 // a localized representation of a list of items.
14394 SemaRef.Diag(Best->Function->getLocation(),
14395 diag::note_not_found_by_two_phase_lookup)
14396 << R.getLookupName() << 2;
14397 }
14398
14399 // Try to recover by calling this function.
14400 return true;
14401 }
14402
14403 R.clear();
14404 }
14405
14406 return false;
14407}
14408
14409/// Attempt to recover from ill-formed use of a non-dependent operator in a
14410/// template, where the non-dependent operator was declared after the template
14411/// was defined.
14412///
14413/// Returns true if a viable candidate was found and a diagnostic was issued.
14414static bool
14415DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14416 SourceLocation OpLoc,
14417 ArrayRef<Expr *> Args) {
14418 DeclarationName OpName =
14419 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14420 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14421 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14422 CSK: OverloadCandidateSet::CSK_Operator,
14423 /*ExplicitTemplateArgs=*/nullptr, Args);
14424}
14425
14426namespace {
14427class BuildRecoveryCallExprRAII {
14428 Sema &SemaRef;
14429 Sema::SatisfactionStackResetRAII SatStack;
14430
14431public:
14432 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14433 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14434 SemaRef.IsBuildingRecoveryCallExpr = true;
14435 }
14436
14437 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14438};
14439}
14440
14441/// Attempts to recover from a call where no functions were found.
14442///
14443/// This function will do one of three things:
14444/// * Diagnose, recover, and return a recovery expression.
14445/// * Diagnose, fail to recover, and return ExprError().
14446/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14447/// expected to diagnose as appropriate.
14448static ExprResult
14449BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14450 UnresolvedLookupExpr *ULE,
14451 SourceLocation LParenLoc,
14452 MutableArrayRef<Expr *> Args,
14453 SourceLocation RParenLoc,
14454 bool EmptyLookup, bool AllowTypoCorrection) {
14455 // Do not try to recover if it is already building a recovery call.
14456 // This stops infinite loops for template instantiations like
14457 //
14458 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14459 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14460 if (SemaRef.IsBuildingRecoveryCallExpr)
14461 return ExprResult();
14462 BuildRecoveryCallExprRAII RCE(SemaRef);
14463
14464 CXXScopeSpec SS;
14465 SS.Adopt(Other: ULE->getQualifierLoc());
14466 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14467
14468 TemplateArgumentListInfo TABuffer;
14469 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14470 if (ULE->hasExplicitTemplateArgs()) {
14471 ULE->copyTemplateArgumentsInto(TABuffer);
14472 ExplicitTemplateArgs = &TABuffer;
14473 }
14474
14475 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14476 Sema::LookupOrdinaryName);
14477 CXXRecordDecl *FoundInClass = nullptr;
14478 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14479 CSK: OverloadCandidateSet::CSK_Normal,
14480 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14481 // OK, diagnosed a two-phase lookup issue.
14482 } else if (EmptyLookup) {
14483 // Try to recover from an empty lookup with typo correction.
14484 R.clear();
14485 NoTypoCorrectionCCC NoTypoValidator{};
14486 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14487 ExplicitTemplateArgs != nullptr,
14488 dyn_cast<MemberExpr>(Val: Fn));
14489 CorrectionCandidateCallback &Validator =
14490 AllowTypoCorrection
14491 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14492 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14493 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14494 Args))
14495 return ExprError();
14496 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14497 // We found a usable declaration of the name in a dependent base of some
14498 // enclosing class.
14499 // FIXME: We should also explain why the candidates found by name lookup
14500 // were not viable.
14501 if (SemaRef.DiagnoseDependentMemberLookup(R))
14502 return ExprError();
14503 } else {
14504 // We had viable candidates and couldn't recover; let the caller diagnose
14505 // this.
14506 return ExprResult();
14507 }
14508
14509 // If we get here, we should have issued a diagnostic and formed a recovery
14510 // lookup result.
14511 assert(!R.empty() && "lookup results empty despite recovery");
14512
14513 // If recovery created an ambiguity, just bail out.
14514 if (R.isAmbiguous()) {
14515 R.suppressDiagnostics();
14516 return ExprError();
14517 }
14518
14519 // Build an implicit member call if appropriate. Just drop the
14520 // casts and such from the call, we don't really care.
14521 ExprResult NewFn = ExprError();
14522 if ((*R.begin())->isCXXClassMember())
14523 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14524 TemplateArgs: ExplicitTemplateArgs, S);
14525 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14526 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14527 TemplateArgs: ExplicitTemplateArgs);
14528 else
14529 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14530
14531 if (NewFn.isInvalid())
14532 return ExprError();
14533
14534 // This shouldn't cause an infinite loop because we're giving it
14535 // an expression with viable lookup results, which should never
14536 // end up here.
14537 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14538 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14539 RParenLoc);
14540}
14541
14542bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14543 UnresolvedLookupExpr *ULE,
14544 MultiExprArg Args,
14545 SourceLocation RParenLoc,
14546 OverloadCandidateSet *CandidateSet,
14547 ExprResult *Result) {
14548#ifndef NDEBUG
14549 if (ULE->requiresADL()) {
14550 // To do ADL, we must have found an unqualified name.
14551 assert(!ULE->getQualifier() && "qualified name with ADL");
14552
14553 // We don't perform ADL for implicit declarations of builtins.
14554 // Verify that this was correctly set up.
14555 FunctionDecl *F;
14556 if (ULE->decls_begin() != ULE->decls_end() &&
14557 ULE->decls_begin() + 1 == ULE->decls_end() &&
14558 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14559 F->getBuiltinID() && F->isImplicit())
14560 llvm_unreachable("performing ADL for builtin");
14561
14562 // We don't perform ADL in C.
14563 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14564 }
14565#endif
14566
14567 UnbridgedCastsSet UnbridgedCasts;
14568 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14569 *Result = ExprError();
14570 return true;
14571 }
14572
14573 // Add the functions denoted by the callee to the set of candidate
14574 // functions, including those from argument-dependent lookup.
14575 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14576
14577 if (getLangOpts().MSVCCompat &&
14578 CurContext->isDependentContext() && !isSFINAEContext() &&
14579 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14580
14581 OverloadCandidateSet::iterator Best;
14582 if (CandidateSet->empty() ||
14583 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14584 OR_No_Viable_Function) {
14585 // In Microsoft mode, if we are inside a template class member function
14586 // then create a type dependent CallExpr. The goal is to postpone name
14587 // lookup to instantiation time to be able to search into type dependent
14588 // base classes.
14589 CallExpr *CE =
14590 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14591 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14592 CE->markDependentForPostponedNameLookup();
14593 *Result = CE;
14594 return true;
14595 }
14596 }
14597
14598 if (CandidateSet->empty())
14599 return false;
14600
14601 UnbridgedCasts.restore();
14602 return false;
14603}
14604
14605// Guess at what the return type for an unresolvable overload should be.
14606static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14607 OverloadCandidateSet::iterator *Best) {
14608 std::optional<QualType> Result;
14609 // Adjust Type after seeing a candidate.
14610 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14611 if (!Candidate.Function)
14612 return;
14613 if (Candidate.Function->isInvalidDecl())
14614 return;
14615 QualType T = Candidate.Function->getReturnType();
14616 if (T.isNull())
14617 return;
14618 if (!Result)
14619 Result = T;
14620 else if (Result != T)
14621 Result = QualType();
14622 };
14623
14624 // Look for an unambiguous type from a progressively larger subset.
14625 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14626 //
14627 // First, consider only the best candidate.
14628 if (Best && *Best != CS.end())
14629 ConsiderCandidate(**Best);
14630 // Next, consider only viable candidates.
14631 if (!Result)
14632 for (const auto &C : CS)
14633 if (C.Viable)
14634 ConsiderCandidate(C);
14635 // Finally, consider all candidates.
14636 if (!Result)
14637 for (const auto &C : CS)
14638 ConsiderCandidate(C);
14639
14640 if (!Result)
14641 return QualType();
14642 auto Value = *Result;
14643 if (Value.isNull() || Value->isUndeducedType())
14644 return QualType();
14645 return Value;
14646}
14647
14648/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14649/// the completed call expression. If overload resolution fails, emits
14650/// diagnostics and returns ExprError()
14651static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14652 UnresolvedLookupExpr *ULE,
14653 SourceLocation LParenLoc,
14654 MultiExprArg Args,
14655 SourceLocation RParenLoc,
14656 Expr *ExecConfig,
14657 OverloadCandidateSet *CandidateSet,
14658 OverloadCandidateSet::iterator *Best,
14659 OverloadingResult OverloadResult,
14660 bool AllowTypoCorrection) {
14661 switch (OverloadResult) {
14662 case OR_Success: {
14663 FunctionDecl *FDecl = (*Best)->Function;
14664 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14665 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14666 return ExprError();
14667 ExprResult Res =
14668 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14669 if (Res.isInvalid())
14670 return ExprError();
14671 return SemaRef.BuildResolvedCallExpr(
14672 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14673 /*IsExecConfig=*/false,
14674 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14675 }
14676
14677 case OR_No_Viable_Function: {
14678 if (*Best != CandidateSet->end() &&
14679 CandidateSet->getKind() ==
14680 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14681 if (CXXMethodDecl *M =
14682 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14683 M && M->isImplicitObjectMemberFunction()) {
14684 CandidateSet->NoteCandidates(
14685 PartialDiagnosticAt(
14686 Fn->getBeginLoc(),
14687 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14688 SemaRef, OCD_AmbiguousCandidates, Args);
14689 return ExprError();
14690 }
14691 }
14692
14693 // Try to recover by looking for viable functions which the user might
14694 // have meant to call.
14695 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14696 Args, RParenLoc,
14697 EmptyLookup: CandidateSet->empty(),
14698 AllowTypoCorrection);
14699 if (Recovery.isInvalid() || Recovery.isUsable())
14700 return Recovery;
14701
14702 // If the user passes in a function that we can't take the address of, we
14703 // generally end up emitting really bad error messages. Here, we attempt to
14704 // emit better ones.
14705 for (const Expr *Arg : Args) {
14706 if (!Arg->getType()->isFunctionType())
14707 continue;
14708 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14709 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14710 if (FD &&
14711 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14712 Loc: Arg->getExprLoc()))
14713 return ExprError();
14714 }
14715 }
14716
14717 CandidateSet->NoteCandidates(
14718 PartialDiagnosticAt(
14719 Fn->getBeginLoc(),
14720 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14721 << ULE->getName() << Fn->getSourceRange()),
14722 SemaRef, OCD_AllCandidates, Args);
14723 break;
14724 }
14725
14726 case OR_Ambiguous:
14727 CandidateSet->NoteCandidates(
14728 PartialDiagnosticAt(Fn->getBeginLoc(),
14729 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14730 << ULE->getName() << Fn->getSourceRange()),
14731 SemaRef, OCD_AmbiguousCandidates, Args);
14732 break;
14733
14734 case OR_Deleted: {
14735 FunctionDecl *FDecl = (*Best)->Function;
14736 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14737 Range: Fn->getSourceRange(), Name: ULE->getName(),
14738 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14739
14740 // We emitted an error for the unavailable/deleted function call but keep
14741 // the call in the AST.
14742 ExprResult Res =
14743 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14744 if (Res.isInvalid())
14745 return ExprError();
14746 return SemaRef.BuildResolvedCallExpr(
14747 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14748 /*IsExecConfig=*/false,
14749 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14750 }
14751 }
14752
14753 // Overload resolution failed, try to recover.
14754 SmallVector<Expr *, 8> SubExprs = {Fn};
14755 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14756 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14757 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14758}
14759
14760static void markUnaddressableCandidatesUnviable(Sema &S,
14761 OverloadCandidateSet &CS) {
14762 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14763 if (I->Viable &&
14764 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14765 I->Viable = false;
14766 I->FailureKind = ovl_fail_addr_not_available;
14767 }
14768 }
14769}
14770
14771ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14772 UnresolvedLookupExpr *ULE,
14773 SourceLocation LParenLoc,
14774 MultiExprArg Args,
14775 SourceLocation RParenLoc,
14776 Expr *ExecConfig,
14777 bool AllowTypoCorrection,
14778 bool CalleesAddressIsTaken) {
14779
14780 OverloadCandidateSet::CandidateSetKind CSK =
14781 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14782 : OverloadCandidateSet::CSK_Normal;
14783
14784 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14785 ExprResult result;
14786
14787 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
14788 Result: &result))
14789 return result;
14790
14791 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14792 // functions that aren't addressible are considered unviable.
14793 if (CalleesAddressIsTaken)
14794 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
14795
14796 OverloadCandidateSet::iterator Best;
14797 OverloadingResult OverloadResult =
14798 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
14799
14800 // [C++23][over.call.func]
14801 // if overload resolution selects a non-static member function,
14802 // the call is ill-formed;
14803 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
14804 Best != CandidateSet.end()) {
14805 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
14806 M && M->isImplicitObjectMemberFunction()) {
14807 OverloadResult = OR_No_Viable_Function;
14808 }
14809 }
14810
14811 // Model the case with a call to a templated function whose definition
14812 // encloses the call and whose return type contains a placeholder type as if
14813 // the UnresolvedLookupExpr was type-dependent.
14814 if (OverloadResult == OR_Success) {
14815 const FunctionDecl *FDecl = Best->Function;
14816 if (LangOpts.CUDA)
14817 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14818 if (FDecl && FDecl->isTemplateInstantiation() &&
14819 FDecl->getReturnType()->isUndeducedType()) {
14820
14821 // Creating dependent CallExpr is not okay if the enclosing context itself
14822 // is not dependent. This situation notably arises if a non-dependent
14823 // member function calls the later-defined overloaded static function.
14824 //
14825 // For example, in
14826 // class A {
14827 // void c() { callee(1); }
14828 // static auto callee(auto x) { }
14829 // };
14830 //
14831 // Here callee(1) is unresolved at the call site, but is not inside a
14832 // dependent context. There will be no further attempt to resolve this
14833 // call if it is made dependent.
14834
14835 if (const auto *TP =
14836 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14837 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14838 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
14839 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
14840 }
14841 }
14842 }
14843
14844 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14845 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
14846 OverloadResult, AllowTypoCorrection);
14847}
14848
14849ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14850 NestedNameSpecifierLoc NNSLoc,
14851 DeclarationNameInfo DNI,
14852 const UnresolvedSetImpl &Fns,
14853 bool PerformADL) {
14854 return UnresolvedLookupExpr::Create(
14855 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
14856 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14857}
14858
14859ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14860 CXXConversionDecl *Method,
14861 bool HadMultipleCandidates) {
14862 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14863 // the FoundDecl as it impedes TransformMemberExpr.
14864 // We go a bit further here: if there's no difference in UnderlyingDecl,
14865 // then using FoundDecl vs Method shouldn't make a difference either.
14866 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14867 FoundDecl = Method;
14868 // Convert the expression to match the conversion function's implicit object
14869 // parameter.
14870 ExprResult Exp;
14871 if (Method->isExplicitObjectMemberFunction())
14872 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14873 else
14874 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14875 FoundDecl, Method);
14876 if (Exp.isInvalid())
14877 return true;
14878
14879 if (Method->getParent()->isLambda() &&
14880 Method->getConversionType()->isBlockPointerType()) {
14881 // This is a lambda conversion to block pointer; check if the argument
14882 // was a LambdaExpr.
14883 Expr *SubE = E;
14884 auto *CE = dyn_cast<CastExpr>(Val: SubE);
14885 if (CE && CE->getCastKind() == CK_NoOp)
14886 SubE = CE->getSubExpr();
14887 SubE = SubE->IgnoreParens();
14888 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
14889 SubE = BE->getSubExpr();
14890 if (isa<LambdaExpr>(Val: SubE)) {
14891 // For the conversion to block pointer on a lambda expression, we
14892 // construct a special BlockLiteral instead; this doesn't really make
14893 // a difference in ARC, but outside of ARC the resulting block literal
14894 // follows the normal lifetime rules for block literals instead of being
14895 // autoreleased.
14896 PushExpressionEvaluationContext(
14897 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
14898 ExprResult BlockExp = BuildBlockForLambdaConversion(
14899 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
14900 PopExpressionEvaluationContext();
14901
14902 // FIXME: This note should be produced by a CodeSynthesisContext.
14903 if (BlockExp.isInvalid())
14904 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14905 return BlockExp;
14906 }
14907 }
14908 CallExpr *CE;
14909 QualType ResultType = Method->getReturnType();
14910 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
14911 ResultType = ResultType.getNonLValueExprType(Context);
14912 if (Method->isExplicitObjectMemberFunction()) {
14913 ExprResult FnExpr =
14914 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14915 HadMultipleCandidates, E->getBeginLoc());
14916 if (FnExpr.isInvalid())
14917 return ExprError();
14918 Expr *ObjectParam = Exp.get();
14919 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
14920 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
14921 FPFeatures: CurFPFeatureOverrides());
14922 CE->setUsesMemberSyntax(true);
14923 } else {
14924 MemberExpr *ME =
14925 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
14926 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
14927 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
14928 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
14929 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
14930
14931 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
14932 RP: Exp.get()->getEndLoc(),
14933 FPFeatures: CurFPFeatureOverrides());
14934 }
14935
14936 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
14937 Proto: Method->getType()->castAs<FunctionProtoType>()))
14938 return ExprError();
14939
14940 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14941}
14942
14943ExprResult
14944Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14945 const UnresolvedSetImpl &Fns,
14946 Expr *Input, bool PerformADL) {
14947 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14948 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14949 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14950 // TODO: provide better source location info.
14951 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14952
14953 if (checkPlaceholderForOverload(S&: *this, E&: Input))
14954 return ExprError();
14955
14956 Expr *Args[2] = { Input, nullptr };
14957 unsigned NumArgs = 1;
14958
14959 // For post-increment and post-decrement, add the implicit '0' as
14960 // the second argument, so that we know this is a post-increment or
14961 // post-decrement.
14962 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14963 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14964 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14965 SourceLocation());
14966 NumArgs = 2;
14967 }
14968
14969 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14970
14971 if (Input->isTypeDependent()) {
14972 ExprValueKind VK = ExprValueKind::VK_PRValue;
14973 // [C++26][expr.unary.op][expr.pre.incr]
14974 // The * operator yields an lvalue of type
14975 // The pre/post increment operators yied an lvalue.
14976 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14977 VK = VK_LValue;
14978
14979 if (Fns.empty())
14980 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
14981 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
14982 FPFeatures: CurFPFeatureOverrides());
14983
14984 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14985 ExprResult Fn = CreateUnresolvedLookupExpr(
14986 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
14987 if (Fn.isInvalid())
14988 return ExprError();
14989 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
14990 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
14991 FPFeatures: CurFPFeatureOverrides());
14992 }
14993
14994 // Build an empty overload set.
14995 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14996
14997 // Add the candidates from the given function set.
14998 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
14999
15000 // Add operator candidates that are member functions.
15001 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15002
15003 // Add candidates from ADL.
15004 if (PerformADL) {
15005 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15006 /*ExplicitTemplateArgs*/nullptr,
15007 CandidateSet);
15008 }
15009
15010 // Add builtin operator candidates.
15011 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15012
15013 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15014
15015 // Perform overload resolution.
15016 OverloadCandidateSet::iterator Best;
15017 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15018 case OR_Success: {
15019 // We found a built-in operator or an overloaded operator.
15020 FunctionDecl *FnDecl = Best->Function;
15021
15022 if (FnDecl) {
15023 Expr *Base = nullptr;
15024 // We matched an overloaded operator. Build a call to that
15025 // operator.
15026
15027 // Convert the arguments.
15028 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15029 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15030
15031 ExprResult InputInit;
15032 if (Method->isExplicitObjectMemberFunction())
15033 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15034 else
15035 InputInit = PerformImplicitObjectArgumentInitialization(
15036 From: Input, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15037 if (InputInit.isInvalid())
15038 return ExprError();
15039 Base = Input = InputInit.get();
15040 } else {
15041 // Convert the arguments.
15042 ExprResult InputInit
15043 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15044 Context,
15045 Parm: FnDecl->getParamDecl(i: 0)),
15046 EqualLoc: SourceLocation(),
15047 Init: Input);
15048 if (InputInit.isInvalid())
15049 return ExprError();
15050 Input = InputInit.get();
15051 }
15052
15053 // Build the actual expression node.
15054 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15055 Base, HadMultipleCandidates,
15056 Loc: OpLoc);
15057 if (FnExpr.isInvalid())
15058 return ExprError();
15059
15060 // Determine the result type.
15061 QualType ResultTy = FnDecl->getReturnType();
15062 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15063 ResultTy = ResultTy.getNonLValueExprType(Context);
15064
15065 Args[0] = Input;
15066 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15067 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15068 FPFeatures: CurFPFeatureOverrides(),
15069 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15070
15071 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15072 return ExprError();
15073
15074 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15075 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15076 return ExprError();
15077 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall), Decl: FnDecl);
15078 } else {
15079 // We matched a built-in operator. Convert the arguments, then
15080 // break out so that we will build the appropriate built-in
15081 // operator node.
15082 ExprResult InputRes = PerformImplicitConversion(
15083 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15084 AssignmentAction::Passing,
15085 CheckedConversionKind::ForBuiltinOverloadedOp);
15086 if (InputRes.isInvalid())
15087 return ExprError();
15088 Input = InputRes.get();
15089 break;
15090 }
15091 }
15092
15093 case OR_No_Viable_Function:
15094 // This is an erroneous use of an operator which can be overloaded by
15095 // a non-member function. Check for non-member operators which were
15096 // defined too late to be candidates.
15097 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15098 // FIXME: Recover by calling the found function.
15099 return ExprError();
15100
15101 // No viable function; fall through to handling this as a
15102 // built-in operator, which will produce an error message for us.
15103 break;
15104
15105 case OR_Ambiguous:
15106 CandidateSet.NoteCandidates(
15107 PartialDiagnosticAt(OpLoc,
15108 PDiag(diag::err_ovl_ambiguous_oper_unary)
15109 << UnaryOperator::getOpcodeStr(Opc)
15110 << Input->getType() << Input->getSourceRange()),
15111 *this, OCD_AmbiguousCandidates, ArgsArray,
15112 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15113 return ExprError();
15114
15115 case OR_Deleted: {
15116 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15117 // object whose method was called. Later in NoteCandidates size of ArgsArray
15118 // is passed further and it eventually ends up compared to number of
15119 // function candidate parameters which never includes the object parameter,
15120 // so slice ArgsArray to make sure apples are compared to apples.
15121 StringLiteral *Msg = Best->Function->getDeletedMessage();
15122 CandidateSet.NoteCandidates(
15123 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15124 << UnaryOperator::getOpcodeStr(Opc)
15125 << (Msg != nullptr)
15126 << (Msg ? Msg->getString() : StringRef())
15127 << Input->getSourceRange()),
15128 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15129 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15130 return ExprError();
15131 }
15132 }
15133
15134 // Either we found no viable overloaded operator or we matched a
15135 // built-in operator. In either case, fall through to trying to
15136 // build a built-in operation.
15137 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15138}
15139
15140void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15141 OverloadedOperatorKind Op,
15142 const UnresolvedSetImpl &Fns,
15143 ArrayRef<Expr *> Args, bool PerformADL) {
15144 SourceLocation OpLoc = CandidateSet.getLocation();
15145
15146 OverloadedOperatorKind ExtraOp =
15147 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15148 ? getRewrittenOverloadedOperator(Kind: Op)
15149 : OO_None;
15150
15151 // Add the candidates from the given function set. This also adds the
15152 // rewritten candidates using these functions if necessary.
15153 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15154
15155 // As template candidates are not deduced immediately,
15156 // persist the array in the overload set.
15157 ArrayRef<Expr *> ReversedArgs;
15158 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15159 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15160 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15161
15162 // Add operator candidates that are member functions.
15163 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15164 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15165 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15166 PO: OverloadCandidateParamOrder::Reversed);
15167
15168 // In C++20, also add any rewritten member candidates.
15169 if (ExtraOp) {
15170 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15171 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15172 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15173 PO: OverloadCandidateParamOrder::Reversed);
15174 }
15175
15176 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15177 // performed for an assignment operator (nor for operator[] nor operator->,
15178 // which don't get here).
15179 if (Op != OO_Equal && PerformADL) {
15180 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15181 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15182 /*ExplicitTemplateArgs*/ nullptr,
15183 CandidateSet);
15184 if (ExtraOp) {
15185 DeclarationName ExtraOpName =
15186 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15187 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15188 /*ExplicitTemplateArgs*/ nullptr,
15189 CandidateSet);
15190 }
15191 }
15192
15193 // Add builtin operator candidates.
15194 //
15195 // FIXME: We don't add any rewritten candidates here. This is strictly
15196 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15197 // resulting in our selecting a rewritten builtin candidate. For example:
15198 //
15199 // enum class E { e };
15200 // bool operator!=(E, E) requires false;
15201 // bool k = E::e != E::e;
15202 //
15203 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15204 // it seems unreasonable to consider rewritten builtin candidates. A core
15205 // issue has been filed proposing to removed this requirement.
15206 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15207}
15208
15209ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15210 BinaryOperatorKind Opc,
15211 const UnresolvedSetImpl &Fns, Expr *LHS,
15212 Expr *RHS, bool PerformADL,
15213 bool AllowRewrittenCandidates,
15214 FunctionDecl *DefaultedFn) {
15215 Expr *Args[2] = { LHS, RHS };
15216 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15217
15218 if (!getLangOpts().CPlusPlus20)
15219 AllowRewrittenCandidates = false;
15220
15221 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15222
15223 // If either side is type-dependent, create an appropriate dependent
15224 // expression.
15225 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15226 if (Fns.empty()) {
15227 // If there are no functions to store, just build a dependent
15228 // BinaryOperator or CompoundAssignment.
15229 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15230 return CompoundAssignOperator::Create(
15231 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15232 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15233 CompResultType: Context.DependentTy);
15234 return BinaryOperator::Create(
15235 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15236 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15237 }
15238
15239 // FIXME: save results of ADL from here?
15240 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15241 // TODO: provide better source location info in DNLoc component.
15242 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15243 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15244 ExprResult Fn = CreateUnresolvedLookupExpr(
15245 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15246 if (Fn.isInvalid())
15247 return ExprError();
15248 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15249 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15250 FPFeatures: CurFPFeatureOverrides());
15251 }
15252
15253 // If this is the .* operator, which is not overloadable, just
15254 // create a built-in binary operator.
15255 if (Opc == BO_PtrMemD) {
15256 auto CheckPlaceholder = [&](Expr *&Arg) {
15257 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15258 if (Res.isUsable())
15259 Arg = Res.get();
15260 return !Res.isUsable();
15261 };
15262
15263 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15264 // expression that contains placeholders (in either the LHS or RHS).
15265 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15266 return ExprError();
15267 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15268 }
15269
15270 // Always do placeholder-like conversions on the RHS.
15271 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15272 return ExprError();
15273
15274 // Do placeholder-like conversion on the LHS; note that we should
15275 // not get here with a PseudoObject LHS.
15276 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15277 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15278 return ExprError();
15279
15280 // If this is the assignment operator, we only perform overload resolution
15281 // if the left-hand side is a class or enumeration type. This is actually
15282 // a hack. The standard requires that we do overload resolution between the
15283 // various built-in candidates, but as DR507 points out, this can lead to
15284 // problems. So we do it this way, which pretty much follows what GCC does.
15285 // Note that we go the traditional code path for compound assignment forms.
15286 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15287 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15288
15289 // Build the overload set.
15290 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15291 OverloadCandidateSet::OperatorRewriteInfo(
15292 Op, OpLoc, AllowRewrittenCandidates));
15293 if (DefaultedFn)
15294 CandidateSet.exclude(DefaultedFn);
15295 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15296
15297 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15298
15299 // Perform overload resolution.
15300 OverloadCandidateSet::iterator Best;
15301 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15302 case OR_Success: {
15303 // We found a built-in operator or an overloaded operator.
15304 FunctionDecl *FnDecl = Best->Function;
15305
15306 bool IsReversed = Best->isReversed();
15307 if (IsReversed)
15308 std::swap(a&: Args[0], b&: Args[1]);
15309
15310 if (FnDecl) {
15311
15312 if (FnDecl->isInvalidDecl())
15313 return ExprError();
15314
15315 Expr *Base = nullptr;
15316 // We matched an overloaded operator. Build a call to that
15317 // operator.
15318
15319 OverloadedOperatorKind ChosenOp =
15320 FnDecl->getDeclName().getCXXOverloadedOperator();
15321
15322 // C++2a [over.match.oper]p9:
15323 // If a rewritten operator== candidate is selected by overload
15324 // resolution for an operator@, its return type shall be cv bool
15325 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15326 !FnDecl->getReturnType()->isBooleanType()) {
15327 bool IsExtension =
15328 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15329 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15330 : diag::err_ovl_rewrite_equalequal_not_bool)
15331 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15332 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15333 Diag(FnDecl->getLocation(), diag::note_declared_at);
15334 if (!IsExtension)
15335 return ExprError();
15336 }
15337
15338 if (AllowRewrittenCandidates && !IsReversed &&
15339 CandidateSet.getRewriteInfo().isReversible()) {
15340 // We could have reversed this operator, but didn't. Check if some
15341 // reversed form was a viable candidate, and if so, if it had a
15342 // better conversion for either parameter. If so, this call is
15343 // formally ambiguous, and allowing it is an extension.
15344 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15345 for (OverloadCandidate &Cand : CandidateSet) {
15346 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15347 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15348 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15349 if (CompareImplicitConversionSequences(
15350 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15351 ICS2: Best->Conversions[ArgIdx]) ==
15352 ImplicitConversionSequence::Better) {
15353 AmbiguousWith.push_back(Elt: Cand.Function);
15354 break;
15355 }
15356 }
15357 }
15358 }
15359
15360 if (!AmbiguousWith.empty()) {
15361 bool AmbiguousWithSelf =
15362 AmbiguousWith.size() == 1 &&
15363 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15364 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15365 << BinaryOperator::getOpcodeStr(Opc)
15366 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15367 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15368 if (AmbiguousWithSelf) {
15369 Diag(FnDecl->getLocation(),
15370 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15371 // Mark member== const or provide matching != to disallow reversed
15372 // args. Eg.
15373 // struct S { bool operator==(const S&); };
15374 // S()==S();
15375 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15376 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15377 !MD->isConst() &&
15378 !MD->hasCXXExplicitFunctionObjectParameter() &&
15379 Context.hasSameUnqualifiedType(
15380 MD->getFunctionObjectParameterType(),
15381 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15382 Context.hasSameUnqualifiedType(
15383 MD->getFunctionObjectParameterType(),
15384 Args[0]->getType()) &&
15385 Context.hasSameUnqualifiedType(
15386 MD->getFunctionObjectParameterType(),
15387 Args[1]->getType()))
15388 Diag(FnDecl->getLocation(),
15389 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15390 } else {
15391 Diag(FnDecl->getLocation(),
15392 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15393 for (auto *F : AmbiguousWith)
15394 Diag(F->getLocation(),
15395 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15396 }
15397 }
15398 }
15399
15400 // Check for nonnull = nullable.
15401 // This won't be caught in the arg's initialization: the parameter to
15402 // the assignment operator is not marked nonnull.
15403 if (Op == OO_Equal)
15404 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15405 SrcType: Args[1]->getType(), Loc: OpLoc);
15406
15407 // Convert the arguments.
15408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15409 // Best->Access is only meaningful for class members.
15410 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15411
15412 ExprResult Arg0, Arg1;
15413 unsigned ParamIdx = 0;
15414 if (Method->isExplicitObjectMemberFunction()) {
15415 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15416 ParamIdx = 1;
15417 } else {
15418 Arg0 = PerformImplicitObjectArgumentInitialization(
15419 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15420 }
15421 Arg1 = PerformCopyInitialization(
15422 Entity: InitializedEntity::InitializeParameter(
15423 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15424 EqualLoc: SourceLocation(), Init: Args[1]);
15425 if (Arg0.isInvalid() || Arg1.isInvalid())
15426 return ExprError();
15427
15428 Base = Args[0] = Arg0.getAs<Expr>();
15429 Args[1] = RHS = Arg1.getAs<Expr>();
15430 } else {
15431 // Convert the arguments.
15432 ExprResult Arg0 = PerformCopyInitialization(
15433 Entity: InitializedEntity::InitializeParameter(Context,
15434 Parm: FnDecl->getParamDecl(i: 0)),
15435 EqualLoc: SourceLocation(), Init: Args[0]);
15436 if (Arg0.isInvalid())
15437 return ExprError();
15438
15439 ExprResult Arg1 =
15440 PerformCopyInitialization(
15441 Entity: InitializedEntity::InitializeParameter(Context,
15442 Parm: FnDecl->getParamDecl(i: 1)),
15443 EqualLoc: SourceLocation(), Init: Args[1]);
15444 if (Arg1.isInvalid())
15445 return ExprError();
15446 Args[0] = LHS = Arg0.getAs<Expr>();
15447 Args[1] = RHS = Arg1.getAs<Expr>();
15448 }
15449
15450 // Build the actual expression node.
15451 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15452 FoundDecl: Best->FoundDecl, Base,
15453 HadMultipleCandidates, Loc: OpLoc);
15454 if (FnExpr.isInvalid())
15455 return ExprError();
15456
15457 // Determine the result type.
15458 QualType ResultTy = FnDecl->getReturnType();
15459 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15460 ResultTy = ResultTy.getNonLValueExprType(Context);
15461
15462 CallExpr *TheCall;
15463 ArrayRef<const Expr *> ArgsArray(Args, 2);
15464 const Expr *ImplicitThis = nullptr;
15465
15466 // We always create a CXXOperatorCallExpr, even for explicit object
15467 // members; CodeGen should take care not to emit the this pointer.
15468 TheCall = CXXOperatorCallExpr::Create(
15469 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15470 FPFeatures: CurFPFeatureOverrides(),
15471 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15472
15473 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15474 Method && Method->isImplicitObjectMemberFunction()) {
15475 // Cut off the implicit 'this'.
15476 ImplicitThis = ArgsArray[0];
15477 ArgsArray = ArgsArray.slice(N: 1);
15478 }
15479
15480 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15481 FD: FnDecl))
15482 return ExprError();
15483
15484 if (Op == OO_Equal) {
15485 // Check for a self move.
15486 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15487 // lifetime check.
15488 checkAssignmentLifetime(
15489 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15490 Init: Args[1]);
15491 }
15492 if (ImplicitThis) {
15493 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15494 QualType ThisTypeFromDecl = Context.getPointerType(
15495 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15496
15497 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15498 ThisTypeFromDecl);
15499 }
15500
15501 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15502 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15503 CallType: VariadicCallType::DoesNotApply);
15504
15505 ExprResult R = MaybeBindToTemporary(TheCall);
15506 if (R.isInvalid())
15507 return ExprError();
15508
15509 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15510 if (R.isInvalid())
15511 return ExprError();
15512
15513 // For a rewritten candidate, we've already reversed the arguments
15514 // if needed. Perform the rest of the rewrite now.
15515 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15516 (Op == OO_Spaceship && IsReversed)) {
15517 if (Op == OO_ExclaimEqual) {
15518 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15519 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15520 } else {
15521 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15522 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15523 Expr *ZeroLiteral =
15524 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
15525
15526 Sema::CodeSynthesisContext Ctx;
15527 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15528 Ctx.Entity = FnDecl;
15529 pushCodeSynthesisContext(Ctx);
15530
15531 R = CreateOverloadedBinOp(
15532 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15533 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15534 /*AllowRewrittenCandidates=*/false);
15535
15536 popCodeSynthesisContext();
15537 }
15538 if (R.isInvalid())
15539 return ExprError();
15540 } else {
15541 assert(ChosenOp == Op && "unexpected operator name");
15542 }
15543
15544 // Make a note in the AST if we did any rewriting.
15545 if (Best->RewriteKind != CRK_None)
15546 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15547
15548 return R;
15549 } else {
15550 // We matched a built-in operator. Convert the arguments, then
15551 // break out so that we will build the appropriate built-in
15552 // operator node.
15553 ExprResult ArgsRes0 = PerformImplicitConversion(
15554 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15555 AssignmentAction::Passing,
15556 CheckedConversionKind::ForBuiltinOverloadedOp);
15557 if (ArgsRes0.isInvalid())
15558 return ExprError();
15559 Args[0] = ArgsRes0.get();
15560
15561 ExprResult ArgsRes1 = PerformImplicitConversion(
15562 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15563 AssignmentAction::Passing,
15564 CheckedConversionKind::ForBuiltinOverloadedOp);
15565 if (ArgsRes1.isInvalid())
15566 return ExprError();
15567 Args[1] = ArgsRes1.get();
15568 break;
15569 }
15570 }
15571
15572 case OR_No_Viable_Function: {
15573 // C++ [over.match.oper]p9:
15574 // If the operator is the operator , [...] and there are no
15575 // viable functions, then the operator is assumed to be the
15576 // built-in operator and interpreted according to clause 5.
15577 if (Opc == BO_Comma)
15578 break;
15579
15580 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15581 // compare result using '==' and '<'.
15582 if (DefaultedFn && Opc == BO_Cmp) {
15583 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15584 RHS: Args[1], DefaultedFn);
15585 if (E.isInvalid() || E.isUsable())
15586 return E;
15587 }
15588
15589 // For class as left operand for assignment or compound assignment
15590 // operator do not fall through to handling in built-in, but report that
15591 // no overloaded assignment operator found
15592 ExprResult Result = ExprError();
15593 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15594 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15595 Args, OpLoc);
15596 DeferDiagsRAII DDR(*this,
15597 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15598 if (Args[0]->getType()->isRecordType() &&
15599 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15600 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15601 << BinaryOperator::getOpcodeStr(Opc)
15602 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15603 if (Args[0]->getType()->isIncompleteType()) {
15604 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15605 << Args[0]->getType()
15606 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15607 }
15608 } else {
15609 // This is an erroneous use of an operator which can be overloaded by
15610 // a non-member function. Check for non-member operators which were
15611 // defined too late to be candidates.
15612 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15613 // FIXME: Recover by calling the found function.
15614 return ExprError();
15615
15616 // No viable function; try to create a built-in operation, which will
15617 // produce an error. Then, show the non-viable candidates.
15618 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15619 }
15620 assert(Result.isInvalid() &&
15621 "C++ binary operator overloading is missing candidates!");
15622 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15623 return Result;
15624 }
15625
15626 case OR_Ambiguous:
15627 CandidateSet.NoteCandidates(
15628 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15629 << BinaryOperator::getOpcodeStr(Opc)
15630 << Args[0]->getType()
15631 << Args[1]->getType()
15632 << Args[0]->getSourceRange()
15633 << Args[1]->getSourceRange()),
15634 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15635 OpLoc);
15636 return ExprError();
15637
15638 case OR_Deleted: {
15639 if (isImplicitlyDeleted(FD: Best->Function)) {
15640 FunctionDecl *DeletedFD = Best->Function;
15641 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15642 if (DFK.isSpecialMember()) {
15643 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15644 << Args[0]->getType() << DFK.asSpecialMember();
15645 } else {
15646 assert(DFK.isComparison());
15647 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15648 << Args[0]->getType() << DeletedFD;
15649 }
15650
15651 // The user probably meant to call this special member. Just
15652 // explain why it's deleted.
15653 NoteDeletedFunction(FD: DeletedFD);
15654 return ExprError();
15655 }
15656
15657 StringLiteral *Msg = Best->Function->getDeletedMessage();
15658 CandidateSet.NoteCandidates(
15659 PartialDiagnosticAt(
15660 OpLoc,
15661 PDiag(diag::err_ovl_deleted_oper)
15662 << getOperatorSpelling(Best->Function->getDeclName()
15663 .getCXXOverloadedOperator())
15664 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15665 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15666 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15667 OpLoc);
15668 return ExprError();
15669 }
15670 }
15671
15672 // We matched a built-in operator; build it.
15673 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15674}
15675
15676ExprResult Sema::BuildSynthesizedThreeWayComparison(
15677 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15678 FunctionDecl *DefaultedFn) {
15679 const ComparisonCategoryInfo *Info =
15680 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15681 // If we're not producing a known comparison category type, we can't
15682 // synthesize a three-way comparison. Let the caller diagnose this.
15683 if (!Info)
15684 return ExprResult((Expr*)nullptr);
15685
15686 // If we ever want to perform this synthesis more generally, we will need to
15687 // apply the temporary materialization conversion to the operands.
15688 assert(LHS->isGLValue() && RHS->isGLValue() &&
15689 "cannot use prvalue expressions more than once");
15690 Expr *OrigLHS = LHS;
15691 Expr *OrigRHS = RHS;
15692
15693 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15694 // each of them multiple times below.
15695 LHS = new (Context)
15696 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15697 LHS->getObjectKind(), LHS);
15698 RHS = new (Context)
15699 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15700 RHS->getObjectKind(), RHS);
15701
15702 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15703 DefaultedFn);
15704 if (Eq.isInvalid())
15705 return ExprError();
15706
15707 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15708 AllowRewrittenCandidates: true, DefaultedFn);
15709 if (Less.isInvalid())
15710 return ExprError();
15711
15712 ExprResult Greater;
15713 if (Info->isPartial()) {
15714 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15715 DefaultedFn);
15716 if (Greater.isInvalid())
15717 return ExprError();
15718 }
15719
15720 // Form the list of comparisons we're going to perform.
15721 struct Comparison {
15722 ExprResult Cmp;
15723 ComparisonCategoryResult Result;
15724 } Comparisons[4] =
15725 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15726 : ComparisonCategoryResult::Equivalent},
15727 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15728 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15729 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15730 };
15731
15732 int I = Info->isPartial() ? 3 : 2;
15733
15734 // Combine the comparisons with suitable conditional expressions.
15735 ExprResult Result;
15736 for (; I >= 0; --I) {
15737 // Build a reference to the comparison category constant.
15738 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15739 // FIXME: Missing a constant for a comparison category. Diagnose this?
15740 if (!VI)
15741 return ExprResult((Expr*)nullptr);
15742 ExprResult ThisResult =
15743 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15744 if (ThisResult.isInvalid())
15745 return ExprError();
15746
15747 // Build a conditional unless this is the final case.
15748 if (Result.get()) {
15749 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15750 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15751 if (Result.isInvalid())
15752 return ExprError();
15753 } else {
15754 Result = ThisResult;
15755 }
15756 }
15757
15758 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15759 // bind the OpaqueValueExprs before they're (repeatedly) used.
15760 Expr *SyntacticForm = BinaryOperator::Create(
15761 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15762 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15763 FPFeatures: CurFPFeatureOverrides());
15764 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15765 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15766}
15767
15768static bool PrepareArgumentsForCallToObjectOfClassType(
15769 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15770 MultiExprArg Args, SourceLocation LParenLoc) {
15771
15772 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15773 unsigned NumParams = Proto->getNumParams();
15774 unsigned NumArgsSlots =
15775 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
15776 // Build the full argument list for the method call (the implicit object
15777 // parameter is placed at the beginning of the list).
15778 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
15779 bool IsError = false;
15780 // Initialize the implicit object parameter.
15781 // Check the argument types.
15782 for (unsigned i = 0; i != NumParams; i++) {
15783 Expr *Arg;
15784 if (i < Args.size()) {
15785 Arg = Args[i];
15786 ExprResult InputInit =
15787 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15788 S.Context, Method->getParamDecl(i)),
15789 EqualLoc: SourceLocation(), Init: Arg);
15790 IsError |= InputInit.isInvalid();
15791 Arg = InputInit.getAs<Expr>();
15792 } else {
15793 ExprResult DefArg =
15794 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
15795 if (DefArg.isInvalid()) {
15796 IsError = true;
15797 break;
15798 }
15799 Arg = DefArg.getAs<Expr>();
15800 }
15801
15802 MethodArgs.push_back(Elt: Arg);
15803 }
15804 return IsError;
15805}
15806
15807ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15808 SourceLocation RLoc,
15809 Expr *Base,
15810 MultiExprArg ArgExpr) {
15811 SmallVector<Expr *, 2> Args;
15812 Args.push_back(Elt: Base);
15813 for (auto *e : ArgExpr) {
15814 Args.push_back(Elt: e);
15815 }
15816 DeclarationName OpName =
15817 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
15818
15819 SourceRange Range = ArgExpr.empty()
15820 ? SourceRange{}
15821 : SourceRange(ArgExpr.front()->getBeginLoc(),
15822 ArgExpr.back()->getEndLoc());
15823
15824 // If either side is type-dependent, create an appropriate dependent
15825 // expression.
15826 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
15827
15828 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15829 // CHECKME: no 'operator' keyword?
15830 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15831 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15832 ExprResult Fn = CreateUnresolvedLookupExpr(
15833 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
15834 if (Fn.isInvalid())
15835 return ExprError();
15836 // Can't add any actual overloads yet
15837
15838 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
15839 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
15840 FPFeatures: CurFPFeatureOverrides());
15841 }
15842
15843 // Handle placeholders
15844 UnbridgedCastsSet UnbridgedCasts;
15845 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
15846 return ExprError();
15847 }
15848 // Build an empty overload set.
15849 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15850
15851 // Subscript can only be overloaded as a member function.
15852
15853 // Add operator candidates that are member functions.
15854 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15855
15856 // Add builtin operator candidates.
15857 if (Args.size() == 2)
15858 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
15859
15860 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15861
15862 // Perform overload resolution.
15863 OverloadCandidateSet::iterator Best;
15864 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
15865 case OR_Success: {
15866 // We found a built-in operator or an overloaded operator.
15867 FunctionDecl *FnDecl = Best->Function;
15868
15869 if (FnDecl) {
15870 // We matched an overloaded operator. Build a call to that
15871 // operator.
15872
15873 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
15874
15875 // Convert the arguments.
15876 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
15877 SmallVector<Expr *, 2> MethodArgs;
15878
15879 // Initialize the object parameter.
15880 if (Method->isExplicitObjectMemberFunction()) {
15881 ExprResult Res =
15882 InitializeExplicitObjectArgument(*this, Args[0], Method);
15883 if (Res.isInvalid())
15884 return ExprError();
15885 Args[0] = Res.get();
15886 ArgExpr = Args;
15887 } else {
15888 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15889 From: Args[0], /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
15890 if (Arg0.isInvalid())
15891 return ExprError();
15892
15893 MethodArgs.push_back(Elt: Arg0.get());
15894 }
15895
15896 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15897 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
15898 if (IsError)
15899 return ExprError();
15900
15901 // Build the actual expression node.
15902 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15903 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15904 ExprResult FnExpr = CreateFunctionRefExpr(
15905 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
15906 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
15907 if (FnExpr.isInvalid())
15908 return ExprError();
15909
15910 // Determine the result type
15911 QualType ResultTy = FnDecl->getReturnType();
15912 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15913 ResultTy = ResultTy.getNonLValueExprType(Context);
15914
15915 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15916 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
15917 FPFeatures: CurFPFeatureOverrides());
15918
15919 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
15920 return ExprError();
15921
15922 if (CheckFunctionCall(FDecl: Method, TheCall,
15923 Proto: Method->getType()->castAs<FunctionProtoType>()))
15924 return ExprError();
15925
15926 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall),
15927 Decl: FnDecl);
15928 } else {
15929 // We matched a built-in operator. Convert the arguments, then
15930 // break out so that we will build the appropriate built-in
15931 // operator node.
15932 ExprResult ArgsRes0 = PerformImplicitConversion(
15933 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15934 AssignmentAction::Passing,
15935 CheckedConversionKind::ForBuiltinOverloadedOp);
15936 if (ArgsRes0.isInvalid())
15937 return ExprError();
15938 Args[0] = ArgsRes0.get();
15939
15940 ExprResult ArgsRes1 = PerformImplicitConversion(
15941 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15942 AssignmentAction::Passing,
15943 CheckedConversionKind::ForBuiltinOverloadedOp);
15944 if (ArgsRes1.isInvalid())
15945 return ExprError();
15946 Args[1] = ArgsRes1.get();
15947
15948 break;
15949 }
15950 }
15951
15952 case OR_No_Viable_Function: {
15953 PartialDiagnostic PD =
15954 CandidateSet.empty()
15955 ? (PDiag(diag::err_ovl_no_oper)
15956 << Args[0]->getType() << /*subscript*/ 0
15957 << Args[0]->getSourceRange() << Range)
15958 : (PDiag(diag::err_ovl_no_viable_subscript)
15959 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15960 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
15961 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
15962 return ExprError();
15963 }
15964
15965 case OR_Ambiguous:
15966 if (Args.size() == 2) {
15967 CandidateSet.NoteCandidates(
15968 PartialDiagnosticAt(
15969 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15970 << "[]" << Args[0]->getType() << Args[1]->getType()
15971 << Args[0]->getSourceRange() << Range),
15972 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15973 } else {
15974 CandidateSet.NoteCandidates(
15975 PartialDiagnosticAt(LLoc,
15976 PDiag(diag::err_ovl_ambiguous_subscript_call)
15977 << Args[0]->getType()
15978 << Args[0]->getSourceRange() << Range),
15979 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15980 }
15981 return ExprError();
15982
15983 case OR_Deleted: {
15984 StringLiteral *Msg = Best->Function->getDeletedMessage();
15985 CandidateSet.NoteCandidates(
15986 PartialDiagnosticAt(LLoc,
15987 PDiag(diag::err_ovl_deleted_oper)
15988 << "[]" << (Msg != nullptr)
15989 << (Msg ? Msg->getString() : StringRef())
15990 << Args[0]->getSourceRange() << Range),
15991 *this, OCD_AllCandidates, Args, "[]", LLoc);
15992 return ExprError();
15993 }
15994 }
15995
15996 // We matched a built-in operator; build it.
15997 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
15998}
15999
16000ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16001 SourceLocation LParenLoc,
16002 MultiExprArg Args,
16003 SourceLocation RParenLoc,
16004 Expr *ExecConfig, bool IsExecConfig,
16005 bool AllowRecovery) {
16006 assert(MemExprE->getType() == Context.BoundMemberTy ||
16007 MemExprE->getType() == Context.OverloadTy);
16008
16009 // Dig out the member expression. This holds both the object
16010 // argument and the member function we're referring to.
16011 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16012
16013 // Determine whether this is a call to a pointer-to-member function.
16014 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16015 assert(op->getType() == Context.BoundMemberTy);
16016 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16017
16018 QualType fnType =
16019 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16020
16021 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16022 QualType resultType = proto->getCallResultType(Context);
16023 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16024
16025 // Check that the object type isn't more qualified than the
16026 // member function we're calling.
16027 Qualifiers funcQuals = proto->getMethodQuals();
16028
16029 QualType objectType = op->getLHS()->getType();
16030 if (op->getOpcode() == BO_PtrMemI)
16031 objectType = objectType->castAs<PointerType>()->getPointeeType();
16032 Qualifiers objectQuals = objectType.getQualifiers();
16033
16034 Qualifiers difference = objectQuals - funcQuals;
16035 difference.removeObjCGCAttr();
16036 difference.removeAddressSpace();
16037 if (difference) {
16038 std::string qualsString = difference.getAsString();
16039 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16040 << fnType.getUnqualifiedType()
16041 << qualsString
16042 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16043 }
16044
16045 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16046 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16047 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16048
16049 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16050 CE: call, FD: nullptr))
16051 return ExprError();
16052
16053 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16054 return ExprError();
16055
16056 if (CheckOtherCall(call, proto))
16057 return ExprError();
16058
16059 return MaybeBindToTemporary(call);
16060 }
16061
16062 // We only try to build a recovery expr at this level if we can preserve
16063 // the return type, otherwise we return ExprError() and let the caller
16064 // recover.
16065 auto BuildRecoveryExpr = [&](QualType Type) {
16066 if (!AllowRecovery)
16067 return ExprError();
16068 std::vector<Expr *> SubExprs = {MemExprE};
16069 llvm::append_range(C&: SubExprs, R&: Args);
16070 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16071 Type);
16072 };
16073 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16074 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16075 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16076
16077 UnbridgedCastsSet UnbridgedCasts;
16078 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16079 return ExprError();
16080
16081 MemberExpr *MemExpr;
16082 CXXMethodDecl *Method = nullptr;
16083 bool HadMultipleCandidates = false;
16084 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16085 NestedNameSpecifier *Qualifier = nullptr;
16086 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16087 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16088 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16089 FoundDecl = MemExpr->getFoundDecl();
16090 Qualifier = MemExpr->getQualifier();
16091 UnbridgedCasts.restore();
16092 } else {
16093 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16094 Qualifier = UnresExpr->getQualifier();
16095
16096 QualType ObjectType = UnresExpr->getBaseType();
16097 Expr::Classification ObjectClassification
16098 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16099 : UnresExpr->getBase()->Classify(Ctx&: Context);
16100
16101 // Add overload candidates
16102 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16103 OverloadCandidateSet::CSK_Normal);
16104
16105 // FIXME: avoid copy.
16106 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16107 if (UnresExpr->hasExplicitTemplateArgs()) {
16108 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16109 TemplateArgs = &TemplateArgsBuffer;
16110 }
16111
16112 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16113 E = UnresExpr->decls_end(); I != E; ++I) {
16114
16115 QualType ExplicitObjectType = ObjectType;
16116
16117 NamedDecl *Func = *I;
16118 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16119 if (isa<UsingShadowDecl>(Val: Func))
16120 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16121
16122 bool HasExplicitParameter = false;
16123 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16124 M && M->hasCXXExplicitFunctionObjectParameter())
16125 HasExplicitParameter = true;
16126 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16127 M &&
16128 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16129 HasExplicitParameter = true;
16130
16131 if (HasExplicitParameter)
16132 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16133
16134 // Microsoft supports direct constructor calls.
16135 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16136 AddOverloadCandidate(cast<CXXConstructorDecl>(Val: Func), I.getPair(), Args,
16137 CandidateSet,
16138 /*SuppressUserConversions*/ false);
16139 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16140 // If explicit template arguments were provided, we can't call a
16141 // non-template member function.
16142 if (TemplateArgs)
16143 continue;
16144
16145 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16146 ObjectClassification, Args, CandidateSet,
16147 /*SuppressUserConversions=*/false);
16148 } else {
16149 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16150 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16151 ObjectType: ExplicitObjectType, ObjectClassification,
16152 Args, CandidateSet,
16153 /*SuppressUserConversions=*/false);
16154 }
16155 }
16156
16157 HadMultipleCandidates = (CandidateSet.size() > 1);
16158
16159 DeclarationName DeclName = UnresExpr->getMemberName();
16160
16161 UnbridgedCasts.restore();
16162
16163 OverloadCandidateSet::iterator Best;
16164 bool Succeeded = false;
16165 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16166 Best)) {
16167 case OR_Success:
16168 Method = cast<CXXMethodDecl>(Val: Best->Function);
16169 FoundDecl = Best->FoundDecl;
16170 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16171 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16172 break;
16173 // If FoundDecl is different from Method (such as if one is a template
16174 // and the other a specialization), make sure DiagnoseUseOfDecl is
16175 // called on both.
16176 // FIXME: This would be more comprehensively addressed by modifying
16177 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16178 // being used.
16179 if (Method != FoundDecl.getDecl() &&
16180 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16181 break;
16182 Succeeded = true;
16183 break;
16184
16185 case OR_No_Viable_Function:
16186 CandidateSet.NoteCandidates(
16187 PartialDiagnosticAt(
16188 UnresExpr->getMemberLoc(),
16189 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16190 << DeclName << MemExprE->getSourceRange()),
16191 *this, OCD_AllCandidates, Args);
16192 break;
16193 case OR_Ambiguous:
16194 CandidateSet.NoteCandidates(
16195 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16196 PDiag(diag::err_ovl_ambiguous_member_call)
16197 << DeclName << MemExprE->getSourceRange()),
16198 *this, OCD_AmbiguousCandidates, Args);
16199 break;
16200 case OR_Deleted:
16201 DiagnoseUseOfDeletedFunction(
16202 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16203 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16204 break;
16205 }
16206 // Overload resolution fails, try to recover.
16207 if (!Succeeded)
16208 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16209
16210 ExprResult Res =
16211 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16212 if (Res.isInvalid())
16213 return ExprError();
16214 MemExprE = Res.get();
16215
16216 // If overload resolution picked a static member
16217 // build a non-member call based on that function.
16218 if (Method->isStatic()) {
16219 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16220 ExecConfig, IsExecConfig);
16221 }
16222
16223 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16224 }
16225
16226 QualType ResultType = Method->getReturnType();
16227 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16228 ResultType = ResultType.getNonLValueExprType(Context);
16229
16230 assert(Method && "Member call to something that isn't a method?");
16231 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16232
16233 CallExpr *TheCall = nullptr;
16234 llvm::SmallVector<Expr *, 8> NewArgs;
16235 if (Method->isExplicitObjectMemberFunction()) {
16236 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16237 NewArgs))
16238 return ExprError();
16239
16240 // Build the actual expression node.
16241 ExprResult FnExpr =
16242 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16243 HadMultipleCandidates, MemExpr->getExprLoc());
16244 if (FnExpr.isInvalid())
16245 return ExprError();
16246
16247 TheCall =
16248 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16249 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16250 TheCall->setUsesMemberSyntax(true);
16251 } else {
16252 // Convert the object argument (for a non-static member function call).
16253 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16254 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16255 if (ObjectArg.isInvalid())
16256 return ExprError();
16257 MemExpr->setBase(ObjectArg.get());
16258 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16259 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16260 MinNumArgs: Proto->getNumParams());
16261 }
16262
16263 // Check for a valid return type.
16264 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16265 CE: TheCall, FD: Method))
16266 return BuildRecoveryExpr(ResultType);
16267
16268 // Convert the rest of the arguments
16269 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto: Proto, Args,
16270 RParenLoc))
16271 return BuildRecoveryExpr(ResultType);
16272
16273 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16274
16275 if (CheckFunctionCall(FDecl: Method, TheCall, Proto: Proto))
16276 return ExprError();
16277
16278 // In the case the method to call was not selected by the overloading
16279 // resolution process, we still need to handle the enable_if attribute. Do
16280 // that here, so it will not hide previous -- and more relevant -- errors.
16281 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16282 if (const EnableIfAttr *Attr =
16283 CheckEnableIf(Method, LParenLoc, Args, true)) {
16284 Diag(MemE->getMemberLoc(),
16285 diag::err_ovl_no_viable_member_function_in_call)
16286 << Method << Method->getSourceRange();
16287 Diag(Method->getLocation(),
16288 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16289 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16290 return ExprError();
16291 }
16292 }
16293
16294 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16295 TheCall->getDirectCallee()->isPureVirtual()) {
16296 const FunctionDecl *MD = TheCall->getDirectCallee();
16297
16298 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16299 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16300 Diag(MemExpr->getBeginLoc(),
16301 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16302 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
16303 << MD->getParent();
16304
16305 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16306 if (getLangOpts().AppleKext)
16307 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16308 << MD->getParent() << MD->getDeclName();
16309 }
16310 }
16311
16312 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16313 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16314 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16315 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16316 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16317 DtorLoc: MemExpr->getMemberLoc());
16318 }
16319
16320 return CheckForImmediateInvocation(E: MaybeBindToTemporary(TheCall),
16321 Decl: TheCall->getDirectCallee());
16322}
16323
16324ExprResult
16325Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16326 SourceLocation LParenLoc,
16327 MultiExprArg Args,
16328 SourceLocation RParenLoc) {
16329 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16330 return ExprError();
16331 ExprResult Object = Obj;
16332
16333 UnbridgedCastsSet UnbridgedCasts;
16334 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16335 return ExprError();
16336
16337 assert(Object.get()->getType()->isRecordType() &&
16338 "Requires object type argument");
16339
16340 // C++ [over.call.object]p1:
16341 // If the primary-expression E in the function call syntax
16342 // evaluates to a class object of type "cv T", then the set of
16343 // candidate functions includes at least the function call
16344 // operators of T. The function call operators of T are obtained by
16345 // ordinary lookup of the name operator() in the context of
16346 // (E).operator().
16347 OverloadCandidateSet CandidateSet(LParenLoc,
16348 OverloadCandidateSet::CSK_Operator);
16349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16350
16351 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16352 diag::err_incomplete_object_call, Object.get()))
16353 return true;
16354
16355 const auto *Record = Object.get()->getType()->castAs<RecordType>();
16356 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16357 LookupQualifiedName(R, Record->getDecl());
16358 R.suppressAccessDiagnostics();
16359
16360 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16361 Oper != OperEnd; ++Oper) {
16362 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16363 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16364 /*SuppressUserConversion=*/SuppressUserConversions: false);
16365 }
16366
16367 // When calling a lambda, both the call operator, and
16368 // the conversion operator to function pointer
16369 // are considered. But when constraint checking
16370 // on the call operator fails, it will also fail on the
16371 // conversion operator as the constraints are always the same.
16372 // As the user probably does not intend to perform a surrogate call,
16373 // we filter them out to produce better error diagnostics, ie to avoid
16374 // showing 2 failed overloads instead of one.
16375 bool IgnoreSurrogateFunctions = false;
16376 if (CandidateSet.nonDeferredCandidatesCount() == 1 &&
16377 Record->getAsCXXRecordDecl()->isLambda()) {
16378 const OverloadCandidate &Candidate = *CandidateSet.begin();
16379 if (!Candidate.Viable &&
16380 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16381 IgnoreSurrogateFunctions = true;
16382 }
16383
16384 // C++ [over.call.object]p2:
16385 // In addition, for each (non-explicit in C++0x) conversion function
16386 // declared in T of the form
16387 //
16388 // operator conversion-type-id () cv-qualifier;
16389 //
16390 // where cv-qualifier is the same cv-qualification as, or a
16391 // greater cv-qualification than, cv, and where conversion-type-id
16392 // denotes the type "pointer to function of (P1,...,Pn) returning
16393 // R", or the type "reference to pointer to function of
16394 // (P1,...,Pn) returning R", or the type "reference to function
16395 // of (P1,...,Pn) returning R", a surrogate call function [...]
16396 // is also considered as a candidate function. Similarly,
16397 // surrogate call functions are added to the set of candidate
16398 // functions for each conversion function declared in an
16399 // accessible base class provided the function is not hidden
16400 // within T by another intervening declaration.
16401 const auto &Conversions =
16402 cast<CXXRecordDecl>(Val: Record->getDecl())->getVisibleConversionFunctions();
16403 for (auto I = Conversions.begin(), E = Conversions.end();
16404 !IgnoreSurrogateFunctions && I != E; ++I) {
16405 NamedDecl *D = *I;
16406 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16407 if (isa<UsingShadowDecl>(Val: D))
16408 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16409
16410 // Skip over templated conversion functions; they aren't
16411 // surrogates.
16412 if (isa<FunctionTemplateDecl>(Val: D))
16413 continue;
16414
16415 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16416 if (!Conv->isExplicit()) {
16417 // Strip the reference type (if any) and then the pointer type (if
16418 // any) to get down to what might be a function type.
16419 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16420 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16421 ConvType = ConvPtrType->getPointeeType();
16422
16423 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16424 {
16425 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16426 Object: Object.get(), Args, CandidateSet);
16427 }
16428 }
16429 }
16430
16431 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16432
16433 // Perform overload resolution.
16434 OverloadCandidateSet::iterator Best;
16435 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16436 Best)) {
16437 case OR_Success:
16438 // Overload resolution succeeded; we'll build the appropriate call
16439 // below.
16440 break;
16441
16442 case OR_No_Viable_Function: {
16443 PartialDiagnostic PD =
16444 CandidateSet.empty()
16445 ? (PDiag(diag::err_ovl_no_oper)
16446 << Object.get()->getType() << /*call*/ 1
16447 << Object.get()->getSourceRange())
16448 : (PDiag(diag::err_ovl_no_viable_object_call)
16449 << Object.get()->getType() << Object.get()->getSourceRange());
16450 CandidateSet.NoteCandidates(
16451 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16452 OCD: OCD_AllCandidates, Args);
16453 break;
16454 }
16455 case OR_Ambiguous:
16456 if (!R.isAmbiguous())
16457 CandidateSet.NoteCandidates(
16458 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16459 PDiag(diag::err_ovl_ambiguous_object_call)
16460 << Object.get()->getType()
16461 << Object.get()->getSourceRange()),
16462 *this, OCD_AmbiguousCandidates, Args);
16463 break;
16464
16465 case OR_Deleted: {
16466 // FIXME: Is this diagnostic here really necessary? It seems that
16467 // 1. we don't have any tests for this diagnostic, and
16468 // 2. we already issue err_deleted_function_use for this later on anyway.
16469 StringLiteral *Msg = Best->Function->getDeletedMessage();
16470 CandidateSet.NoteCandidates(
16471 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16472 PDiag(diag::err_ovl_deleted_object_call)
16473 << Object.get()->getType() << (Msg != nullptr)
16474 << (Msg ? Msg->getString() : StringRef())
16475 << Object.get()->getSourceRange()),
16476 *this, OCD_AllCandidates, Args);
16477 break;
16478 }
16479 }
16480
16481 if (Best == CandidateSet.end())
16482 return true;
16483
16484 UnbridgedCasts.restore();
16485
16486 if (Best->Function == nullptr) {
16487 // Since there is no function declaration, this is one of the
16488 // surrogate candidates. Dig out the conversion function.
16489 CXXConversionDecl *Conv
16490 = cast<CXXConversionDecl>(
16491 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16492
16493 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16494 FoundDecl: Best->FoundDecl);
16495 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16496 return ExprError();
16497 assert(Conv == Best->FoundDecl.getDecl() &&
16498 "Found Decl & conversion-to-functionptr should be same, right?!");
16499 // We selected one of the surrogate functions that converts the
16500 // object parameter to a function pointer. Perform the conversion
16501 // on the object argument, then let BuildCallExpr finish the job.
16502
16503 // Create an implicit member expr to refer to the conversion operator.
16504 // and then call it.
16505 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16506 Method: Conv, HadMultipleCandidates);
16507 if (Call.isInvalid())
16508 return ExprError();
16509 // Record usage of conversion in an implicit cast.
16510 Call = ImplicitCastExpr::Create(
16511 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16512 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16513
16514 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16515 }
16516
16517 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16518
16519 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16520 // that calls this method, using Object for the implicit object
16521 // parameter and passing along the remaining arguments.
16522 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16523
16524 // An error diagnostic has already been printed when parsing the declaration.
16525 if (Method->isInvalidDecl())
16526 return ExprError();
16527
16528 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16529 unsigned NumParams = Proto->getNumParams();
16530
16531 DeclarationNameInfo OpLocInfo(
16532 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16533 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16534 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16535 Obj, HadMultipleCandidates,
16536 OpLocInfo.getLoc(),
16537 OpLocInfo.getInfo());
16538 if (NewFn.isInvalid())
16539 return true;
16540
16541 SmallVector<Expr *, 8> MethodArgs;
16542 MethodArgs.reserve(N: NumParams + 1);
16543
16544 bool IsError = false;
16545
16546 // Initialize the object parameter.
16547 llvm::SmallVector<Expr *, 8> NewArgs;
16548 if (Method->isExplicitObjectMemberFunction()) {
16549 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16550 } else {
16551 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16552 From: Object.get(), /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
16553 if (ObjRes.isInvalid())
16554 IsError = true;
16555 else
16556 Object = ObjRes;
16557 MethodArgs.push_back(Elt: Object.get());
16558 }
16559
16560 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16561 S&: *this, MethodArgs, Method, Args, LParenLoc);
16562
16563 // If this is a variadic call, handle args passed through "...".
16564 if (Proto->isVariadic()) {
16565 // Promote the arguments (C99 6.5.2.2p7).
16566 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16567 ExprResult Arg = DefaultVariadicArgumentPromotion(
16568 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16569 IsError |= Arg.isInvalid();
16570 MethodArgs.push_back(Elt: Arg.get());
16571 }
16572 }
16573
16574 if (IsError)
16575 return true;
16576
16577 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16578
16579 // Once we've built TheCall, all of the expressions are properly owned.
16580 QualType ResultTy = Method->getReturnType();
16581 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16582 ResultTy = ResultTy.getNonLValueExprType(Context);
16583
16584 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16585 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16586 FPFeatures: CurFPFeatureOverrides());
16587
16588 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16589 return true;
16590
16591 if (CheckFunctionCall(FDecl: Method, TheCall, Proto: Proto))
16592 return true;
16593
16594 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16595}
16596
16597ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16598 SourceLocation OpLoc,
16599 bool *NoArrowOperatorFound) {
16600 assert(Base->getType()->isRecordType() &&
16601 "left-hand side must have class type");
16602
16603 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16604 return ExprError();
16605
16606 SourceLocation Loc = Base->getExprLoc();
16607
16608 // C++ [over.ref]p1:
16609 //
16610 // [...] An expression x->m is interpreted as (x.operator->())->m
16611 // for a class object x of type T if T::operator->() exists and if
16612 // the operator is selected as the best match function by the
16613 // overload resolution mechanism (13.3).
16614 DeclarationName OpName =
16615 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16616 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16617
16618 if (RequireCompleteType(Loc, Base->getType(),
16619 diag::err_typecheck_incomplete_tag, Base))
16620 return ExprError();
16621
16622 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16623 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16624 R.suppressAccessDiagnostics();
16625
16626 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16627 Oper != OperEnd; ++Oper) {
16628 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16629 Args: {}, CandidateSet,
16630 /*SuppressUserConversion=*/SuppressUserConversions: false);
16631 }
16632
16633 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16634
16635 // Perform overload resolution.
16636 OverloadCandidateSet::iterator Best;
16637 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16638 case OR_Success:
16639 // Overload resolution succeeded; we'll build the call below.
16640 break;
16641
16642 case OR_No_Viable_Function: {
16643 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16644 if (CandidateSet.empty()) {
16645 QualType BaseType = Base->getType();
16646 if (NoArrowOperatorFound) {
16647 // Report this specific error to the caller instead of emitting a
16648 // diagnostic, as requested.
16649 *NoArrowOperatorFound = true;
16650 return ExprError();
16651 }
16652 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16653 << BaseType << Base->getSourceRange();
16654 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16655 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16656 << FixItHint::CreateReplacement(OpLoc, ".");
16657 }
16658 } else
16659 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16660 << "operator->" << Base->getSourceRange();
16661 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16662 return ExprError();
16663 }
16664 case OR_Ambiguous:
16665 if (!R.isAmbiguous())
16666 CandidateSet.NoteCandidates(
16667 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16668 << "->" << Base->getType()
16669 << Base->getSourceRange()),
16670 *this, OCD_AmbiguousCandidates, Base);
16671 return ExprError();
16672
16673 case OR_Deleted: {
16674 StringLiteral *Msg = Best->Function->getDeletedMessage();
16675 CandidateSet.NoteCandidates(
16676 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16677 << "->" << (Msg != nullptr)
16678 << (Msg ? Msg->getString() : StringRef())
16679 << Base->getSourceRange()),
16680 *this, OCD_AllCandidates, Base);
16681 return ExprError();
16682 }
16683 }
16684
16685 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16686
16687 // Convert the object parameter.
16688 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16689
16690 if (Method->isExplicitObjectMemberFunction()) {
16691 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16692 if (R.isInvalid())
16693 return ExprError();
16694 Base = R.get();
16695 } else {
16696 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16697 From: Base, /*Qualifier=*/nullptr, FoundDecl: Best->FoundDecl, Method);
16698 if (BaseResult.isInvalid())
16699 return ExprError();
16700 Base = BaseResult.get();
16701 }
16702
16703 // Build the operator call.
16704 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16705 Base, HadMultipleCandidates, OpLoc);
16706 if (FnExpr.isInvalid())
16707 return ExprError();
16708
16709 QualType ResultTy = Method->getReturnType();
16710 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16711 ResultTy = ResultTy.getNonLValueExprType(Context);
16712
16713 CallExpr *TheCall =
16714 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16715 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16716
16717 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16718 return ExprError();
16719
16720 if (CheckFunctionCall(FDecl: Method, TheCall,
16721 Proto: Method->getType()->castAs<FunctionProtoType>()))
16722 return ExprError();
16723
16724 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16725}
16726
16727ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16728 DeclarationNameInfo &SuffixInfo,
16729 ArrayRef<Expr*> Args,
16730 SourceLocation LitEndLoc,
16731 TemplateArgumentListInfo *TemplateArgs) {
16732 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16733
16734 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16735 OverloadCandidateSet::CSK_Normal);
16736 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16737 ExplicitTemplateArgs: TemplateArgs);
16738
16739 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16740
16741 // Perform overload resolution. This will usually be trivial, but might need
16742 // to perform substitutions for a literal operator template.
16743 OverloadCandidateSet::iterator Best;
16744 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16745 case OR_Success:
16746 case OR_Deleted:
16747 break;
16748
16749 case OR_No_Viable_Function:
16750 CandidateSet.NoteCandidates(
16751 PartialDiagnosticAt(UDSuffixLoc,
16752 PDiag(diag::err_ovl_no_viable_function_in_call)
16753 << R.getLookupName()),
16754 *this, OCD_AllCandidates, Args);
16755 return ExprError();
16756
16757 case OR_Ambiguous:
16758 CandidateSet.NoteCandidates(
16759 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16760 << R.getLookupName()),
16761 *this, OCD_AmbiguousCandidates, Args);
16762 return ExprError();
16763 }
16764
16765 FunctionDecl *FD = Best->Function;
16766 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16767 Base: nullptr, HadMultipleCandidates,
16768 Loc: SuffixInfo.getLoc(),
16769 LocInfo: SuffixInfo.getInfo());
16770 if (Fn.isInvalid())
16771 return true;
16772
16773 // Check the argument types. This should almost always be a no-op, except
16774 // that array-to-pointer decay is applied to string literals.
16775 Expr *ConvArgs[2];
16776 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16777 ExprResult InputInit = PerformCopyInitialization(
16778 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
16779 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
16780 if (InputInit.isInvalid())
16781 return true;
16782 ConvArgs[ArgIdx] = InputInit.get();
16783 }
16784
16785 QualType ResultTy = FD->getReturnType();
16786 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16787 ResultTy = ResultTy.getNonLValueExprType(Context);
16788
16789 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16790 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
16791 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
16792
16793 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16794 return ExprError();
16795
16796 if (CheckFunctionCall(FD, UDL, nullptr))
16797 return ExprError();
16798
16799 return CheckForImmediateInvocation(E: MaybeBindToTemporary(UDL), Decl: FD);
16800}
16801
16802Sema::ForRangeStatus
16803Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16804 SourceLocation RangeLoc,
16805 const DeclarationNameInfo &NameInfo,
16806 LookupResult &MemberLookup,
16807 OverloadCandidateSet *CandidateSet,
16808 Expr *Range, ExprResult *CallExpr) {
16809 Scope *S = nullptr;
16810
16811 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
16812 if (!MemberLookup.empty()) {
16813 ExprResult MemberRef =
16814 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
16815 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
16816 /*TemplateKWLoc=*/SourceLocation(),
16817 /*FirstQualifierInScope=*/nullptr,
16818 R&: MemberLookup,
16819 /*TemplateArgs=*/nullptr, S);
16820 if (MemberRef.isInvalid()) {
16821 *CallExpr = ExprError();
16822 return FRS_DiagnosticIssued;
16823 }
16824 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
16825 if (CallExpr->isInvalid()) {
16826 *CallExpr = ExprError();
16827 return FRS_DiagnosticIssued;
16828 }
16829 } else {
16830 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16831 NNSLoc: NestedNameSpecifierLoc(),
16832 DNI: NameInfo, Fns: UnresolvedSet<0>());
16833 if (FnR.isInvalid())
16834 return FRS_DiagnosticIssued;
16835 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
16836
16837 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16838 CandidateSet, CallExpr);
16839 if (CandidateSet->empty() || CandidateSetError) {
16840 *CallExpr = ExprError();
16841 return FRS_NoViableFunction;
16842 }
16843 OverloadCandidateSet::iterator Best;
16844 OverloadingResult OverloadResult =
16845 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
16846
16847 if (OverloadResult == OR_No_Viable_Function) {
16848 *CallExpr = ExprError();
16849 return FRS_NoViableFunction;
16850 }
16851 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16852 Loc, nullptr, CandidateSet, &Best,
16853 OverloadResult,
16854 /*AllowTypoCorrection=*/false);
16855 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16856 *CallExpr = ExprError();
16857 return FRS_DiagnosticIssued;
16858 }
16859 }
16860 return FRS_Success;
16861}
16862
16863ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16864 FunctionDecl *Fn) {
16865 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
16866 ExprResult SubExpr =
16867 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
16868 if (SubExpr.isInvalid())
16869 return ExprError();
16870 if (SubExpr.get() == PE->getSubExpr())
16871 return PE;
16872
16873 return new (Context)
16874 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16875 }
16876
16877 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
16878 ExprResult SubExpr =
16879 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16880 if (SubExpr.isInvalid())
16881 return ExprError();
16882 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16883 SubExpr.get()->getType()) &&
16884 "Implicit cast type cannot be determined from overload");
16885 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16886 if (SubExpr.get() == ICE->getSubExpr())
16887 return ICE;
16888
16889 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
16890 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
16891 FPO: CurFPFeatureOverrides());
16892 }
16893
16894 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
16895 if (!GSE->isResultDependent()) {
16896 ExprResult SubExpr =
16897 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
16898 if (SubExpr.isInvalid())
16899 return ExprError();
16900 if (SubExpr.get() == GSE->getResultExpr())
16901 return GSE;
16902
16903 // Replace the resulting type information before rebuilding the generic
16904 // selection expression.
16905 ArrayRef<Expr *> A = GSE->getAssocExprs();
16906 SmallVector<Expr *, 4> AssocExprs(A);
16907 unsigned ResultIdx = GSE->getResultIndex();
16908 AssocExprs[ResultIdx] = SubExpr.get();
16909
16910 if (GSE->isExprPredicate())
16911 return GenericSelectionExpr::Create(
16912 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16913 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16914 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16915 ResultIdx);
16916 return GenericSelectionExpr::Create(
16917 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16918 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16919 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16920 ResultIdx);
16921 }
16922 // Rather than fall through to the unreachable, return the original generic
16923 // selection expression.
16924 return GSE;
16925 }
16926
16927 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
16928 assert(UnOp->getOpcode() == UO_AddrOf &&
16929 "Can only take the address of an overloaded function");
16930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
16931 if (!Method->isImplicitObjectMemberFunction()) {
16932 // Do nothing: the address of static and
16933 // explicit object member functions is a (non-member) function pointer.
16934 } else {
16935 // Fix the subexpression, which really has to be an
16936 // UnresolvedLookupExpr holding an overloaded member function
16937 // or template.
16938 ExprResult SubExpr =
16939 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16940 if (SubExpr.isInvalid())
16941 return ExprError();
16942 if (SubExpr.get() == UnOp->getSubExpr())
16943 return UnOp;
16944
16945 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
16946 Op: SubExpr.get(), MD: Method))
16947 return ExprError();
16948
16949 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16950 "fixed to something other than a decl ref");
16951 NestedNameSpecifier *Qualifier =
16952 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
16953 assert(Qualifier &&
16954 "fixed to a member ref with no nested name qualifier");
16955
16956 // We have taken the address of a pointer to member
16957 // function. Perform the computation here so that we get the
16958 // appropriate pointer to member type.
16959 QualType MemPtrType = Context.getMemberPointerType(
16960 T: Fn->getType(), Qualifier,
16961 Cls: cast<CXXRecordDecl>(Method->getDeclContext()));
16962 // Under the MS ABI, lock down the inheritance model now.
16963 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16964 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
16965
16966 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
16967 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
16968 l: UnOp->getOperatorLoc(), CanOverflow: false,
16969 FPFeatures: CurFPFeatureOverrides());
16970 }
16971 }
16972 ExprResult SubExpr =
16973 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
16974 if (SubExpr.isInvalid())
16975 return ExprError();
16976 if (SubExpr.get() == UnOp->getSubExpr())
16977 return UnOp;
16978
16979 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
16980 InputExpr: SubExpr.get());
16981 }
16982
16983 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
16984 if (Found.getAccess() == AS_none) {
16985 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
16986 }
16987 // FIXME: avoid copy.
16988 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16989 if (ULE->hasExplicitTemplateArgs()) {
16990 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16991 TemplateArgs = &TemplateArgsBuffer;
16992 }
16993
16994 QualType Type = Fn->getType();
16995 ExprValueKind ValueKind =
16996 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16997 ? VK_LValue
16998 : VK_PRValue;
16999
17000 // FIXME: Duplicated from BuildDeclarationNameExpr.
17001 if (unsigned BID = Fn->getBuiltinID()) {
17002 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17003 Type = Context.BuiltinFnTy;
17004 ValueKind = VK_PRValue;
17005 }
17006 }
17007
17008 DeclRefExpr *DRE = BuildDeclRefExpr(
17009 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17010 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17011 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17012 return DRE;
17013 }
17014
17015 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17016 // FIXME: avoid copy.
17017 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17018 if (MemExpr->hasExplicitTemplateArgs()) {
17019 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17020 TemplateArgs = &TemplateArgsBuffer;
17021 }
17022
17023 Expr *Base;
17024
17025 // If we're filling in a static method where we used to have an
17026 // implicit member access, rewrite to a simple decl ref.
17027 if (MemExpr->isImplicitAccess()) {
17028 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17029 DeclRefExpr *DRE = BuildDeclRefExpr(
17030 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17031 MemExpr->getQualifierLoc(), Found.getDecl(),
17032 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17033 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17034 return DRE;
17035 } else {
17036 SourceLocation Loc = MemExpr->getMemberLoc();
17037 if (MemExpr->getQualifier())
17038 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17039 Base =
17040 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17041 }
17042 } else
17043 Base = MemExpr->getBase();
17044
17045 ExprValueKind valueKind;
17046 QualType type;
17047 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17048 valueKind = VK_LValue;
17049 type = Fn->getType();
17050 } else {
17051 valueKind = VK_PRValue;
17052 type = Context.BoundMemberTy;
17053 }
17054
17055 return BuildMemberExpr(
17056 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17057 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17058 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17059 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17060 }
17061
17062 llvm_unreachable("Invalid reference to overloaded function");
17063}
17064
17065ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17066 DeclAccessPair Found,
17067 FunctionDecl *Fn) {
17068 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17069}
17070
17071bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17072 FunctionDecl *Function) {
17073 if (!PartialOverloading || !Function)
17074 return true;
17075 if (Function->isVariadic())
17076 return false;
17077 if (const auto *Proto =
17078 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17079 if (Proto->isTemplateVariadic())
17080 return false;
17081 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17082 if (const auto *Proto =
17083 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17084 if (Proto->isTemplateVariadic())
17085 return false;
17086 return true;
17087}
17088
17089void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17090 DeclarationName Name,
17091 OverloadCandidateSet &CandidateSet,
17092 FunctionDecl *Fn, MultiExprArg Args,
17093 bool IsMember) {
17094 StringLiteral *Msg = Fn->getDeletedMessage();
17095 CandidateSet.NoteCandidates(
17096 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17097 << IsMember << Name << (Msg != nullptr)
17098 << (Msg ? Msg->getString() : StringRef())
17099 << Range),
17100 *this, OCD_AllCandidates, Args);
17101}
17102

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/Sema/SemaOverload.cpp