1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTDiagnostic.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/DiagnosticOptions.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaAMDGPU.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaHLSL.h"
38#include "clang/Sema/SemaInternal.h"
39#include "clang/Sema/SemaObjC.h"
40#include "clang/Sema/SemaProxy.h"
41#include "clang/Sema/Template.h"
42#include "clang/Sema/TemplateDeduction.h"
43#include "llvm/ADT/DenseSet.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/STLForwardCompat.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/ADT/SmallPtrSet.h"
48#include "llvm/ADT/SmallVector.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdlib>
53#include <optional>
54
55using namespace clang;
56using namespace sema;
57
58using AllowedExplicit = Sema::AllowedExplicit;
59
60static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
61 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
62 return P->hasAttr<PassObjectSizeAttr>();
63 });
64}
65
66/// A convenience routine for creating a decayed reference to a function.
67static ExprResult CreateFunctionRefExpr(
68 Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
69 FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
70 bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo,
71 const TemplateArgumentListInfo *TemplateArgs) {
72 SourceLocation Loc = NameInfo.getLoc();
73
74 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
75 return ExprError();
76 // If FoundDecl is different from Fn (such as if one is a template
77 // and the other a specialization), make sure DiagnoseUseOfDecl is
78 // called on both.
79 // FIXME: This would be more comprehensively addressed by modifying
80 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
81 // being used.
82 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
83 return ExprError();
84 auto *DRE = DeclRefExpr::Create(Context: S.Context, QualifierLoc, TemplateKWLoc, D: Fn,
85 /*RefersToEnclosingVariableOrCapture=*/false,
86 NameInfo, T: Fn->getType(), VK: VK_LValue, FoundD: FoundDecl,
87 TemplateArgs);
88 if (HadMultipleCandidates)
89 DRE->setHadMultipleCandidates(true);
90
91 S.MarkDeclRefReferenced(E: DRE, Base);
92 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
93 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
94 S.ResolveExceptionSpec(Loc, FPT);
95 DRE->setType(Fn->getType());
96 }
97 }
98 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
99 CK: CK_FunctionToPointerDecay);
100}
101
102static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
103 NamedDecl *FoundDecl, const Expr *Base,
104 bool HadMultipleCandidates,
105 const DeclarationNameInfo &NameInfo) {
106 return CreateFunctionRefExpr(S, /*QualifierLoc=*/{}, /*TemplateKWLoc=*/{}, Fn,
107 FoundDecl, Base, HadMultipleCandidates, NameInfo,
108 /*TemplateArgs=*/nullptr);
109}
110
111static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
112 NamedDecl *FoundDecl, const Expr *Base,
113 bool HadMultipleCandidates,
114 SourceLocation Loc) {
115 return CreateFunctionRefExpr(S, Fn, FoundDecl, Base, HadMultipleCandidates,
116 NameInfo: DeclarationNameInfo(Fn->getDeclName(), Loc));
117}
118
119static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
120 bool InOverloadResolution,
121 StandardConversionSequence &SCS,
122 bool CStyle,
123 bool AllowObjCWritebackConversion);
124
125static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
126 QualType &ToType,
127 bool InOverloadResolution,
128 StandardConversionSequence &SCS,
129 bool CStyle);
130static OverloadingResult
131IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
132 UserDefinedConversionSequence& User,
133 OverloadCandidateSet& Conversions,
134 AllowedExplicit AllowExplicit,
135 bool AllowObjCConversionOnExplicit);
136
137static ImplicitConversionSequence::CompareKind
138CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
139 const StandardConversionSequence& SCS1,
140 const StandardConversionSequence& SCS2);
141
142static ImplicitConversionSequence::CompareKind
143CompareQualificationConversions(Sema &S,
144 const StandardConversionSequence& SCS1,
145 const StandardConversionSequence& SCS2);
146
147static ImplicitConversionSequence::CompareKind
148CompareOverflowBehaviorConversions(Sema &S,
149 const StandardConversionSequence &SCS1,
150 const StandardConversionSequence &SCS2);
151
152static ImplicitConversionSequence::CompareKind
153CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
154 const StandardConversionSequence& SCS1,
155 const StandardConversionSequence& SCS2);
156
157/// GetConversionRank - Retrieve the implicit conversion rank
158/// corresponding to the given implicit conversion kind.
159ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
160 static const ImplicitConversionRank Rank[] = {
161 ICR_Exact_Match,
162 ICR_Exact_Match,
163 ICR_Exact_Match,
164 ICR_Exact_Match,
165 ICR_Exact_Match,
166 ICR_Exact_Match,
167 ICR_Promotion,
168 ICR_Promotion,
169 ICR_Promotion,
170 ICR_Conversion,
171 ICR_Conversion,
172 ICR_Conversion,
173 ICR_Conversion,
174 ICR_Conversion,
175 ICR_Conversion,
176 ICR_Conversion,
177 ICR_Conversion,
178 ICR_Conversion,
179 ICR_Conversion,
180 ICR_Conversion,
181 ICR_Conversion,
182 ICR_OCL_Scalar_Widening,
183 ICR_Complex_Real_Conversion,
184 ICR_Conversion,
185 ICR_Conversion,
186 ICR_Writeback_Conversion,
187 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
188 // it was omitted by the patch that added
189 // ICK_Zero_Event_Conversion
190 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
191 // it was omitted by the patch that added
192 // ICK_Zero_Queue_Conversion
193 ICR_C_Conversion,
194 ICR_C_Conversion_Extension,
195 ICR_Conversion,
196 ICR_HLSL_Dimension_Reduction,
197 ICR_HLSL_Dimension_Reduction,
198 ICR_Conversion,
199 ICR_HLSL_Scalar_Widening,
200 ICR_HLSL_Scalar_Widening,
201 ICR_Conversion,
202 };
203 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
204 return Rank[(int)Kind];
205}
206
207ImplicitConversionRank
208clang::GetDimensionConversionRank(ImplicitConversionRank Base,
209 ImplicitConversionKind Dimension) {
210 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
211 if (Rank == ICR_HLSL_Scalar_Widening) {
212 if (Base == ICR_Promotion)
213 return ICR_HLSL_Scalar_Widening_Promotion;
214 if (Base == ICR_Conversion)
215 return ICR_HLSL_Scalar_Widening_Conversion;
216 }
217 if (Rank == ICR_HLSL_Dimension_Reduction) {
218 if (Base == ICR_Promotion)
219 return ICR_HLSL_Dimension_Reduction_Promotion;
220 if (Base == ICR_Conversion)
221 return ICR_HLSL_Dimension_Reduction_Conversion;
222 }
223 return Rank;
224}
225
226/// GetImplicitConversionName - Return the name of this kind of
227/// implicit conversion.
228static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
229 static const char *const Name[] = {
230 "No conversion",
231 "Lvalue-to-rvalue",
232 "Array-to-pointer",
233 "Function-to-pointer",
234 "Function pointer conversion",
235 "Qualification",
236 "Integral promotion",
237 "Floating point promotion",
238 "Complex promotion",
239 "Integral conversion",
240 "Floating conversion",
241 "Complex conversion",
242 "Floating-integral conversion",
243 "Pointer conversion",
244 "Pointer-to-member conversion",
245 "Boolean conversion",
246 "Compatible-types conversion",
247 "Derived-to-base conversion",
248 "Vector conversion",
249 "SVE Vector conversion",
250 "RVV Vector conversion",
251 "Vector splat",
252 "Complex-real conversion",
253 "Block Pointer conversion",
254 "Transparent Union Conversion",
255 "Writeback conversion",
256 "OpenCL Zero Event Conversion",
257 "OpenCL Zero Queue Conversion",
258 "C specific type conversion",
259 "Incompatible pointer conversion",
260 "Fixed point conversion",
261 "HLSL vector truncation",
262 "HLSL matrix truncation",
263 "Non-decaying array conversion",
264 "HLSL vector splat",
265 "HLSL matrix splat",
266 "HLSL packed type conversion",
267 };
268 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
269 return Name[Kind];
270}
271
272/// StandardConversionSequence - Set the standard conversion
273/// sequence to the identity conversion.
274void StandardConversionSequence::setAsIdentityConversion() {
275 First = ICK_Identity;
276 Second = ICK_Identity;
277 Dimension = ICK_Identity;
278 Third = ICK_Identity;
279 DeprecatedStringLiteralToCharPtr = false;
280 QualificationIncludesObjCLifetime = false;
281 ReferenceBinding = false;
282 DirectBinding = false;
283 IsLvalueReference = true;
284 BindsToFunctionLvalue = false;
285 BindsToRvalue = false;
286 BindsImplicitObjectArgumentWithoutRefQualifier = false;
287 ObjCLifetimeConversionBinding = false;
288 FromBracedInitList = false;
289 CopyConstructor = nullptr;
290}
291
292/// getRank - Retrieve the rank of this standard conversion sequence
293/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
294/// implicit conversions.
295ImplicitConversionRank StandardConversionSequence::getRank() const {
296 ImplicitConversionRank Rank = ICR_Exact_Match;
297 if (GetConversionRank(Kind: First) > Rank)
298 Rank = GetConversionRank(Kind: First);
299 if (GetConversionRank(Kind: Second) > Rank)
300 Rank = GetConversionRank(Kind: Second);
301 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
302 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
303 if (GetConversionRank(Kind: Third) > Rank)
304 Rank = GetConversionRank(Kind: Third);
305 return Rank;
306}
307
308/// isPointerConversionToBool - Determines whether this conversion is
309/// a conversion of a pointer or pointer-to-member to bool. This is
310/// used as part of the ranking of standard conversion sequences
311/// (C++ 13.3.3.2p4).
312bool StandardConversionSequence::isPointerConversionToBool() const {
313 // Note that FromType has not necessarily been transformed by the
314 // array-to-pointer or function-to-pointer implicit conversions, so
315 // check for their presence as well as checking whether FromType is
316 // a pointer.
317 if (getToType(Idx: 1)->isBooleanType() &&
318 (getFromType()->isPointerType() ||
319 getFromType()->isMemberPointerType() ||
320 getFromType()->isObjCObjectPointerType() ||
321 getFromType()->isBlockPointerType() ||
322 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
323 return true;
324
325 return false;
326}
327
328/// isPointerConversionToVoidPointer - Determines whether this
329/// conversion is a conversion of a pointer to a void pointer. This is
330/// used as part of the ranking of standard conversion sequences (C++
331/// 13.3.3.2p4).
332bool
333StandardConversionSequence::
334isPointerConversionToVoidPointer(ASTContext& Context) const {
335 QualType FromType = getFromType();
336 QualType ToType = getToType(Idx: 1);
337
338 // Note that FromType has not necessarily been transformed by the
339 // array-to-pointer implicit conversion, so check for its presence
340 // and redo the conversion to get a pointer.
341 if (First == ICK_Array_To_Pointer)
342 FromType = Context.getArrayDecayedType(T: FromType);
343
344 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
345 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
346 return ToPtrType->getPointeeType()->isVoidType();
347
348 return false;
349}
350
351/// Skip any implicit casts which could be either part of a narrowing conversion
352/// or after one in an implicit conversion.
353static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
354 const Expr *Converted) {
355 // We can have cleanups wrapping the converted expression; these need to be
356 // preserved so that destructors run if necessary.
357 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
358 Expr *Inner =
359 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
360 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
361 objects: EWC->getObjects());
362 }
363
364 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
365 switch (ICE->getCastKind()) {
366 case CK_NoOp:
367 case CK_IntegralCast:
368 case CK_IntegralToBoolean:
369 case CK_IntegralToFloating:
370 case CK_BooleanToSignedIntegral:
371 case CK_FloatingToIntegral:
372 case CK_FloatingToBoolean:
373 case CK_FloatingCast:
374 Converted = ICE->getSubExpr();
375 continue;
376
377 default:
378 return Converted;
379 }
380 }
381
382 return Converted;
383}
384
385/// Check if this standard conversion sequence represents a narrowing
386/// conversion, according to C++11 [dcl.init.list]p7.
387///
388/// \param Ctx The AST context.
389/// \param Converted The result of applying this standard conversion sequence.
390/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
391/// value of the expression prior to the narrowing conversion.
392/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
393/// type of the expression prior to the narrowing conversion.
394/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
395/// from floating point types to integral types should be ignored.
396/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
397/// to conform MSVC compiler behavior.
398NarrowingKind StandardConversionSequence::getNarrowingKind(
399 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
400 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
401 bool AllowRelaxedEval) const {
402 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
403 "narrowing check outside C++");
404
405 // C++11 [dcl.init.list]p7:
406 // A narrowing conversion is an implicit conversion ...
407 QualType FromType = getToType(Idx: 0);
408 QualType ToType = getToType(Idx: 1);
409
410 // A conversion to an enumeration type is narrowing if the conversion to
411 // the underlying type is narrowing. This only arises for expressions of
412 // the form 'Enum{init}'.
413 if (const auto *ED = ToType->getAsEnumDecl())
414 ToType = ED->getIntegerType();
415
416 switch (Second) {
417 // 'bool' is an integral type; dispatch to the right place to handle it.
418 case ICK_Boolean_Conversion:
419 if (FromType->isRealFloatingType())
420 goto FloatingIntegralConversion;
421 if (FromType->isIntegralOrUnscopedEnumerationType())
422 goto IntegralConversion;
423 // -- from a pointer type or pointer-to-member type to bool, or
424 return NK_Type_Narrowing;
425
426 // -- from a floating-point type to an integer type, or
427 //
428 // -- from an integer type or unscoped enumeration type to a floating-point
429 // type, except where the source is a constant expression and the actual
430 // value after conversion will fit into the target type and will produce
431 // the original value when converted back to the original type, or
432 case ICK_Floating_Integral:
433 FloatingIntegralConversion:
434 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
435 return NK_Type_Narrowing;
436 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
437 ToType->isRealFloatingType()) {
438 if (IgnoreFloatToIntegralConversion)
439 return NK_Not_Narrowing;
440 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
441 assert(Initializer && "Unknown conversion expression");
442
443 // If it's value-dependent, we can't tell whether it's narrowing.
444 if (Initializer->isValueDependent())
445 return NK_Dependent_Narrowing;
446
447 if (std::optional<llvm::APSInt> IntConstantValue =
448 Initializer->getIntegerConstantExpr(Ctx)) {
449 // Convert the integer to the floating type.
450 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
451 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
452 RM: llvm::APFloat::rmNearestTiesToEven);
453 // And back.
454 llvm::APSInt ConvertedValue = *IntConstantValue;
455 bool ignored;
456 llvm::APFloat::opStatus Status = Result.convertToInteger(
457 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
458 // If the converted-back integer has unspecified value, or if the
459 // resulting value is different, this was a narrowing conversion.
460 if (Status == llvm::APFloat::opInvalidOp ||
461 *IntConstantValue != ConvertedValue) {
462 ConstantValue = APValue(*IntConstantValue);
463 ConstantType = Initializer->getType();
464 return NK_Constant_Narrowing;
465 }
466 } else {
467 // Variables are always narrowings.
468 return NK_Variable_Narrowing;
469 }
470 }
471 return NK_Not_Narrowing;
472
473 // -- from long double to double or float, or from double to float, except
474 // where the source is a constant expression and the actual value after
475 // conversion is within the range of values that can be represented (even
476 // if it cannot be represented exactly), or
477 case ICK_Floating_Conversion:
478 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
479 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
480 // FromType is larger than ToType.
481 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
482
483 // If it's value-dependent, we can't tell whether it's narrowing.
484 if (Initializer->isValueDependent())
485 return NK_Dependent_Narrowing;
486
487 Expr::EvalResult R;
488 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
489 ((Ctx.getLangOpts().CPlusPlus &&
490 Initializer->isCXX11ConstantExpr(Ctx, Result&: ConstantValue,
491 AllowRelaxedEval)))) {
492 // Constant!
493 if (Ctx.getLangOpts().C23)
494 ConstantValue = R.Val;
495 assert(ConstantValue.isFloat());
496 llvm::APFloat FloatVal = ConstantValue.getFloat();
497 // Convert the source value into the target type.
498 bool ignored;
499 llvm::APFloat Converted = FloatVal;
500 llvm::APFloat::opStatus ConvertStatus =
501 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
502 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
503 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
504 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
505 if (Ctx.getLangOpts().C23) {
506 if (FloatVal.isNaN() && Converted.isNaN() &&
507 !FloatVal.isSignaling() && !Converted.isSignaling()) {
508 // Quiet NaNs are considered the same value, regardless of
509 // payloads.
510 return NK_Not_Narrowing;
511 }
512 // For normal values, check exact equality.
513 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
514 ConstantType = Initializer->getType();
515 return NK_Constant_Narrowing;
516 }
517 } else {
518 // If there was no overflow, the source value is within the range of
519 // values that can be represented.
520 if (ConvertStatus & llvm::APFloat::opOverflow) {
521 ConstantType = Initializer->getType();
522 return NK_Constant_Narrowing;
523 }
524 }
525 } else {
526 return NK_Variable_Narrowing;
527 }
528 }
529 return NK_Not_Narrowing;
530
531 // -- from an integer type or unscoped enumeration type to an integer type
532 // that cannot represent all the values of the original type, except where
533 // (CWG2627) -- the source is a bit-field whose width w is less than that
534 // of its type (or, for an enumeration type, its underlying type) and the
535 // target type can represent all the values of a hypothetical extended
536 // integer type with width w and with the same signedness as the original
537 // type or
538 // -- the source is a constant expression and the actual value after
539 // conversion will fit into the target type and will produce the original
540 // value when converted back to the original type.
541 case ICK_Integral_Conversion:
542 IntegralConversion: {
543 assert(FromType->isIntegralOrUnscopedEnumerationType());
544 assert(ToType->isIntegralOrUnscopedEnumerationType());
545 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
546 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
547 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
548 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
549
550 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
551 bool ToSigned, unsigned ToWidth) {
552 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
553 !(FromSigned && !ToSigned);
554 };
555
556 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
557 return NK_Not_Narrowing;
558
559 // Not all values of FromType can be represented in ToType.
560 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
561
562 bool DependentBitField = false;
563 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
564 if (BitField->getBitWidth()->isValueDependent())
565 DependentBitField = true;
566 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
567 BitFieldWidth < FromWidth) {
568 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
569 return NK_Not_Narrowing;
570
571 // The initializer will be truncated to the bit-field width
572 FromWidth = BitFieldWidth;
573 }
574 }
575
576 // If it's value-dependent, we can't tell whether it's narrowing.
577 if (Initializer->isValueDependent())
578 return NK_Dependent_Narrowing;
579
580 std::optional<llvm::APSInt> OptInitializerValue =
581 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
582 if (!OptInitializerValue) {
583 // If the bit-field width was dependent, it might end up being small
584 // enough to fit in the target type (unless the target type is unsigned
585 // and the source type is signed, in which case it will never fit)
586 if (DependentBitField && !(FromSigned && !ToSigned))
587 return NK_Dependent_Narrowing;
588
589 // Otherwise, such a conversion is always narrowing
590 return NK_Variable_Narrowing;
591 }
592 llvm::APSInt &InitializerValue = *OptInitializerValue;
593 bool Narrowing = false;
594 if (FromWidth < ToWidth) {
595 // Negative -> unsigned is narrowing. Otherwise, more bits is never
596 // narrowing.
597 if (InitializerValue.isSigned() && InitializerValue.isNegative())
598 Narrowing = true;
599 } else {
600 // Add a bit to the InitializerValue so we don't have to worry about
601 // signed vs. unsigned comparisons.
602 InitializerValue =
603 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
604 // Convert the initializer to and from the target width and signed-ness.
605 llvm::APSInt ConvertedValue = InitializerValue;
606 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
607 ConvertedValue.setIsSigned(ToSigned);
608 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
609 ConvertedValue.setIsSigned(InitializerValue.isSigned());
610 // If the result is different, this was a narrowing conversion.
611 if (ConvertedValue != InitializerValue)
612 Narrowing = true;
613 }
614 if (Narrowing) {
615 ConstantType = Initializer->getType();
616 ConstantValue = APValue(InitializerValue);
617 return NK_Constant_Narrowing;
618 }
619
620 return NK_Not_Narrowing;
621 }
622 case ICK_Complex_Real:
623 if (FromType->isComplexType() && !ToType->isComplexType())
624 return NK_Type_Narrowing;
625 return NK_Not_Narrowing;
626
627 case ICK_Floating_Promotion:
628 if (Ctx.getLangOpts().C23) {
629 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
630 Expr::EvalResult R;
631 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
632 ConstantValue = R.Val;
633 assert(ConstantValue.isFloat());
634 llvm::APFloat FloatVal = ConstantValue.getFloat();
635 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
636 // value, the unqualified versions of the type of the initializer and
637 // the corresponding real type of the object declared shall be
638 // compatible.
639 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
640 ConstantType = Initializer->getType();
641 return NK_Constant_Narrowing;
642 }
643 }
644 }
645 return NK_Not_Narrowing;
646 default:
647 // Other kinds of conversions are not narrowings.
648 return NK_Not_Narrowing;
649 }
650}
651
652/// dump - Print this standard conversion sequence to standard
653/// error. Useful for debugging overloading issues.
654LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
655 raw_ostream &OS = llvm::errs();
656 bool PrintedSomething = false;
657 if (First != ICK_Identity) {
658 OS << GetImplicitConversionName(Kind: First);
659 PrintedSomething = true;
660 }
661
662 if (Second != ICK_Identity) {
663 if (PrintedSomething) {
664 OS << " -> ";
665 }
666 OS << GetImplicitConversionName(Kind: Second);
667
668 if (CopyConstructor) {
669 OS << " (by copy constructor)";
670 } else if (DirectBinding) {
671 OS << " (direct reference binding)";
672 } else if (ReferenceBinding) {
673 OS << " (reference binding)";
674 }
675 PrintedSomething = true;
676 }
677
678 if (Third != ICK_Identity) {
679 if (PrintedSomething) {
680 OS << " -> ";
681 }
682 OS << GetImplicitConversionName(Kind: Third);
683 PrintedSomething = true;
684 }
685
686 if (!PrintedSomething) {
687 OS << "No conversions required";
688 }
689}
690
691/// dump - Print this user-defined conversion sequence to standard
692/// error. Useful for debugging overloading issues.
693void UserDefinedConversionSequence::dump() const {
694 raw_ostream &OS = llvm::errs();
695 if (Before.First || Before.Second || Before.Third) {
696 Before.dump();
697 OS << " -> ";
698 }
699 if (ConversionFunction)
700 OS << '\'' << *ConversionFunction << '\'';
701 else
702 OS << "aggregate initialization";
703 if (After.First || After.Second || After.Third) {
704 OS << " -> ";
705 After.dump();
706 }
707}
708
709/// dump - Print this implicit conversion sequence to standard
710/// error. Useful for debugging overloading issues.
711void ImplicitConversionSequence::dump() const {
712 raw_ostream &OS = llvm::errs();
713 if (hasInitializerListContainerType())
714 OS << "Worst list element conversion: ";
715 switch (ConversionKind) {
716 case StandardConversion:
717 OS << "Standard conversion: ";
718 Standard.dump();
719 break;
720 case UserDefinedConversion:
721 OS << "User-defined conversion: ";
722 UserDefined.dump();
723 break;
724 case EllipsisConversion:
725 OS << "Ellipsis conversion";
726 break;
727 case AmbiguousConversion:
728 OS << "Ambiguous conversion";
729 break;
730 case BadConversion:
731 OS << "Bad conversion";
732 break;
733 }
734
735 OS << "\n";
736}
737
738void AmbiguousConversionSequence::construct() {
739 new (&conversions()) ConversionSet();
740}
741
742void AmbiguousConversionSequence::destruct() {
743 conversions().~ConversionSet();
744}
745
746void
747AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
748 FromTypePtr = O.FromTypePtr;
749 ToTypePtr = O.ToTypePtr;
750 new (&conversions()) ConversionSet(O.conversions());
751}
752
753namespace {
754 // Structure used by DeductionFailureInfo to store
755 // template argument information.
756 struct DFIArguments {
757 TemplateArgument FirstArg;
758 TemplateArgument SecondArg;
759 };
760 // Structure used by DeductionFailureInfo to store
761 // template parameter and template argument information.
762 struct DFIParamWithArguments : DFIArguments {
763 TemplateParameter Param;
764 };
765 // Structure used by DeductionFailureInfo to store template argument
766 // information and the index of the problematic call argument.
767 struct DFIDeducedMismatchArgs : DFIArguments {
768 TemplateArgumentList *TemplateArgs;
769 unsigned CallArgIndex;
770 };
771 // Structure used by DeductionFailureInfo to store information about
772 // unsatisfied constraints.
773 struct CNSInfo {
774 TemplateArgumentList *TemplateArgs;
775 ConstraintSatisfaction Satisfaction;
776 };
777}
778
779/// Convert from Sema's representation of template deduction information
780/// to the form used in overload-candidate information.
781DeductionFailureInfo
782clang::MakeDeductionFailureInfo(ASTContext &Context,
783 TemplateDeductionResult TDK,
784 TemplateDeductionInfo &Info) {
785 DeductionFailureInfo Result;
786 Result.Result = static_cast<unsigned>(TDK);
787 Result.HasDiagnostic = false;
788 switch (TDK) {
789 case TemplateDeductionResult::Invalid:
790 case TemplateDeductionResult::InstantiationDepth:
791 case TemplateDeductionResult::TooManyArguments:
792 case TemplateDeductionResult::TooFewArguments:
793 case TemplateDeductionResult::MiscellaneousDeductionFailure:
794 case TemplateDeductionResult::CUDATargetMismatch:
795 Result.Data = nullptr;
796 break;
797
798 case TemplateDeductionResult::Incomplete:
799 Result.Data = Info.Param.getOpaqueValue();
800 break;
801 case TemplateDeductionResult::InvalidExplicitArguments:
802 Result.Data = Info.Param.getOpaqueValue();
803 if (Info.hasSFINAEDiagnostic()) {
804 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
805 SourceLocation(), PartialDiagnostic::NullDiagnostic());
806 Info.takeSFINAEDiagnostic(PD&: *Diag);
807 Result.HasDiagnostic = true;
808 }
809 break;
810
811 case TemplateDeductionResult::DeducedMismatch:
812 case TemplateDeductionResult::DeducedMismatchNested: {
813 // FIXME: Should allocate from normal heap so that we can free this later.
814 auto *Saved = new (Context) DFIDeducedMismatchArgs;
815 Saved->FirstArg = Info.FirstArg;
816 Saved->SecondArg = Info.SecondArg;
817 Saved->TemplateArgs = Info.takeSugared();
818 Saved->CallArgIndex = Info.CallArgIndex;
819 Result.Data = Saved;
820 break;
821 }
822
823 case TemplateDeductionResult::NonDeducedMismatch: {
824 // FIXME: Should allocate from normal heap so that we can free this later.
825 DFIArguments *Saved = new (Context) DFIArguments;
826 Saved->FirstArg = Info.FirstArg;
827 Saved->SecondArg = Info.SecondArg;
828 Result.Data = Saved;
829 break;
830 }
831
832 case TemplateDeductionResult::IncompletePack:
833 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
834 case TemplateDeductionResult::Inconsistent:
835 case TemplateDeductionResult::Underqualified: {
836 // FIXME: Should allocate from normal heap so that we can free this later.
837 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
838 Saved->Param = Info.Param;
839 Saved->FirstArg = Info.FirstArg;
840 Saved->SecondArg = Info.SecondArg;
841 Result.Data = Saved;
842 break;
843 }
844
845 case TemplateDeductionResult::SubstitutionFailure:
846 Result.Data = Info.takeSugared();
847 if (Info.hasSFINAEDiagnostic()) {
848 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
849 SourceLocation(), PartialDiagnostic::NullDiagnostic());
850 Info.takeSFINAEDiagnostic(PD&: *Diag);
851 Result.HasDiagnostic = true;
852 }
853 break;
854
855 case TemplateDeductionResult::ConstraintsNotSatisfied: {
856 CNSInfo *Saved = new (Context) CNSInfo;
857 Saved->TemplateArgs = Info.takeSugared();
858 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
859 Result.Data = Saved;
860 break;
861 }
862
863 case TemplateDeductionResult::Success:
864 case TemplateDeductionResult::NonDependentConversionFailure:
865 case TemplateDeductionResult::AlreadyDiagnosed:
866 llvm_unreachable("not a deduction failure");
867 }
868
869 return Result;
870}
871
872void DeductionFailureInfo::Destroy() {
873 switch (static_cast<TemplateDeductionResult>(Result)) {
874 case TemplateDeductionResult::Success:
875 case TemplateDeductionResult::Invalid:
876 case TemplateDeductionResult::InstantiationDepth:
877 case TemplateDeductionResult::Incomplete:
878 case TemplateDeductionResult::TooManyArguments:
879 case TemplateDeductionResult::TooFewArguments:
880 case TemplateDeductionResult::CUDATargetMismatch:
881 case TemplateDeductionResult::NonDependentConversionFailure:
882 break;
883
884 case TemplateDeductionResult::IncompletePack:
885 case TemplateDeductionResult::Inconsistent:
886 case TemplateDeductionResult::Underqualified:
887 case TemplateDeductionResult::DeducedMismatch:
888 case TemplateDeductionResult::DeducedMismatchNested:
889 case TemplateDeductionResult::NonDeducedMismatch:
890 // FIXME: Destroy the data?
891 Data = nullptr;
892 break;
893
894 case TemplateDeductionResult::InvalidExplicitArguments:
895 case TemplateDeductionResult::SubstitutionFailure:
896 // FIXME: Destroy the template argument list?
897 Data = nullptr;
898 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
899 Diag->~PartialDiagnosticAt();
900 HasDiagnostic = false;
901 }
902 break;
903
904 case TemplateDeductionResult::ConstraintsNotSatisfied:
905 // FIXME: Destroy the template argument list?
906 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
907 Data = nullptr;
908 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
909 Diag->~PartialDiagnosticAt();
910 HasDiagnostic = false;
911 }
912 break;
913
914 // Unhandled
915 case TemplateDeductionResult::MiscellaneousDeductionFailure:
916 case TemplateDeductionResult::AlreadyDiagnosed:
917 break;
918 }
919}
920
921PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
922 if (HasDiagnostic)
923 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
924 return nullptr;
925}
926
927TemplateParameter DeductionFailureInfo::getTemplateParameter() {
928 switch (static_cast<TemplateDeductionResult>(Result)) {
929 case TemplateDeductionResult::Success:
930 case TemplateDeductionResult::Invalid:
931 case TemplateDeductionResult::InstantiationDepth:
932 case TemplateDeductionResult::TooManyArguments:
933 case TemplateDeductionResult::TooFewArguments:
934 case TemplateDeductionResult::SubstitutionFailure:
935 case TemplateDeductionResult::DeducedMismatch:
936 case TemplateDeductionResult::DeducedMismatchNested:
937 case TemplateDeductionResult::NonDeducedMismatch:
938 case TemplateDeductionResult::CUDATargetMismatch:
939 case TemplateDeductionResult::NonDependentConversionFailure:
940 case TemplateDeductionResult::ConstraintsNotSatisfied:
941 return TemplateParameter();
942
943 case TemplateDeductionResult::Incomplete:
944 case TemplateDeductionResult::InvalidExplicitArguments:
945 return TemplateParameter::getFromOpaqueValue(VP: Data);
946
947 case TemplateDeductionResult::IncompletePack:
948 case TemplateDeductionResult::Inconsistent:
949 case TemplateDeductionResult::Underqualified:
950 return static_cast<DFIParamWithArguments*>(Data)->Param;
951
952 // Unhandled
953 case TemplateDeductionResult::MiscellaneousDeductionFailure:
954 case TemplateDeductionResult::AlreadyDiagnosed:
955 break;
956 }
957
958 return TemplateParameter();
959}
960
961TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
962 switch (static_cast<TemplateDeductionResult>(Result)) {
963 case TemplateDeductionResult::Success:
964 case TemplateDeductionResult::Invalid:
965 case TemplateDeductionResult::InstantiationDepth:
966 case TemplateDeductionResult::TooManyArguments:
967 case TemplateDeductionResult::TooFewArguments:
968 case TemplateDeductionResult::Incomplete:
969 case TemplateDeductionResult::IncompletePack:
970 case TemplateDeductionResult::InvalidExplicitArguments:
971 case TemplateDeductionResult::Inconsistent:
972 case TemplateDeductionResult::Underqualified:
973 case TemplateDeductionResult::NonDeducedMismatch:
974 case TemplateDeductionResult::CUDATargetMismatch:
975 case TemplateDeductionResult::NonDependentConversionFailure:
976 return nullptr;
977
978 case TemplateDeductionResult::DeducedMismatch:
979 case TemplateDeductionResult::DeducedMismatchNested:
980 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
981
982 case TemplateDeductionResult::SubstitutionFailure:
983 return static_cast<TemplateArgumentList*>(Data);
984
985 case TemplateDeductionResult::ConstraintsNotSatisfied:
986 return static_cast<CNSInfo*>(Data)->TemplateArgs;
987
988 // Unhandled
989 case TemplateDeductionResult::MiscellaneousDeductionFailure:
990 case TemplateDeductionResult::AlreadyDiagnosed:
991 break;
992 }
993
994 return nullptr;
995}
996
997const TemplateArgument *DeductionFailureInfo::getFirstArg() {
998 switch (static_cast<TemplateDeductionResult>(Result)) {
999 case TemplateDeductionResult::Success:
1000 case TemplateDeductionResult::Invalid:
1001 case TemplateDeductionResult::InstantiationDepth:
1002 case TemplateDeductionResult::Incomplete:
1003 case TemplateDeductionResult::TooManyArguments:
1004 case TemplateDeductionResult::TooFewArguments:
1005 case TemplateDeductionResult::InvalidExplicitArguments:
1006 case TemplateDeductionResult::SubstitutionFailure:
1007 case TemplateDeductionResult::CUDATargetMismatch:
1008 case TemplateDeductionResult::NonDependentConversionFailure:
1009 case TemplateDeductionResult::ConstraintsNotSatisfied:
1010 return nullptr;
1011
1012 case TemplateDeductionResult::IncompletePack:
1013 case TemplateDeductionResult::Inconsistent:
1014 case TemplateDeductionResult::Underqualified:
1015 case TemplateDeductionResult::DeducedMismatch:
1016 case TemplateDeductionResult::DeducedMismatchNested:
1017 case TemplateDeductionResult::NonDeducedMismatch:
1018 return &static_cast<DFIArguments*>(Data)->FirstArg;
1019
1020 // Unhandled
1021 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1022 case TemplateDeductionResult::AlreadyDiagnosed:
1023 break;
1024 }
1025
1026 return nullptr;
1027}
1028
1029const TemplateArgument *DeductionFailureInfo::getSecondArg() {
1030 switch (static_cast<TemplateDeductionResult>(Result)) {
1031 case TemplateDeductionResult::Success:
1032 case TemplateDeductionResult::Invalid:
1033 case TemplateDeductionResult::InstantiationDepth:
1034 case TemplateDeductionResult::Incomplete:
1035 case TemplateDeductionResult::IncompletePack:
1036 case TemplateDeductionResult::TooManyArguments:
1037 case TemplateDeductionResult::TooFewArguments:
1038 case TemplateDeductionResult::InvalidExplicitArguments:
1039 case TemplateDeductionResult::SubstitutionFailure:
1040 case TemplateDeductionResult::CUDATargetMismatch:
1041 case TemplateDeductionResult::NonDependentConversionFailure:
1042 case TemplateDeductionResult::ConstraintsNotSatisfied:
1043 return nullptr;
1044
1045 case TemplateDeductionResult::Inconsistent:
1046 case TemplateDeductionResult::Underqualified:
1047 case TemplateDeductionResult::DeducedMismatch:
1048 case TemplateDeductionResult::DeducedMismatchNested:
1049 case TemplateDeductionResult::NonDeducedMismatch:
1050 return &static_cast<DFIArguments*>(Data)->SecondArg;
1051
1052 // Unhandled
1053 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1054 case TemplateDeductionResult::AlreadyDiagnosed:
1055 break;
1056 }
1057
1058 return nullptr;
1059}
1060
1061UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1062 switch (static_cast<TemplateDeductionResult>(Result)) {
1063 case TemplateDeductionResult::DeducedMismatch:
1064 case TemplateDeductionResult::DeducedMismatchNested:
1065 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1066
1067 default:
1068 return std::nullopt;
1069 }
1070}
1071
1072static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1073 const FunctionDecl *Y) {
1074 if (!X || !Y)
1075 return false;
1076 if (X->getNumParams() != Y->getNumParams())
1077 return false;
1078 // FIXME: when do rewritten comparison operators
1079 // with explicit object parameters correspond?
1080 // https://cplusplus.github.io/CWG/issues/2797.html
1081 for (unsigned I = 0; I < X->getNumParams(); ++I)
1082 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1083 T2: Y->getParamDecl(i: I)->getType()))
1084 return false;
1085 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1086 auto *FTY = Y->getDescribedFunctionTemplate();
1087 if (!FTY)
1088 return false;
1089 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1090 Y: FTY->getTemplateParameters()))
1091 return false;
1092 }
1093 return true;
1094}
1095
1096static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1097 Expr *FirstOperand, FunctionDecl *EqFD) {
1098 assert(EqFD->getOverloadedOperator() ==
1099 OverloadedOperatorKind::OO_EqualEqual);
1100 // C++2a [over.match.oper]p4:
1101 // A non-template function or function template F named operator== is a
1102 // rewrite target with first operand o unless a search for the name operator!=
1103 // in the scope S from the instantiation context of the operator expression
1104 // finds a function or function template that would correspond
1105 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1106 // scope of the class type of o if F is a class member, and the namespace
1107 // scope of which F is a member otherwise. A function template specialization
1108 // named operator== is a rewrite target if its function template is a rewrite
1109 // target.
1110 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1111 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1112 if (isa<CXXMethodDecl>(Val: EqFD)) {
1113 // If F is a class member, search scope is class type of first operand.
1114 QualType RHS = FirstOperand->getType();
1115 auto *RHSRec = RHS->getAsCXXRecordDecl();
1116 if (!RHSRec)
1117 return true;
1118 LookupResult Members(S, NotEqOp, OpLoc,
1119 Sema::LookupNameKind::LookupMemberName);
1120 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1121 Members.suppressAccessDiagnostics();
1122 for (NamedDecl *Op : Members)
1123 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1124 return false;
1125 return true;
1126 }
1127 // Otherwise the search scope is the namespace scope of which F is a member.
1128 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1129 auto *NotEqFD = Op->getAsFunction();
1130 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1131 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1132 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1133 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1134 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1135 return false;
1136 }
1137 return true;
1138}
1139
1140bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1141 OverloadedOperatorKind Op) const {
1142 if (!AllowRewrittenCandidates)
1143 return false;
1144 return Op == OO_EqualEqual || Op == OO_Spaceship;
1145}
1146
1147bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1148 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1149 auto Op = FD->getOverloadedOperator();
1150 if (!allowsReversed(Op))
1151 return false;
1152 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1153 assert(OriginalArgs.size() == 2);
1154 if (!shouldAddReversedEqEq(
1155 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1156 return false;
1157 }
1158 // Don't bother adding a reversed candidate that can never be a better
1159 // match than the non-reversed version.
1160 return FD->getNumNonObjectParams() != 2 ||
1161 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1162 T2: FD->getParamDecl(i: 1)->getType()) ||
1163 FD->hasAttr<EnableIfAttr>();
1164}
1165
1166void OverloadCandidateSet::destroyCandidates() {
1167 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1168 for (auto &C : i->Conversions)
1169 C.~ImplicitConversionSequence();
1170 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1171 i->DeductionFailure.Destroy();
1172 }
1173}
1174
1175void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1176 destroyCandidates();
1177 SlabAllocator.Reset();
1178 NumInlineBytesUsed = 0;
1179 Candidates.clear();
1180 Functions.clear();
1181 Kind = CSK;
1182 FirstDeferredCandidate = nullptr;
1183 DeferredCandidatesCount = 0;
1184 HasDeferredTemplateConstructors = false;
1185 ResolutionByPerfectCandidateIsDisabled = false;
1186}
1187
1188namespace {
1189 class UnbridgedCastsSet {
1190 struct Entry {
1191 Expr **Addr;
1192 Expr *Saved;
1193 };
1194 SmallVector<Entry, 2> Entries;
1195
1196 public:
1197 void save(Sema &S, Expr *&E) {
1198 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1199 Entry entry = { .Addr: &E, .Saved: E };
1200 Entries.push_back(Elt: entry);
1201 E = S.ObjC().stripARCUnbridgedCast(e: E);
1202 }
1203
1204 void restore() {
1205 for (SmallVectorImpl<Entry>::iterator
1206 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1207 *i->Addr = i->Saved;
1208 }
1209 };
1210}
1211
1212/// checkPlaceholderForOverload - Do any interesting placeholder-like
1213/// preprocessing on the given expression.
1214///
1215/// \param unbridgedCasts a collection to which to add unbridged casts;
1216/// without this, they will be immediately diagnosed as errors
1217///
1218/// Return true on unrecoverable error.
1219static bool
1220checkPlaceholderForOverload(Sema &S, Expr *&E,
1221 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1222 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1223 // We can't handle overloaded expressions here because overload
1224 // resolution might reasonably tweak them.
1225 if (placeholder->getKind() == BuiltinType::Overload) return false;
1226
1227 // If the context potentially accepts unbridged ARC casts, strip
1228 // the unbridged cast and add it to the collection for later restoration.
1229 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1230 unbridgedCasts) {
1231 unbridgedCasts->save(S, E);
1232 return false;
1233 }
1234
1235 // Go ahead and check everything else.
1236 ExprResult result = S.CheckPlaceholderExpr(E);
1237 if (result.isInvalid())
1238 return true;
1239
1240 E = result.get();
1241 return false;
1242 }
1243
1244 // Nothing to do.
1245 return false;
1246}
1247
1248/// checkArgPlaceholdersForOverload - Check a set of call operands for
1249/// placeholders.
1250static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1251 UnbridgedCastsSet &unbridged) {
1252 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1253 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1254 return true;
1255
1256 return false;
1257}
1258
1259OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1260 const LookupResult &Old, NamedDecl *&Match,
1261 bool NewIsUsingDecl) {
1262 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1263 I != E; ++I) {
1264 NamedDecl *OldD = *I;
1265
1266 bool OldIsUsingDecl = false;
1267 if (isa<UsingShadowDecl>(Val: OldD)) {
1268 OldIsUsingDecl = true;
1269
1270 // We can always introduce two using declarations into the same
1271 // context, even if they have identical signatures.
1272 if (NewIsUsingDecl) continue;
1273
1274 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1275 }
1276
1277 // A using-declaration does not conflict with another declaration
1278 // if one of them is hidden.
1279 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1280 continue;
1281
1282 // If either declaration was introduced by a using declaration,
1283 // we'll need to use slightly different rules for matching.
1284 // Essentially, these rules are the normal rules, except that
1285 // function templates hide function templates with different
1286 // return types or template parameter lists.
1287 bool UseMemberUsingDeclRules =
1288 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1289 !New->getFriendObjectKind();
1290
1291 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1292 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1293 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1294 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1295 continue;
1296 }
1297
1298 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1299 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1300 continue;
1301
1302 Match = *I;
1303 return OverloadKind::Match;
1304 }
1305
1306 // Builtins that have custom typechecking or have a reference should
1307 // not be overloadable or redeclarable.
1308 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1309 Match = *I;
1310 return OverloadKind::NonFunction;
1311 }
1312 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1313 // We can overload with these, which can show up when doing
1314 // redeclaration checks for UsingDecls.
1315 assert(Old.getLookupKind() == LookupUsingDeclName);
1316 } else if (isa<TagDecl>(Val: OldD)) {
1317 // We can always overload with tags by hiding them.
1318 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1319 // Optimistically assume that an unresolved using decl will
1320 // overload; if it doesn't, we'll have to diagnose during
1321 // template instantiation.
1322 //
1323 // Exception: if the scope is dependent and this is not a class
1324 // member, the using declaration can only introduce an enumerator.
1325 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1326 Match = *I;
1327 return OverloadKind::NonFunction;
1328 }
1329 } else {
1330 // (C++ 13p1):
1331 // Only function declarations can be overloaded; object and type
1332 // declarations cannot be overloaded.
1333 Match = *I;
1334 return OverloadKind::NonFunction;
1335 }
1336 }
1337
1338 // C++ [temp.friend]p1:
1339 // For a friend function declaration that is not a template declaration:
1340 // -- if the name of the friend is a qualified or unqualified template-id,
1341 // [...], otherwise
1342 // -- if the name of the friend is a qualified-id and a matching
1343 // non-template function is found in the specified class or namespace,
1344 // the friend declaration refers to that function, otherwise,
1345 // -- if the name of the friend is a qualified-id and a matching function
1346 // template is found in the specified class or namespace, the friend
1347 // declaration refers to the deduced specialization of that function
1348 // template, otherwise
1349 // -- the name shall be an unqualified-id [...]
1350 // If we get here for a qualified friend declaration, we've just reached the
1351 // third bullet. If the type of the friend is dependent, skip this lookup
1352 // until instantiation.
1353 if (New->getFriendObjectKind() && New->getQualifier() &&
1354 !New->getDescribedFunctionTemplate() &&
1355 !New->getDependentSpecializationInfo() &&
1356 !New->getType()->isDependentType()) {
1357 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1358 TemplateSpecResult.addAllDecls(Other: Old);
1359 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1360 /*QualifiedFriend*/true)) {
1361 New->setInvalidDecl();
1362 return OverloadKind::Overload;
1363 }
1364
1365 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1366 return OverloadKind::Match;
1367 }
1368
1369 return OverloadKind::Overload;
1370}
1371
1372template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1373 assert(D && "function decl should not be null");
1374 if (auto *A = D->getAttr<AttrT>())
1375 return !A->isImplicit();
1376 return false;
1377}
1378
1379static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1380 FunctionDecl *Old,
1381 bool UseMemberUsingDeclRules,
1382 bool ConsiderCudaAttrs,
1383 bool UseOverrideRules = false) {
1384 // C++ [basic.start.main]p2: This function shall not be overloaded.
1385 if (New->isMain())
1386 return false;
1387
1388 // MSVCRT user defined entry points cannot be overloaded.
1389 if (New->isMSVCRTEntryPoint())
1390 return false;
1391
1392 NamedDecl *OldDecl = Old;
1393 NamedDecl *NewDecl = New;
1394 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1395 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1396
1397 // C++ [temp.fct]p2:
1398 // A function template can be overloaded with other function templates
1399 // and with normal (non-template) functions.
1400 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1401 return true;
1402
1403 // Is the function New an overload of the function Old?
1404 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1405 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1406
1407 // Compare the signatures (C++ 1.3.10) of the two functions to
1408 // determine whether they are overloads. If we find any mismatch
1409 // in the signature, they are overloads.
1410
1411 // If either of these functions is a K&R-style function (no
1412 // prototype), then we consider them to have matching signatures.
1413 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1414 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1415 return false;
1416
1417 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1418 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1419
1420 // The signature of a function includes the types of its
1421 // parameters (C++ 1.3.10), which includes the presence or absence
1422 // of the ellipsis; see C++ DR 357).
1423 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1424 return true;
1425
1426 // For member-like friends, the enclosing class is part of the signature.
1427 if ((New->isMemberLikeConstrainedFriend() ||
1428 Old->isMemberLikeConstrainedFriend()) &&
1429 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1430 return true;
1431
1432 // Compare the parameter lists.
1433 // This can only be done once we have establish that friend functions
1434 // inhabit the same context, otherwise we might tried to instantiate
1435 // references to non-instantiated entities during constraint substitution.
1436 // GH78101.
1437 if (NewTemplate) {
1438 OldDecl = OldTemplate;
1439 NewDecl = NewTemplate;
1440 // C++ [temp.over.link]p4:
1441 // The signature of a function template consists of its function
1442 // signature, its return type and its template parameter list. The names
1443 // of the template parameters are significant only for establishing the
1444 // relationship between the template parameters and the rest of the
1445 // signature.
1446 //
1447 // We check the return type and template parameter lists for function
1448 // templates first; the remaining checks follow.
1449 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1450 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1451 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1452 bool SameReturnType = SemaRef.Context.hasSameType(
1453 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1454 // FIXME(GH58571): Match template parameter list even for non-constrained
1455 // template heads. This currently ensures that the code prior to C++20 is
1456 // not newly broken.
1457 bool ConstraintsInTemplateHead =
1458 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1459 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1460 // C++ [namespace.udecl]p11:
1461 // The set of declarations named by a using-declarator that inhabits a
1462 // class C does not include member functions and member function
1463 // templates of a base class that "correspond" to (and thus would
1464 // conflict with) a declaration of a function or function template in
1465 // C.
1466 // Comparing return types is not required for the "correspond" check to
1467 // decide whether a member introduced by a shadow declaration is hidden.
1468 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1469 !SameTemplateParameterList)
1470 return true;
1471 if (!UseMemberUsingDeclRules &&
1472 (!SameTemplateParameterList || !SameReturnType))
1473 return true;
1474 }
1475
1476 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1477 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1478
1479 int OldParamsOffset = 0;
1480 int NewParamsOffset = 0;
1481
1482 // When determining if a method is an overload from a base class, act as if
1483 // the implicit object parameter are of the same type.
1484
1485 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1486 if (M->isExplicitObjectMemberFunction()) {
1487 auto ThisType = M->getFunctionObjectParameterReferenceType();
1488 if (ThisType.isConstQualified())
1489 Q.removeConst();
1490 return Q;
1491 }
1492
1493 // We do not allow overloading based off of '__restrict'.
1494 Q.removeRestrict();
1495
1496 // We may not have applied the implicit const for a constexpr member
1497 // function yet (because we haven't yet resolved whether this is a static
1498 // or non-static member function). Add it now, on the assumption that this
1499 // is a redeclaration of OldMethod.
1500 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1501 (M->isConstexpr() || M->isConsteval()) &&
1502 !isa<CXXConstructorDecl>(Val: NewMethod))
1503 Q.addConst();
1504 return Q;
1505 };
1506
1507 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1508 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1509 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1510
1511 if (OldMethod->isExplicitObjectMemberFunction()) {
1512 BS.Quals.removeVolatile();
1513 DS.Quals.removeVolatile();
1514 }
1515
1516 return BS.Quals == DS.Quals;
1517 };
1518
1519 auto CompareType = [&](QualType Base, QualType D) {
1520 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1521 auto DS = D.getNonReferenceType().getCanonicalType().split();
1522
1523 if (!AreQualifiersEqual(BS, DS))
1524 return false;
1525
1526 if (OldMethod->isImplicitObjectMemberFunction() &&
1527 OldMethod->getParent() != NewMethod->getParent()) {
1528 CanQualType ParentType =
1529 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1530 if (ParentType.getTypePtr() != BS.Ty)
1531 return false;
1532 BS.Ty = DS.Ty;
1533 }
1534
1535 // FIXME: should we ignore some type attributes here?
1536 if (BS.Ty != DS.Ty)
1537 return false;
1538
1539 if (Base->isLValueReferenceType())
1540 return D->isLValueReferenceType();
1541 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1542 };
1543
1544 // If the function is a class member, its signature includes the
1545 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1546 auto DiagnoseInconsistentRefQualifiers = [&]() {
1547 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1548 return false;
1549 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1550 return false;
1551 if (OldMethod->isExplicitObjectMemberFunction() ||
1552 NewMethod->isExplicitObjectMemberFunction())
1553 return false;
1554 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1555 NewMethod->getRefQualifier() == RQ_None)) {
1556 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1557 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1558 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1559 return true;
1560 }
1561 return false;
1562 };
1563
1564 // We look at the parameters first, as it is the common case.
1565 // However we should not emit diagnostic before checking
1566 // the overloads do not differ by constraints or other discriminant.
1567 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1568 bool HaveInconsistentQualifiers = false;
1569
1570 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1571 OldParamsOffset++;
1572 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1573 NewParamsOffset++;
1574
1575 if (OldType->getNumParams() - OldParamsOffset !=
1576 NewType->getNumParams() - NewParamsOffset ||
1577 !SemaRef.FunctionParamTypesAreEqual(
1578 Old: {OldType->param_type_begin() + OldParamsOffset,
1579 OldType->param_type_end()},
1580 New: {NewType->param_type_begin() + NewParamsOffset,
1581 NewType->param_type_end()},
1582 ArgPos: nullptr)) {
1583 return true;
1584 }
1585
1586 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1587 !NewMethod->isStatic()) {
1588 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1589 const CXXMethodDecl *New) {
1590 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1591 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1592
1593 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1594 return F->getRefQualifier() == RQ_None &&
1595 !F->isExplicitObjectMemberFunction();
1596 };
1597
1598 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1599 CompareType(OldObjectType.getNonReferenceType(),
1600 NewObjectType.getNonReferenceType()))
1601 return true;
1602 return CompareType(OldObjectType, NewObjectType);
1603 }(OldMethod, NewMethod);
1604
1605 if (!HaveCorrespondingObjectParameters) {
1606 ShouldDiagnoseInconsistentRefQualifiers = true;
1607 // CWG2554
1608 // and, if at least one is an explicit object member function, ignoring
1609 // object parameters
1610 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1611 !OldMethod->isExplicitObjectMemberFunction()))
1612 HaveInconsistentQualifiers = true;
1613 }
1614 }
1615
1616 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1617 NewMethod->isImplicitObjectMemberFunction())
1618 ShouldDiagnoseInconsistentRefQualifiers = true;
1619
1620 if (!UseOverrideRules &&
1621 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1622 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1623 OldRC = Old->getTrailingRequiresClause();
1624 if (!NewRC != !OldRC)
1625 return true;
1626 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1627 return true;
1628 if (NewRC &&
1629 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1630 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1631 return true;
1632 }
1633
1634 // Though pass_object_size is placed on parameters and takes an argument, we
1635 // consider it to be a function-level modifier for the sake of function
1636 // identity. Either the function has one or more parameters with
1637 // pass_object_size or it doesn't.
1638 if (functionHasPassObjectSizeParams(FD: New) !=
1639 functionHasPassObjectSizeParams(FD: Old))
1640 return true;
1641
1642 // enable_if attributes are an order-sensitive part of the signature.
1643 for (specific_attr_iterator<EnableIfAttr>
1644 NewI = New->specific_attr_begin<EnableIfAttr>(),
1645 NewE = New->specific_attr_end<EnableIfAttr>(),
1646 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1647 OldE = Old->specific_attr_end<EnableIfAttr>();
1648 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1649 if (NewI == NewE || OldI == OldE)
1650 return true;
1651 llvm::FoldingSetNodeID NewID, OldID;
1652 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1653 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1654 if (NewID != OldID)
1655 return true;
1656 }
1657
1658 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1659 DiagnoseInconsistentRefQualifiers()) ||
1660 HaveInconsistentQualifiers)
1661 return true;
1662
1663 // At this point, it is known that the two functions have the same signature.
1664 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1665 // Don't allow overloading of destructors. (In theory we could, but it
1666 // would be a giant change to clang.)
1667 if (!isa<CXXDestructorDecl>(Val: New)) {
1668 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1669 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1670 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1671 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1672 "Unexpected invalid target.");
1673
1674 // Allow overloading of functions with same signature and different CUDA
1675 // target attributes.
1676 if (NewTarget != OldTarget) {
1677 // Special case: non-constexpr function is allowed to override
1678 // constexpr virtual function
1679 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1680 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1681 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1682 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1683 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1684 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1685 return false;
1686 }
1687 return true;
1688 }
1689 }
1690 }
1691 }
1692
1693 // The signatures match; this is not an overload.
1694 return false;
1695}
1696
1697bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1698 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1699 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1700 ConsiderCudaAttrs);
1701}
1702
1703bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1704 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1705 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1706 /*UseMemberUsingDeclRules=*/false,
1707 /*ConsiderCudaAttrs=*/true,
1708 /*UseOverrideRules=*/true);
1709}
1710
1711/// Tries a user-defined conversion from From to ToType.
1712///
1713/// Produces an implicit conversion sequence for when a standard conversion
1714/// is not an option. See TryImplicitConversion for more information.
1715static ImplicitConversionSequence
1716TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1717 bool SuppressUserConversions,
1718 AllowedExplicit AllowExplicit,
1719 bool InOverloadResolution,
1720 bool CStyle,
1721 bool AllowObjCWritebackConversion,
1722 bool AllowObjCConversionOnExplicit) {
1723 ImplicitConversionSequence ICS;
1724
1725 if (SuppressUserConversions) {
1726 // We're not in the case above, so there is no conversion that
1727 // we can perform.
1728 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1729 return ICS;
1730 }
1731
1732 // Attempt user-defined conversion.
1733 OverloadCandidateSet Conversions(From->getExprLoc(),
1734 OverloadCandidateSet::CSK_Normal);
1735 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1736 Conversions, AllowExplicit,
1737 AllowObjCConversionOnExplicit)) {
1738 case OR_Success:
1739 case OR_Deleted:
1740 ICS.setUserDefined();
1741 // C++ [over.ics.user]p4:
1742 // A conversion of an expression of class type to the same class
1743 // type is given Exact Match rank, and a conversion of an
1744 // expression of class type to a base class of that type is
1745 // given Conversion rank, in spite of the fact that a copy
1746 // constructor (i.e., a user-defined conversion function) is
1747 // called for those cases.
1748 if (CXXConstructorDecl *Constructor
1749 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1750 QualType FromType;
1751 SourceLocation FromLoc;
1752 // C++11 [over.ics.list]p6, per DR2137:
1753 // C++17 [over.ics.list]p6:
1754 // If C is not an initializer-list constructor and the initializer list
1755 // has a single element of type cv U, where U is X or a class derived
1756 // from X, the implicit conversion sequence has Exact Match rank if U is
1757 // X, or Conversion rank if U is derived from X.
1758 bool FromListInit = false;
1759 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1760 InitList && InitList->getNumInits() == 1 &&
1761 !S.isInitListConstructor(Ctor: Constructor)) {
1762 const Expr *SingleInit = InitList->getInit(Init: 0);
1763 FromType = SingleInit->getType();
1764 FromLoc = SingleInit->getBeginLoc();
1765 FromListInit = true;
1766 } else {
1767 FromType = From->getType();
1768 FromLoc = From->getBeginLoc();
1769 }
1770 QualType FromCanon =
1771 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1772 QualType ToCanon
1773 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1774 if ((FromCanon == ToCanon ||
1775 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1776 // Turn this into a "standard" conversion sequence, so that it
1777 // gets ranked with standard conversion sequences.
1778 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1779 ICS.setStandard();
1780 ICS.Standard.setAsIdentityConversion();
1781 ICS.Standard.setFromType(FromType);
1782 ICS.Standard.setAllToTypes(ToType);
1783 ICS.Standard.FromBracedInitList = FromListInit;
1784 ICS.Standard.CopyConstructor = Constructor;
1785 ICS.Standard.FoundCopyConstructor = Found;
1786 if (ToCanon != FromCanon)
1787 ICS.Standard.Second = ICK_Derived_To_Base;
1788 }
1789 }
1790 break;
1791
1792 case OR_Ambiguous:
1793 ICS.setAmbiguous();
1794 ICS.Ambiguous.setFromType(From->getType());
1795 ICS.Ambiguous.setToType(ToType);
1796 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1797 Cand != Conversions.end(); ++Cand)
1798 if (Cand->Best)
1799 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1800 break;
1801
1802 // Fall through.
1803 case OR_No_Viable_Function:
1804 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1805 break;
1806 }
1807
1808 return ICS;
1809}
1810
1811/// TryImplicitConversion - Attempt to perform an implicit conversion
1812/// from the given expression (Expr) to the given type (ToType). This
1813/// function returns an implicit conversion sequence that can be used
1814/// to perform the initialization. Given
1815///
1816/// void f(float f);
1817/// void g(int i) { f(i); }
1818///
1819/// this routine would produce an implicit conversion sequence to
1820/// describe the initialization of f from i, which will be a standard
1821/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1822/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1823//
1824/// Note that this routine only determines how the conversion can be
1825/// performed; it does not actually perform the conversion. As such,
1826/// it will not produce any diagnostics if no conversion is available,
1827/// but will instead return an implicit conversion sequence of kind
1828/// "BadConversion".
1829///
1830/// If @p SuppressUserConversions, then user-defined conversions are
1831/// not permitted.
1832/// If @p AllowExplicit, then explicit user-defined conversions are
1833/// permitted.
1834///
1835/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1836/// writeback conversion, which allows __autoreleasing id* parameters to
1837/// be initialized with __strong id* or __weak id* arguments.
1838static ImplicitConversionSequence
1839TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1840 bool SuppressUserConversions,
1841 AllowedExplicit AllowExplicit,
1842 bool InOverloadResolution,
1843 bool CStyle,
1844 bool AllowObjCWritebackConversion,
1845 bool AllowObjCConversionOnExplicit) {
1846 ImplicitConversionSequence ICS;
1847 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1848 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1849 ICS.setStandard();
1850 return ICS;
1851 }
1852
1853 if (!S.getLangOpts().CPlusPlus) {
1854 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1855 return ICS;
1856 }
1857
1858 // C++ [over.ics.user]p4:
1859 // A conversion of an expression of class type to the same class
1860 // type is given Exact Match rank, and a conversion of an
1861 // expression of class type to a base class of that type is
1862 // given Conversion rank, in spite of the fact that a copy/move
1863 // constructor (i.e., a user-defined conversion function) is
1864 // called for those cases.
1865 QualType FromType = From->getType();
1866 if (ToType->isRecordType() &&
1867 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1868 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1869 ICS.setStandard();
1870 ICS.Standard.setAsIdentityConversion();
1871 ICS.Standard.setFromType(FromType);
1872 ICS.Standard.setAllToTypes(ToType);
1873
1874 // We don't actually check at this point whether there is a valid
1875 // copy/move constructor, since overloading just assumes that it
1876 // exists. When we actually perform initialization, we'll find the
1877 // appropriate constructor to copy the returned object, if needed.
1878 ICS.Standard.CopyConstructor = nullptr;
1879
1880 // In HLSL, a conversion of an expression of class type to the same class
1881 // type needs implicit LvaluetoRvalue conversion.
1882 if (S.getLangOpts().HLSL)
1883 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
1884
1885 // Determine whether this is considered a derived-to-base conversion.
1886 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1887 ICS.Standard.Second = ICK_Derived_To_Base;
1888
1889 return ICS;
1890 }
1891
1892 if (S.getLangOpts().HLSL) {
1893 // Handle conversion of the HLSL resource types.
1894 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1895 if (FromTy->isHLSLAttributedResourceType()) {
1896 // Attributed resource types can convert to other attributed
1897 // resource types with the same attributes and contained types,
1898 // or to __hlsl_resource_t without any attributes.
1899 bool CanConvert = false;
1900 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1901 if (ToTy->isHLSLAttributedResourceType()) {
1902 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1903 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1904 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1905 T2: FromResType->getWrappedType()) &&
1906 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1907 T2: FromResType->getContainedType()) &&
1908 ToResType->getAttrs() == FromResType->getAttrs())
1909 CanConvert = true;
1910 } else if (ToTy->isHLSLResourceType()) {
1911 CanConvert = true;
1912 }
1913 if (CanConvert) {
1914 ICS.setStandard();
1915 ICS.Standard.setAsIdentityConversion();
1916 ICS.Standard.setFromType(FromType);
1917 ICS.Standard.setAllToTypes(ToType);
1918 return ICS;
1919 }
1920 }
1921 }
1922
1923 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1924 AllowExplicit, InOverloadResolution, CStyle,
1925 AllowObjCWritebackConversion,
1926 AllowObjCConversionOnExplicit);
1927}
1928
1929ImplicitConversionSequence
1930Sema::TryImplicitConversion(Expr *From, QualType ToType,
1931 bool SuppressUserConversions,
1932 AllowedExplicit AllowExplicit,
1933 bool InOverloadResolution,
1934 bool CStyle,
1935 bool AllowObjCWritebackConversion) {
1936 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1937 AllowExplicit, InOverloadResolution, CStyle,
1938 AllowObjCWritebackConversion,
1939 /*AllowObjCConversionOnExplicit=*/false);
1940}
1941
1942ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1943 AssignmentAction Action,
1944 bool AllowExplicit) {
1945 if (checkPlaceholderForOverload(S&: *this, E&: From))
1946 return ExprError();
1947
1948 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1949 bool AllowObjCWritebackConversion =
1950 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1951 Action == AssignmentAction::Sending);
1952 if (getLangOpts().ObjC)
1953 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1954 SrcType: From->getType(), SrcExpr&: From);
1955 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1956 S&: *this, From, ToType,
1957 /*SuppressUserConversions=*/false,
1958 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1959 /*InOverloadResolution=*/false,
1960 /*CStyle=*/false, AllowObjCWritebackConversion,
1961 /*AllowObjCConversionOnExplicit=*/false);
1962 return PerformImplicitConversion(From, ToType, ICS, Action);
1963}
1964
1965bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1966 QualType &ResultTy) const {
1967 bool Changed = IsFunctionConversion(FromType, ToType);
1968 if (Changed)
1969 ResultTy = ToType;
1970 return Changed;
1971}
1972
1973bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1974 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1975 return false;
1976
1977 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1978 // or F(t noexcept) -> F(t)
1979 // where F adds one of the following at most once:
1980 // - a pointer
1981 // - a member pointer
1982 // - a block pointer
1983 // Changes here need matching changes in FindCompositePointerType.
1984 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1985 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1986 Type::TypeClass TyClass = CanTo->getTypeClass();
1987 if (TyClass != CanFrom->getTypeClass()) return false;
1988 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1989 if (TyClass == Type::Pointer) {
1990 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1991 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1992 } else if (TyClass == Type::BlockPointer) {
1993 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1994 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1995 } else if (TyClass == Type::MemberPointer) {
1996 auto ToMPT = CanTo.castAs<MemberPointerType>();
1997 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1998 // A function pointer conversion cannot change the class of the function.
1999 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
2000 D2: FromMPT->getMostRecentCXXRecordDecl()))
2001 return false;
2002 CanTo = ToMPT->getPointeeType();
2003 CanFrom = FromMPT->getPointeeType();
2004 } else {
2005 return false;
2006 }
2007
2008 TyClass = CanTo->getTypeClass();
2009 if (TyClass != CanFrom->getTypeClass()) return false;
2010 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
2011 return false;
2012 }
2013
2014 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
2015 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
2016
2017 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
2018 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
2019
2020 bool Changed = false;
2021
2022 // Drop 'noreturn' if not present in target type.
2023 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
2024 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
2025 Changed = true;
2026 }
2027
2028 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
2029 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
2030
2031 if (FromFPT && ToFPT) {
2032 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2033 QualType NewTy = Context.getFunctionType(
2034 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
2035 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2036 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
2037 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
2038 FromFn = FromFPT;
2039 Changed = true;
2040 }
2041 }
2042
2043 // Drop 'noexcept' if not present in target type.
2044 if (FromFPT && ToFPT) {
2045 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2046 FromFn = cast<FunctionType>(
2047 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
2048 ESI: EST_None)
2049 .getTypePtr());
2050 Changed = true;
2051 }
2052
2053 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2054 // only if the ExtParameterInfo lists of the two function prototypes can be
2055 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2056 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2057 bool CanUseToFPT, CanUseFromFPT;
2058 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2059 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2060 CanUseToFPT && !CanUseFromFPT) {
2061 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2062 ExtInfo.ExtParameterInfos =
2063 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2064 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2065 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2066 FromFn = QT->getAs<FunctionType>();
2067 Changed = true;
2068 }
2069
2070 if (Context.hasAnyFunctionEffects()) {
2071 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2072
2073 // Transparently add/drop effects; here we are concerned with
2074 // language rules/canonicalization. Adding/dropping effects is a warning.
2075 const auto FromFX = FromFPT->getFunctionEffects();
2076 const auto ToFX = ToFPT->getFunctionEffects();
2077 if (FromFX != ToFX) {
2078 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2079 ExtInfo.FunctionEffects = ToFX;
2080 QualType QT = Context.getFunctionType(
2081 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2082 FromFn = QT->getAs<FunctionType>();
2083 Changed = true;
2084 }
2085 }
2086 }
2087
2088 if (!Changed)
2089 return false;
2090
2091 assert(QualType(FromFn, 0).isCanonical());
2092 if (QualType(FromFn, 0) != CanTo) return false;
2093
2094 return true;
2095}
2096
2097/// Determine whether the conversion from FromType to ToType is a valid
2098/// floating point conversion.
2099///
2100static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2101 QualType ToType) {
2102 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2103 return false;
2104 // FIXME: disable conversions between long double, __ibm128 and __float128
2105 // if their representation is different until there is back end support
2106 // We of course allow this conversion if long double is really double.
2107
2108 // Conversions between bfloat16 and float16 are currently not supported.
2109 if ((FromType->isBFloat16Type() &&
2110 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2111 (ToType->isBFloat16Type() &&
2112 (FromType->isFloat16Type() || FromType->isHalfType())))
2113 return false;
2114
2115 // Conversions between IEEE-quad and IBM-extended semantics are not
2116 // permitted.
2117 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2118 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2119 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2120 &ToSem == &llvm::APFloat::IEEEquad()) ||
2121 (&FromSem == &llvm::APFloat::IEEEquad() &&
2122 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2123 return false;
2124 return true;
2125}
2126
2127static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2128 QualType ToType,
2129 ImplicitConversionKind &ICK,
2130 Expr *From) {
2131 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2132 return true;
2133
2134 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2135 ICK = ICK_Floating_Promotion;
2136 return true;
2137 }
2138
2139 if (IsFloatingPointConversion(S, FromType, ToType)) {
2140 ICK = ICK_Floating_Conversion;
2141 return true;
2142 }
2143
2144 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2145 ICK = ICK_Boolean_Conversion;
2146 return true;
2147 }
2148
2149 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2150 (FromType->isIntegralOrUnscopedEnumerationType() &&
2151 ToType->isRealFloatingType())) {
2152 ICK = ICK_Floating_Integral;
2153 return true;
2154 }
2155
2156 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2157 ICK = ICK_Integral_Promotion;
2158 return true;
2159 }
2160
2161 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2162 ToType->isIntegralType(Ctx: S.Context)) {
2163 ICK = ICK_Integral_Conversion;
2164 return true;
2165 }
2166
2167 return false;
2168}
2169
2170/// Determine whether the conversion from FromType to ToType is a valid
2171/// matrix conversion.
2172///
2173/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2174/// conversion.
2175static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2176 ImplicitConversionKind &ICK,
2177 ImplicitConversionKind &ElConv, Expr *From,
2178 bool InOverloadResolution, bool CStyle) {
2179 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2180 if (!S.getLangOpts().HLSL)
2181 return false;
2182
2183 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2184 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2185
2186 // If both arguments are matrix, handle possible matrix truncation and
2187 // element conversion.
2188 if (ToMatrixType && FromMatrixType) {
2189 unsigned FromCols = FromMatrixType->getNumColumns();
2190 unsigned ToCols = ToMatrixType->getNumColumns();
2191 if (FromCols < ToCols)
2192 return false;
2193
2194 unsigned FromRows = FromMatrixType->getNumRows();
2195 unsigned ToRows = ToMatrixType->getNumRows();
2196 if (FromRows < ToRows)
2197 return false;
2198
2199 if (FromRows == ToRows && FromCols == ToCols)
2200 ElConv = ICK_Identity;
2201 else
2202 ElConv = ICK_HLSL_Matrix_Truncation;
2203
2204 QualType FromElTy = FromMatrixType->getElementType();
2205 QualType ToElTy = ToMatrixType->getElementType();
2206 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2207 return true;
2208 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2209 }
2210
2211 // Matrix splat from any arithmetic type to a matrix.
2212 if (ToMatrixType && FromType->isArithmeticType()) {
2213 ElConv = ICK_HLSL_Matrix_Splat;
2214 QualType ToElTy = ToMatrixType->getElementType();
2215 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2216 }
2217 if (FromMatrixType && !ToMatrixType) {
2218 ElConv = ICK_HLSL_Matrix_Truncation;
2219 QualType FromElTy = FromMatrixType->getElementType();
2220 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2221 return true;
2222 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2223 }
2224
2225 return false;
2226}
2227
2228/// Determine whether the conversion from FromType to ToType is a valid
2229/// vector conversion.
2230///
2231/// \param ICK Will be set to the vector conversion kind, if this is a vector
2232/// conversion.
2233static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2234 ImplicitConversionKind &ICK,
2235 ImplicitConversionKind &ElConv, Expr *From,
2236 bool InOverloadResolution, bool CStyle) {
2237 // We need at least one of these types to be a vector type to have a vector
2238 // conversion.
2239 if (!ToType->isVectorType() && !FromType->isVectorType())
2240 return false;
2241
2242 // Identical types require no conversions.
2243 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2244 return false;
2245
2246 // HLSL allows implicit truncation of vector types.
2247 if (S.getLangOpts().HLSL) {
2248 auto *ToExtType = ToType->getAs<ExtVectorType>();
2249 auto *FromExtType = FromType->getAs<ExtVectorType>();
2250
2251 // If both arguments are vectors, handle possible vector truncation and
2252 // element conversion.
2253 if (ToExtType && FromExtType) {
2254 unsigned FromElts = FromExtType->getNumElements();
2255 unsigned ToElts = ToExtType->getNumElements();
2256 if (FromElts < ToElts)
2257 return false;
2258 if (FromElts == ToElts)
2259 ElConv = ICK_Identity;
2260 else
2261 ElConv = ICK_HLSL_Vector_Truncation;
2262
2263 QualType FromElTy = FromExtType->getElementType();
2264 QualType ToElTy = ToExtType->getElementType();
2265 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2266 return true;
2267 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2268 }
2269 if (FromExtType && !ToExtType) {
2270 ElConv = ICK_HLSL_Vector_Truncation;
2271 QualType FromElTy = FromExtType->getElementType();
2272 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2273 return true;
2274 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2275 }
2276 // Fallthrough for the case where ToType is a vector and FromType is not.
2277 }
2278
2279 // There are no conversions between extended vector types, only identity.
2280 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2281 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2282 // Implicit conversions require the same number of elements.
2283 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2284 return false;
2285
2286 // Permit implicit conversions from integral values to boolean vectors.
2287 if (ToType->isExtVectorBoolType() &&
2288 FromExtType->getElementType()->isIntegerType()) {
2289 ICK = ICK_Boolean_Conversion;
2290 return true;
2291 }
2292 // There are no other conversions between extended vector types.
2293 return false;
2294 }
2295
2296 // Vector splat from any arithmetic type to a vector.
2297 if (FromType->isArithmeticType()) {
2298 if (S.getLangOpts().HLSL) {
2299 ElConv = ICK_HLSL_Vector_Splat;
2300 QualType ToElTy = ToExtType->getElementType();
2301 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2302 From);
2303 }
2304 ICK = ICK_Vector_Splat;
2305 return true;
2306 }
2307 }
2308
2309 if (ToType->isSVESizelessBuiltinType() ||
2310 FromType->isSVESizelessBuiltinType())
2311 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2312 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2313 ICK = ICK_SVE_Vector_Conversion;
2314 return true;
2315 }
2316
2317 if (ToType->isRVVSizelessBuiltinType() ||
2318 FromType->isRVVSizelessBuiltinType())
2319 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2320 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2321 ICK = ICK_RVV_Vector_Conversion;
2322 return true;
2323 }
2324
2325 // We can perform the conversion between vector types in the following cases:
2326 // 1)vector types are equivalent AltiVec and GCC vector types
2327 // 2)lax vector conversions are permitted and the vector types are of the
2328 // same size
2329 // 3)the destination type does not have the ARM MVE strict-polymorphism
2330 // attribute, which inhibits lax vector conversion for overload resolution
2331 // only
2332 if (ToType->isVectorType() && FromType->isVectorType()) {
2333 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2334 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2335 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2336 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2337 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2338 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2339 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2340 !InOverloadResolution && !CStyle) {
2341 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2342 << FromType << ToType;
2343 }
2344 ICK = ICK_Vector_Conversion;
2345 return true;
2346 }
2347 }
2348
2349 return false;
2350}
2351
2352static bool IsHLSLPackedTypeConversion(Sema &S, QualType FromType,
2353 QualType ToType,
2354 ImplicitConversionKind &ICK,
2355 ImplicitConversionKind &DimensionICK,
2356 Expr *From) {
2357 if (!S.getLangOpts().HLSL)
2358 return false;
2359 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2360 return false;
2361
2362 const bool FromPacked = FromType->isHLSLBuiltinPackedType();
2363 const bool ToPacked = ToType->isHLSLBuiltinPackedType();
2364
2365 if (FromPacked && ToPacked) {
2366 ICK = ICK_Integral_Conversion;
2367 DimensionICK = ICK_Identity;
2368 return true;
2369 }
2370
2371 // Only convert packed types to and from uint
2372 QualType UIntTy = S.Context.UnsignedIntTy;
2373 const bool ToIsUint = S.Context.hasSameUnqualifiedType(T1: ToType, T2: UIntTy);
2374 if (FromPacked && !ToIsUint)
2375 return false;
2376
2377 const bool FromIsUint = S.Context.hasSameUnqualifiedType(T1: FromType, T2: UIntTy);
2378 if (ToPacked && !FromIsUint)
2379 return false;
2380
2381 // Converting to or from uint
2382 if (FromIsUint || ToIsUint) {
2383 ICK = ICK_HLSL_Packed_Type_Conversion;
2384 DimensionICK = ICK_Identity;
2385 return true;
2386 }
2387
2388 return false;
2389}
2390
2391static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2392 bool InOverloadResolution,
2393 StandardConversionSequence &SCS,
2394 bool CStyle);
2395
2396static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2397 QualType ToType,
2398 bool InOverloadResolution,
2399 StandardConversionSequence &SCS,
2400 bool CStyle);
2401
2402/// IsStandardConversion - Determines whether there is a standard
2403/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2404/// expression From to the type ToType. Standard conversion sequences
2405/// only consider non-class types; for conversions that involve class
2406/// types, use TryImplicitConversion. If a conversion exists, SCS will
2407/// contain the standard conversion sequence required to perform this
2408/// conversion and this routine will return true. Otherwise, this
2409/// routine will return false and the value of SCS is unspecified.
2410static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2411 bool InOverloadResolution,
2412 StandardConversionSequence &SCS,
2413 bool CStyle,
2414 bool AllowObjCWritebackConversion) {
2415 QualType FromType = From->getType();
2416
2417 // Standard conversions (C++ [conv])
2418 SCS.setAsIdentityConversion();
2419 SCS.IncompatibleObjC = false;
2420 SCS.setFromType(FromType);
2421 SCS.CopyConstructor = nullptr;
2422
2423 // There are no standard conversions for class types in C++, so
2424 // abort early. When overloading in C, however, we do permit them.
2425 if (S.getLangOpts().CPlusPlus &&
2426 (FromType->isRecordType() || ToType->isRecordType()))
2427 return false;
2428
2429 // The first conversion can be an lvalue-to-rvalue conversion,
2430 // array-to-pointer conversion, or function-to-pointer conversion
2431 // (C++ 4p1).
2432
2433 if (FromType == S.Context.OverloadTy) {
2434 DeclAccessPair AccessPair;
2435 if (FunctionDecl *Fn
2436 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2437 Found&: AccessPair)) {
2438 // We were able to resolve the address of the overloaded function,
2439 // so we can convert to the type of that function.
2440 FromType = Fn->getType();
2441 SCS.setFromType(FromType);
2442
2443 // we can sometimes resolve &foo<int> regardless of ToType, so check
2444 // if the type matches (identity) or we are converting to bool
2445 if (!S.Context.hasSameUnqualifiedType(
2446 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2447 // if the function type matches except for [[noreturn]], it's ok
2448 if (!S.IsFunctionConversion(FromType,
2449 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2450 // otherwise, only a boolean conversion is standard
2451 if (!ToType->isBooleanType())
2452 return false;
2453 }
2454
2455 // Check if the "from" expression is taking the address of an overloaded
2456 // function and recompute the FromType accordingly. Take advantage of the
2457 // fact that non-static member functions *must* have such an address-of
2458 // expression.
2459 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2460 if (Method && !Method->isStatic() &&
2461 !Method->isExplicitObjectMemberFunction()) {
2462 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2463 "Non-unary operator on non-static member address");
2464 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2465 == UO_AddrOf &&
2466 "Non-address-of operator on non-static member address");
2467 FromType = S.Context.getMemberPointerType(
2468 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2469 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2470 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2471 UO_AddrOf &&
2472 "Non-address-of operator for overloaded function expression");
2473 FromType = S.Context.getPointerType(T: FromType);
2474 }
2475 } else {
2476 return false;
2477 }
2478 }
2479
2480 bool argIsLValue = From->isGLValue();
2481 // To handle conversion from ArrayParameterType to ConstantArrayType
2482 // this block must be above the one below because Array parameters
2483 // do not decay and when handling HLSLOutArgExprs and
2484 // the From expression is an LValue.
2485 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2486 ToType->isConstantArrayType()) {
2487 // HLSL constant array parameters do not decay, so if the argument is a
2488 // constant array and the parameter is an ArrayParameterType we have special
2489 // handling here.
2490 if (ToType->isArrayParameterType()) {
2491 FromType = S.Context.getArrayParameterType(Ty: FromType);
2492 } else if (FromType->isArrayParameterType()) {
2493 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2494 FromType = APT->getConstantArrayType(Ctx: S.Context);
2495 }
2496
2497 SCS.First = ICK_HLSL_Array_RValue;
2498
2499 // Don't consider qualifiers, which include things like address spaces
2500 if (FromType.getCanonicalType().getUnqualifiedType() !=
2501 ToType.getCanonicalType().getUnqualifiedType())
2502 return false;
2503
2504 SCS.setAllToTypes(ToType);
2505 return true;
2506 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2507 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2508 // Lvalue-to-rvalue conversion (C++11 4.1):
2509 // A glvalue (3.10) of a non-function, non-array type T can
2510 // be converted to a prvalue.
2511
2512 SCS.First = ICK_Lvalue_To_Rvalue;
2513
2514 // C11 6.3.2.1p2:
2515 // ... if the lvalue has atomic type, the value has the non-atomic version
2516 // of the type of the lvalue ...
2517 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2518 FromType = Atomic->getValueType();
2519
2520 // If T is a non-class type, the type of the rvalue is the
2521 // cv-unqualified version of T. Otherwise, the type of the rvalue
2522 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2523 // just strip the qualifiers because they don't matter.
2524 FromType = FromType.getUnqualifiedType();
2525 } else if (FromType->isArrayType()) {
2526 // Array-to-pointer conversion (C++ 4.2)
2527 SCS.First = ICK_Array_To_Pointer;
2528
2529 // An lvalue or rvalue of type "array of N T" or "array of unknown
2530 // bound of T" can be converted to an rvalue of type "pointer to
2531 // T" (C++ 4.2p1).
2532 FromType = S.Context.getArrayDecayedType(T: FromType);
2533
2534 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2535 // This conversion is deprecated in C++03 (D.4)
2536 SCS.DeprecatedStringLiteralToCharPtr = true;
2537
2538 // For the purpose of ranking in overload resolution
2539 // (13.3.3.1.1), this conversion is considered an
2540 // array-to-pointer conversion followed by a qualification
2541 // conversion (4.4). (C++ 4.2p2)
2542 SCS.Second = ICK_Identity;
2543 SCS.Third = ICK_Qualification;
2544 SCS.QualificationIncludesObjCLifetime = false;
2545 SCS.setAllToTypes(FromType);
2546 return true;
2547 }
2548 } else if (FromType->isFunctionType() && argIsLValue) {
2549 // Function-to-pointer conversion (C++ 4.3).
2550 SCS.First = ICK_Function_To_Pointer;
2551
2552 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2553 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2554 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2555 return false;
2556
2557 // An lvalue of function type T can be converted to an rvalue of
2558 // type "pointer to T." The result is a pointer to the
2559 // function. (C++ 4.3p1).
2560 FromType = S.Context.getPointerType(T: FromType);
2561 } else {
2562 // We don't require any conversions for the first step.
2563 SCS.First = ICK_Identity;
2564 }
2565 SCS.setToType(Idx: 0, T: FromType);
2566
2567 // The second conversion can be an integral promotion, floating
2568 // point promotion, integral conversion, floating point conversion,
2569 // floating-integral conversion, pointer conversion,
2570 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2571 // For overloading in C, this can also be a "compatible-type"
2572 // conversion.
2573 bool IncompatibleObjC = false;
2574 ImplicitConversionKind SecondICK = ICK_Identity;
2575 ImplicitConversionKind DimensionICK = ICK_Identity;
2576 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2577 // The unqualified versions of the types are the same: there's no
2578 // conversion to do.
2579 SCS.Second = ICK_Identity;
2580 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2581 // Integral promotion (C++ 4.5).
2582 SCS.Second = ICK_Integral_Promotion;
2583 FromType = ToType.getUnqualifiedType();
2584 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2585 // Floating point promotion (C++ 4.6).
2586 SCS.Second = ICK_Floating_Promotion;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (S.IsComplexPromotion(FromType, ToType)) {
2589 // Complex promotion (Clang extension)
2590 SCS.Second = ICK_Complex_Promotion;
2591 FromType = ToType.getUnqualifiedType();
2592 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2593 // OverflowBehaviorType promotions
2594 SCS.Second = ICK_Integral_Promotion;
2595 FromType = ToType.getUnqualifiedType();
2596 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2597 // OverflowBehaviorType conversions
2598 SCS.Second = ICK_Integral_Conversion;
2599 FromType = ToType.getUnqualifiedType();
2600 } else if (ToType->isBooleanType() &&
2601 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2602 FromType->isBlockPointerType() ||
2603 FromType->isMemberPointerType())) {
2604 // Boolean conversions (C++ 4.12).
2605 SCS.Second = ICK_Boolean_Conversion;
2606 FromType = S.Context.BoolTy;
2607 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2608 ToType->isIntegralType(Ctx: S.Context)) {
2609 // Integral conversions (C++ 4.7).
2610 SCS.Second = ICK_Integral_Conversion;
2611 FromType = ToType.getUnqualifiedType();
2612 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2613 // Complex conversions (C99 6.3.1.6)
2614 SCS.Second = ICK_Complex_Conversion;
2615 FromType = ToType.getUnqualifiedType();
2616 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2617 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2618 // Complex-real conversions (C99 6.3.1.7)
2619 SCS.Second = ICK_Complex_Real;
2620 FromType = ToType.getUnqualifiedType();
2621 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2622 // Floating point conversions (C++ 4.8).
2623 SCS.Second = ICK_Floating_Conversion;
2624 FromType = ToType.getUnqualifiedType();
2625 } else if ((FromType->isRealFloatingType() &&
2626 ToType->isIntegralType(Ctx: S.Context)) ||
2627 (FromType->isIntegralOrUnscopedEnumerationType() &&
2628 ToType->isRealFloatingType())) {
2629
2630 // Floating-integral conversions (C++ 4.9).
2631 SCS.Second = ICK_Floating_Integral;
2632 FromType = ToType.getUnqualifiedType();
2633 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2634 SCS.Second = ICK_Block_Pointer_Conversion;
2635 } else if (AllowObjCWritebackConversion &&
2636 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2637 SCS.Second = ICK_Writeback_Conversion;
2638 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2639 ConvertedType&: FromType, IncompatibleObjC)) {
2640 // Pointer conversions (C++ 4.10).
2641 SCS.Second = ICK_Pointer_Conversion;
2642 SCS.IncompatibleObjC = IncompatibleObjC;
2643 FromType = FromType.getUnqualifiedType();
2644 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2645 InOverloadResolution, ConvertedType&: FromType)) {
2646 // Pointer to member conversions (4.11).
2647 SCS.Second = ICK_Pointer_Member;
2648 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2649 From, InOverloadResolution, CStyle)) {
2650 SCS.Second = SecondICK;
2651 SCS.Dimension = DimensionICK;
2652 FromType = ToType.getUnqualifiedType();
2653 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2654 From, InOverloadResolution, CStyle)) {
2655 SCS.Second = SecondICK;
2656 SCS.Dimension = DimensionICK;
2657 FromType = ToType.getUnqualifiedType();
2658 } else if (IsHLSLPackedTypeConversion(S, FromType, ToType, ICK&: SecondICK,
2659 DimensionICK, From)) {
2660 SCS.Second = SecondICK;
2661 SCS.Dimension = DimensionICK;
2662 FromType = ToType.getUnqualifiedType();
2663 } else if (!S.getLangOpts().CPlusPlus &&
2664 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2665 // Compatible conversions (Clang extension for C function overloading)
2666 SCS.Second = ICK_Compatible_Conversion;
2667 FromType = ToType.getUnqualifiedType();
2668 } else if (IsTransparentUnionStandardConversion(
2669 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2670 SCS.Second = ICK_TransparentUnionConversion;
2671 FromType = ToType;
2672 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2673 CStyle)) {
2674 // tryAtomicConversion has updated the standard conversion sequence
2675 // appropriately.
2676 return true;
2677 } else if (tryOverflowBehaviorTypeConversion(
2678 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2679 return true;
2680 } else if (ToType->isEventT() &&
2681 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2682 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2683 SCS.Second = ICK_Zero_Event_Conversion;
2684 FromType = ToType;
2685 } else if (ToType->isQueueT() &&
2686 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2687 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2688 SCS.Second = ICK_Zero_Queue_Conversion;
2689 FromType = ToType;
2690 } else if (ToType->isSamplerT() &&
2691 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2692 SCS.Second = ICK_Compatible_Conversion;
2693 FromType = ToType;
2694 } else if ((ToType->isFixedPointType() &&
2695 FromType->isConvertibleToFixedPointType()) ||
2696 (FromType->isFixedPointType() &&
2697 ToType->isConvertibleToFixedPointType())) {
2698 SCS.Second = ICK_Fixed_Point_Conversion;
2699 FromType = ToType;
2700 } else {
2701 // No second conversion required.
2702 SCS.Second = ICK_Identity;
2703 }
2704 SCS.setToType(Idx: 1, T: FromType);
2705
2706 // The third conversion can be a function pointer conversion or a
2707 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2708 bool ObjCLifetimeConversion;
2709 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2710 // Function pointer conversions (removing 'noexcept') including removal of
2711 // 'noreturn' (Clang extension).
2712 SCS.Third = ICK_Function_Conversion;
2713 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2714 ObjCLifetimeConversion)) {
2715 SCS.Third = ICK_Qualification;
2716 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2717 FromType = ToType;
2718 } else {
2719 // No conversion required
2720 SCS.Third = ICK_Identity;
2721 }
2722
2723 // C++ [over.best.ics]p6:
2724 // [...] Any difference in top-level cv-qualification is
2725 // subsumed by the initialization itself and does not constitute
2726 // a conversion. [...]
2727 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2728 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2729 if (CanonFrom.getLocalUnqualifiedType()
2730 == CanonTo.getLocalUnqualifiedType() &&
2731 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2732 FromType = ToType;
2733 CanonFrom = CanonTo;
2734 }
2735
2736 SCS.setToType(Idx: 2, T: FromType);
2737
2738 if (CanonFrom == CanonTo)
2739 return true;
2740
2741 // If we have not converted the argument type to the parameter type,
2742 // this is a bad conversion sequence, unless we're resolving an overload in C.
2743 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2744 return false;
2745
2746 ExprResult ER = ExprResult{From};
2747 AssignConvertType Conv =
2748 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2749 /*Diagnose=*/false,
2750 /*DiagnoseCFAudited=*/false,
2751 /*ConvertRHS=*/false);
2752 ImplicitConversionKind SecondConv;
2753 switch (Conv) {
2754 case AssignConvertType::Compatible:
2755 case AssignConvertType::
2756 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2757 SecondConv = ICK_C_Only_Conversion;
2758 break;
2759 // For our purposes, discarding qualifiers is just as bad as using an
2760 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2761 // qualifiers, as well.
2762 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2763 case AssignConvertType::IncompatiblePointer:
2764 case AssignConvertType::IncompatiblePointerSign:
2765 SecondConv = ICK_Incompatible_Pointer_Conversion;
2766 break;
2767 default:
2768 return false;
2769 }
2770
2771 // First can only be an lvalue conversion, so we pretend that this was the
2772 // second conversion. First should already be valid from earlier in the
2773 // function.
2774 SCS.Second = SecondConv;
2775 SCS.setToType(Idx: 1, T: ToType);
2776
2777 // Third is Identity, because Second should rank us worse than any other
2778 // conversion. This could also be ICK_Qualification, but it's simpler to just
2779 // lump everything in with the second conversion, and we don't gain anything
2780 // from making this ICK_Qualification.
2781 SCS.Third = ICK_Identity;
2782 SCS.setToType(Idx: 2, T: ToType);
2783 return true;
2784}
2785
2786static bool
2787IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2788 QualType &ToType,
2789 bool InOverloadResolution,
2790 StandardConversionSequence &SCS,
2791 bool CStyle) {
2792
2793 const RecordType *UT = ToType->getAsUnionType();
2794 if (!UT)
2795 return false;
2796 // The field to initialize within the transparent union.
2797 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2798 if (!UD->hasAttr<TransparentUnionAttr>())
2799 return false;
2800 // It's compatible if the expression matches any of the fields.
2801 for (const auto *it : UD->fields()) {
2802 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2803 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2804 ToType = it->getType();
2805 return true;
2806 }
2807 }
2808 return false;
2809}
2810
2811bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2812 const BuiltinType *To = ToType->getAs<BuiltinType>();
2813 // All integers are built-in.
2814 if (!To) {
2815 return false;
2816 }
2817
2818 // An rvalue of type char, signed char, unsigned char, short int, or
2819 // unsigned short int can be converted to an rvalue of type int if
2820 // int can represent all the values of the source type; otherwise,
2821 // the source rvalue can be converted to an rvalue of type unsigned
2822 // int (C++ 4.5p1).
2823 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2824 !FromType->isEnumeralType()) {
2825 if ( // We can promote any signed, promotable integer type to an int
2826 (FromType->isSignedIntegerType() ||
2827 // We can promote any unsigned integer type whose size is
2828 // less than int to an int.
2829 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2830 return To->getKind() == BuiltinType::Int;
2831 }
2832
2833 return To->getKind() == BuiltinType::UInt;
2834 }
2835
2836 // C++11 [conv.prom]p3:
2837 // A prvalue of an unscoped enumeration type whose underlying type is not
2838 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2839 // following types that can represent all the values of the enumeration
2840 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2841 // unsigned int, long int, unsigned long int, long long int, or unsigned
2842 // long long int. If none of the types in that list can represent all the
2843 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2844 // type can be converted to an rvalue a prvalue of the extended integer type
2845 // with lowest integer conversion rank (4.13) greater than the rank of long
2846 // long in which all the values of the enumeration can be represented. If
2847 // there are two such extended types, the signed one is chosen.
2848 // C++11 [conv.prom]p4:
2849 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2850 // can be converted to a prvalue of its underlying type. Moreover, if
2851 // integral promotion can be applied to its underlying type, a prvalue of an
2852 // unscoped enumeration type whose underlying type is fixed can also be
2853 // converted to a prvalue of the promoted underlying type.
2854 if (const auto *FromED = FromType->getAsEnumDecl()) {
2855 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2856 // provided for a scoped enumeration.
2857 if (FromED->isScoped())
2858 return false;
2859
2860 // We can perform an integral promotion to the underlying type of the enum,
2861 // even if that's not the promoted type. Note that the check for promoting
2862 // the underlying type is based on the type alone, and does not consider
2863 // the bitfield-ness of the actual source expression.
2864 if (FromED->isFixed()) {
2865 QualType Underlying = FromED->getIntegerType();
2866 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2867 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2868 }
2869
2870 // We have already pre-calculated the promotion type, so this is trivial.
2871 if (ToType->isIntegerType() &&
2872 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2873 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2874
2875 // C++ [conv.prom]p5:
2876 // If the bit-field has an enumerated type, it is treated as any other
2877 // value of that type for promotion purposes.
2878 //
2879 // ... so do not fall through into the bit-field checks below in C++.
2880 if (getLangOpts().CPlusPlus)
2881 return false;
2882 }
2883
2884 // C++0x [conv.prom]p2:
2885 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2886 // to an rvalue a prvalue of the first of the following types that can
2887 // represent all the values of its underlying type: int, unsigned int,
2888 // long int, unsigned long int, long long int, or unsigned long long int.
2889 // If none of the types in that list can represent all the values of its
2890 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2891 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2892 // type.
2893 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2894 ToType->isIntegerType()) {
2895 // Determine whether the type we're converting from is signed or
2896 // unsigned.
2897 bool FromIsSigned = FromType->isSignedIntegerType();
2898 uint64_t FromSize = Context.getTypeSize(T: FromType);
2899
2900 // The types we'll try to promote to, in the appropriate
2901 // order. Try each of these types.
2902 QualType PromoteTypes[6] = {
2903 Context.IntTy, Context.UnsignedIntTy,
2904 Context.LongTy, Context.UnsignedLongTy ,
2905 Context.LongLongTy, Context.UnsignedLongLongTy
2906 };
2907 for (int Idx = 0; Idx < 6; ++Idx) {
2908 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2909 if (FromSize < ToSize ||
2910 (FromSize == ToSize &&
2911 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2912 // We found the type that we can promote to. If this is the
2913 // type we wanted, we have a promotion. Otherwise, no
2914 // promotion.
2915 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2916 }
2917 }
2918 }
2919
2920 // An rvalue for an integral bit-field (9.6) can be converted to an
2921 // rvalue of type int if int can represent all the values of the
2922 // bit-field; otherwise, it can be converted to unsigned int if
2923 // unsigned int can represent all the values of the bit-field. If
2924 // the bit-field is larger yet, no integral promotion applies to
2925 // it. If the bit-field has an enumerated type, it is treated as any
2926 // other value of that type for promotion purposes (C++ 4.5p3).
2927 // FIXME: We should delay checking of bit-fields until we actually perform the
2928 // conversion.
2929 //
2930 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2931 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2932 // bit-fields and those whose underlying type is larger than int) for GCC
2933 // compatibility.
2934 if (From) {
2935 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2936 std::optional<llvm::APSInt> BitWidth;
2937 if (FromType->isIntegralType(Ctx: Context) &&
2938 (BitWidth =
2939 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2940 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2941 ToSize = Context.getTypeSize(T: ToType);
2942
2943 // Are we promoting to an int from a bitfield that fits in an int?
2944 if (*BitWidth < ToSize ||
2945 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2946 return To->getKind() == BuiltinType::Int;
2947 }
2948
2949 // Are we promoting to an unsigned int from an unsigned bitfield
2950 // that fits into an unsigned int?
2951 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2952 return To->getKind() == BuiltinType::UInt;
2953 }
2954
2955 return false;
2956 }
2957 }
2958 }
2959
2960 // An rvalue of type bool can be converted to an rvalue of type int,
2961 // with false becoming zero and true becoming one (C++ 4.5p4).
2962 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2963 return true;
2964 }
2965
2966 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2967 // integral type.
2968 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2969 ToType->isIntegerType())
2970 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2971
2972 return false;
2973}
2974
2975bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2976 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2977 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2978 /// An rvalue of type float can be converted to an rvalue of type
2979 /// double. (C++ 4.6p1).
2980 if (FromBuiltin->getKind() == BuiltinType::Float &&
2981 ToBuiltin->getKind() == BuiltinType::Double)
2982 return true;
2983
2984 // C99 6.3.1.5p1:
2985 // When a float is promoted to double or long double, or a
2986 // double is promoted to long double [...].
2987 if (!getLangOpts().CPlusPlus &&
2988 (FromBuiltin->getKind() == BuiltinType::Float ||
2989 FromBuiltin->getKind() == BuiltinType::Double) &&
2990 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2991 ToBuiltin->getKind() == BuiltinType::Float128 ||
2992 ToBuiltin->getKind() == BuiltinType::Ibm128))
2993 return true;
2994
2995 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2996 // or not native half types are enabled.
2997 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2998 (ToBuiltin->getKind() == BuiltinType::Float ||
2999 ToBuiltin->getKind() == BuiltinType::Double))
3000 return true;
3001
3002 // Half can be promoted to float.
3003 if (!getLangOpts().NativeHalfType &&
3004 FromBuiltin->getKind() == BuiltinType::Half &&
3005 ToBuiltin->getKind() == BuiltinType::Float)
3006 return true;
3007 }
3008
3009 return false;
3010}
3011
3012bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
3013 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
3014 if (!FromComplex)
3015 return false;
3016
3017 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
3018 if (!ToComplex)
3019 return false;
3020
3021 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
3022 ToType: ToComplex->getElementType()) ||
3023 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
3024 ToType: ToComplex->getElementType());
3025}
3026
3027bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
3028 if (!getLangOpts().OverflowBehaviorTypes)
3029 return false;
3030
3031 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
3032 return false;
3033
3034 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
3035}
3036
3037bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
3038 QualType ToType) {
3039 if (!getLangOpts().OverflowBehaviorTypes)
3040 return false;
3041
3042 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
3043 if (ToType->isBooleanType())
3044 return false;
3045 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
3046 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
3047 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
3048 if (ToED->isScoped())
3049 return false;
3050 }
3051 return true;
3052 }
3053
3054 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3055 return true;
3056
3057 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3058 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
3059
3060 return false;
3061}
3062
3063/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
3064/// the pointer type FromPtr to a pointer to type ToPointee, with the
3065/// same type qualifiers as FromPtr has on its pointee type. ToType,
3066/// if non-empty, will be a pointer to ToType that may or may not have
3067/// the right set of qualifiers on its pointee.
3068///
3069static QualType
3070BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
3071 QualType ToPointee, QualType ToType,
3072 ASTContext &Context,
3073 bool StripObjCLifetime = false) {
3074 assert((FromPtr->getTypeClass() == Type::Pointer ||
3075 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3076 "Invalid similarly-qualified pointer type");
3077
3078 /// Conversions to 'id' subsume cv-qualifier conversions.
3079 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3080 return ToType.getUnqualifiedType();
3081
3082 QualType CanonFromPointee
3083 = Context.getCanonicalType(T: FromPtr->getPointeeType());
3084 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
3085 Qualifiers Quals = CanonFromPointee.getQualifiers();
3086
3087 if (StripObjCLifetime)
3088 Quals.removeObjCLifetime();
3089
3090 // Exact qualifier match -> return the pointer type we're converting to.
3091 if (CanonToPointee.getLocalQualifiers() == Quals) {
3092 // ToType is exactly what we need. Return it.
3093 if (!ToType.isNull())
3094 return ToType.getUnqualifiedType();
3095
3096 // Build a pointer to ToPointee. It has the right qualifiers
3097 // already.
3098 if (isa<ObjCObjectPointerType>(Val: ToType))
3099 return Context.getObjCObjectPointerType(OIT: ToPointee);
3100 return Context.getPointerType(T: ToPointee);
3101 }
3102
3103 // Just build a canonical type that has the right qualifiers.
3104 QualType QualifiedCanonToPointee
3105 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3106
3107 if (isa<ObjCObjectPointerType>(Val: ToType))
3108 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3109 return Context.getPointerType(T: QualifiedCanonToPointee);
3110}
3111
3112static bool isNullPointerConstantForConversion(Expr *Expr,
3113 bool InOverloadResolution,
3114 ASTContext &Context) {
3115 // Handle value-dependent integral null pointer constants correctly.
3116 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3117 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3118 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3119 return !InOverloadResolution;
3120
3121 return Expr->isNullPointerConstant(Ctx&: Context,
3122 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3123 : Expr::NPC_ValueDependentIsNull);
3124}
3125
3126bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3127 bool InOverloadResolution,
3128 QualType& ConvertedType,
3129 bool &IncompatibleObjC) {
3130 IncompatibleObjC = false;
3131 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3132 IncompatibleObjC))
3133 return true;
3134
3135 // Conversion from a null pointer constant to any Objective-C pointer type.
3136 if (ToType->isObjCObjectPointerType() &&
3137 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3138 ConvertedType = ToType;
3139 return true;
3140 }
3141
3142 // Blocks: Block pointers can be converted to void*.
3143 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3144 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3145 ConvertedType = ToType;
3146 return true;
3147 }
3148 // Blocks: A null pointer constant can be converted to a block
3149 // pointer type.
3150 if (ToType->isBlockPointerType() &&
3151 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3152 ConvertedType = ToType;
3153 return true;
3154 }
3155
3156 // If the left-hand-side is nullptr_t, the right side can be a null
3157 // pointer constant.
3158 if (ToType->isNullPtrType() &&
3159 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3160 ConvertedType = ToType;
3161 return true;
3162 }
3163
3164 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3165 if (!ToTypePtr)
3166 return false;
3167
3168 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3169 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3170 ConvertedType = ToType;
3171 return true;
3172 }
3173
3174 // Beyond this point, both types need to be pointers
3175 // , including objective-c pointers.
3176 QualType ToPointeeType = ToTypePtr->getPointeeType();
3177 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3178 !getLangOpts().ObjCAutoRefCount) {
3179 ConvertedType = BuildSimilarlyQualifiedPointerType(
3180 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3181 Context);
3182 return true;
3183 }
3184 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3185 if (!FromTypePtr)
3186 return false;
3187
3188 QualType FromPointeeType = FromTypePtr->getPointeeType();
3189
3190 // If the unqualified pointee types are the same, this can't be a
3191 // pointer conversion, so don't do all of the work below.
3192 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3193 return false;
3194
3195 // An rvalue of type "pointer to cv T," where T is an object type,
3196 // can be converted to an rvalue of type "pointer to cv void" (C++
3197 // 4.10p2).
3198 if (FromPointeeType->isIncompleteOrObjectType() &&
3199 ToPointeeType->isVoidType()) {
3200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3201 ToPointee: ToPointeeType,
3202 ToType, Context,
3203 /*StripObjCLifetime=*/true);
3204 return true;
3205 }
3206
3207 // MSVC allows implicit function to void* type conversion.
3208 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3209 ToPointeeType->isVoidType()) {
3210 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3211 ToPointee: ToPointeeType,
3212 ToType, Context);
3213 return true;
3214 }
3215
3216 // When we're overloading in C, we allow a special kind of pointer
3217 // conversion for compatible-but-not-identical pointee types.
3218 if (!getLangOpts().CPlusPlus &&
3219 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3220 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3221 ToPointee: ToPointeeType,
3222 ToType, Context);
3223 return true;
3224 }
3225
3226 // C++ [conv.ptr]p3:
3227 //
3228 // An rvalue of type "pointer to cv D," where D is a class type,
3229 // can be converted to an rvalue of type "pointer to cv B," where
3230 // B is a base class (clause 10) of D. If B is an inaccessible
3231 // (clause 11) or ambiguous (10.2) base class of D, a program that
3232 // necessitates this conversion is ill-formed. The result of the
3233 // conversion is a pointer to the base class sub-object of the
3234 // derived class object. The null pointer value is converted to
3235 // the null pointer value of the destination type.
3236 //
3237 // Note that we do not check for ambiguity or inaccessibility
3238 // here. That is handled by CheckPointerConversion.
3239 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3240 ToPointeeType->isRecordType() &&
3241 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3242 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3243 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3244 ToPointee: ToPointeeType,
3245 ToType, Context);
3246 return true;
3247 }
3248
3249 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3250 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3251 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3252 ToPointee: ToPointeeType,
3253 ToType, Context);
3254 return true;
3255 }
3256
3257 return false;
3258}
3259
3260/// Adopt the given qualifiers for the given type.
3261static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3262 Qualifiers TQs = T.getQualifiers();
3263
3264 // Check whether qualifiers already match.
3265 if (TQs == Qs)
3266 return T;
3267
3268 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3269 return Context.getQualifiedType(T, Qs);
3270
3271 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3272}
3273
3274bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3275 QualType& ConvertedType,
3276 bool &IncompatibleObjC) {
3277 if (!getLangOpts().ObjC)
3278 return false;
3279
3280 // The set of qualifiers on the type we're converting from.
3281 Qualifiers FromQualifiers = FromType.getQualifiers();
3282
3283 // First, we handle all conversions on ObjC object pointer types.
3284 const ObjCObjectPointerType* ToObjCPtr =
3285 ToType->getAs<ObjCObjectPointerType>();
3286 const ObjCObjectPointerType *FromObjCPtr =
3287 FromType->getAs<ObjCObjectPointerType>();
3288
3289 if (ToObjCPtr && FromObjCPtr) {
3290 // If the pointee types are the same (ignoring qualifications),
3291 // then this is not a pointer conversion.
3292 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3293 T2: FromObjCPtr->getPointeeType()))
3294 return false;
3295
3296 // Conversion between Objective-C pointers.
3297 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3298 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3299 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3300 if (getLangOpts().CPlusPlus && LHS && RHS &&
3301 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3302 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3303 return false;
3304 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3305 ToPointee: ToObjCPtr->getPointeeType(),
3306 ToType, Context);
3307 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3308 return true;
3309 }
3310
3311 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3312 // Okay: this is some kind of implicit downcast of Objective-C
3313 // interfaces, which is permitted. However, we're going to
3314 // complain about it.
3315 IncompatibleObjC = true;
3316 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3317 ToPointee: ToObjCPtr->getPointeeType(),
3318 ToType, Context);
3319 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3320 return true;
3321 }
3322 }
3323 // Beyond this point, both types need to be C pointers or block pointers.
3324 QualType ToPointeeType;
3325 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3326 ToPointeeType = ToCPtr->getPointeeType();
3327 else if (const BlockPointerType *ToBlockPtr =
3328 ToType->getAs<BlockPointerType>()) {
3329 // Objective C++: We're able to convert from a pointer to any object
3330 // to a block pointer type.
3331 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3332 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3333 return true;
3334 }
3335 ToPointeeType = ToBlockPtr->getPointeeType();
3336 }
3337 else if (FromType->getAs<BlockPointerType>() &&
3338 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3339 // Objective C++: We're able to convert from a block pointer type to a
3340 // pointer to any object.
3341 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3342 return true;
3343 }
3344 else
3345 return false;
3346
3347 QualType FromPointeeType;
3348 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3349 FromPointeeType = FromCPtr->getPointeeType();
3350 else if (const BlockPointerType *FromBlockPtr =
3351 FromType->getAs<BlockPointerType>())
3352 FromPointeeType = FromBlockPtr->getPointeeType();
3353 else
3354 return false;
3355
3356 // If we have pointers to pointers, recursively check whether this
3357 // is an Objective-C conversion.
3358 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3359 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3360 IncompatibleObjC)) {
3361 // We always complain about this conversion.
3362 IncompatibleObjC = true;
3363 ConvertedType = Context.getPointerType(T: ConvertedType);
3364 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3365 return true;
3366 }
3367 // Allow conversion of pointee being objective-c pointer to another one;
3368 // as in I* to id.
3369 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3370 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3371 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3372 IncompatibleObjC)) {
3373
3374 ConvertedType = Context.getPointerType(T: ConvertedType);
3375 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3376 return true;
3377 }
3378
3379 // If we have pointers to functions or blocks, check whether the only
3380 // differences in the argument and result types are in Objective-C
3381 // pointer conversions. If so, we permit the conversion (but
3382 // complain about it).
3383 const FunctionProtoType *FromFunctionType
3384 = FromPointeeType->getAs<FunctionProtoType>();
3385 const FunctionProtoType *ToFunctionType
3386 = ToPointeeType->getAs<FunctionProtoType>();
3387 if (FromFunctionType && ToFunctionType) {
3388 // If the function types are exactly the same, this isn't an
3389 // Objective-C pointer conversion.
3390 if (Context.getCanonicalType(T: FromPointeeType)
3391 == Context.getCanonicalType(T: ToPointeeType))
3392 return false;
3393
3394 // Perform the quick checks that will tell us whether these
3395 // function types are obviously different.
3396 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3397 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3398 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3399 return false;
3400
3401 bool HasObjCConversion = false;
3402 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3403 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3404 // Okay, the types match exactly. Nothing to do.
3405 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3406 ToType: ToFunctionType->getReturnType(),
3407 ConvertedType, IncompatibleObjC)) {
3408 // Okay, we have an Objective-C pointer conversion.
3409 HasObjCConversion = true;
3410 } else {
3411 // Function types are too different. Abort.
3412 return false;
3413 }
3414
3415 // Check argument types.
3416 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3417 ArgIdx != NumArgs; ++ArgIdx) {
3418 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3419 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3420 if (Context.getCanonicalType(T: FromArgType)
3421 == Context.getCanonicalType(T: ToArgType)) {
3422 // Okay, the types match exactly. Nothing to do.
3423 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3424 ConvertedType, IncompatibleObjC)) {
3425 // Okay, we have an Objective-C pointer conversion.
3426 HasObjCConversion = true;
3427 } else {
3428 // Argument types are too different. Abort.
3429 return false;
3430 }
3431 }
3432
3433 if (HasObjCConversion) {
3434 // We had an Objective-C conversion. Allow this pointer
3435 // conversion, but complain about it.
3436 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3437 IncompatibleObjC = true;
3438 return true;
3439 }
3440 }
3441
3442 return false;
3443}
3444
3445bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3446 QualType& ConvertedType) {
3447 QualType ToPointeeType;
3448 if (const BlockPointerType *ToBlockPtr =
3449 ToType->getAs<BlockPointerType>())
3450 ToPointeeType = ToBlockPtr->getPointeeType();
3451 else
3452 return false;
3453
3454 QualType FromPointeeType;
3455 if (const BlockPointerType *FromBlockPtr =
3456 FromType->getAs<BlockPointerType>())
3457 FromPointeeType = FromBlockPtr->getPointeeType();
3458 else
3459 return false;
3460 // We have pointer to blocks, check whether the only
3461 // differences in the argument and result types are in Objective-C
3462 // pointer conversions. If so, we permit the conversion.
3463
3464 const FunctionProtoType *FromFunctionType
3465 = FromPointeeType->getAs<FunctionProtoType>();
3466 const FunctionProtoType *ToFunctionType
3467 = ToPointeeType->getAs<FunctionProtoType>();
3468
3469 if (!FromFunctionType || !ToFunctionType)
3470 return false;
3471
3472 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3473 return true;
3474
3475 // Perform the quick checks that will tell us whether these
3476 // function types are obviously different.
3477 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3478 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3479 return false;
3480
3481 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3482 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3483 if (FromEInfo != ToEInfo)
3484 return false;
3485
3486 bool IncompatibleObjC = false;
3487 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3488 T2: ToFunctionType->getReturnType())) {
3489 // Okay, the types match exactly. Nothing to do.
3490 } else {
3491 QualType RHS = FromFunctionType->getReturnType();
3492 QualType LHS = ToFunctionType->getReturnType();
3493 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3494 !RHS.hasQualifiers() && LHS.hasQualifiers())
3495 LHS = LHS.getUnqualifiedType();
3496
3497 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3498 // OK exact match.
3499 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3500 ConvertedType, IncompatibleObjC)) {
3501 if (IncompatibleObjC)
3502 return false;
3503 // Okay, we have an Objective-C pointer conversion.
3504 }
3505 else
3506 return false;
3507 }
3508
3509 // Check argument types.
3510 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3511 ArgIdx != NumArgs; ++ArgIdx) {
3512 IncompatibleObjC = false;
3513 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3514 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3515 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3516 // Okay, the types match exactly. Nothing to do.
3517 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3518 ConvertedType, IncompatibleObjC)) {
3519 if (IncompatibleObjC)
3520 return false;
3521 // Okay, we have an Objective-C pointer conversion.
3522 } else
3523 // Argument types are too different. Abort.
3524 return false;
3525 }
3526
3527 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3528 bool CanUseToFPT, CanUseFromFPT;
3529 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3530 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3531 NewParamInfos))
3532 return false;
3533
3534 ConvertedType = ToType;
3535 return true;
3536}
3537
3538enum {
3539 ft_default,
3540 ft_different_class,
3541 ft_parameter_arity,
3542 ft_parameter_mismatch,
3543 ft_return_type,
3544 ft_qualifer_mismatch,
3545 ft_noexcept
3546};
3547
3548/// Attempts to get the FunctionProtoType from a Type. Handles
3549/// MemberFunctionPointers properly.
3550static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3551 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3552 return FPT;
3553
3554 if (auto *MPT = FromType->getAs<MemberPointerType>())
3555 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3556
3557 return nullptr;
3558}
3559
3560void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3561 QualType FromType, QualType ToType) {
3562 // If either type is not valid, include no extra info.
3563 if (FromType.isNull() || ToType.isNull()) {
3564 PDiag << ft_default;
3565 return;
3566 }
3567
3568 // Get the function type from the pointers.
3569 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3570 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3571 *ToMember = ToType->castAs<MemberPointerType>();
3572 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3573 D2: ToMember->getMostRecentCXXRecordDecl())) {
3574 PDiag << ft_different_class;
3575 if (ToMember->isSugared())
3576 PDiag << Context.getCanonicalTagType(
3577 TD: ToMember->getMostRecentCXXRecordDecl());
3578 else
3579 PDiag << ToMember->getQualifier();
3580 if (FromMember->isSugared())
3581 PDiag << Context.getCanonicalTagType(
3582 TD: FromMember->getMostRecentCXXRecordDecl());
3583 else
3584 PDiag << FromMember->getQualifier();
3585 return;
3586 }
3587 FromType = FromMember->getPointeeType();
3588 ToType = ToMember->getPointeeType();
3589 }
3590
3591 if (FromType->isPointerType())
3592 FromType = FromType->getPointeeType();
3593 if (ToType->isPointerType())
3594 ToType = ToType->getPointeeType();
3595
3596 // Remove references.
3597 FromType = FromType.getNonReferenceType();
3598 ToType = ToType.getNonReferenceType();
3599
3600 // Don't print extra info for non-specialized template functions.
3601 if (FromType->isInstantiationDependentType() &&
3602 !FromType->getAs<TemplateSpecializationType>()) {
3603 PDiag << ft_default;
3604 return;
3605 }
3606
3607 // No extra info for same types.
3608 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3609 PDiag << ft_default;
3610 return;
3611 }
3612
3613 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3614 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3615
3616 // Both types need to be function types.
3617 if (!FromFunction || !ToFunction) {
3618 PDiag << ft_default;
3619 return;
3620 }
3621
3622 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3623 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3624 << FromFunction->getNumParams();
3625 return;
3626 }
3627
3628 // Handle different parameter types.
3629 unsigned ArgPos;
3630 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3631 PDiag << ft_parameter_mismatch << ArgPos + 1
3632 << ToFunction->getParamType(i: ArgPos)
3633 << FromFunction->getParamType(i: ArgPos);
3634 return;
3635 }
3636
3637 // Handle different return type.
3638 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3639 T2: ToFunction->getReturnType())) {
3640 PDiag << ft_return_type << ToFunction->getReturnType()
3641 << FromFunction->getReturnType();
3642 return;
3643 }
3644
3645 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3646 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3647 << FromFunction->getMethodQuals();
3648 return;
3649 }
3650
3651 // Handle exception specification differences on canonical type (in C++17
3652 // onwards).
3653 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3654 ->isNothrow() !=
3655 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3656 ->isNothrow()) {
3657 PDiag << ft_noexcept;
3658 return;
3659 }
3660
3661 // Unable to find a difference, so add no extra info.
3662 PDiag << ft_default;
3663}
3664
3665bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3666 ArrayRef<QualType> New, unsigned *ArgPos,
3667 bool Reversed) {
3668 assert(llvm::size(Old) == llvm::size(New) &&
3669 "Can't compare parameters of functions with different number of "
3670 "parameters!");
3671
3672 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3673 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3674 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3675
3676 // Ignore address spaces in pointee type. This is to disallow overloading
3677 // on __ptr32/__ptr64 address spaces.
3678 QualType OldType =
3679 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3680 QualType NewType =
3681 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3682
3683 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3684 if (ArgPos)
3685 *ArgPos = Idx;
3686 return false;
3687 }
3688 }
3689 return true;
3690}
3691
3692bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3693 const FunctionProtoType *NewType,
3694 unsigned *ArgPos, bool Reversed) {
3695 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3696 New: NewType->param_types(), ArgPos, Reversed);
3697}
3698
3699bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3700 const FunctionDecl *NewFunction,
3701 unsigned *ArgPos,
3702 bool Reversed) {
3703
3704 if (OldFunction->getNumNonObjectParams() !=
3705 NewFunction->getNumNonObjectParams())
3706 return false;
3707
3708 unsigned OldIgnore =
3709 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3710 unsigned NewIgnore =
3711 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3712
3713 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3714 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3715
3716 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3717 New: NewPT->param_types().slice(N: NewIgnore),
3718 ArgPos, Reversed);
3719}
3720
3721bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3722 CastKind &Kind,
3723 CXXCastPath& BasePath,
3724 bool IgnoreBaseAccess,
3725 bool Diagnose) {
3726 QualType FromType = From->getType();
3727 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3728
3729 Kind = CK_BitCast;
3730
3731 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3732 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3733 Expr::NPCK_ZeroExpression) {
3734 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3735 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3736 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3737 << ToType << From->getSourceRange());
3738 else if (!isUnevaluatedContext())
3739 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3740 << ToType << From->getSourceRange();
3741 }
3742 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3743 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3744 QualType FromPointeeType = FromPtrType->getPointeeType(),
3745 ToPointeeType = ToPtrType->getPointeeType();
3746
3747 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3748 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3749 // We must have a derived-to-base conversion. Check an
3750 // ambiguous or inaccessible conversion.
3751 unsigned InaccessibleID = 0;
3752 unsigned AmbiguousID = 0;
3753 if (Diagnose) {
3754 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3755 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3756 }
3757 if (CheckDerivedToBaseConversion(
3758 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3759 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3760 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3761 return true;
3762
3763 // The conversion was successful.
3764 Kind = CK_DerivedToBase;
3765 }
3766
3767 if (Diagnose && !IsCStyleOrFunctionalCast &&
3768 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3769 assert(getLangOpts().MSVCCompat &&
3770 "this should only be possible with MSVCCompat!");
3771 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3772 << From->getSourceRange();
3773 }
3774 }
3775 } else if (const ObjCObjectPointerType *ToPtrType =
3776 ToType->getAs<ObjCObjectPointerType>()) {
3777 if (const ObjCObjectPointerType *FromPtrType =
3778 FromType->getAs<ObjCObjectPointerType>()) {
3779 // Objective-C++ conversions are always okay.
3780 // FIXME: We should have a different class of conversions for the
3781 // Objective-C++ implicit conversions.
3782 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3783 return false;
3784 } else if (FromType->isBlockPointerType()) {
3785 Kind = CK_BlockPointerToObjCPointerCast;
3786 } else {
3787 Kind = CK_CPointerToObjCPointerCast;
3788 }
3789 } else if (ToType->isBlockPointerType()) {
3790 if (!FromType->isBlockPointerType())
3791 Kind = CK_AnyPointerToBlockPointerCast;
3792 }
3793
3794 // We shouldn't fall into this case unless it's valid for other
3795 // reasons.
3796 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3797 Kind = CK_NullToPointer;
3798
3799 return false;
3800}
3801
3802bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3803 QualType ToType,
3804 bool InOverloadResolution,
3805 QualType &ConvertedType) {
3806 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3807 if (!ToTypePtr)
3808 return false;
3809
3810 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3811 if (From->isNullPointerConstant(Ctx&: Context,
3812 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3813 : Expr::NPC_ValueDependentIsNull)) {
3814 ConvertedType = ToType;
3815 return true;
3816 }
3817
3818 // Otherwise, both types have to be member pointers.
3819 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3820 if (!FromTypePtr)
3821 return false;
3822
3823 // A pointer to member of B can be converted to a pointer to member of D,
3824 // where D is derived from B (C++ 4.11p2).
3825 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3826 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3827
3828 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3829 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3830 ConvertedType = Context.getMemberPointerType(
3831 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3832 return true;
3833 }
3834
3835 return false;
3836}
3837
3838Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3839 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3840 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3841 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3842 // Lock down the inheritance model right now in MS ABI, whether or not the
3843 // pointee types are the same.
3844 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3845 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3846 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3847 }
3848
3849 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3850 if (!FromPtrType) {
3851 // This must be a null pointer to member pointer conversion
3852 Kind = CK_NullToMemberPointer;
3853 return MemberPointerConversionResult::Success;
3854 }
3855
3856 // T == T, modulo cv
3857 if (Direction == MemberPointerConversionDirection::Upcast &&
3858 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3859 T2: ToPtrType->getPointeeType()))
3860 return MemberPointerConversionResult::DifferentPointee;
3861
3862 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3863 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3864
3865 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3866 const CXXRecordDecl *Cls) {
3867 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3868 PD << Qual;
3869 else
3870 PD << Context.getCanonicalTagType(TD: Cls);
3871 };
3872 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3873 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3874 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3875 return PD;
3876 };
3877
3878 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3879 if (Direction == MemberPointerConversionDirection::Upcast)
3880 std::swap(a&: Base, b&: Derived);
3881
3882 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3883 /*DetectVirtual=*/true);
3884 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3885 return MemberPointerConversionResult::NotDerived;
3886
3887 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3888 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3889 PD << int(Direction);
3890 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3891 Diag(Loc: CheckLoc, PD);
3892 return MemberPointerConversionResult::Ambiguous;
3893 }
3894
3895 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3896 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3897 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3898 Diag(Loc: CheckLoc, PD);
3899 return MemberPointerConversionResult::Virtual;
3900 }
3901
3902 // Must be a base to derived member conversion.
3903 BuildBasePathArray(Paths, BasePath);
3904 Kind = Direction == MemberPointerConversionDirection::Upcast
3905 ? CK_DerivedToBaseMemberPointer
3906 : CK_BaseToDerivedMemberPointer;
3907
3908 if (!IgnoreBaseAccess)
3909 switch (CheckBaseClassAccess(
3910 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3911 DiagID: Direction == MemberPointerConversionDirection::Upcast
3912 ? diag::err_upcast_to_inaccessible_base
3913 : diag::err_downcast_from_inaccessible_base,
3914 SetupPDiag: [&](PartialDiagnostic &PD) {
3915 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3916 DerivedQual = ToPtrType->getQualifier();
3917 if (Direction == MemberPointerConversionDirection::Upcast)
3918 std::swap(a&: BaseQual, b&: DerivedQual);
3919 DiagCls(PD, DerivedQual, Derived);
3920 DiagCls(PD, BaseQual, Base);
3921 })) {
3922 case Sema::AR_accessible:
3923 case Sema::AR_delayed:
3924 case Sema::AR_dependent:
3925 // Optimistically assume that the delayed and dependent cases
3926 // will work out.
3927 break;
3928
3929 case Sema::AR_inaccessible:
3930 return MemberPointerConversionResult::Inaccessible;
3931 }
3932
3933 return MemberPointerConversionResult::Success;
3934}
3935
3936/// Determine whether the lifetime conversion between the two given
3937/// qualifiers sets is nontrivial.
3938static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3939 Qualifiers ToQuals) {
3940 // Converting anything to const __unsafe_unretained is trivial.
3941 if (ToQuals.hasConst() &&
3942 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3943 return false;
3944
3945 return true;
3946}
3947
3948/// Perform a single iteration of the loop for checking if a qualification
3949/// conversion is valid.
3950///
3951/// Specifically, check whether any change between the qualifiers of \p
3952/// FromType and \p ToType is permissible, given knowledge about whether every
3953/// outer layer is const-qualified.
3954static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3955 bool CStyle, bool IsTopLevel,
3956 bool &PreviousToQualsIncludeConst,
3957 bool &ObjCLifetimeConversion,
3958 const ASTContext &Ctx) {
3959 Qualifiers FromQuals = FromType.getQualifiers();
3960 Qualifiers ToQuals = ToType.getQualifiers();
3961
3962 // Ignore __unaligned qualifier.
3963 FromQuals.removeUnaligned();
3964
3965 // Objective-C ARC:
3966 // Check Objective-C lifetime conversions.
3967 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3968 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3969 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3970 ObjCLifetimeConversion = true;
3971 FromQuals.removeObjCLifetime();
3972 ToQuals.removeObjCLifetime();
3973 } else {
3974 // Qualification conversions cannot cast between different
3975 // Objective-C lifetime qualifiers.
3976 return false;
3977 }
3978 }
3979
3980 // Allow addition/removal of GC attributes but not changing GC attributes.
3981 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3982 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3983 FromQuals.removeObjCGCAttr();
3984 ToQuals.removeObjCGCAttr();
3985 }
3986
3987 // __ptrauth qualifiers must match exactly.
3988 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3989 return false;
3990
3991 // -- for every j > 0, if const is in cv 1,j then const is in cv
3992 // 2,j, and similarly for volatile.
3993 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3994 return false;
3995
3996 // If address spaces mismatch:
3997 // - in top level it is only valid to convert to addr space that is a
3998 // superset in all cases apart from C-style casts where we allow
3999 // conversions between overlapping address spaces.
4000 // - in non-top levels it is not a valid conversion.
4001 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
4002 (!IsTopLevel ||
4003 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
4004 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
4005 return false;
4006
4007 // -- if the cv 1,j and cv 2,j are different, then const is in
4008 // every cv for 0 < k < j.
4009 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
4010 !PreviousToQualsIncludeConst)
4011 return false;
4012
4013 // The following wording is from C++20, where the result of the conversion
4014 // is T3, not T2.
4015 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
4016 // "array of unknown bound of"
4017 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
4018 return false;
4019
4020 // -- if the resulting P3,i is different from P1,i [...], then const is
4021 // added to every cv 3_k for 0 < k < i.
4022 if (!CStyle && FromType->isConstantArrayType() &&
4023 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
4024 return false;
4025
4026 // Keep track of whether all prior cv-qualifiers in the "to" type
4027 // include const.
4028 PreviousToQualsIncludeConst =
4029 PreviousToQualsIncludeConst && ToQuals.hasConst();
4030 return true;
4031}
4032
4033bool
4034Sema::IsQualificationConversion(QualType FromType, QualType ToType,
4035 bool CStyle, bool &ObjCLifetimeConversion) {
4036 FromType = Context.getCanonicalType(T: FromType);
4037 ToType = Context.getCanonicalType(T: ToType);
4038 ObjCLifetimeConversion = false;
4039
4040 // If FromType and ToType are the same type, this is not a
4041 // qualification conversion.
4042 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
4043 return false;
4044
4045 // (C++ 4.4p4):
4046 // A conversion can add cv-qualifiers at levels other than the first
4047 // in multi-level pointers, subject to the following rules: [...]
4048 bool PreviousToQualsIncludeConst = true;
4049 bool UnwrappedAnyPointer = false;
4050 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
4051 if (!isQualificationConversionStep(FromType, ToType, CStyle,
4052 IsTopLevel: !UnwrappedAnyPointer,
4053 PreviousToQualsIncludeConst,
4054 ObjCLifetimeConversion, Ctx: getASTContext()))
4055 return false;
4056 UnwrappedAnyPointer = true;
4057 }
4058
4059 // We are left with FromType and ToType being the pointee types
4060 // after unwrapping the original FromType and ToType the same number
4061 // of times. If we unwrapped any pointers, and if FromType and
4062 // ToType have the same unqualified type (since we checked
4063 // qualifiers above), then this is a qualification conversion.
4064 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
4065}
4066
4067/// - Determine whether this is a conversion from a scalar type to an
4068/// atomic type.
4069///
4070/// If successful, updates \c SCS's second and third steps in the conversion
4071/// sequence to finish the conversion.
4072static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4073 bool InOverloadResolution,
4074 StandardConversionSequence &SCS,
4075 bool CStyle) {
4076 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4077 if (!ToAtomic)
4078 return false;
4079
4080 StandardConversionSequence InnerSCS;
4081 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
4082 InOverloadResolution, SCS&: InnerSCS,
4083 CStyle, /*AllowObjCWritebackConversion=*/false))
4084 return false;
4085
4086 SCS.Second = InnerSCS.Second;
4087 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4088 SCS.Third = InnerSCS.Third;
4089 SCS.QualificationIncludesObjCLifetime
4090 = InnerSCS.QualificationIncludesObjCLifetime;
4091 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4092 return true;
4093}
4094
4095static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
4096 QualType ToType,
4097 bool InOverloadResolution,
4098 StandardConversionSequence &SCS,
4099 bool CStyle) {
4100 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4101 if (!ToOBT)
4102 return false;
4103
4104 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4105 QualType FromType = From->getType();
4106 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4107 return false;
4108
4109 StandardConversionSequence InnerSCS;
4110 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4111 InOverloadResolution, SCS&: InnerSCS, CStyle,
4112 /*AllowObjCWritebackConversion=*/false))
4113 return false;
4114
4115 SCS.Second = InnerSCS.Second;
4116 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4117 SCS.Third = InnerSCS.Third;
4118 SCS.QualificationIncludesObjCLifetime =
4119 InnerSCS.QualificationIncludesObjCLifetime;
4120 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4121 return true;
4122}
4123
4124static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4125 CXXConstructorDecl *Constructor,
4126 QualType Type) {
4127 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4128 if (CtorType->getNumParams() > 0) {
4129 QualType FirstArg = CtorType->getParamType(i: 0);
4130 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4131 return true;
4132 }
4133 return false;
4134}
4135
4136static OverloadingResult
4137IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4138 CXXRecordDecl *To,
4139 UserDefinedConversionSequence &User,
4140 OverloadCandidateSet &CandidateSet,
4141 bool AllowExplicit) {
4142 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4143 for (auto *D : S.LookupConstructors(Class: To)) {
4144 auto Info = getConstructorInfo(ND: D);
4145 if (!Info)
4146 continue;
4147
4148 bool Usable = !Info.Constructor->isInvalidDecl() &&
4149 S.isInitListConstructor(Ctor: Info.Constructor);
4150 if (Usable) {
4151 bool SuppressUserConversions = false;
4152 if (Info.ConstructorTmpl)
4153 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4154 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4155 CandidateSet, SuppressUserConversions,
4156 /*PartialOverloading*/ false,
4157 AllowExplicit);
4158 else
4159 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4160 CandidateSet, SuppressUserConversions,
4161 /*PartialOverloading*/ false, AllowExplicit);
4162 }
4163 }
4164
4165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4166
4167 OverloadCandidateSet::iterator Best;
4168 switch (auto Result =
4169 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4170 case OR_Deleted:
4171 case OR_Success: {
4172 // Record the standard conversion we used and the conversion function.
4173 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4174 QualType ThisType = Constructor->getFunctionObjectParameterType();
4175 // Initializer lists don't have conversions as such.
4176 User.Before.setAsIdentityConversion();
4177 User.HadMultipleCandidates = HadMultipleCandidates;
4178 User.ConversionFunction = Constructor;
4179 User.FoundConversionFunction = Best->FoundDecl;
4180 User.After.setAsIdentityConversion();
4181 User.After.setFromType(ThisType);
4182 User.After.setAllToTypes(ToType);
4183 return Result;
4184 }
4185
4186 case OR_No_Viable_Function:
4187 return OR_No_Viable_Function;
4188 case OR_Ambiguous:
4189 return OR_Ambiguous;
4190 }
4191
4192 llvm_unreachable("Invalid OverloadResult!");
4193}
4194
4195/// Determines whether there is a user-defined conversion sequence
4196/// (C++ [over.ics.user]) that converts expression From to the type
4197/// ToType. If such a conversion exists, User will contain the
4198/// user-defined conversion sequence that performs such a conversion
4199/// and this routine will return true. Otherwise, this routine returns
4200/// false and User is unspecified.
4201///
4202/// \param AllowExplicit true if the conversion should consider C++0x
4203/// "explicit" conversion functions as well as non-explicit conversion
4204/// functions (C++0x [class.conv.fct]p2).
4205///
4206/// \param AllowObjCConversionOnExplicit true if the conversion should
4207/// allow an extra Objective-C pointer conversion on uses of explicit
4208/// constructors. Requires \c AllowExplicit to also be set.
4209static OverloadingResult
4210IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4211 UserDefinedConversionSequence &User,
4212 OverloadCandidateSet &CandidateSet,
4213 AllowedExplicit AllowExplicit,
4214 bool AllowObjCConversionOnExplicit) {
4215 assert(AllowExplicit != AllowedExplicit::None ||
4216 !AllowObjCConversionOnExplicit);
4217 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4218
4219 // Whether we will only visit constructors.
4220 bool ConstructorsOnly = false;
4221
4222 // If the type we are conversion to is a class type, enumerate its
4223 // constructors.
4224 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4225 // C++ [over.match.ctor]p1:
4226 // When objects of class type are direct-initialized (8.5), or
4227 // copy-initialized from an expression of the same or a
4228 // derived class type (8.5), overload resolution selects the
4229 // constructor. [...] For copy-initialization, the candidate
4230 // functions are all the converting constructors (12.3.1) of
4231 // that class. The argument list is the expression-list within
4232 // the parentheses of the initializer.
4233 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4234 (From->getType()->isRecordType() &&
4235 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4236 ConstructorsOnly = true;
4237
4238 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4239 // We're not going to find any constructors.
4240 } else if (auto *ToRecordDecl =
4241 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4242 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4243
4244 Expr **Args = &From;
4245 unsigned NumArgs = 1;
4246 bool ListInitializing = false;
4247 SmallVector<Expr *, 8> ExpandedInits;
4248 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4249 // But first, see if there is an init-list-constructor that will work.
4250 OverloadingResult Result = IsInitializerListConstructorConversion(
4251 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4252 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4253 if (Result != OR_No_Viable_Function)
4254 return Result;
4255 // Never mind.
4256 CandidateSet.clear(
4257 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4258
4259 // If we're list-initializing, we pass the individual elements as
4260 // arguments, not the entire list.
4261 MultiExprArg Inits =
4262 S.getInitsWithEmbedExpanded(ILE: InitList, Storage&: ExpandedInits);
4263 Args = Inits.data();
4264 NumArgs = Inits.size();
4265 ListInitializing = true;
4266 }
4267
4268 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4269 auto Info = getConstructorInfo(ND: D);
4270 if (!Info)
4271 continue;
4272
4273 bool Usable = !Info.Constructor->isInvalidDecl();
4274 if (!ListInitializing)
4275 Usable = Usable && Info.Constructor->isConvertingConstructor(
4276 /*AllowExplicit*/ true);
4277 if (Usable) {
4278 bool SuppressUserConversions = !ConstructorsOnly;
4279 // C++20 [over.best.ics.general]/4.5:
4280 // if the target is the first parameter of a constructor [of class
4281 // X] and the constructor [...] is a candidate by [...] the second
4282 // phase of [over.match.list] when the initializer list has exactly
4283 // one element that is itself an initializer list, [...] and the
4284 // conversion is to X or reference to cv X, user-defined conversion
4285 // sequences are not considered.
4286 if (SuppressUserConversions && ListInitializing) {
4287 SuppressUserConversions =
4288 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4289 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4290 Type: ToType);
4291 }
4292 if (Info.ConstructorTmpl)
4293 S.AddTemplateOverloadCandidate(
4294 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4295 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4296 CandidateSet, SuppressUserConversions,
4297 /*PartialOverloading*/ false,
4298 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4299 else
4300 // Allow one user-defined conversion when user specifies a
4301 // From->ToType conversion via an static cast (c-style, etc).
4302 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4303 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4304 SuppressUserConversions,
4305 /*PartialOverloading*/ false,
4306 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4307 }
4308 }
4309 }
4310 }
4311
4312 // Enumerate conversion functions, if we're allowed to.
4313 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4314 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4315 // No conversion functions from incomplete types.
4316 } else if (const RecordType *FromRecordType =
4317 From->getType()->getAsCanonical<RecordType>()) {
4318 if (auto *FromRecordDecl =
4319 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4320 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4321 // Add all of the conversion functions as candidates.
4322 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4323 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4324 DeclAccessPair FoundDecl = I.getPair();
4325 NamedDecl *D = FoundDecl.getDecl();
4326 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4327 if (isa<UsingShadowDecl>(Val: D))
4328 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4329
4330 CXXConversionDecl *Conv;
4331 FunctionTemplateDecl *ConvTemplate;
4332 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4333 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4334 else
4335 Conv = cast<CXXConversionDecl>(Val: D);
4336
4337 if (ConvTemplate)
4338 S.AddTemplateConversionCandidate(
4339 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4340 CandidateSet, AllowObjCConversionOnExplicit,
4341 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4342 else
4343 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4344 CandidateSet, AllowObjCConversionOnExplicit,
4345 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4346 }
4347 }
4348 }
4349
4350 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4351
4352 OverloadCandidateSet::iterator Best;
4353 switch (auto Result =
4354 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4355 case OR_Success:
4356 case OR_Deleted:
4357 // Record the standard conversion we used and the conversion function.
4358 if (CXXConstructorDecl *Constructor
4359 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4360 // C++ [over.ics.user]p1:
4361 // If the user-defined conversion is specified by a
4362 // constructor (12.3.1), the initial standard conversion
4363 // sequence converts the source type to the type required by
4364 // the argument of the constructor.
4365 //
4366 if (isa<InitListExpr>(Val: From)) {
4367 // Initializer lists don't have conversions as such.
4368 User.Before.setAsIdentityConversion();
4369 User.Before.FromBracedInitList = true;
4370 } else {
4371 if (Best->Conversions[0].isEllipsis())
4372 User.EllipsisConversion = true;
4373 else {
4374 User.Before = Best->Conversions[0].Standard;
4375 User.EllipsisConversion = false;
4376 }
4377 }
4378 User.HadMultipleCandidates = HadMultipleCandidates;
4379 User.ConversionFunction = Constructor;
4380 User.FoundConversionFunction = Best->FoundDecl;
4381 User.After.setAsIdentityConversion();
4382 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4383 User.After.setAllToTypes(ToType);
4384 return Result;
4385 }
4386 if (CXXConversionDecl *Conversion
4387 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4388
4389 assert(Best->HasFinalConversion);
4390
4391 // C++ [over.ics.user]p1:
4392 //
4393 // [...] If the user-defined conversion is specified by a
4394 // conversion function (12.3.2), the initial standard
4395 // conversion sequence converts the source type to the
4396 // implicit object parameter of the conversion function.
4397 User.Before = Best->Conversions[0].Standard;
4398 User.HadMultipleCandidates = HadMultipleCandidates;
4399 User.ConversionFunction = Conversion;
4400 User.FoundConversionFunction = Best->FoundDecl;
4401 User.EllipsisConversion = false;
4402
4403 // C++ [over.ics.user]p2:
4404 // The second standard conversion sequence converts the
4405 // result of the user-defined conversion to the target type
4406 // for the sequence. Since an implicit conversion sequence
4407 // is an initialization, the special rules for
4408 // initialization by user-defined conversion apply when
4409 // selecting the best user-defined conversion for a
4410 // user-defined conversion sequence (see 13.3.3 and
4411 // 13.3.3.1).
4412 User.After = Best->FinalConversion;
4413 return Result;
4414 }
4415 llvm_unreachable("Not a constructor or conversion function?");
4416
4417 case OR_No_Viable_Function:
4418 return OR_No_Viable_Function;
4419
4420 case OR_Ambiguous:
4421 return OR_Ambiguous;
4422 }
4423
4424 llvm_unreachable("Invalid OverloadResult!");
4425}
4426
4427bool
4428Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4429 ImplicitConversionSequence ICS;
4430 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4431 OverloadCandidateSet::CSK_Normal);
4432 OverloadingResult OvResult =
4433 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4434 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4435
4436 if (!(OvResult == OR_Ambiguous ||
4437 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4438 return false;
4439
4440 auto Cands = CandidateSet.CompleteCandidates(
4441 S&: *this,
4442 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4443 Args: From);
4444 if (OvResult == OR_Ambiguous)
4445 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4446 << From->getType() << ToType << From->getSourceRange();
4447 else { // OR_No_Viable_Function && !CandidateSet.empty()
4448 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4449 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4450 Args: From->getType(), Args: From->getSourceRange()))
4451 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4452 << false << From->getType() << From->getSourceRange() << ToType;
4453 }
4454
4455 CandidateSet.NoteCandidates(
4456 S&: *this, Args: From, Cands);
4457 return true;
4458}
4459
4460// Helper for compareConversionFunctions that gets the FunctionType that the
4461// conversion-operator return value 'points' to, or nullptr.
4462static const FunctionType *
4463getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4464 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4465 const PointerType *RetPtrTy =
4466 ConvFuncTy->getReturnType()->getAs<PointerType>();
4467
4468 if (!RetPtrTy)
4469 return nullptr;
4470
4471 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4472}
4473
4474/// Compare the user-defined conversion functions or constructors
4475/// of two user-defined conversion sequences to determine whether any ordering
4476/// is possible.
4477static ImplicitConversionSequence::CompareKind
4478compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4479 FunctionDecl *Function2) {
4480 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4481 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4482 if (!Conv1 || !Conv2)
4483 return ImplicitConversionSequence::Indistinguishable;
4484
4485 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4486 return ImplicitConversionSequence::Indistinguishable;
4487
4488 // Objective-C++:
4489 // If both conversion functions are implicitly-declared conversions from
4490 // a lambda closure type to a function pointer and a block pointer,
4491 // respectively, always prefer the conversion to a function pointer,
4492 // because the function pointer is more lightweight and is more likely
4493 // to keep code working.
4494 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4495 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4496 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4497 if (Block1 != Block2)
4498 return Block1 ? ImplicitConversionSequence::Worse
4499 : ImplicitConversionSequence::Better;
4500 }
4501
4502 // In order to support multiple calling conventions for the lambda conversion
4503 // operator (such as when the free and member function calling convention is
4504 // different), prefer the 'free' mechanism, followed by the calling-convention
4505 // of operator(). The latter is in place to support the MSVC-like solution of
4506 // defining ALL of the possible conversions in regards to calling-convention.
4507 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4508 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4509
4510 if (Conv1FuncRet && Conv2FuncRet &&
4511 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4512 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4513 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4514
4515 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4516 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4517
4518 CallingConv CallOpCC =
4519 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4520 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4521 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4522 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4523 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4524
4525 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4526 for (CallingConv CC : PrefOrder) {
4527 if (Conv1CC == CC)
4528 return ImplicitConversionSequence::Better;
4529 if (Conv2CC == CC)
4530 return ImplicitConversionSequence::Worse;
4531 }
4532 }
4533
4534 return ImplicitConversionSequence::Indistinguishable;
4535}
4536
4537static bool hasDeprecatedStringLiteralToCharPtrConversion(
4538 const ImplicitConversionSequence &ICS) {
4539 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4540 (ICS.isUserDefined() &&
4541 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4542}
4543
4544/// CompareImplicitConversionSequences - Compare two implicit
4545/// conversion sequences to determine whether one is better than the
4546/// other or if they are indistinguishable (C++ 13.3.3.2).
4547static ImplicitConversionSequence::CompareKind
4548CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4549 const ImplicitConversionSequence& ICS1,
4550 const ImplicitConversionSequence& ICS2)
4551{
4552 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4553 // conversion sequences (as defined in 13.3.3.1)
4554 // -- a standard conversion sequence (13.3.3.1.1) is a better
4555 // conversion sequence than a user-defined conversion sequence or
4556 // an ellipsis conversion sequence, and
4557 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4558 // conversion sequence than an ellipsis conversion sequence
4559 // (13.3.3.1.3).
4560 //
4561 // C++0x [over.best.ics]p10:
4562 // For the purpose of ranking implicit conversion sequences as
4563 // described in 13.3.3.2, the ambiguous conversion sequence is
4564 // treated as a user-defined sequence that is indistinguishable
4565 // from any other user-defined conversion sequence.
4566
4567 // String literal to 'char *' conversion has been deprecated in C++03. It has
4568 // been removed from C++11. We still accept this conversion, if it happens at
4569 // the best viable function. Otherwise, this conversion is considered worse
4570 // than ellipsis conversion. Consider this as an extension; this is not in the
4571 // standard. For example:
4572 //
4573 // int &f(...); // #1
4574 // void f(char*); // #2
4575 // void g() { int &r = f("foo"); }
4576 //
4577 // In C++03, we pick #2 as the best viable function.
4578 // In C++11, we pick #1 as the best viable function, because ellipsis
4579 // conversion is better than string-literal to char* conversion (since there
4580 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4581 // convert arguments, #2 would be the best viable function in C++11.
4582 // If the best viable function has this conversion, a warning will be issued
4583 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4584
4585 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4586 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4587 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4588 // Ill-formedness must not differ
4589 ICS1.isBad() == ICS2.isBad())
4590 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4591 ? ImplicitConversionSequence::Worse
4592 : ImplicitConversionSequence::Better;
4593
4594 if (ICS1.getKindRank() < ICS2.getKindRank())
4595 return ImplicitConversionSequence::Better;
4596 if (ICS2.getKindRank() < ICS1.getKindRank())
4597 return ImplicitConversionSequence::Worse;
4598
4599 // The following checks require both conversion sequences to be of
4600 // the same kind.
4601 if (ICS1.getKind() != ICS2.getKind())
4602 return ImplicitConversionSequence::Indistinguishable;
4603
4604 ImplicitConversionSequence::CompareKind Result =
4605 ImplicitConversionSequence::Indistinguishable;
4606
4607 // Two implicit conversion sequences of the same form are
4608 // indistinguishable conversion sequences unless one of the
4609 // following rules apply: (C++ 13.3.3.2p3):
4610
4611 // List-initialization sequence L1 is a better conversion sequence than
4612 // list-initialization sequence L2 if:
4613 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4614 // if not that,
4615 // — L1 and L2 convert to arrays of the same element type, and either the
4616 // number of elements n_1 initialized by L1 is less than the number of
4617 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4618 // an array of unknown bound and L1 does not,
4619 // even if one of the other rules in this paragraph would otherwise apply.
4620 if (!ICS1.isBad()) {
4621 bool StdInit1 = false, StdInit2 = false;
4622 if (ICS1.hasInitializerListContainerType())
4623 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4624 Element: nullptr);
4625 if (ICS2.hasInitializerListContainerType())
4626 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4627 Element: nullptr);
4628 if (StdInit1 != StdInit2)
4629 return StdInit1 ? ImplicitConversionSequence::Better
4630 : ImplicitConversionSequence::Worse;
4631
4632 if (ICS1.hasInitializerListContainerType() &&
4633 ICS2.hasInitializerListContainerType())
4634 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4635 T: ICS1.getInitializerListContainerType()))
4636 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4637 T: ICS2.getInitializerListContainerType())) {
4638 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4639 T2: CAT2->getElementType())) {
4640 // Both to arrays of the same element type
4641 if (CAT1->getSize() != CAT2->getSize())
4642 // Different sized, the smaller wins
4643 return CAT1->getSize().ult(RHS: CAT2->getSize())
4644 ? ImplicitConversionSequence::Better
4645 : ImplicitConversionSequence::Worse;
4646 if (ICS1.isInitializerListOfIncompleteArray() !=
4647 ICS2.isInitializerListOfIncompleteArray())
4648 // One is incomplete, it loses
4649 return ICS2.isInitializerListOfIncompleteArray()
4650 ? ImplicitConversionSequence::Better
4651 : ImplicitConversionSequence::Worse;
4652 }
4653 }
4654 }
4655
4656 if (ICS1.isStandard())
4657 // Standard conversion sequence S1 is a better conversion sequence than
4658 // standard conversion sequence S2 if [...]
4659 Result = CompareStandardConversionSequences(S, Loc,
4660 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4661 else if (ICS1.isUserDefined()) {
4662 // With lazy template loading, it is possible to find non-canonical
4663 // FunctionDecls, depending on when redecl chains are completed. Make sure
4664 // to compare the canonical decls of conversion functions. This avoids
4665 // ambiguity problems for templated conversion operators.
4666 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4667 if (ConvFunc1)
4668 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4669 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4670 if (ConvFunc2)
4671 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4672 // User-defined conversion sequence U1 is a better conversion
4673 // sequence than another user-defined conversion sequence U2 if
4674 // they contain the same user-defined conversion function or
4675 // constructor and if the second standard conversion sequence of
4676 // U1 is better than the second standard conversion sequence of
4677 // U2 (C++ 13.3.3.2p3).
4678 if (ConvFunc1 == ConvFunc2)
4679 Result = CompareStandardConversionSequences(S, Loc,
4680 SCS1: ICS1.UserDefined.After,
4681 SCS2: ICS2.UserDefined.After);
4682 else
4683 Result = compareConversionFunctions(S,
4684 Function1: ICS1.UserDefined.ConversionFunction,
4685 Function2: ICS2.UserDefined.ConversionFunction);
4686 }
4687
4688 return Result;
4689}
4690
4691// Per 13.3.3.2p3, compare the given standard conversion sequences to
4692// determine if one is a proper subset of the other.
4693static ImplicitConversionSequence::CompareKind
4694compareStandardConversionSubsets(ASTContext &Context,
4695 const StandardConversionSequence& SCS1,
4696 const StandardConversionSequence& SCS2) {
4697 ImplicitConversionSequence::CompareKind Result
4698 = ImplicitConversionSequence::Indistinguishable;
4699
4700 // the identity conversion sequence is considered to be a subsequence of
4701 // any non-identity conversion sequence
4702 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4703 return ImplicitConversionSequence::Better;
4704 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4705 return ImplicitConversionSequence::Worse;
4706
4707 if (SCS1.Second != SCS2.Second) {
4708 if (SCS1.Second == ICK_Identity)
4709 Result = ImplicitConversionSequence::Better;
4710 else if (SCS2.Second == ICK_Identity)
4711 Result = ImplicitConversionSequence::Worse;
4712 else
4713 return ImplicitConversionSequence::Indistinguishable;
4714 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4715 return ImplicitConversionSequence::Indistinguishable;
4716
4717 if (SCS1.Third == SCS2.Third) {
4718 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4719 : ImplicitConversionSequence::Indistinguishable;
4720 }
4721
4722 if (SCS1.Third == ICK_Identity)
4723 return Result == ImplicitConversionSequence::Worse
4724 ? ImplicitConversionSequence::Indistinguishable
4725 : ImplicitConversionSequence::Better;
4726
4727 if (SCS2.Third == ICK_Identity)
4728 return Result == ImplicitConversionSequence::Better
4729 ? ImplicitConversionSequence::Indistinguishable
4730 : ImplicitConversionSequence::Worse;
4731
4732 return ImplicitConversionSequence::Indistinguishable;
4733}
4734
4735/// Determine whether one of the given reference bindings is better
4736/// than the other based on what kind of bindings they are.
4737static bool
4738isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4739 const StandardConversionSequence &SCS2) {
4740 // C++0x [over.ics.rank]p3b4:
4741 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4742 // implicit object parameter of a non-static member function declared
4743 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4744 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4745 // lvalue reference to a function lvalue and S2 binds an rvalue
4746 // reference*.
4747 //
4748 // FIXME: Rvalue references. We're going rogue with the above edits,
4749 // because the semantics in the current C++0x working paper (N3225 at the
4750 // time of this writing) break the standard definition of std::forward
4751 // and std::reference_wrapper when dealing with references to functions.
4752 // Proposed wording changes submitted to CWG for consideration.
4753 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4754 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4755 return false;
4756
4757 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4758 SCS2.IsLvalueReference) ||
4759 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4760 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4761}
4762
4763enum class FixedEnumPromotion {
4764 None,
4765 ToUnderlyingType,
4766 ToPromotedUnderlyingType
4767};
4768
4769/// Returns kind of fixed enum promotion the \a SCS uses.
4770static FixedEnumPromotion
4771getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4772
4773 if (SCS.Second != ICK_Integral_Promotion)
4774 return FixedEnumPromotion::None;
4775
4776 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4777 if (!Enum)
4778 return FixedEnumPromotion::None;
4779
4780 if (!Enum->isFixed())
4781 return FixedEnumPromotion::None;
4782
4783 QualType UnderlyingType = Enum->getIntegerType();
4784 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4785 return FixedEnumPromotion::ToUnderlyingType;
4786
4787 return FixedEnumPromotion::ToPromotedUnderlyingType;
4788}
4789
4790/// CompareStandardConversionSequences - Compare two standard
4791/// conversion sequences to determine whether one is better than the
4792/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4793static ImplicitConversionSequence::CompareKind
4794CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4795 const StandardConversionSequence& SCS1,
4796 const StandardConversionSequence& SCS2)
4797{
4798 // Standard conversion sequence S1 is a better conversion sequence
4799 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4800
4801 // -- S1 is a proper subsequence of S2 (comparing the conversion
4802 // sequences in the canonical form defined by 13.3.3.1.1,
4803 // excluding any Lvalue Transformation; the identity conversion
4804 // sequence is considered to be a subsequence of any
4805 // non-identity conversion sequence) or, if not that,
4806 if (ImplicitConversionSequence::CompareKind CK
4807 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4808 return CK;
4809
4810 // -- the rank of S1 is better than the rank of S2 (by the rules
4811 // defined below), or, if not that,
4812 ImplicitConversionRank Rank1 = SCS1.getRank();
4813 ImplicitConversionRank Rank2 = SCS2.getRank();
4814 if (Rank1 < Rank2)
4815 return ImplicitConversionSequence::Better;
4816 else if (Rank2 < Rank1)
4817 return ImplicitConversionSequence::Worse;
4818
4819 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4820 // are indistinguishable unless one of the following rules
4821 // applies:
4822
4823 // A conversion that is not a conversion of a pointer, or
4824 // pointer to member, to bool is better than another conversion
4825 // that is such a conversion.
4826 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4827 return SCS2.isPointerConversionToBool()
4828 ? ImplicitConversionSequence::Better
4829 : ImplicitConversionSequence::Worse;
4830
4831 // C++14 [over.ics.rank]p4b2:
4832 // This is retroactively applied to C++11 by CWG 1601.
4833 //
4834 // A conversion that promotes an enumeration whose underlying type is fixed
4835 // to its underlying type is better than one that promotes to the promoted
4836 // underlying type, if the two are different.
4837 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4838 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4839 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4840 FEP1 != FEP2)
4841 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4842 ? ImplicitConversionSequence::Better
4843 : ImplicitConversionSequence::Worse;
4844
4845 // C++ [over.ics.rank]p4b2:
4846 //
4847 // If class B is derived directly or indirectly from class A,
4848 // conversion of B* to A* is better than conversion of B* to
4849 // void*, and conversion of A* to void* is better than conversion
4850 // of B* to void*.
4851 bool SCS1ConvertsToVoid
4852 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4853 bool SCS2ConvertsToVoid
4854 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4855 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4856 // Exactly one of the conversion sequences is a conversion to
4857 // a void pointer; it's the worse conversion.
4858 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4859 : ImplicitConversionSequence::Worse;
4860 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4861 // Neither conversion sequence converts to a void pointer; compare
4862 // their derived-to-base conversions.
4863 if (ImplicitConversionSequence::CompareKind DerivedCK
4864 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4865 return DerivedCK;
4866 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4867 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4868 // Both conversion sequences are conversions to void
4869 // pointers. Compare the source types to determine if there's an
4870 // inheritance relationship in their sources.
4871 QualType FromType1 = SCS1.getFromType();
4872 QualType FromType2 = SCS2.getFromType();
4873
4874 // Adjust the types we're converting from via the array-to-pointer
4875 // conversion, if we need to.
4876 if (SCS1.First == ICK_Array_To_Pointer)
4877 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4878 if (SCS2.First == ICK_Array_To_Pointer)
4879 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4880
4881 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4882 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4883
4884 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4885 return ImplicitConversionSequence::Better;
4886 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4887 return ImplicitConversionSequence::Worse;
4888
4889 // Objective-C++: If one interface is more specific than the
4890 // other, it is the better one.
4891 const ObjCObjectPointerType* FromObjCPtr1
4892 = FromType1->getAs<ObjCObjectPointerType>();
4893 const ObjCObjectPointerType* FromObjCPtr2
4894 = FromType2->getAs<ObjCObjectPointerType>();
4895 if (FromObjCPtr1 && FromObjCPtr2) {
4896 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4897 RHSOPT: FromObjCPtr2);
4898 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4899 RHSOPT: FromObjCPtr1);
4900 if (AssignLeft != AssignRight) {
4901 return AssignLeft? ImplicitConversionSequence::Better
4902 : ImplicitConversionSequence::Worse;
4903 }
4904 }
4905 }
4906
4907 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4908 // Check for a better reference binding based on the kind of bindings.
4909 if (isBetterReferenceBindingKind(SCS1, SCS2))
4910 return ImplicitConversionSequence::Better;
4911 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4912 return ImplicitConversionSequence::Worse;
4913 }
4914
4915 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4916 // bullet 3).
4917 if (ImplicitConversionSequence::CompareKind QualCK
4918 = CompareQualificationConversions(S, SCS1, SCS2))
4919 return QualCK;
4920
4921 if (ImplicitConversionSequence::CompareKind ObtCK =
4922 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4923 return ObtCK;
4924
4925 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4926 // C++ [over.ics.rank]p3b4:
4927 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4928 // which the references refer are the same type except for
4929 // top-level cv-qualifiers, and the type to which the reference
4930 // initialized by S2 refers is more cv-qualified than the type
4931 // to which the reference initialized by S1 refers.
4932 QualType T1 = SCS1.getToType(Idx: 2);
4933 QualType T2 = SCS2.getToType(Idx: 2);
4934 T1 = S.Context.getCanonicalType(T: T1);
4935 T2 = S.Context.getCanonicalType(T: T2);
4936 Qualifiers T1Quals, T2Quals;
4937 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4938 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4939 if (UnqualT1 == UnqualT2) {
4940 // Objective-C++ ARC: If the references refer to objects with different
4941 // lifetimes, prefer bindings that don't change lifetime.
4942 if (SCS1.ObjCLifetimeConversionBinding !=
4943 SCS2.ObjCLifetimeConversionBinding) {
4944 return SCS1.ObjCLifetimeConversionBinding
4945 ? ImplicitConversionSequence::Worse
4946 : ImplicitConversionSequence::Better;
4947 }
4948
4949 // If the type is an array type, promote the element qualifiers to the
4950 // type for comparison.
4951 if (isa<ArrayType>(Val: T1) && T1Quals)
4952 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4953 if (isa<ArrayType>(Val: T2) && T2Quals)
4954 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4955 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4956 return ImplicitConversionSequence::Better;
4957 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4958 return ImplicitConversionSequence::Worse;
4959 }
4960 }
4961
4962 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4963 // floating-to-integral conversion if the integral conversion
4964 // is between types of the same size.
4965 // For example:
4966 // void f(float);
4967 // void f(int);
4968 // int main {
4969 // long a;
4970 // f(a);
4971 // }
4972 // Here, MSVC will call f(int) instead of generating a compile error
4973 // as clang will do in standard mode.
4974 if (S.getLangOpts().MSVCCompat &&
4975 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4976 SCS1.Second == ICK_Integral_Conversion &&
4977 SCS2.Second == ICK_Floating_Integral &&
4978 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4979 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4980 return ImplicitConversionSequence::Better;
4981
4982 // Prefer a compatible vector conversion over a lax vector conversion
4983 // For example:
4984 //
4985 // typedef float __v4sf __attribute__((__vector_size__(16)));
4986 // void f(vector float);
4987 // void f(vector signed int);
4988 // int main() {
4989 // __v4sf a;
4990 // f(a);
4991 // }
4992 // Here, we'd like to choose f(vector float) and not
4993 // report an ambiguous call error
4994 if (SCS1.Second == ICK_Vector_Conversion &&
4995 SCS2.Second == ICK_Vector_Conversion) {
4996 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4997 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4998 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4999 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
5000
5001 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
5002 return SCS1IsCompatibleVectorConversion
5003 ? ImplicitConversionSequence::Better
5004 : ImplicitConversionSequence::Worse;
5005 }
5006
5007 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
5008 SCS2.Second == ICK_SVE_Vector_Conversion) {
5009 bool SCS1IsCompatibleSVEVectorConversion =
5010 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
5011 bool SCS2IsCompatibleSVEVectorConversion =
5012 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
5013
5014 if (SCS1IsCompatibleSVEVectorConversion !=
5015 SCS2IsCompatibleSVEVectorConversion)
5016 return SCS1IsCompatibleSVEVectorConversion
5017 ? ImplicitConversionSequence::Better
5018 : ImplicitConversionSequence::Worse;
5019 }
5020
5021 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
5022 SCS2.Second == ICK_RVV_Vector_Conversion) {
5023 bool SCS1IsCompatibleRVVVectorConversion =
5024 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
5025 bool SCS2IsCompatibleRVVVectorConversion =
5026 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
5027
5028 if (SCS1IsCompatibleRVVVectorConversion !=
5029 SCS2IsCompatibleRVVVectorConversion)
5030 return SCS1IsCompatibleRVVVectorConversion
5031 ? ImplicitConversionSequence::Better
5032 : ImplicitConversionSequence::Worse;
5033 }
5034 return ImplicitConversionSequence::Indistinguishable;
5035}
5036
5037/// CompareOverflowBehaviorConversions - Compares two standard conversion
5038/// sequences to determine whether they can be ranked based on their
5039/// OverflowBehaviorType's underlying type.
5040static ImplicitConversionSequence::CompareKind
5041CompareOverflowBehaviorConversions(Sema &S,
5042 const StandardConversionSequence &SCS1,
5043 const StandardConversionSequence &SCS2) {
5044
5045 if (SCS1.getFromType()->isOverflowBehaviorType() &&
5046 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
5047 return ImplicitConversionSequence::Better;
5048
5049 if (SCS2.getFromType()->isOverflowBehaviorType() &&
5050 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
5051 return ImplicitConversionSequence::Worse;
5052
5053 return ImplicitConversionSequence::Indistinguishable;
5054}
5055
5056/// CompareQualificationConversions - Compares two standard conversion
5057/// sequences to determine whether they can be ranked based on their
5058/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
5059static ImplicitConversionSequence::CompareKind
5060CompareQualificationConversions(Sema &S,
5061 const StandardConversionSequence& SCS1,
5062 const StandardConversionSequence& SCS2) {
5063 // C++ [over.ics.rank]p3:
5064 // -- S1 and S2 differ only in their qualification conversion and
5065 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
5066 // [C++98]
5067 // [...] and the cv-qualification signature of type T1 is a proper subset
5068 // of the cv-qualification signature of type T2, and S1 is not the
5069 // deprecated string literal array-to-pointer conversion (4.2).
5070 // [C++2a]
5071 // [...] where T1 can be converted to T2 by a qualification conversion.
5072 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5073 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5074 return ImplicitConversionSequence::Indistinguishable;
5075
5076 // FIXME: the example in the standard doesn't use a qualification
5077 // conversion (!)
5078 QualType T1 = SCS1.getToType(Idx: 2);
5079 QualType T2 = SCS2.getToType(Idx: 2);
5080 T1 = S.Context.getCanonicalType(T: T1);
5081 T2 = S.Context.getCanonicalType(T: T2);
5082 assert(!T1->isReferenceType() && !T2->isReferenceType());
5083 Qualifiers T1Quals, T2Quals;
5084 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5085 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5086
5087 // If the types are the same, we won't learn anything by unwrapping
5088 // them.
5089 if (UnqualT1 == UnqualT2)
5090 return ImplicitConversionSequence::Indistinguishable;
5091
5092 // Don't ever prefer a standard conversion sequence that uses the deprecated
5093 // string literal array to pointer conversion.
5094 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5095 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5096
5097 // Objective-C++ ARC:
5098 // Prefer qualification conversions not involving a change in lifetime
5099 // to qualification conversions that do change lifetime.
5100 if (SCS1.QualificationIncludesObjCLifetime &&
5101 !SCS2.QualificationIncludesObjCLifetime)
5102 CanPick1 = false;
5103 if (SCS2.QualificationIncludesObjCLifetime &&
5104 !SCS1.QualificationIncludesObjCLifetime)
5105 CanPick2 = false;
5106
5107 bool ObjCLifetimeConversion;
5108 if (CanPick1 &&
5109 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5110 CanPick1 = false;
5111 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5112 // directions, so we can't short-cut this second check in general.
5113 if (CanPick2 &&
5114 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5115 CanPick2 = false;
5116
5117 if (CanPick1 != CanPick2)
5118 return CanPick1 ? ImplicitConversionSequence::Better
5119 : ImplicitConversionSequence::Worse;
5120 return ImplicitConversionSequence::Indistinguishable;
5121}
5122
5123/// CompareDerivedToBaseConversions - Compares two standard conversion
5124/// sequences to determine whether they can be ranked based on their
5125/// various kinds of derived-to-base conversions (C++
5126/// [over.ics.rank]p4b3). As part of these checks, we also look at
5127/// conversions between Objective-C interface types.
5128static ImplicitConversionSequence::CompareKind
5129CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5130 const StandardConversionSequence& SCS1,
5131 const StandardConversionSequence& SCS2) {
5132 QualType FromType1 = SCS1.getFromType();
5133 QualType ToType1 = SCS1.getToType(Idx: 1);
5134 QualType FromType2 = SCS2.getFromType();
5135 QualType ToType2 = SCS2.getToType(Idx: 1);
5136
5137 // Adjust the types we're converting from via the array-to-pointer
5138 // conversion, if we need to.
5139 if (SCS1.First == ICK_Array_To_Pointer)
5140 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5141 if (SCS2.First == ICK_Array_To_Pointer)
5142 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5143
5144 // Canonicalize all of the types.
5145 FromType1 = S.Context.getCanonicalType(T: FromType1);
5146 ToType1 = S.Context.getCanonicalType(T: ToType1);
5147 FromType2 = S.Context.getCanonicalType(T: FromType2);
5148 ToType2 = S.Context.getCanonicalType(T: ToType2);
5149
5150 // C++ [over.ics.rank]p4b3:
5151 //
5152 // If class B is derived directly or indirectly from class A and
5153 // class C is derived directly or indirectly from B,
5154 //
5155 // Compare based on pointer conversions.
5156 if (SCS1.Second == ICK_Pointer_Conversion &&
5157 SCS2.Second == ICK_Pointer_Conversion &&
5158 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5159 FromType1->isPointerType() && FromType2->isPointerType() &&
5160 ToType1->isPointerType() && ToType2->isPointerType()) {
5161 QualType FromPointee1 =
5162 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5163 QualType ToPointee1 =
5164 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5165 QualType FromPointee2 =
5166 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5167 QualType ToPointee2 =
5168 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5169
5170 // -- conversion of C* to B* is better than conversion of C* to A*,
5171 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5172 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5173 return ImplicitConversionSequence::Better;
5174 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5175 return ImplicitConversionSequence::Worse;
5176 }
5177
5178 // -- conversion of B* to A* is better than conversion of C* to A*,
5179 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5180 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5181 return ImplicitConversionSequence::Better;
5182 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5183 return ImplicitConversionSequence::Worse;
5184 }
5185 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5186 SCS2.Second == ICK_Pointer_Conversion) {
5187 const ObjCObjectPointerType *FromPtr1
5188 = FromType1->getAs<ObjCObjectPointerType>();
5189 const ObjCObjectPointerType *FromPtr2
5190 = FromType2->getAs<ObjCObjectPointerType>();
5191 const ObjCObjectPointerType *ToPtr1
5192 = ToType1->getAs<ObjCObjectPointerType>();
5193 const ObjCObjectPointerType *ToPtr2
5194 = ToType2->getAs<ObjCObjectPointerType>();
5195
5196 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5197 // Apply the same conversion ranking rules for Objective-C pointer types
5198 // that we do for C++ pointers to class types. However, we employ the
5199 // Objective-C pseudo-subtyping relationship used for assignment of
5200 // Objective-C pointer types.
5201 bool FromAssignLeft
5202 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5203 bool FromAssignRight
5204 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5205 bool ToAssignLeft
5206 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5207 bool ToAssignRight
5208 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5209
5210 // A conversion to an a non-id object pointer type or qualified 'id'
5211 // type is better than a conversion to 'id'.
5212 if (ToPtr1->isObjCIdType() &&
5213 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5214 return ImplicitConversionSequence::Worse;
5215 if (ToPtr2->isObjCIdType() &&
5216 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5217 return ImplicitConversionSequence::Better;
5218
5219 // A conversion to a non-id object pointer type is better than a
5220 // conversion to a qualified 'id' type
5221 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5222 return ImplicitConversionSequence::Worse;
5223 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5224 return ImplicitConversionSequence::Better;
5225
5226 // A conversion to an a non-Class object pointer type or qualified 'Class'
5227 // type is better than a conversion to 'Class'.
5228 if (ToPtr1->isObjCClassType() &&
5229 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5230 return ImplicitConversionSequence::Worse;
5231 if (ToPtr2->isObjCClassType() &&
5232 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5233 return ImplicitConversionSequence::Better;
5234
5235 // A conversion to a non-Class object pointer type is better than a
5236 // conversion to a qualified 'Class' type.
5237 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5238 return ImplicitConversionSequence::Worse;
5239 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5240 return ImplicitConversionSequence::Better;
5241
5242 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5243 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5244 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5245 (ToAssignLeft != ToAssignRight)) {
5246 if (FromPtr1->isSpecialized()) {
5247 // "conversion of B<A> * to B * is better than conversion of B * to
5248 // C *.
5249 bool IsFirstSame =
5250 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5251 bool IsSecondSame =
5252 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5253 if (IsFirstSame) {
5254 if (!IsSecondSame)
5255 return ImplicitConversionSequence::Better;
5256 } else if (IsSecondSame)
5257 return ImplicitConversionSequence::Worse;
5258 }
5259 return ToAssignLeft? ImplicitConversionSequence::Worse
5260 : ImplicitConversionSequence::Better;
5261 }
5262
5263 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5264 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5265 (FromAssignLeft != FromAssignRight))
5266 return FromAssignLeft? ImplicitConversionSequence::Better
5267 : ImplicitConversionSequence::Worse;
5268 }
5269 }
5270
5271 // Ranking of member-pointer types.
5272 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5273 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5274 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5275 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5276 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5277 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5278 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5279 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5280 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5281 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5282 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5283 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5284 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5285 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5286 return ImplicitConversionSequence::Worse;
5287 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5288 return ImplicitConversionSequence::Better;
5289 }
5290 // conversion of B::* to C::* is better than conversion of A::* to C::*
5291 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5292 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5293 return ImplicitConversionSequence::Better;
5294 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5295 return ImplicitConversionSequence::Worse;
5296 }
5297 }
5298
5299 if (SCS1.Second == ICK_Derived_To_Base) {
5300 // -- conversion of C to B is better than conversion of C to A,
5301 // -- binding of an expression of type C to a reference of type
5302 // B& is better than binding an expression of type C to a
5303 // reference of type A&,
5304 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5305 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5306 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5307 return ImplicitConversionSequence::Better;
5308 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5309 return ImplicitConversionSequence::Worse;
5310 }
5311
5312 // -- conversion of B to A is better than conversion of C to A.
5313 // -- binding of an expression of type B to a reference of type
5314 // A& is better than binding an expression of type C to a
5315 // reference of type A&,
5316 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5317 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5318 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5319 return ImplicitConversionSequence::Better;
5320 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5321 return ImplicitConversionSequence::Worse;
5322 }
5323 }
5324
5325 return ImplicitConversionSequence::Indistinguishable;
5326}
5327
5328static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5329 if (!T.getQualifiers().hasUnaligned())
5330 return T;
5331
5332 Qualifiers Q;
5333 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5334 Q.removeUnaligned();
5335 return Ctx.getQualifiedType(T, Qs: Q);
5336}
5337
5338Sema::ReferenceCompareResult
5339Sema::CompareReferenceRelationship(SourceLocation Loc,
5340 QualType OrigT1, QualType OrigT2,
5341 ReferenceConversions *ConvOut) {
5342 assert(!OrigT1->isReferenceType() &&
5343 "T1 must be the pointee type of the reference type");
5344 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5345
5346 QualType T1 = Context.getCanonicalType(T: OrigT1);
5347 QualType T2 = Context.getCanonicalType(T: OrigT2);
5348 Qualifiers T1Quals, T2Quals;
5349 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5350 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5351
5352 ReferenceConversions ConvTmp;
5353 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5354 Conv = ReferenceConversions();
5355
5356 // C++2a [dcl.init.ref]p4:
5357 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5358 // reference-related to "cv2 T2" if T1 is similar to T2, or
5359 // T1 is a base class of T2.
5360 // "cv1 T1" is reference-compatible with "cv2 T2" if
5361 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5362 // "pointer to cv1 T1" via a standard conversion sequence.
5363
5364 // Check for standard conversions we can apply to pointers: derived-to-base
5365 // conversions, ObjC pointer conversions, and function pointer conversions.
5366 // (Qualification conversions are checked last.)
5367 if (UnqualT1 == UnqualT2) {
5368 // Nothing to do.
5369 } else if (isCompleteType(Loc, T: OrigT2) &&
5370 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5371 Conv |= ReferenceConversions::DerivedToBase;
5372 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5373 UnqualT2->isObjCObjectOrInterfaceType() &&
5374 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5375 Conv |= ReferenceConversions::ObjC;
5376 else if (UnqualT2->isFunctionType() &&
5377 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5378 Conv |= ReferenceConversions::Function;
5379 // No need to check qualifiers; function types don't have them.
5380 return Ref_Compatible;
5381 }
5382 bool ConvertedReferent = Conv != 0;
5383
5384 // We can have a qualification conversion. Compute whether the types are
5385 // similar at the same time.
5386 bool PreviousToQualsIncludeConst = true;
5387 bool TopLevel = true;
5388 do {
5389 if (T1 == T2)
5390 break;
5391
5392 // We will need a qualification conversion.
5393 Conv |= ReferenceConversions::Qualification;
5394
5395 // Track whether we performed a qualification conversion anywhere other
5396 // than the top level. This matters for ranking reference bindings in
5397 // overload resolution.
5398 if (!TopLevel)
5399 Conv |= ReferenceConversions::NestedQualification;
5400
5401 // MS compiler ignores __unaligned qualifier for references; do the same.
5402 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5403 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5404
5405 // If we find a qualifier mismatch, the types are not reference-compatible,
5406 // but are still be reference-related if they're similar.
5407 bool ObjCLifetimeConversion = false;
5408 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5409 PreviousToQualsIncludeConst,
5410 ObjCLifetimeConversion, Ctx: getASTContext()))
5411 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5412 ? Ref_Related
5413 : Ref_Incompatible;
5414
5415 // FIXME: Should we track this for any level other than the first?
5416 if (ObjCLifetimeConversion)
5417 Conv |= ReferenceConversions::ObjCLifetime;
5418
5419 TopLevel = false;
5420 } while (Context.UnwrapSimilarTypes(T1, T2));
5421
5422 // At this point, if the types are reference-related, we must either have the
5423 // same inner type (ignoring qualifiers), or must have already worked out how
5424 // to convert the referent.
5425 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5426 ? Ref_Compatible
5427 : Ref_Incompatible;
5428}
5429
5430/// Look for a user-defined conversion to a value reference-compatible
5431/// with DeclType. Return true if something definite is found.
5432static bool
5433FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5434 QualType DeclType, SourceLocation DeclLoc,
5435 Expr *Init, QualType T2, bool AllowRvalues,
5436 bool AllowExplicit) {
5437 assert(T2->isRecordType() && "Can only find conversions of record types.");
5438 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5439 OverloadCandidateSet CandidateSet(
5440 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5441 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5442 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5443 NamedDecl *D = *I;
5444 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5445 if (isa<UsingShadowDecl>(Val: D))
5446 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5447
5448 FunctionTemplateDecl *ConvTemplate
5449 = dyn_cast<FunctionTemplateDecl>(Val: D);
5450 CXXConversionDecl *Conv;
5451 if (ConvTemplate)
5452 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5453 else
5454 Conv = cast<CXXConversionDecl>(Val: D);
5455
5456 if (AllowRvalues) {
5457 // If we are initializing an rvalue reference, don't permit conversion
5458 // functions that return lvalues.
5459 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5460 const ReferenceType *RefType
5461 = Conv->getConversionType()->getAs<LValueReferenceType>();
5462 if (RefType && !RefType->getPointeeType()->isFunctionType())
5463 continue;
5464 }
5465
5466 if (!ConvTemplate &&
5467 S.CompareReferenceRelationship(
5468 Loc: DeclLoc,
5469 OrigT1: Conv->getConversionType()
5470 .getNonReferenceType()
5471 .getUnqualifiedType(),
5472 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5473 Sema::Ref_Incompatible)
5474 continue;
5475 } else {
5476 // If the conversion function doesn't return a reference type,
5477 // it can't be considered for this conversion. An rvalue reference
5478 // is only acceptable if its referencee is a function type.
5479
5480 const ReferenceType *RefType =
5481 Conv->getConversionType()->getAs<ReferenceType>();
5482 if (!RefType ||
5483 (!RefType->isLValueReferenceType() &&
5484 !RefType->getPointeeType()->isFunctionType()))
5485 continue;
5486 }
5487
5488 if (ConvTemplate)
5489 S.AddTemplateConversionCandidate(
5490 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5491 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5492 else
5493 S.AddConversionCandidate(
5494 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5495 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5496 }
5497
5498 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5499
5500 OverloadCandidateSet::iterator Best;
5501 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5502 case OR_Success:
5503
5504 assert(Best->HasFinalConversion);
5505
5506 // C++ [over.ics.ref]p1:
5507 //
5508 // [...] If the parameter binds directly to the result of
5509 // applying a conversion function to the argument
5510 // expression, the implicit conversion sequence is a
5511 // user-defined conversion sequence (13.3.3.1.2), with the
5512 // second standard conversion sequence either an identity
5513 // conversion or, if the conversion function returns an
5514 // entity of a type that is a derived class of the parameter
5515 // type, a derived-to-base Conversion.
5516 if (!Best->FinalConversion.DirectBinding)
5517 return false;
5518
5519 ICS.setUserDefined();
5520 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5521 ICS.UserDefined.After = Best->FinalConversion;
5522 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5523 ICS.UserDefined.ConversionFunction = Best->Function;
5524 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5525 ICS.UserDefined.EllipsisConversion = false;
5526 assert(ICS.UserDefined.After.ReferenceBinding &&
5527 ICS.UserDefined.After.DirectBinding &&
5528 "Expected a direct reference binding!");
5529 return true;
5530
5531 case OR_Ambiguous:
5532 ICS.setAmbiguous();
5533 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5534 Cand != CandidateSet.end(); ++Cand)
5535 if (Cand->Best)
5536 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5537 return true;
5538
5539 case OR_No_Viable_Function:
5540 case OR_Deleted:
5541 // There was no suitable conversion, or we found a deleted
5542 // conversion; continue with other checks.
5543 return false;
5544 }
5545
5546 llvm_unreachable("Invalid OverloadResult!");
5547}
5548
5549/// Compute an implicit conversion sequence for reference
5550/// initialization.
5551static ImplicitConversionSequence
5552TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5553 SourceLocation DeclLoc,
5554 bool SuppressUserConversions,
5555 bool AllowExplicit) {
5556 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5557
5558 // Most paths end in a failed conversion.
5559 ImplicitConversionSequence ICS;
5560 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5561
5562 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5563 QualType T2 = Init->getType();
5564
5565 // If the initializer is the address of an overloaded function, try
5566 // to resolve the overloaded function. If all goes well, T2 is the
5567 // type of the resulting function.
5568 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5569 DeclAccessPair Found;
5570 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5571 Complain: false, Found))
5572 T2 = Fn->getType();
5573 }
5574
5575 // Compute some basic properties of the types and the initializer.
5576 bool isRValRef = DeclType->isRValueReferenceType();
5577 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5578
5579 Sema::ReferenceConversions RefConv;
5580 Sema::ReferenceCompareResult RefRelationship =
5581 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5582
5583 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5584 ICS.setStandard();
5585 ICS.Standard.First = ICK_Identity;
5586 // FIXME: A reference binding can be a function conversion too. We should
5587 // consider that when ordering reference-to-function bindings.
5588 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5589 ? ICK_Derived_To_Base
5590 : (RefConv & Sema::ReferenceConversions::ObjC)
5591 ? ICK_Compatible_Conversion
5592 : ICK_Identity;
5593 ICS.Standard.Dimension = ICK_Identity;
5594 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5595 // a reference binding that performs a non-top-level qualification
5596 // conversion as a qualification conversion, not as an identity conversion.
5597 ICS.Standard.Third = (RefConv &
5598 Sema::ReferenceConversions::NestedQualification)
5599 ? ICK_Qualification
5600 : ICK_Identity;
5601 ICS.Standard.setFromType(T2);
5602 ICS.Standard.setToType(Idx: 0, T: T2);
5603 ICS.Standard.setToType(Idx: 1, T: T1);
5604 ICS.Standard.setToType(Idx: 2, T: T1);
5605 ICS.Standard.ReferenceBinding = true;
5606 ICS.Standard.DirectBinding = BindsDirectly;
5607 ICS.Standard.IsLvalueReference = !isRValRef;
5608 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5609 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5610 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5611 ICS.Standard.ObjCLifetimeConversionBinding =
5612 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5613 ICS.Standard.FromBracedInitList = false;
5614 ICS.Standard.CopyConstructor = nullptr;
5615 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5616 };
5617
5618 // C++0x [dcl.init.ref]p5:
5619 // A reference to type "cv1 T1" is initialized by an expression
5620 // of type "cv2 T2" as follows:
5621
5622 // -- If reference is an lvalue reference and the initializer expression
5623 if (!isRValRef) {
5624 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5625 // reference-compatible with "cv2 T2," or
5626 //
5627 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5628 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5629 // C++ [over.ics.ref]p1:
5630 // When a parameter of reference type binds directly (8.5.3)
5631 // to an argument expression, the implicit conversion sequence
5632 // is the identity conversion, unless the argument expression
5633 // has a type that is a derived class of the parameter type,
5634 // in which case the implicit conversion sequence is a
5635 // derived-to-base Conversion (13.3.3.1).
5636 SetAsReferenceBinding(/*BindsDirectly=*/true);
5637
5638 // Nothing more to do: the inaccessibility/ambiguity check for
5639 // derived-to-base conversions is suppressed when we're
5640 // computing the implicit conversion sequence (C++
5641 // [over.best.ics]p2).
5642 return ICS;
5643 }
5644
5645 // -- has a class type (i.e., T2 is a class type), where T1 is
5646 // not reference-related to T2, and can be implicitly
5647 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5648 // is reference-compatible with "cv3 T3" 92) (this
5649 // conversion is selected by enumerating the applicable
5650 // conversion functions (13.3.1.6) and choosing the best
5651 // one through overload resolution (13.3)),
5652 if (!SuppressUserConversions && T2->isRecordType() &&
5653 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5654 RefRelationship == Sema::Ref_Incompatible) {
5655 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5656 Init, T2, /*AllowRvalues=*/false,
5657 AllowExplicit))
5658 return ICS;
5659 }
5660 }
5661
5662 // -- Otherwise, the reference shall be an lvalue reference to a
5663 // non-volatile const type (i.e., cv1 shall be const), or the reference
5664 // shall be an rvalue reference.
5665 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5666 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5667 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5668 return ICS;
5669 }
5670
5671 // -- If the initializer expression
5672 //
5673 // -- is an xvalue, class prvalue, array prvalue or function
5674 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5675 if (RefRelationship == Sema::Ref_Compatible &&
5676 (InitCategory.isXValue() ||
5677 (InitCategory.isPRValue() &&
5678 (T2->isRecordType() || T2->isArrayType())) ||
5679 (InitCategory.isLValue() && T2->isFunctionType()))) {
5680 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5681 // binding unless we're binding to a class prvalue.
5682 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5683 // allow the use of rvalue references in C++98/03 for the benefit of
5684 // standard library implementors; therefore, we need the xvalue check here.
5685 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5686 !(InitCategory.isPRValue() || T2->isRecordType()));
5687 return ICS;
5688 }
5689
5690 // -- has a class type (i.e., T2 is a class type), where T1 is not
5691 // reference-related to T2, and can be implicitly converted to
5692 // an xvalue, class prvalue, or function lvalue of type
5693 // "cv3 T3", where "cv1 T1" is reference-compatible with
5694 // "cv3 T3",
5695 //
5696 // then the reference is bound to the value of the initializer
5697 // expression in the first case and to the result of the conversion
5698 // in the second case (or, in either case, to an appropriate base
5699 // class subobject).
5700 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5701 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5702 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5703 Init, T2, /*AllowRvalues=*/true,
5704 AllowExplicit)) {
5705 // In the second case, if the reference is an rvalue reference
5706 // and the second standard conversion sequence of the
5707 // user-defined conversion sequence includes an lvalue-to-rvalue
5708 // conversion, the program is ill-formed.
5709 if (ICS.isUserDefined() && isRValRef &&
5710 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5711 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5712
5713 return ICS;
5714 }
5715
5716 // A temporary of function type cannot be created; don't even try.
5717 if (T1->isFunctionType())
5718 return ICS;
5719
5720 // -- Otherwise, a temporary of type "cv1 T1" is created and
5721 // initialized from the initializer expression using the
5722 // rules for a non-reference copy initialization (8.5). The
5723 // reference is then bound to the temporary. If T1 is
5724 // reference-related to T2, cv1 must be the same
5725 // cv-qualification as, or greater cv-qualification than,
5726 // cv2; otherwise, the program is ill-formed.
5727 if (RefRelationship == Sema::Ref_Related) {
5728 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5729 // we would be reference-compatible or reference-compatible with
5730 // added qualification. But that wasn't the case, so the reference
5731 // initialization fails.
5732 //
5733 // Note that we only want to check address spaces and cvr-qualifiers here.
5734 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5735 Qualifiers T1Quals = T1.getQualifiers();
5736 Qualifiers T2Quals = T2.getQualifiers();
5737 T1Quals.removeObjCGCAttr();
5738 T1Quals.removeObjCLifetime();
5739 T2Quals.removeObjCGCAttr();
5740 T2Quals.removeObjCLifetime();
5741 // MS compiler ignores __unaligned qualifier for references; do the same.
5742 T1Quals.removeUnaligned();
5743 T2Quals.removeUnaligned();
5744 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5745 return ICS;
5746 }
5747
5748 // If at least one of the types is a class type, the types are not
5749 // related, and we aren't allowed any user conversions, the
5750 // reference binding fails. This case is important for breaking
5751 // recursion, since TryImplicitConversion below will attempt to
5752 // create a temporary through the use of a copy constructor.
5753 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5754 (T1->isRecordType() || T2->isRecordType()))
5755 return ICS;
5756
5757 // If T1 is reference-related to T2 and the reference is an rvalue
5758 // reference, the initializer expression shall not be an lvalue.
5759 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5760 Init->Classify(Ctx&: S.Context).isLValue()) {
5761 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5762 return ICS;
5763 }
5764
5765 // C++ [over.ics.ref]p2:
5766 // When a parameter of reference type is not bound directly to
5767 // an argument expression, the conversion sequence is the one
5768 // required to convert the argument expression to the
5769 // underlying type of the reference according to
5770 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5771 // to copy-initializing a temporary of the underlying type with
5772 // the argument expression. Any difference in top-level
5773 // cv-qualification is subsumed by the initialization itself
5774 // and does not constitute a conversion.
5775 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5776 AllowExplicit: AllowedExplicit::None,
5777 /*InOverloadResolution=*/false,
5778 /*CStyle=*/false,
5779 /*AllowObjCWritebackConversion=*/false,
5780 /*AllowObjCConversionOnExplicit=*/false);
5781
5782 // Of course, that's still a reference binding.
5783 if (ICS.isStandard()) {
5784 ICS.Standard.ReferenceBinding = true;
5785 ICS.Standard.IsLvalueReference = !isRValRef;
5786 ICS.Standard.BindsToFunctionLvalue = false;
5787 ICS.Standard.BindsToRvalue = true;
5788 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5789 ICS.Standard.ObjCLifetimeConversionBinding = false;
5790 } else if (ICS.isUserDefined()) {
5791 const ReferenceType *LValRefType =
5792 ICS.UserDefined.ConversionFunction->getReturnType()
5793 ->getAs<LValueReferenceType>();
5794
5795 // C++ [over.ics.ref]p3:
5796 // Except for an implicit object parameter, for which see 13.3.1, a
5797 // standard conversion sequence cannot be formed if it requires [...]
5798 // binding an rvalue reference to an lvalue other than a function
5799 // lvalue.
5800 // Note that the function case is not possible here.
5801 if (isRValRef && LValRefType) {
5802 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5803 return ICS;
5804 }
5805
5806 ICS.UserDefined.After.ReferenceBinding = true;
5807 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5808 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5809 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5810 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5811 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5812 ICS.UserDefined.After.FromBracedInitList = false;
5813 }
5814
5815 return ICS;
5816}
5817
5818static ImplicitConversionSequence
5819TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5820 bool SuppressUserConversions,
5821 bool InOverloadResolution,
5822 bool AllowObjCWritebackConversion,
5823 bool AllowExplicit = false);
5824
5825/// TryListConversion - Try to copy-initialize a value of type ToType from the
5826/// initializer list From.
5827static ImplicitConversionSequence
5828TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5829 bool SuppressUserConversions,
5830 bool InOverloadResolution,
5831 bool AllowObjCWritebackConversion) {
5832 // C++11 [over.ics.list]p1:
5833 // When an argument is an initializer list, it is not an expression and
5834 // special rules apply for converting it to a parameter type.
5835
5836 ImplicitConversionSequence Result;
5837 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5838
5839 // We need a complete type for what follows. With one C++20 exception,
5840 // incomplete types can never be initialized from init lists.
5841 QualType InitTy = ToType;
5842 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5843 if (AT && S.getLangOpts().CPlusPlus20)
5844 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5845 // C++20 allows list initialization of an incomplete array type.
5846 InitTy = IAT->getElementType();
5847 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5848 return Result;
5849
5850 // C++20 [over.ics.list]/2:
5851 // If the initializer list is a designated-initializer-list, a conversion
5852 // is only possible if the parameter has an aggregate type
5853 //
5854 // FIXME: The exception for reference initialization here is not part of the
5855 // language rules, but follow other compilers in adding it as a tentative DR
5856 // resolution.
5857 bool IsDesignatedInit = From->hasDesignatedInit();
5858 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5859 IsDesignatedInit)
5860 return Result;
5861
5862 // Per DR1467 and DR2137:
5863 // If the parameter type is an aggregate class X and the initializer list
5864 // has a single element of type cv U, where U is X or a class derived from
5865 // X, the implicit conversion sequence is the one required to convert the
5866 // element to the parameter type.
5867 //
5868 // Otherwise, if the parameter type is a character array [... ]
5869 // and the initializer list has a single element that is an
5870 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5871 // implicit conversion sequence is the identity conversion.
5872 if (From->hasOneInit() && !IsDesignatedInit) {
5873 if (ToType->isRecordType() && ToType->isAggregateType()) {
5874 QualType InitType = From->getInit(Init: 0)->getType();
5875 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5876 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5877 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5878 SuppressUserConversions,
5879 InOverloadResolution,
5880 AllowObjCWritebackConversion);
5881 }
5882
5883 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5884 InitializedEntity Entity =
5885 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5886 /*Consumed=*/false);
5887 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5888 Result.setStandard();
5889 Result.Standard.setAsIdentityConversion();
5890 Result.Standard.setFromType(ToType);
5891 Result.Standard.setAllToTypes(ToType);
5892 return Result;
5893 }
5894 }
5895 }
5896
5897 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5898 // C++11 [over.ics.list]p2:
5899 // If the parameter type is std::initializer_list<X> or "array of X" and
5900 // all the elements can be implicitly converted to X, the implicit
5901 // conversion sequence is the worst conversion necessary to convert an
5902 // element of the list to X.
5903 //
5904 // C++14 [over.ics.list]p3:
5905 // Otherwise, if the parameter type is "array of N X", if the initializer
5906 // list has exactly N elements or if it has fewer than N elements and X is
5907 // default-constructible, and if all the elements of the initializer list
5908 // can be implicitly converted to X, the implicit conversion sequence is
5909 // the worst conversion necessary to convert an element of the list to X.
5910 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5911 unsigned e = From->getNumInitsWithEmbedExpanded();
5912 ImplicitConversionSequence DfltElt;
5913 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5914 ToType: QualType());
5915 QualType ContTy = ToType;
5916 bool IsUnbounded = false;
5917 if (AT) {
5918 InitTy = AT->getElementType();
5919 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5920 if (CT->getSize().ult(RHS: e)) {
5921 // Too many inits, fatally bad
5922 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5923 ToType);
5924 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5925 return Result;
5926 }
5927 if (CT->getSize().ugt(RHS: e)) {
5928 // Need an init from empty {}, is there one?
5929 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5930 From->getEndLoc(), /*isExplicit=*/false);
5931 EmptyList.setType(S.Context.VoidTy);
5932 DfltElt = TryListConversion(
5933 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5934 InOverloadResolution, AllowObjCWritebackConversion);
5935 if (DfltElt.isBad()) {
5936 // No {} init, fatally bad
5937 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5938 ToType);
5939 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5940 return Result;
5941 }
5942 }
5943 } else {
5944 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5945 IsUnbounded = true;
5946 if (!e) {
5947 // Cannot convert to zero-sized.
5948 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5949 ToType);
5950 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5951 return Result;
5952 }
5953 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5954 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5955 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5956 }
5957 }
5958
5959 Result.setStandard();
5960 Result.Standard.setAsIdentityConversion();
5961 Result.Standard.setFromType(InitTy);
5962 Result.Standard.setAllToTypes(InitTy);
5963 // An EmbedExpr is a single int prvalue, so one conversion sequence covers
5964 // all of its elements; narrowing is checked per element after resolution.
5965 for (Expr *Init : From->inits()) {
5966 ImplicitConversionSequence ICS = TryCopyInitialization(
5967 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5968 AllowObjCWritebackConversion);
5969
5970 // Keep the worse conversion seen so far.
5971 // FIXME: Sequences are not totally ordered, so 'worse' can be
5972 // ambiguous. CWG has been informed.
5973 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5974 ICS2: Result) ==
5975 ImplicitConversionSequence::Worse) {
5976 Result = ICS;
5977 // Bail as soon as we find something unconvertible.
5978 if (Result.isBad()) {
5979 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5980 return Result;
5981 }
5982 }
5983 }
5984
5985 // If we needed any implicit {} initialization, compare that now.
5986 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5987 // has been informed that this might not be the best thing.
5988 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5989 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5990 ImplicitConversionSequence::Worse)
5991 Result = DfltElt;
5992 // Record the type being initialized so that we may compare sequences
5993 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5994 return Result;
5995 }
5996
5997 // C++14 [over.ics.list]p4:
5998 // C++11 [over.ics.list]p3:
5999 // Otherwise, if the parameter is a non-aggregate class X and overload
6000 // resolution chooses a single best constructor [...] the implicit
6001 // conversion sequence is a user-defined conversion sequence. If multiple
6002 // constructors are viable but none is better than the others, the
6003 // implicit conversion sequence is a user-defined conversion sequence.
6004 if (ToType->isRecordType() && !ToType->isAggregateType()) {
6005 // This function can deal with initializer lists.
6006 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
6007 AllowExplicit: AllowedExplicit::None,
6008 InOverloadResolution, /*CStyle=*/false,
6009 AllowObjCWritebackConversion,
6010 /*AllowObjCConversionOnExplicit=*/false);
6011 }
6012
6013 // C++14 [over.ics.list]p5:
6014 // C++11 [over.ics.list]p4:
6015 // Otherwise, if the parameter has an aggregate type which can be
6016 // initialized from the initializer list [...] the implicit conversion
6017 // sequence is a user-defined conversion sequence.
6018 if (ToType->isAggregateType()) {
6019 // Type is an aggregate, argument is an init list. At this point it comes
6020 // down to checking whether the initialization works.
6021 // FIXME: Find out whether this parameter is consumed or not.
6022 InitializedEntity Entity =
6023 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
6024 /*Consumed=*/false);
6025 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
6026 From)) {
6027 Result.setUserDefined();
6028 Result.UserDefined.Before.setAsIdentityConversion();
6029 // Initializer lists don't have a type.
6030 Result.UserDefined.Before.setFromType(QualType());
6031 Result.UserDefined.Before.setAllToTypes(QualType());
6032
6033 Result.UserDefined.After.setAsIdentityConversion();
6034 Result.UserDefined.After.setFromType(ToType);
6035 Result.UserDefined.After.setAllToTypes(ToType);
6036 Result.UserDefined.ConversionFunction = nullptr;
6037 }
6038 return Result;
6039 }
6040
6041 // C++14 [over.ics.list]p6:
6042 // C++11 [over.ics.list]p5:
6043 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
6044 if (ToType->isReferenceType()) {
6045 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
6046 // mention initializer lists in any way. So we go by what list-
6047 // initialization would do and try to extrapolate from that.
6048
6049 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
6050
6051 // If the initializer list has a single element that is reference-related
6052 // to the parameter type, we initialize the reference from that.
6053 if (From->hasOneInit() && !IsDesignatedInit) {
6054 Expr *Init = From->getInit(Init: 0);
6055
6056 QualType T2 = Init->getType();
6057
6058 // If the initializer is the address of an overloaded function, try
6059 // to resolve the overloaded function. If all goes well, T2 is the
6060 // type of the resulting function.
6061 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
6062 DeclAccessPair Found;
6063 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
6064 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
6065 T2 = Fn->getType();
6066 }
6067
6068 // Compute some basic properties of the types and the initializer.
6069 Sema::ReferenceCompareResult RefRelationship =
6070 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
6071
6072 if (RefRelationship >= Sema::Ref_Related) {
6073 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
6074 SuppressUserConversions,
6075 /*AllowExplicit=*/false);
6076 }
6077 }
6078
6079 // Otherwise, we bind the reference to a temporary created from the
6080 // initializer list.
6081 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
6082 InOverloadResolution,
6083 AllowObjCWritebackConversion);
6084 if (Result.isFailure())
6085 return Result;
6086 assert(!Result.isEllipsis() &&
6087 "Sub-initialization cannot result in ellipsis conversion.");
6088
6089 // Can we even bind to a temporary?
6090 if (ToType->isRValueReferenceType() ||
6091 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6092 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6093 Result.UserDefined.After;
6094 SCS.ReferenceBinding = true;
6095 SCS.IsLvalueReference = ToType->isLValueReferenceType();
6096 SCS.BindsToRvalue = true;
6097 SCS.BindsToFunctionLvalue = false;
6098 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
6099 SCS.ObjCLifetimeConversionBinding = false;
6100 SCS.FromBracedInitList = false;
6101
6102 } else
6103 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6104 FromExpr: From, ToType);
6105 return Result;
6106 }
6107
6108 // C++14 [over.ics.list]p7:
6109 // C++11 [over.ics.list]p6:
6110 // Otherwise, if the parameter type is not a class:
6111 if (!ToType->isRecordType()) {
6112 // - if the initializer list has one element that is not itself an
6113 // initializer list, the implicit conversion sequence is the one
6114 // required to convert the element to the parameter type.
6115 if (From->hasOneInit() && !isa<InitListExpr>(Val: From->getInit(Init: 0))) {
6116 Result = TryCopyInitialization(
6117 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6118 InOverloadResolution, AllowObjCWritebackConversion);
6119 if (Result.isStandard())
6120 Result.Standard.FromBracedInitList = true;
6121 }
6122 // - if the initializer list has no elements, the implicit conversion
6123 // sequence is the identity conversion.
6124 else if (From->hasZeroInits()) {
6125 Result.setStandard();
6126 Result.Standard.setAsIdentityConversion();
6127 Result.Standard.setFromType(ToType);
6128 Result.Standard.setAllToTypes(ToType);
6129 }
6130 return Result;
6131 }
6132
6133 // C++14 [over.ics.list]p8:
6134 // C++11 [over.ics.list]p7:
6135 // In all cases other than those enumerated above, no conversion is possible
6136 return Result;
6137}
6138
6139/// TryCopyInitialization - Try to copy-initialize a value of type
6140/// ToType from the expression From. Return the implicit conversion
6141/// sequence required to pass this argument, which may be a bad
6142/// conversion sequence (meaning that the argument cannot be passed to
6143/// a parameter of this type). If @p SuppressUserConversions, then we
6144/// do not permit any user-defined conversion sequences.
6145static ImplicitConversionSequence
6146TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6147 bool SuppressUserConversions,
6148 bool InOverloadResolution,
6149 bool AllowObjCWritebackConversion,
6150 bool AllowExplicit) {
6151 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6152 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6153 InOverloadResolution,AllowObjCWritebackConversion);
6154
6155 if (ToType->isReferenceType())
6156 return TryReferenceInit(S, Init: From, DeclType: ToType,
6157 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6158 SuppressUserConversions, AllowExplicit);
6159
6160 return TryImplicitConversion(S, From, ToType,
6161 SuppressUserConversions,
6162 AllowExplicit: AllowedExplicit::None,
6163 InOverloadResolution,
6164 /*CStyle=*/false,
6165 AllowObjCWritebackConversion,
6166 /*AllowObjCConversionOnExplicit=*/false);
6167}
6168
6169static bool TryCopyInitialization(const CanQualType FromQTy,
6170 const CanQualType ToQTy,
6171 Sema &S,
6172 SourceLocation Loc,
6173 ExprValueKind FromVK) {
6174 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6175 ImplicitConversionSequence ICS =
6176 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6177
6178 return !ICS.isBad();
6179}
6180
6181/// TryObjectArgumentInitialization - Try to initialize the object
6182/// parameter of the given member function (@c Method) from the
6183/// expression @p From.
6184static ImplicitConversionSequence TryObjectArgumentInitialization(
6185 Sema &S, SourceLocation Loc, QualType FromType,
6186 Expr::Classification FromClassification, CXXMethodDecl *Method,
6187 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6188 QualType ExplicitParameterType = QualType(),
6189 bool SuppressUserConversion = false) {
6190
6191 // We need to have an object of class type.
6192 if (const auto *PT = FromType->getAs<PointerType>()) {
6193 FromType = PT->getPointeeType();
6194
6195 // When we had a pointer, it's implicitly dereferenced, so we
6196 // better have an lvalue.
6197 assert(FromClassification.isLValue());
6198 }
6199
6200 auto ValueKindFromClassification = [](Expr::Classification C) {
6201 if (C.isPRValue())
6202 return clang::VK_PRValue;
6203 if (C.isXValue())
6204 return VK_XValue;
6205 return clang::VK_LValue;
6206 };
6207
6208 if (Method->isExplicitObjectMemberFunction()) {
6209 if (ExplicitParameterType.isNull())
6210 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6211 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6212 ValueKindFromClassification(FromClassification));
6213 return TryCopyInitialization(S, From: &TmpExpr, ToType: ExplicitParameterType,
6214 SuppressUserConversions: SuppressUserConversion,
6215 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6216 }
6217
6218 assert(FromType->isRecordType());
6219
6220 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6221 // C++98 [class.dtor]p2:
6222 // A destructor can be invoked for a const, volatile or const volatile
6223 // object.
6224 // C++98 [over.match.funcs]p4:
6225 // For static member functions, the implicit object parameter is considered
6226 // to match any object (since if the function is selected, the object is
6227 // discarded).
6228 Qualifiers Quals = Method->getMethodQualifiers();
6229 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6230 Quals.addConst();
6231 Quals.addVolatile();
6232 }
6233
6234 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6235
6236 // Set up the conversion sequence as a "bad" conversion, to allow us
6237 // to exit early.
6238 ImplicitConversionSequence ICS;
6239
6240 // C++0x [over.match.funcs]p4:
6241 // For non-static member functions, the type of the implicit object
6242 // parameter is
6243 //
6244 // - "lvalue reference to cv X" for functions declared without a
6245 // ref-qualifier or with the & ref-qualifier
6246 // - "rvalue reference to cv X" for functions declared with the &&
6247 // ref-qualifier
6248 //
6249 // where X is the class of which the function is a member and cv is the
6250 // cv-qualification on the member function declaration.
6251 //
6252 // However, when finding an implicit conversion sequence for the argument, we
6253 // are not allowed to perform user-defined conversions
6254 // (C++ [over.match.funcs]p5). We perform a simplified version of
6255 // reference binding here, that allows class rvalues to bind to
6256 // non-constant references.
6257
6258 // First check the qualifiers.
6259 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6260 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6261 if (ImplicitParamType.getCVRQualifiers() !=
6262 FromTypeCanon.getLocalCVRQualifiers() &&
6263 !ImplicitParamType.isAtLeastAsQualifiedAs(
6264 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6265 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6266 FromType, ToType: ImplicitParamType);
6267 return ICS;
6268 }
6269
6270 if (FromTypeCanon.hasAddressSpace()) {
6271 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6272 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6273 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6274 Ctx: S.getASTContext())) {
6275 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6276 FromType, ToType: ImplicitParamType);
6277 return ICS;
6278 }
6279 }
6280
6281 // Check that we have either the same type or a derived type. It
6282 // affects the conversion rank.
6283 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6284 ImplicitConversionKind SecondKind;
6285 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6286 SecondKind = ICK_Identity;
6287 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6288 SecondKind = ICK_Derived_To_Base;
6289 } else if (!Method->isExplicitObjectMemberFunction()) {
6290 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6291 FromType, ToType: ImplicitParamType);
6292 return ICS;
6293 }
6294
6295 // Check the ref-qualifier.
6296 switch (Method->getRefQualifier()) {
6297 case RQ_None:
6298 // Do nothing; we don't care about lvalueness or rvalueness.
6299 break;
6300
6301 case RQ_LValue:
6302 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6303 // non-const lvalue reference cannot bind to an rvalue
6304 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6305 ToType: ImplicitParamType);
6306 return ICS;
6307 }
6308 break;
6309
6310 case RQ_RValue:
6311 if (!FromClassification.isRValue()) {
6312 // rvalue reference cannot bind to an lvalue
6313 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6314 ToType: ImplicitParamType);
6315 return ICS;
6316 }
6317 break;
6318 }
6319
6320 // Success. Mark this as a reference binding.
6321 ICS.setStandard();
6322 ICS.Standard.setAsIdentityConversion();
6323 ICS.Standard.Second = SecondKind;
6324 ICS.Standard.setFromType(FromType);
6325 ICS.Standard.setAllToTypes(ImplicitParamType);
6326 ICS.Standard.ReferenceBinding = true;
6327 ICS.Standard.DirectBinding = true;
6328 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6329 ICS.Standard.BindsToFunctionLvalue = false;
6330 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6331 ICS.Standard.FromBracedInitList = false;
6332 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6333 = (Method->getRefQualifier() == RQ_None);
6334 return ICS;
6335}
6336
6337/// PerformObjectArgumentInitialization - Perform initialization of
6338/// the implicit object parameter for the given Method with the given
6339/// expression.
6340ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6341 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6342 CXXMethodDecl *Method) {
6343 QualType FromRecordType, DestType;
6344 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6345
6346 LangAS FromAS = From->getType().getAddressSpace();
6347 if (getLangOpts().HLSL &&
6348 (FromAS == LangAS::hlsl_constant ||
6349 (FromAS == LangAS::hlsl_groupshared && Method->isConst()))) {
6350 QualType CastType = From->getType().getLocalUnqualifiedType().withConst();
6351 From = ImplicitCastExpr::Create(Context, T: CastType, Kind: CK_LValueToRValue, Operand: From,
6352 /*BasePath=*/nullptr, Cat: VK_PRValue,
6353 FPO: FPOptionsOverride());
6354 } else if (getLangOpts().HLSL && FromAS == LangAS::hlsl_groupshared) {
6355 ASTContext &Ctx = SemaRef.getASTContext();
6356 QualType Ty = From->getType().getLocalUnqualifiedType();
6357 InitializedEntity TempEntity =
6358 InitializedEntity::InitializeTemporary(Type: Ty.getNonLValueExprType(Context: Ctx));
6359 ExprResult Res = SemaRef.HLSL().CreateOutArgExpr(
6360 Arg: From, ArgTy: Ty, ParamTy: Ty, Entity: TempEntity, Loc: From->getBeginLoc(), /*IsInOut=*/true);
6361 if (Res.isInvalid())
6362 return ExprError();
6363 From = Res.get();
6364 }
6365
6366 Expr::Classification FromClassification;
6367 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6368 FromRecordType = PT->getPointeeType();
6369 DestType = Method->getThisType();
6370 FromClassification = Expr::Classification::makeSimpleLValue();
6371 } else {
6372 FromRecordType = From->getType();
6373 DestType = ImplicitParamRecordType;
6374 FromClassification = From->Classify(Ctx&: Context);
6375
6376 // CWG2813 [expr.call]p6:
6377 // If the function is an implicit object member function, the object
6378 // expression of the class member access shall be a glvalue [...]
6379 if (From->isPRValue()) {
6380 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6381 BoundToLvalueReference: Method->getRefQualifier() !=
6382 RefQualifierKind::RQ_RValue);
6383 }
6384 }
6385
6386 // Note that we always use the true parent context when performing
6387 // the actual argument initialization.
6388 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6389 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6390 ActingContext: Method->getParent());
6391 if (ICS.isBad()) {
6392 switch (ICS.Bad.Kind) {
6393 case BadConversionSequence::bad_qualifiers: {
6394 Qualifiers FromQs = FromRecordType.getQualifiers();
6395 Qualifiers ToQs = DestType.getQualifiers();
6396 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6397 if (CVR) {
6398 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6399 << Method->getDeclName() << FromRecordType << (CVR - 1)
6400 << From->getSourceRange();
6401 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6402 << Method->getDeclName();
6403 return ExprError();
6404 }
6405 break;
6406 }
6407
6408 case BadConversionSequence::lvalue_ref_to_rvalue:
6409 case BadConversionSequence::rvalue_ref_to_lvalue: {
6410 bool IsRValueQualified =
6411 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6412 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6413 << Method->getDeclName() << FromClassification.isRValue()
6414 << IsRValueQualified;
6415 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6416 << Method->getDeclName();
6417 return ExprError();
6418 }
6419
6420 case BadConversionSequence::no_conversion:
6421 case BadConversionSequence::unrelated_class:
6422 break;
6423
6424 case BadConversionSequence::too_few_initializers:
6425 case BadConversionSequence::too_many_initializers:
6426 llvm_unreachable("Lists are not objects");
6427 }
6428
6429 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6430 << ImplicitParamRecordType << FromRecordType
6431 << From->getSourceRange();
6432 }
6433
6434 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6435 ExprResult FromRes =
6436 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6437 if (FromRes.isInvalid())
6438 return ExprError();
6439 From = FromRes.get();
6440 }
6441
6442 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6443 CastKind CK;
6444 QualType PteeTy = DestType->getPointeeType();
6445 LangAS DestAS =
6446 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6447 if (FromRecordType.getAddressSpace() != DestAS)
6448 CK = CK_AddressSpaceConversion;
6449 else
6450 CK = CK_NoOp;
6451 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6452 }
6453 return From;
6454}
6455
6456/// TryContextuallyConvertToBool - Attempt to contextually convert the
6457/// expression From to bool (C++0x [conv]p3).
6458static ImplicitConversionSequence
6459TryContextuallyConvertToBool(Sema &S, Expr *From) {
6460 // C++ [dcl.init]/17.8:
6461 // - Otherwise, if the initialization is direct-initialization, the source
6462 // type is std::nullptr_t, and the destination type is bool, the initial
6463 // value of the object being initialized is false.
6464 if (From->getType()->isNullPtrType())
6465 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6466 DestType: S.Context.BoolTy,
6467 NeedLValToRVal: From->isGLValue());
6468
6469 // All other direct-initialization of bool is equivalent to an implicit
6470 // conversion to bool in which explicit conversions are permitted.
6471 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6472 /*SuppressUserConversions=*/false,
6473 AllowExplicit: AllowedExplicit::Conversions,
6474 /*InOverloadResolution=*/false,
6475 /*CStyle=*/false,
6476 /*AllowObjCWritebackConversion=*/false,
6477 /*AllowObjCConversionOnExplicit=*/false);
6478}
6479
6480ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6481 if (checkPlaceholderForOverload(S&: *this, E&: From))
6482 return ExprError();
6483 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6484 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6485
6486 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6487 if (!ICS.isBad())
6488 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6489 Action: AssignmentAction::Converting);
6490 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6491 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6492 << From->getType() << From->getSourceRange();
6493 return ExprError();
6494}
6495
6496/// Check that the specified conversion is permitted in a converted constant
6497/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6498/// is acceptable.
6499static bool CheckConvertedConstantConversions(Sema &S,
6500 StandardConversionSequence &SCS) {
6501 // Since we know that the target type is an integral or unscoped enumeration
6502 // type, most conversion kinds are impossible. All possible First and Third
6503 // conversions are fine.
6504 switch (SCS.Second) {
6505 case ICK_Identity:
6506 case ICK_Integral_Promotion:
6507 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6508 case ICK_Zero_Queue_Conversion:
6509 return true;
6510
6511 case ICK_Boolean_Conversion:
6512 // Conversion from an integral or unscoped enumeration type to bool is
6513 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6514 // conversion, so we allow it in a converted constant expression.
6515 //
6516 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6517 // a lot of popular code. We should at least add a warning for this
6518 // (non-conforming) extension.
6519 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6520 SCS.getToType(Idx: 2)->isBooleanType();
6521
6522 case ICK_Pointer_Conversion:
6523 case ICK_Pointer_Member:
6524 // C++1z: null pointer conversions and null member pointer conversions are
6525 // only permitted if the source type is std::nullptr_t.
6526 return SCS.getFromType()->isNullPtrType();
6527
6528 case ICK_Floating_Promotion:
6529 case ICK_Complex_Promotion:
6530 case ICK_Floating_Conversion:
6531 case ICK_Complex_Conversion:
6532 case ICK_Floating_Integral:
6533 case ICK_Compatible_Conversion:
6534 case ICK_Derived_To_Base:
6535 case ICK_Vector_Conversion:
6536 case ICK_SVE_Vector_Conversion:
6537 case ICK_RVV_Vector_Conversion:
6538 case ICK_HLSL_Vector_Splat:
6539 case ICK_HLSL_Matrix_Splat:
6540 case ICK_Vector_Splat:
6541 case ICK_Complex_Real:
6542 case ICK_Block_Pointer_Conversion:
6543 case ICK_TransparentUnionConversion:
6544 case ICK_Writeback_Conversion:
6545 case ICK_Zero_Event_Conversion:
6546 case ICK_C_Only_Conversion:
6547 case ICK_Incompatible_Pointer_Conversion:
6548 case ICK_Fixed_Point_Conversion:
6549 case ICK_HLSL_Vector_Truncation:
6550 case ICK_HLSL_Matrix_Truncation:
6551 case ICK_HLSL_Packed_Type_Conversion:
6552 return false;
6553
6554 case ICK_Lvalue_To_Rvalue:
6555 case ICK_Array_To_Pointer:
6556 case ICK_Function_To_Pointer:
6557 case ICK_HLSL_Array_RValue:
6558 llvm_unreachable("found a first conversion kind in Second");
6559
6560 case ICK_Function_Conversion:
6561 case ICK_Qualification:
6562 llvm_unreachable("found a third conversion kind in Second");
6563
6564 case ICK_Num_Conversion_Kinds:
6565 break;
6566 }
6567
6568 llvm_unreachable("unknown conversion kind");
6569}
6570
6571/// BuildConvertedConstantExpression - Check that the expression From is a
6572/// converted constant expression of type T, perform the conversion but
6573/// does not evaluate the expression
6574static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6575 QualType T, CCEKind CCE,
6576 NamedDecl *Dest,
6577 APValue &PreNarrowingValue) {
6578 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6579 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool ||
6580 CCE == CCEKind::PackIndex);
6581 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6582 "converted constant expression outside C++11 or TTP matching");
6583
6584 if (checkPlaceholderForOverload(S, E&: From))
6585 return ExprError();
6586
6587 // C++1z [expr.const]p3:
6588 // A converted constant expression of type T is an expression,
6589 // implicitly converted to type T, where the converted
6590 // expression is a constant expression and the implicit conversion
6591 // sequence contains only [... list of conversions ...].
6592 ImplicitConversionSequence ICS =
6593 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6594 ? TryContextuallyConvertToBool(S, From)
6595 : TryCopyInitialization(S, From, ToType: T,
6596 /*SuppressUserConversions=*/false,
6597 /*InOverloadResolution=*/false,
6598 /*AllowObjCWritebackConversion=*/false,
6599 /*AllowExplicit=*/false);
6600 StandardConversionSequence *SCS = nullptr;
6601 switch (ICS.getKind()) {
6602 case ImplicitConversionSequence::StandardConversion:
6603 SCS = &ICS.Standard;
6604 break;
6605 case ImplicitConversionSequence::UserDefinedConversion:
6606 if (T->isRecordType())
6607 SCS = &ICS.UserDefined.Before;
6608 else
6609 SCS = &ICS.UserDefined.After;
6610 break;
6611 case ImplicitConversionSequence::AmbiguousConversion:
6612 case ImplicitConversionSequence::BadConversion:
6613 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6614 return S.Diag(Loc: From->getBeginLoc(),
6615 DiagID: diag::err_typecheck_converted_constant_expression)
6616 << From->getType() << From->getSourceRange() << T;
6617 return ExprError();
6618
6619 case ImplicitConversionSequence::EllipsisConversion:
6620 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6621 llvm_unreachable("bad conversion in converted constant expression");
6622 }
6623
6624 // Check that we would only use permitted conversions.
6625 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6626 return S.Diag(Loc: From->getBeginLoc(),
6627 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6628 << From->getType() << From->getSourceRange() << T;
6629 }
6630 // [...] and where the reference binding (if any) binds directly.
6631 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6632 return S.Diag(Loc: From->getBeginLoc(),
6633 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6634 << From->getType() << From->getSourceRange() << T;
6635 }
6636 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6637 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6638 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6639 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6640 // case explicitly.
6641 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6642 return S.Diag(Loc: From->getBeginLoc(),
6643 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6644 << From->getSourceRange();
6645 }
6646
6647 // Usually we can simply apply the ImplicitConversionSequence we formed
6648 // earlier, but that's not guaranteed to work when initializing an object of
6649 // class type.
6650 ExprResult Result;
6651 bool IsTemplateArgument =
6652 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6653 if (T->isRecordType()) {
6654 assert(IsTemplateArgument &&
6655 "unexpected class type converted constant expr");
6656 Result = S.PerformCopyInitialization(
6657 Entity: InitializedEntity::InitializeTemplateParameter(
6658 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6659 EqualLoc: SourceLocation(), Init: From);
6660 } else {
6661 Result =
6662 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6663 }
6664 if (Result.isInvalid())
6665 return Result;
6666
6667 // C++2a [intro.execution]p5:
6668 // A full-expression is [...] a constant-expression [...]
6669 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6670 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6671 IsTemplateArgument);
6672 if (Result.isInvalid())
6673 return Result;
6674
6675 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6676
6677 // Check for a narrowing implicit conversion.
6678 bool ReturnPreNarrowingValue = false;
6679 QualType PreNarrowingType;
6680 switch (SCS->getNarrowingKind(
6681 Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue, ConstantType&: PreNarrowingType,
6682 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6683 case NK_Variable_Narrowing:
6684 // Implicit conversion to a narrower type, and the value is not a constant
6685 // expression. We'll diagnose this in a moment.
6686 case NK_Not_Narrowing:
6687 break;
6688
6689 case NK_Constant_Narrowing:
6690 if (CCE == CCEKind::ArrayBound &&
6691 PreNarrowingType->isIntegralOrEnumerationType() &&
6692 PreNarrowingValue.isInt()) {
6693 // Don't diagnose array bound narrowing here; we produce more precise
6694 // errors by allowing the un-narrowed value through.
6695 ReturnPreNarrowingValue = true;
6696 break;
6697 }
6698 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6699 << CCE << /*Constant*/ 1
6700 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6701 // If this is an SFINAE Context, treat the result as invalid so it stops
6702 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6703 // FIXME: Should do this whenever the above diagnostic is an error, but
6704 // without further changes this would degrade some other diagnostics.
6705 if (S.isSFINAEContext())
6706 return ExprError();
6707 break;
6708
6709 case NK_Dependent_Narrowing:
6710 // Implicit conversion to a narrower type, but the expression is
6711 // value-dependent so we can't tell whether it's actually narrowing.
6712 // For matching the parameters of a TTP, the conversion is ill-formed
6713 // if it may narrow.
6714 if (CCE != CCEKind::TempArgStrict)
6715 break;
6716 [[fallthrough]];
6717 case NK_Type_Narrowing:
6718 // FIXME: It would be better to diagnose that the expression is not a
6719 // constant expression.
6720 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6721 << CCE << /*Constant*/ 0 << From->getType() << T;
6722 if (S.isSFINAEContext())
6723 return ExprError();
6724 break;
6725 }
6726 if (!ReturnPreNarrowingValue)
6727 PreNarrowingValue = {};
6728
6729 return Result;
6730}
6731
6732/// CheckConvertedConstantExpression - Check that the expression From is a
6733/// converted constant expression of type T, perform the conversion and produce
6734/// the converted expression, per C++11 [expr.const]p3.
6735static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6736 QualType T, APValue &Value,
6737 CCEKind CCE, bool RequireInt,
6738 NamedDecl *Dest) {
6739
6740 APValue PreNarrowingValue;
6741 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6742 PreNarrowingValue);
6743 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6744 Value = APValue();
6745 return Result;
6746 }
6747 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6748 RequireInt, PreNarrowingValue);
6749}
6750
6751ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6752 CCEKind CCE,
6753 NamedDecl *Dest) {
6754 APValue PreNarrowingValue;
6755 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6756 PreNarrowingValue);
6757}
6758
6759ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6760 APValue &Value, CCEKind CCE,
6761 NamedDecl *Dest) {
6762 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6763 Dest);
6764}
6765
6766ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6767 llvm::APSInt &Value,
6768 CCEKind CCE) {
6769 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6770
6771 APValue V;
6772 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6773 /*Dest=*/nullptr);
6774 if (!R.isInvalid() && !R.get()->isValueDependent())
6775 Value = V.getInt();
6776 return R;
6777}
6778
6779ExprResult
6780Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6781 CCEKind CCE, bool RequireInt,
6782 const APValue &PreNarrowingValue) {
6783
6784 ExprResult Result = E;
6785 // Check the expression is a constant expression.
6786 SmallVector<PartialDiagnosticAt, 8> Notes;
6787 SmallVector<PartialDiagnosticAt> MSWarning;
6788 Expr::EvalResult Eval;
6789 Eval.Diag = &Notes;
6790 Eval.ExtendedDiag = &MSWarning;
6791
6792 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6793
6794 ConstantExprKind Kind;
6795 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6796 Kind = ConstantExprKind::ClassTemplateArgument;
6797 else if (CCE == CCEKind::TemplateArg)
6798 Kind = ConstantExprKind::NonClassTemplateArgument;
6799 else
6800 Kind = ConstantExprKind::Normal;
6801
6802 EvalProxy SProxy(*this);
6803 if (!E->EvaluateAsMandatedConstantExpr(Result&: Eval, Ctx: Context, SProxy, Kind) ||
6804 (RequireInt && !Eval.Val.isInt())) {
6805 // The expression can't be folded, so we can't keep it at this position in
6806 // the AST.
6807 Result = ExprError();
6808 } else {
6809 Value = Eval.Val;
6810 // For -fms-compatibility mode we relax some requirements
6811 // for constant folding in non-SFINAE contexts
6812 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6813 if (Notes.empty() && !CantFold) {
6814 for (auto &Info : MSWarning)
6815 Diag(Loc: Info.first, PD: Info.second);
6816 // It's a constant expression.
6817 Expr *E = Result.get();
6818 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6819 // We expect a ConstantExpr to have a value associated with it
6820 // by this point.
6821 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6822 "ConstantExpr has no value associated with it");
6823 (void)CE;
6824 } else {
6825 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6826 }
6827 if (!PreNarrowingValue.isAbsent())
6828 Value = std::move(PreNarrowingValue);
6829 return E;
6830 }
6831 }
6832
6833 // It's not a constant expression. Produce an appropriate diagnostic.
6834 if (Notes.size() == 1 &&
6835 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6836 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6837 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6838 diag::note_constexpr_invalid_template_arg) {
6839 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6840 for (unsigned I = 0; I < Notes.size(); ++I)
6841 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6842 } else {
6843 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6844 << CCE << E->getSourceRange();
6845 for (unsigned I = 0; I < Notes.size(); ++I)
6846 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6847 }
6848 return ExprError();
6849}
6850
6851/// dropPointerConversions - If the given standard conversion sequence
6852/// involves any pointer conversions, remove them. This may change
6853/// the result type of the conversion sequence.
6854static void dropPointerConversion(StandardConversionSequence &SCS) {
6855 if (SCS.Second == ICK_Pointer_Conversion) {
6856 SCS.Second = ICK_Identity;
6857 SCS.Dimension = ICK_Identity;
6858 SCS.Third = ICK_Identity;
6859 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6860 }
6861}
6862
6863/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6864/// convert the expression From to an Objective-C pointer type.
6865static ImplicitConversionSequence
6866TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6867 // Do an implicit conversion to 'id'.
6868 QualType Ty = S.Context.getObjCIdType();
6869 ImplicitConversionSequence ICS
6870 = TryImplicitConversion(S, From, ToType: Ty,
6871 // FIXME: Are these flags correct?
6872 /*SuppressUserConversions=*/false,
6873 AllowExplicit: AllowedExplicit::Conversions,
6874 /*InOverloadResolution=*/false,
6875 /*CStyle=*/false,
6876 /*AllowObjCWritebackConversion=*/false,
6877 /*AllowObjCConversionOnExplicit=*/true);
6878
6879 // Strip off any final conversions to 'id'.
6880 switch (ICS.getKind()) {
6881 case ImplicitConversionSequence::BadConversion:
6882 case ImplicitConversionSequence::AmbiguousConversion:
6883 case ImplicitConversionSequence::EllipsisConversion:
6884 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6885 break;
6886
6887 case ImplicitConversionSequence::UserDefinedConversion:
6888 dropPointerConversion(SCS&: ICS.UserDefined.After);
6889 break;
6890
6891 case ImplicitConversionSequence::StandardConversion:
6892 dropPointerConversion(SCS&: ICS.Standard);
6893 break;
6894 }
6895
6896 return ICS;
6897}
6898
6899ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6900 if (checkPlaceholderForOverload(S&: *this, E&: From))
6901 return ExprError();
6902
6903 QualType Ty = Context.getObjCIdType();
6904 ImplicitConversionSequence ICS =
6905 TryContextuallyConvertToObjCPointer(S&: *this, From);
6906 if (!ICS.isBad())
6907 return PerformImplicitConversion(From, ToType: Ty, ICS,
6908 Action: AssignmentAction::Converting);
6909 return ExprResult();
6910}
6911
6912static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6913 const Expr *Base = nullptr;
6914 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6915 "expected a member expression");
6916
6917 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6918 M && !M->isImplicitAccess())
6919 Base = M->getBase();
6920 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6921 M && !M->isImplicitAccess())
6922 Base = M->getBase();
6923
6924 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6925
6926 if (T->isPointerType())
6927 T = T->getPointeeType();
6928
6929 return T;
6930}
6931
6932static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6933 const FunctionDecl *Fun) {
6934 QualType ObjType = Obj->getType();
6935 if (ObjType->isPointerType()) {
6936 ObjType = ObjType->getPointeeType();
6937 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6938 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6939 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6940 }
6941 return Obj;
6942}
6943
6944ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6945 FunctionDecl *Fun) {
6946 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6947 return S.PerformCopyInitialization(
6948 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6949 EqualLoc: Obj->getExprLoc(), Init: Obj);
6950}
6951
6952static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6953 Expr *Object, MultiExprArg &Args,
6954 SmallVectorImpl<Expr *> &NewArgs) {
6955 assert(Method->isExplicitObjectMemberFunction() &&
6956 "Method is not an explicit member function");
6957 assert(NewArgs.empty() && "NewArgs should be empty");
6958
6959 NewArgs.reserve(N: Args.size() + 1);
6960 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6961 NewArgs.push_back(Elt: This);
6962 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6963 Args = NewArgs;
6964 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6965 Method, CallLoc: Object->getBeginLoc());
6966}
6967
6968/// Determine whether the provided type is an integral type, or an enumeration
6969/// type of a permitted flavor.
6970bool Sema::ICEConvertDiagnoser::match(QualType T) {
6971 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6972 : T->isIntegralOrUnscopedEnumerationType();
6973}
6974
6975static ExprResult
6976diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6977 Sema::ContextualImplicitConverter &Converter,
6978 QualType T, UnresolvedSetImpl &ViableConversions) {
6979
6980 if (Converter.Suppress)
6981 return ExprError();
6982
6983 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6984 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6985 CXXConversionDecl *Conv =
6986 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6987 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6988 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6989 }
6990 return From;
6991}
6992
6993static bool
6994diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6995 Sema::ContextualImplicitConverter &Converter,
6996 QualType T, bool HadMultipleCandidates,
6997 UnresolvedSetImpl &ExplicitConversions) {
6998 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6999 DeclAccessPair Found = ExplicitConversions[0];
7000 CXXConversionDecl *Conversion =
7001 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
7002
7003 // The user probably meant to invoke the given explicit
7004 // conversion; use it.
7005 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
7006 std::string TypeStr;
7007 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
7008
7009 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
7010 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
7011 Code: "static_cast<" + TypeStr + ">(")
7012 << FixItHint::CreateInsertion(
7013 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
7014 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
7015
7016 // If we aren't in a SFINAE context, build a call to the
7017 // explicit conversion function.
7018 if (SemaRef.isSFINAEContext())
7019 return true;
7020
7021 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
7022 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
7023 HadMultipleCandidates);
7024 if (Result.isInvalid())
7025 return true;
7026
7027 // Replace the conversion with a RecoveryExpr, so we don't try to
7028 // instantiate it later, but can further diagnose here.
7029 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
7030 SubExprs: From, T: Result.get()->getType());
7031 if (Result.isInvalid())
7032 return true;
7033 From = Result.get();
7034 }
7035 return false;
7036}
7037
7038static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
7039 Sema::ContextualImplicitConverter &Converter,
7040 QualType T, bool HadMultipleCandidates,
7041 DeclAccessPair &Found) {
7042 CXXConversionDecl *Conversion =
7043 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
7044 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
7045
7046 QualType ToType = Conversion->getConversionType().getNonReferenceType();
7047 if (!Converter.SuppressConversion) {
7048 if (SemaRef.isSFINAEContext())
7049 return true;
7050
7051 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
7052 << From->getSourceRange();
7053 }
7054
7055 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
7056 HadMultipleCandidates);
7057 if (Result.isInvalid())
7058 return true;
7059 // Record usage of conversion in an implicit cast.
7060 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
7061 Kind: CK_UserDefinedConversion, Operand: Result.get(),
7062 BasePath: nullptr, Cat: Result.get()->getValueKind(),
7063 FPO: SemaRef.CurFPFeatureOverrides());
7064 return false;
7065}
7066
7067static ExprResult finishContextualImplicitConversion(
7068 Sema &SemaRef, SourceLocation Loc, Expr *From,
7069 Sema::ContextualImplicitConverter &Converter) {
7070 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
7071 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
7072 << From->getSourceRange();
7073
7074 return SemaRef.DefaultLvalueConversion(E: From);
7075}
7076
7077static void
7078collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
7079 UnresolvedSetImpl &ViableConversions,
7080 OverloadCandidateSet &CandidateSet) {
7081 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7082 NamedDecl *D = FoundDecl.getDecl();
7083 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
7084 if (isa<UsingShadowDecl>(Val: D))
7085 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
7086
7087 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
7088 SemaRef.AddTemplateConversionCandidate(
7089 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7090 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7091 continue;
7092 }
7093 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
7094 SemaRef.AddConversionCandidate(
7095 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7096 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7097 }
7098}
7099
7100/// Attempt to convert the given expression to a type which is accepted
7101/// by the given converter.
7102///
7103/// This routine will attempt to convert an expression of class type to a
7104/// type accepted by the specified converter. In C++11 and before, the class
7105/// must have a single non-explicit conversion function converting to a matching
7106/// type. In C++1y, there can be multiple such conversion functions, but only
7107/// one target type.
7108///
7109/// \param Loc The source location of the construct that requires the
7110/// conversion.
7111///
7112/// \param From The expression we're converting from.
7113///
7114/// \param Converter Used to control and diagnose the conversion process.
7115///
7116/// \returns The expression, converted to an integral or enumeration type if
7117/// successful.
7118ExprResult Sema::PerformContextualImplicitConversion(
7119 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7120 // We can't perform any more checking for type-dependent expressions.
7121 if (From->isTypeDependent())
7122 return From;
7123
7124 // Process placeholders immediately.
7125 if (From->hasPlaceholderType()) {
7126 ExprResult result = CheckPlaceholderExpr(E: From);
7127 if (result.isInvalid())
7128 return result;
7129 From = result.get();
7130 }
7131
7132 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7133 ExprResult Converted = DefaultLvalueConversion(E: From);
7134 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7135 From = Converted.isUsable() ? Converted.get() : nullptr;
7136 // If the expression already has a matching type, we're golden.
7137 if (Converter.match(T))
7138 return Converted;
7139
7140 // FIXME: Check for missing '()' if T is a function type?
7141
7142 // We can only perform contextual implicit conversions on objects of class
7143 // type.
7144 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7145 if (!RecordTy || !getLangOpts().CPlusPlus) {
7146 if (!Converter.Suppress)
7147 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7148 return From;
7149 }
7150
7151 // We must have a complete class type.
7152 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7153 ContextualImplicitConverter &Converter;
7154 Expr *From;
7155
7156 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7157 : Converter(Converter), From(From) {}
7158
7159 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7160 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7161 }
7162 } IncompleteDiagnoser(Converter, From);
7163
7164 if (Converter.Suppress ? !isCompleteType(Loc, T)
7165 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7166 return From;
7167
7168 // Look for a conversion to an integral or enumeration type.
7169 UnresolvedSet<4>
7170 ViableConversions; // These are *potentially* viable in C++1y.
7171 UnresolvedSet<4> ExplicitConversions;
7172 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7173 ->getDefinitionOrSelf()
7174 ->getVisibleConversionFunctions();
7175
7176 bool HadMultipleCandidates =
7177 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7178
7179 // To check that there is only one target type, in C++1y:
7180 QualType ToType;
7181 bool HasUniqueTargetType = true;
7182
7183 // Collect explicit or viable (potentially in C++1y) conversions.
7184 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7185 NamedDecl *D = (*I)->getUnderlyingDecl();
7186 CXXConversionDecl *Conversion;
7187 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7188 if (ConvTemplate) {
7189 if (getLangOpts().CPlusPlus14)
7190 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7191 else
7192 continue; // C++11 does not consider conversion operator templates(?).
7193 } else
7194 Conversion = cast<CXXConversionDecl>(Val: D);
7195
7196 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7197 "Conversion operator templates are considered potentially "
7198 "viable in C++1y");
7199
7200 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7201 if (Converter.match(T: CurToType) || ConvTemplate) {
7202
7203 if (Conversion->isExplicit()) {
7204 // FIXME: For C++1y, do we need this restriction?
7205 // cf. diagnoseNoViableConversion()
7206 if (!ConvTemplate)
7207 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7208 } else {
7209 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7210 if (ToType.isNull())
7211 ToType = CurToType.getUnqualifiedType();
7212 else if (HasUniqueTargetType &&
7213 (CurToType.getUnqualifiedType() != ToType))
7214 HasUniqueTargetType = false;
7215 }
7216 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7217 }
7218 }
7219 }
7220
7221 if (getLangOpts().CPlusPlus14) {
7222 // C++1y [conv]p6:
7223 // ... An expression e of class type E appearing in such a context
7224 // is said to be contextually implicitly converted to a specified
7225 // type T and is well-formed if and only if e can be implicitly
7226 // converted to a type T that is determined as follows: E is searched
7227 // for conversion functions whose return type is cv T or reference to
7228 // cv T such that T is allowed by the context. There shall be
7229 // exactly one such T.
7230
7231 // If no unique T is found:
7232 if (ToType.isNull()) {
7233 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7234 HadMultipleCandidates,
7235 ExplicitConversions))
7236 return ExprError();
7237 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7238 }
7239
7240 // If more than one unique Ts are found:
7241 if (!HasUniqueTargetType)
7242 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7243 ViableConversions);
7244
7245 // If one unique T is found:
7246 // First, build a candidate set from the previously recorded
7247 // potentially viable conversions.
7248 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7249 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7250 CandidateSet);
7251
7252 // Then, perform overload resolution over the candidate set.
7253 OverloadCandidateSet::iterator Best;
7254 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7255 case OR_Success: {
7256 // Apply this conversion.
7257 DeclAccessPair Found =
7258 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7259 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7260 HadMultipleCandidates, Found))
7261 return ExprError();
7262 break;
7263 }
7264 case OR_Ambiguous:
7265 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7266 ViableConversions);
7267 case OR_No_Viable_Function:
7268 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7269 HadMultipleCandidates,
7270 ExplicitConversions))
7271 return ExprError();
7272 [[fallthrough]];
7273 case OR_Deleted:
7274 // We'll complain below about a non-integral condition type.
7275 break;
7276 }
7277 } else {
7278 switch (ViableConversions.size()) {
7279 case 0: {
7280 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7281 HadMultipleCandidates,
7282 ExplicitConversions))
7283 return ExprError();
7284
7285 // We'll complain below about a non-integral condition type.
7286 break;
7287 }
7288 case 1: {
7289 // Apply this conversion.
7290 DeclAccessPair Found = ViableConversions[0];
7291 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7292 HadMultipleCandidates, Found))
7293 return ExprError();
7294 break;
7295 }
7296 default:
7297 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7298 ViableConversions);
7299 }
7300 }
7301
7302 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7303}
7304
7305/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7306/// an acceptable non-member overloaded operator for a call whose
7307/// arguments have types T1 (and, if non-empty, T2). This routine
7308/// implements the check in C++ [over.match.oper]p3b2 concerning
7309/// enumeration types.
7310static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7311 FunctionDecl *Fn,
7312 ArrayRef<Expr *> Args) {
7313 QualType T1 = Args[0]->getType();
7314 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7315
7316 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7317 return true;
7318
7319 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7320 return true;
7321
7322 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7323 if (Proto->getNumParams() < 1)
7324 return false;
7325
7326 if (T1->isEnumeralType()) {
7327 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7328 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7329 return true;
7330 }
7331
7332 if (Proto->getNumParams() < 2)
7333 return false;
7334
7335 if (!T2.isNull() && T2->isEnumeralType()) {
7336 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7337 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7338 return true;
7339 }
7340
7341 return false;
7342}
7343
7344static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7345 if (FD->isTargetMultiVersionDefault())
7346 return false;
7347
7348 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7349 return FD->isTargetMultiVersion();
7350
7351 if (!FD->isMultiVersion())
7352 return false;
7353
7354 // Among multiple target versions consider either the default,
7355 // or the first non-default in the absence of default version.
7356 unsigned SeenAt = 0;
7357 unsigned I = 0;
7358 bool HasDefault = false;
7359 FD->getASTContext().forEachMultiversionedFunctionVersion(
7360 FD, Pred: [&](const FunctionDecl *CurFD) {
7361 if (FD == CurFD)
7362 SeenAt = I;
7363 else if (CurFD->isTargetMultiVersionDefault())
7364 HasDefault = true;
7365 ++I;
7366 });
7367 return HasDefault || SeenAt != 0;
7368}
7369
7370void Sema::AddOverloadCandidate(
7371 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7372 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7373 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7374 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7375 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7376 bool StrictPackMatch) {
7377 const FunctionProtoType *Proto
7378 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7379 assert(Proto && "Functions without a prototype cannot be overloaded");
7380 assert(!Function->getDescribedFunctionTemplate() &&
7381 "Use AddTemplateOverloadCandidate for function templates");
7382
7383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7384 if (!isa<CXXConstructorDecl>(Val: Method)) {
7385 // If we get here, it's because we're calling a member function
7386 // that is named without a member access expression (e.g.,
7387 // "this->f") that was either written explicitly or created
7388 // implicitly. This can happen with a qualified call to a member
7389 // function, e.g., X::f(). We use an empty type for the implied
7390 // object argument (C++ [over.call.func]p3), and the acting context
7391 // is irrelevant.
7392 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7393 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7394 CandidateSet, SuppressUserConversions,
7395 PartialOverloading, EarlyConversions, PO,
7396 StrictPackMatch);
7397 return;
7398 }
7399 // We treat a constructor like a non-member function, since its object
7400 // argument doesn't participate in overload resolution.
7401 }
7402
7403 if (!CandidateSet.isNewCandidate(F: Function, PO))
7404 return;
7405
7406 // C++11 [class.copy]p11: [DR1402]
7407 // A defaulted move constructor that is defined as deleted is ignored by
7408 // overload resolution.
7409 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7410 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7411 Constructor->isMoveConstructor())
7412 return;
7413
7414 // Overload resolution is always an unevaluated context.
7415 EnterExpressionEvaluationContext Unevaluated(
7416 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7417
7418 // C++ [over.match.oper]p3:
7419 // if no operand has a class type, only those non-member functions in the
7420 // lookup set that have a first parameter of type T1 or "reference to
7421 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7422 // is a right operand) a second parameter of type T2 or "reference to
7423 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7424 // candidate functions.
7425 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7426 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7427 return;
7428
7429 // Add this candidate
7430 OverloadCandidate &Candidate =
7431 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7432 Candidate.FoundDecl = FoundDecl;
7433 Candidate.Function = Function;
7434 Candidate.Viable = true;
7435 Candidate.RewriteKind =
7436 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7437 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7438 Candidate.ExplicitCallArguments = Args.size();
7439 Candidate.StrictPackMatch = StrictPackMatch;
7440
7441 // Explicit functions are not actually candidates at all if we're not
7442 // allowing them in this context, but keep them around so we can point
7443 // to them in diagnostics.
7444 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7445 Candidate.Viable = false;
7446 Candidate.FailureKind = ovl_fail_explicit;
7447 return;
7448 }
7449
7450 // Functions with internal linkage are only viable in the same module unit.
7451 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7452 /// FIXME: Currently, the semantics of linkage in clang is slightly
7453 /// different from the semantics in C++ spec. In C++ spec, only names
7454 /// have linkage. So that all entities of the same should share one
7455 /// linkage. But in clang, different entities of the same could have
7456 /// different linkage.
7457 const NamedDecl *ND = Function;
7458 bool IsImplicitlyInstantiated = false;
7459 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7460 ND = SpecInfo->getTemplate();
7461 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7462 TSK_ImplicitInstantiation;
7463 }
7464
7465 /// Don't remove inline functions with internal linkage from the overload
7466 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7467 /// However:
7468 /// - Inline functions with internal linkage are a common pattern in
7469 /// headers to avoid ODR issues.
7470 /// - The global module is meant to be a transition mechanism for C and C++
7471 /// headers, and the current rules as written work against that goal.
7472 const bool IsInlineFunctionInGMF =
7473 Function->isFromGlobalModule() &&
7474 (IsImplicitlyInstantiated || Function->isInlined());
7475
7476 // Don't exclude internal-linkage entities from the current TU's global
7477 // module fragment.
7478 const Module *CurrentModule = getCurrentModule();
7479 const bool IsCurrentUnitGMFDecl =
7480 Function->isFromGlobalModule() && CurrentModule &&
7481 Function->getOwningModule()->getTopLevelModule() ==
7482 CurrentModule->getTopLevelModule();
7483
7484 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7485 !IsCurrentUnitGMFDecl) {
7486 Candidate.Viable = false;
7487 Candidate.FailureKind = ovl_fail_module_mismatched;
7488 return;
7489 }
7490 }
7491
7492 if (isNonViableMultiVersionOverload(FD: Function)) {
7493 Candidate.Viable = false;
7494 Candidate.FailureKind = ovl_non_default_multiversion_function;
7495 return;
7496 }
7497
7498 if (Constructor) {
7499 // C++ [class.copy]p3:
7500 // A member function template is never instantiated to perform the copy
7501 // of a class object to an object of its class type.
7502 CanQualType ClassType =
7503 Context.getCanonicalTagType(TD: Constructor->getParent());
7504 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7505 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7506 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7507 Base: ClassType))) {
7508 Candidate.Viable = false;
7509 Candidate.FailureKind = ovl_fail_illegal_constructor;
7510 return;
7511 }
7512
7513 // C++ [over.match.funcs]p8: (proposed DR resolution)
7514 // A constructor inherited from class type C that has a first parameter
7515 // of type "reference to P" (including such a constructor instantiated
7516 // from a template) is excluded from the set of candidate functions when
7517 // constructing an object of type cv D if the argument list has exactly
7518 // one argument and D is reference-related to P and P is reference-related
7519 // to C.
7520 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7521 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7522 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7523 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7524 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7525 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7526 SourceLocation Loc = Args.front()->getExprLoc();
7527 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7528 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7529 Candidate.Viable = false;
7530 Candidate.FailureKind = ovl_fail_inhctor_slice;
7531 return;
7532 }
7533 }
7534
7535 // Check that the constructor is capable of constructing an object in the
7536 // destination address space.
7537 if (!Qualifiers::isAddressSpaceSupersetOf(
7538 A: Constructor->getMethodQualifiers().getAddressSpace(),
7539 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7540 Candidate.Viable = false;
7541 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7542 }
7543 }
7544
7545 unsigned NumParams = Proto->getNumParams();
7546
7547 // (C++ 13.3.2p2): A candidate function having fewer than m
7548 // parameters is viable only if it has an ellipsis in its parameter
7549 // list (8.3.5).
7550 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7551 !Proto->isVariadic() &&
7552 shouldEnforceArgLimit(PartialOverloading, Function)) {
7553 Candidate.Viable = false;
7554 Candidate.FailureKind = ovl_fail_too_many_arguments;
7555 return;
7556 }
7557
7558 // (C++ 13.3.2p2): A candidate function having more than m parameters
7559 // is viable only if the (m+1)st parameter has a default argument
7560 // (8.3.6). For the purposes of overload resolution, the
7561 // parameter list is truncated on the right, so that there are
7562 // exactly m parameters.
7563 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7564 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7565 !PartialOverloading) {
7566 // Not enough arguments.
7567 Candidate.Viable = false;
7568 Candidate.FailureKind = ovl_fail_too_few_arguments;
7569 return;
7570 }
7571
7572 // (CUDA B.1): Check for invalid calls between targets.
7573 if (getLangOpts().CUDA) {
7574 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7575 // Skip the check for callers that are implicit members, because in this
7576 // case we may not yet know what the member's target is; the target is
7577 // inferred for the member automatically, based on the bases and fields of
7578 // the class.
7579 if (!(Caller && Caller->isImplicit()) &&
7580 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7581 Candidate.Viable = false;
7582 Candidate.FailureKind = ovl_fail_bad_target;
7583 return;
7584 }
7585 }
7586
7587 if (Function->getTrailingRequiresClause()) {
7588 ConstraintSatisfaction Satisfaction;
7589 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7590 /*ForOverloadResolution*/ true) ||
7591 !Satisfaction.IsSatisfied) {
7592 Candidate.Viable = false;
7593 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7594 return;
7595 }
7596 }
7597
7598 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7599 // Determine the implicit conversion sequences for each of the
7600 // arguments.
7601 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7602 unsigned ConvIdx =
7603 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7604 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7605 // We already formed a conversion sequence for this parameter during
7606 // template argument deduction.
7607 } else if (ArgIdx < NumParams) {
7608 // (C++ 13.3.2p3): for F to be a viable function, there shall
7609 // exist for each argument an implicit conversion sequence
7610 // (13.3.3.1) that converts that argument to the corresponding
7611 // parameter of F.
7612 QualType ParamType = Proto->getParamType(i: ArgIdx);
7613 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7614 if (ParamABI == ParameterABI::HLSLOut ||
7615 ParamABI == ParameterABI::HLSLInOut) {
7616 ParamType = ParamType.getNonReferenceType();
7617 if (ParamABI == ParameterABI::HLSLInOut &&
7618 Args[ArgIdx]->getType().getAddressSpace() ==
7619 LangAS::hlsl_groupshared)
7620 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7621 }
7622 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7623 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7624 /*InOverloadResolution=*/true,
7625 /*AllowObjCWritebackConversion=*/
7626 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7627 if (Candidate.Conversions[ConvIdx].isBad()) {
7628 Candidate.Viable = false;
7629 Candidate.FailureKind = ovl_fail_bad_conversion;
7630 return;
7631 }
7632 } else {
7633 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7634 // argument for which there is no corresponding parameter is
7635 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7636 Candidate.Conversions[ConvIdx].setEllipsis();
7637 }
7638 }
7639
7640 if (EnableIfAttr *FailedAttr =
7641 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7642 Candidate.Viable = false;
7643 Candidate.FailureKind = ovl_fail_enable_if;
7644 Candidate.DeductionFailure.Data = FailedAttr;
7645 return;
7646 }
7647}
7648
7649ObjCMethodDecl *
7650Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7651 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7652 if (Methods.size() <= 1)
7653 return nullptr;
7654
7655 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7656 bool Match = true;
7657 ObjCMethodDecl *Method = Methods[b];
7658 unsigned NumNamedArgs = Sel.getNumArgs();
7659 // Method might have more arguments than selector indicates. This is due
7660 // to addition of c-style arguments in method.
7661 if (Method->param_size() > NumNamedArgs)
7662 NumNamedArgs = Method->param_size();
7663 if (Args.size() < NumNamedArgs)
7664 continue;
7665
7666 for (unsigned i = 0; i < NumNamedArgs; i++) {
7667 // We can't do any type-checking on a type-dependent argument.
7668 if (Args[i]->isTypeDependent()) {
7669 Match = false;
7670 break;
7671 }
7672
7673 ParmVarDecl *param = Method->parameters()[i];
7674 Expr *argExpr = Args[i];
7675 assert(argExpr && "SelectBestMethod(): missing expression");
7676
7677 // Strip the unbridged-cast placeholder expression off unless it's
7678 // a consumed argument.
7679 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7680 !param->hasAttr<CFConsumedAttr>())
7681 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7682
7683 // If the parameter is __unknown_anytype, move on to the next method.
7684 if (param->getType() == Context.UnknownAnyTy) {
7685 Match = false;
7686 break;
7687 }
7688
7689 ImplicitConversionSequence ConversionState
7690 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7691 /*SuppressUserConversions*/false,
7692 /*InOverloadResolution=*/true,
7693 /*AllowObjCWritebackConversion=*/
7694 getLangOpts().ObjCAutoRefCount,
7695 /*AllowExplicit*/false);
7696 // This function looks for a reasonably-exact match, so we consider
7697 // incompatible pointer conversions to be a failure here.
7698 if (ConversionState.isBad() ||
7699 (ConversionState.isStandard() &&
7700 ConversionState.Standard.Second ==
7701 ICK_Incompatible_Pointer_Conversion)) {
7702 Match = false;
7703 break;
7704 }
7705 }
7706 // Promote additional arguments to variadic methods.
7707 if (Match && Method->isVariadic()) {
7708 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7709 if (Args[i]->isTypeDependent()) {
7710 Match = false;
7711 break;
7712 }
7713 ExprResult Arg = DefaultVariadicArgumentPromotion(
7714 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7715 if (Arg.isInvalid()) {
7716 Match = false;
7717 break;
7718 }
7719 }
7720 } else {
7721 // Check for extra arguments to non-variadic methods.
7722 if (Args.size() != NumNamedArgs)
7723 Match = false;
7724 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7725 // Special case when selectors have no argument. In this case, select
7726 // one with the most general result type of 'id'.
7727 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7728 QualType ReturnT = Methods[b]->getReturnType();
7729 if (ReturnT->isObjCIdType())
7730 return Methods[b];
7731 }
7732 }
7733 }
7734
7735 if (Match)
7736 return Method;
7737 }
7738 return nullptr;
7739}
7740
7741static bool convertArgsForAvailabilityChecks(
7742 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7743 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7744 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7745 if (ThisArg) {
7746 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7747 assert(!isa<CXXConstructorDecl>(Method) &&
7748 "Shouldn't have `this` for ctors!");
7749 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7750 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7751 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7752 if (R.isInvalid())
7753 return false;
7754 ConvertedThis = R.get();
7755 } else {
7756 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7757 (void)MD;
7758 assert((MissingImplicitThis || MD->isStatic() ||
7759 isa<CXXConstructorDecl>(MD)) &&
7760 "Expected `this` for non-ctor instance methods");
7761 }
7762 ConvertedThis = nullptr;
7763 }
7764
7765 // Ignore any variadic arguments. Converting them is pointless, since the
7766 // user can't refer to them in the function condition.
7767 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7768
7769 // Convert the arguments.
7770 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7771 ExprResult R;
7772 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7773 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7774 EqualLoc: SourceLocation(), Init: Args[I]);
7775
7776 if (R.isInvalid())
7777 return false;
7778
7779 ConvertedArgs.push_back(Elt: R.get());
7780 }
7781
7782 if (Trap.hasErrorOccurred())
7783 return false;
7784
7785 // Push default arguments if needed.
7786 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7787 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7788 ParmVarDecl *P = Function->getParamDecl(i);
7789 if (!P->hasDefaultArg())
7790 return false;
7791 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7792 if (R.isInvalid())
7793 return false;
7794 ConvertedArgs.push_back(Elt: R.get());
7795 }
7796
7797 if (Trap.hasErrorOccurred())
7798 return false;
7799 }
7800 return true;
7801}
7802
7803EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7804 SourceLocation CallLoc,
7805 ArrayRef<Expr *> Args,
7806 bool MissingImplicitThis) {
7807 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7808 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7809 return nullptr;
7810
7811 SFINAETrap Trap(*this);
7812 // Perform the access checking immediately so any access diagnostics are
7813 // caught by the SFINAE trap.
7814 llvm::scope_exit UndelayDiags(
7815 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7816 DelayedDiagnostics.popUndelayed(state: CurrentState);
7817 });
7818 SmallVector<Expr *, 16> ConvertedArgs;
7819 // FIXME: We should look into making enable_if late-parsed.
7820 Expr *DiscardedThis;
7821 if (!convertArgsForAvailabilityChecks(
7822 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7823 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7824 return *EnableIfAttrs.begin();
7825
7826 for (auto *EIA : EnableIfAttrs) {
7827 APValue Result;
7828 // FIXME: This doesn't consider value-dependent cases, because doing so is
7829 // very difficult. Ideally, we should handle them more gracefully.
7830 if (EIA->getCond()->isValueDependent() ||
7831 !EIA->getCond()->EvaluateWithSubstitution(
7832 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7833 return EIA;
7834
7835 if (!Result.isInt() || !Result.getInt().getBoolValue())
7836 return EIA;
7837 }
7838 return nullptr;
7839}
7840
7841template <typename CheckFn>
7842static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7843 bool ArgDependent, SourceLocation Loc,
7844 CheckFn &&IsSuccessful) {
7845 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7846 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7847 if (ArgDependent == DIA->getArgDependent())
7848 Attrs.push_back(Elt: DIA);
7849 }
7850
7851 // Common case: No diagnose_if attributes, so we can quit early.
7852 if (Attrs.empty())
7853 return false;
7854
7855 auto WarningBegin = std::stable_partition(
7856 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7857 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7858 DIA->getWarningGroup().empty();
7859 });
7860
7861 // Note that diagnose_if attributes are late-parsed, so they appear in the
7862 // correct order (unlike enable_if attributes).
7863 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7864 IsSuccessful);
7865 if (ErrAttr != WarningBegin) {
7866 const DiagnoseIfAttr *DIA = *ErrAttr;
7867 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7868 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7869 << DIA->getParent() << DIA->getCond()->getSourceRange();
7870 return true;
7871 }
7872
7873 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7874 switch (Sev) {
7875 case DiagnoseIfAttr::DS_warning:
7876 return diag::Severity::Warning;
7877 case DiagnoseIfAttr::DS_error:
7878 return diag::Severity::Error;
7879 }
7880 llvm_unreachable("Fully covered switch above!");
7881 };
7882
7883 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7884 if (IsSuccessful(DIA)) {
7885 if (DIA->getWarningGroup().empty() &&
7886 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7887 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7888 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7889 << DIA->getParent() << DIA->getCond()->getSourceRange();
7890 } else {
7891 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7892 DIA->getWarningGroup());
7893 assert(DiagGroup);
7894 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7895 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7896 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7897 S.Diag(Loc, DiagID) << DIA->getMessage();
7898 }
7899 }
7900
7901 return false;
7902}
7903
7904bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7905 const Expr *ThisArg,
7906 ArrayRef<const Expr *> Args,
7907 SourceLocation Loc) {
7908 return diagnoseDiagnoseIfAttrsWith(
7909 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7910 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7911 APValue Result;
7912 // It's sane to use the same Args for any redecl of this function, since
7913 // EvaluateWithSubstitution only cares about the position of each
7914 // argument in the arg list, not the ParmVarDecl* it maps to.
7915 if (!DIA->getCond()->EvaluateWithSubstitution(
7916 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7917 return false;
7918 return Result.isInt() && Result.getInt().getBoolValue();
7919 });
7920}
7921
7922bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7923 SourceLocation Loc) {
7924 return diagnoseDiagnoseIfAttrsWith(
7925 S&: *this, ND, /*ArgDependent=*/false, Loc,
7926 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7927 bool Result;
7928 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7929 Result;
7930 });
7931}
7932
7933void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7934 ArrayRef<Expr *> Args,
7935 OverloadCandidateSet &CandidateSet,
7936 TemplateArgumentListInfo *ExplicitTemplateArgs,
7937 bool SuppressUserConversions,
7938 bool PartialOverloading,
7939 bool FirstArgumentIsBase) {
7940 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7941 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7942 ArrayRef<Expr *> FunctionArgs = Args;
7943
7944 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7945 FunctionDecl *FD =
7946 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7947
7948 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7949 QualType ObjectType;
7950 Expr::Classification ObjectClassification;
7951 if (Args.size() > 0) {
7952 if (Expr *E = Args[0]) {
7953 // Use the explicit base to restrict the lookup:
7954 ObjectType = E->getType();
7955 // Pointers in the object arguments are implicitly dereferenced, so we
7956 // always classify them as l-values.
7957 if (!ObjectType.isNull() && ObjectType->isPointerType())
7958 ObjectClassification = Expr::Classification::makeSimpleLValue();
7959 else
7960 ObjectClassification = E->Classify(Ctx&: Context);
7961 } // .. else there is an implicit base.
7962 FunctionArgs = Args.slice(N: 1);
7963 }
7964 if (FunTmpl) {
7965 AddMethodTemplateCandidate(
7966 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7967 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7968 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7969 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7970 PartialOverloading);
7971 } else {
7972 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7973 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7974 ObjectClassification, Args: FunctionArgs, CandidateSet,
7975 SuppressUserConversions, PartialOverloading);
7976 }
7977 } else {
7978 // This branch handles both standalone functions and static methods.
7979
7980 // Slice the first argument (which is the base) when we access
7981 // static method as non-static.
7982 if (Args.size() > 0 &&
7983 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7984 !isa<CXXConstructorDecl>(Val: FD)))) {
7985 assert(cast<CXXMethodDecl>(FD)->isStatic());
7986 FunctionArgs = Args.slice(N: 1);
7987 }
7988 if (FunTmpl) {
7989 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7990 ExplicitTemplateArgs, Args: FunctionArgs,
7991 CandidateSet, SuppressUserConversions,
7992 PartialOverloading);
7993 } else {
7994 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7995 SuppressUserConversions, PartialOverloading);
7996 }
7997 }
7998 }
7999}
8000
8001void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
8002 Expr::Classification ObjectClassification,
8003 ArrayRef<Expr *> Args,
8004 OverloadCandidateSet &CandidateSet,
8005 bool SuppressUserConversions,
8006 OverloadCandidateParamOrder PO) {
8007 NamedDecl *Decl = FoundDecl.getDecl();
8008 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
8009
8010 if (isa<UsingShadowDecl>(Val: Decl))
8011 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
8012
8013 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
8014 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
8015 "Expected a member function template");
8016 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
8017 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
8018 ObjectClassification, Args, CandidateSet,
8019 SuppressUserConversions, PartialOverloading: false, PO);
8020 } else {
8021 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
8022 ObjectType, ObjectClassification, Args, CandidateSet,
8023 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
8024 }
8025}
8026
8027void Sema::AddMethodCandidate(
8028 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
8029 CXXRecordDecl *ActingContext, QualType ObjectType,
8030 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8031 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8032 bool PartialOverloading, ConversionSequenceList EarlyConversions,
8033 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
8034 const FunctionProtoType *Proto
8035 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
8036 assert(Proto && "Methods without a prototype cannot be overloaded");
8037 assert(!isa<CXXConstructorDecl>(Method) &&
8038 "Use AddOverloadCandidate for constructors");
8039
8040 if (!CandidateSet.isNewCandidate(F: Method, PO))
8041 return;
8042
8043 // C++11 [class.copy]p23: [DR1402]
8044 // A defaulted move assignment operator that is defined as deleted is
8045 // ignored by overload resolution.
8046 if (Method->isDefaulted() && Method->isDeleted() &&
8047 Method->isMoveAssignmentOperator())
8048 return;
8049
8050 // Overload resolution is always an unevaluated context.
8051 EnterExpressionEvaluationContext Unevaluated(
8052 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8053
8054 bool IgnoreExplicitObject =
8055 (Method->isExplicitObjectMemberFunction() &&
8056 CandidateSet.getKind() ==
8057 OverloadCandidateSet::CSK_AddressOfOverloadSet);
8058 bool ImplicitObjectMethodTreatedAsStatic =
8059 CandidateSet.getKind() ==
8060 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
8061 Method->isImplicitObjectMemberFunction();
8062
8063 unsigned ExplicitOffset =
8064 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8065
8066 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8067 int(ImplicitObjectMethodTreatedAsStatic);
8068
8069 unsigned ExtraArgs =
8070 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
8071 ? 0
8072 : 1;
8073
8074 // Add this candidate
8075 OverloadCandidate &Candidate =
8076 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
8077 Candidate.FoundDecl = FoundDecl;
8078 Candidate.Function = Method;
8079 Candidate.RewriteKind =
8080 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
8081 Candidate.TookAddressOfOverload =
8082 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8083 Candidate.ExplicitCallArguments = Args.size();
8084 Candidate.StrictPackMatch = StrictPackMatch;
8085
8086 // (C++ 13.3.2p2): A candidate function having fewer than m
8087 // parameters is viable only if it has an ellipsis in its parameter
8088 // list (8.3.5).
8089 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
8090 !Proto->isVariadic() &&
8091 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
8092 Candidate.Viable = false;
8093 Candidate.FailureKind = ovl_fail_too_many_arguments;
8094 return;
8095 }
8096
8097 // (C++ 13.3.2p2): A candidate function having more than m parameters
8098 // is viable only if the (m+1)st parameter has a default argument
8099 // (8.3.6). For the purposes of overload resolution, the
8100 // parameter list is truncated on the right, so that there are
8101 // exactly m parameters.
8102 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8103 ExplicitOffset +
8104 int(ImplicitObjectMethodTreatedAsStatic);
8105
8106 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8107 // Not enough arguments.
8108 Candidate.Viable = false;
8109 Candidate.FailureKind = ovl_fail_too_few_arguments;
8110 return;
8111 }
8112
8113 Candidate.Viable = true;
8114
8115 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8116 if (!IgnoreExplicitObject) {
8117 if (ObjectType.isNull())
8118 Candidate.IgnoreObjectArgument = true;
8119 else if (Method->isStatic()) {
8120 // [over.best.ics.general]p8
8121 // When the parameter is the implicit object parameter of a static member
8122 // function, the implicit conversion sequence is a standard conversion
8123 // sequence that is neither better nor worse than any other standard
8124 // conversion sequence.
8125 //
8126 // This is a rule that was introduced in C++23 to support static lambdas.
8127 // We apply it retroactively because we want to support static lambdas as
8128 // an extension and it doesn't hurt previous code.
8129 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8130 } else {
8131 // Determine the implicit conversion sequence for the object
8132 // parameter.
8133 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8134 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8135 Method, ActingContext, /*InOverloadResolution=*/true);
8136 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8137 Candidate.Viable = false;
8138 Candidate.FailureKind = ovl_fail_bad_conversion;
8139 return;
8140 }
8141 }
8142 }
8143
8144 // (CUDA B.1): Check for invalid calls between targets.
8145 if (getLangOpts().CUDA)
8146 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8147 Callee: Method)) {
8148 Candidate.Viable = false;
8149 Candidate.FailureKind = ovl_fail_bad_target;
8150 return;
8151 }
8152
8153 if (Method->getTrailingRequiresClause()) {
8154 ConstraintSatisfaction Satisfaction;
8155 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8156 /*ForOverloadResolution*/ true) ||
8157 !Satisfaction.IsSatisfied) {
8158 Candidate.Viable = false;
8159 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8160 return;
8161 }
8162 }
8163
8164 // Determine the implicit conversion sequences for each of the
8165 // arguments.
8166 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8167 unsigned ConvIdx =
8168 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8169 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8170 // We already formed a conversion sequence for this parameter during
8171 // template argument deduction.
8172 } else if (ArgIdx < NumParams) {
8173 // (C++ 13.3.2p3): for F to be a viable function, there shall
8174 // exist for each argument an implicit conversion sequence
8175 // (13.3.3.1) that converts that argument to the corresponding
8176 // parameter of F.
8177 QualType ParamType;
8178 if (ImplicitObjectMethodTreatedAsStatic) {
8179 ParamType = ArgIdx == 0
8180 ? Method->getFunctionObjectParameterReferenceType()
8181 : Proto->getParamType(i: ArgIdx - 1);
8182 } else {
8183 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8184 }
8185 Candidate.Conversions[ConvIdx]
8186 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8187 SuppressUserConversions,
8188 /*InOverloadResolution=*/true,
8189 /*AllowObjCWritebackConversion=*/
8190 getLangOpts().ObjCAutoRefCount);
8191 if (Candidate.Conversions[ConvIdx].isBad()) {
8192 Candidate.Viable = false;
8193 Candidate.FailureKind = ovl_fail_bad_conversion;
8194 return;
8195 }
8196 } else {
8197 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8198 // argument for which there is no corresponding parameter is
8199 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8200 Candidate.Conversions[ConvIdx].setEllipsis();
8201 }
8202 }
8203
8204 if (EnableIfAttr *FailedAttr =
8205 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8206 Candidate.Viable = false;
8207 Candidate.FailureKind = ovl_fail_enable_if;
8208 Candidate.DeductionFailure.Data = FailedAttr;
8209 return;
8210 }
8211
8212 if (isNonViableMultiVersionOverload(FD: Method)) {
8213 Candidate.Viable = false;
8214 Candidate.FailureKind = ovl_non_default_multiversion_function;
8215 }
8216}
8217
8218static void AddMethodTemplateCandidateImmediately(
8219 Sema &S, OverloadCandidateSet &CandidateSet,
8220 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8221 CXXRecordDecl *ActingContext,
8222 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8223 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8224 bool SuppressUserConversions, bool PartialOverloading,
8225 OverloadCandidateParamOrder PO) {
8226
8227 // C++ [over.match.funcs]p7:
8228 // In each case where a candidate is a function template, candidate
8229 // function template specializations are generated using template argument
8230 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8231 // candidate functions in the usual way.113) A given name can refer to one
8232 // or more function templates and also to a set of overloaded non-template
8233 // functions. In such a case, the candidate functions generated from each
8234 // function template are combined with the set of non-template candidate
8235 // functions.
8236 TemplateDeductionInfo Info(CandidateSet.getLocation());
8237 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8238 FunctionDecl *Specialization = nullptr;
8239 ConversionSequenceList Conversions;
8240 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8241 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8242 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8243 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8244 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8245 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8246 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8247 bool OnlyInitializeNonUserDefinedConversions) {
8248 return S.CheckNonDependentConversions(
8249 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8250 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8251 SuppressUserConversions,
8252 OnlyInitializeNonUserDefinedConversions),
8253 ActingContext, ObjectType, ObjectClassification, PO);
8254 });
8255 Result != TemplateDeductionResult::Success) {
8256 OverloadCandidate &Candidate =
8257 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8258 Candidate.FoundDecl = FoundDecl;
8259 Candidate.Function = Method;
8260 Candidate.Viable = false;
8261 Candidate.RewriteKind =
8262 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8263 Candidate.IsSurrogate = false;
8264 Candidate.TookAddressOfOverload =
8265 CandidateSet.getKind() ==
8266 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8267
8268 Candidate.IgnoreObjectArgument =
8269 Method->isStatic() ||
8270 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8271 Candidate.ExplicitCallArguments = Args.size();
8272 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8273 Candidate.FailureKind = ovl_fail_bad_conversion;
8274 else {
8275 Candidate.FailureKind = ovl_fail_bad_deduction;
8276 Candidate.DeductionFailure =
8277 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8278 }
8279 return;
8280 }
8281
8282 // Add the function template specialization produced by template argument
8283 // deduction as a candidate.
8284 assert(Specialization && "Missing member function template specialization?");
8285 assert(isa<CXXMethodDecl>(Specialization) &&
8286 "Specialization is not a member function?");
8287 S.AddMethodCandidate(
8288 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8289 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8290 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8291}
8292
8293void Sema::AddMethodTemplateCandidate(
8294 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8295 CXXRecordDecl *ActingContext,
8296 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8297 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8298 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8299 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8300 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8301 return;
8302
8303 if (ExplicitTemplateArgs ||
8304 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this)) {
8305 AddMethodTemplateCandidateImmediately(
8306 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8307 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8308 SuppressUserConversions, PartialOverloading, PO);
8309 return;
8310 }
8311
8312 CandidateSet.AddDeferredMethodTemplateCandidate(
8313 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8314 Args, SuppressUserConversions, PartialOverloading, PO);
8315}
8316
8317/// Determine whether a given function template has a simple explicit specifier
8318/// or a non-value-dependent explicit-specification that evaluates to true.
8319static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8320 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8321}
8322
8323static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8324 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8325 ExplicitSpecKind::Unresolved;
8326}
8327
8328static void AddTemplateOverloadCandidateImmediately(
8329 Sema &S, OverloadCandidateSet &CandidateSet,
8330 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8331 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8332 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8333 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8334 bool AggregateCandidateDeduction) {
8335
8336 // If the function template has a non-dependent explicit specification,
8337 // exclude it now if appropriate; we are not permitted to perform deduction
8338 // and substitution in this case.
8339 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8340 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8341 Candidate.FoundDecl = FoundDecl;
8342 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8343 Candidate.Viable = false;
8344 Candidate.FailureKind = ovl_fail_explicit;
8345 return;
8346 }
8347
8348 // C++ [over.match.funcs]p7:
8349 // In each case where a candidate is a function template, candidate
8350 // function template specializations are generated using template argument
8351 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8352 // candidate functions in the usual way.113) A given name can refer to one
8353 // or more function templates and also to a set of overloaded non-template
8354 // functions. In such a case, the candidate functions generated from each
8355 // function template are combined with the set of non-template candidate
8356 // functions.
8357 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8358 FunctionTemplate->getTemplateDepth());
8359 FunctionDecl *Specialization = nullptr;
8360 ConversionSequenceList Conversions;
8361 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8362 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8363 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8364 /*PartialOrdering=*/false,
8365 /*ObjectType=*/QualType(),
8366 /*ObjectClassification=*/Expr::Classification(),
8367 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8368 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8369 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8370 bool OnlyInitializeNonUserDefinedConversions) {
8371 return S.CheckNonDependentConversions(
8372 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8373 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8374 SuppressUserConversions,
8375 OnlyInitializeNonUserDefinedConversions),
8376 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8377 });
8378 Result != TemplateDeductionResult::Success) {
8379 OverloadCandidate &Candidate =
8380 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8381 Candidate.FoundDecl = FoundDecl;
8382 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8383 Candidate.Viable = false;
8384 Candidate.RewriteKind =
8385 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8386 Candidate.IsSurrogate = false;
8387 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8388 // Ignore the object argument if there is one, since we don't have an object
8389 // type.
8390 Candidate.TookAddressOfOverload =
8391 CandidateSet.getKind() ==
8392 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8393
8394 Candidate.IgnoreObjectArgument =
8395 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8396 !cast<CXXMethodDecl>(Val: Candidate.Function)
8397 ->isExplicitObjectMemberFunction() &&
8398 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8399
8400 Candidate.ExplicitCallArguments = Args.size();
8401 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8402 Candidate.FailureKind = ovl_fail_bad_conversion;
8403 else {
8404 Candidate.FailureKind = ovl_fail_bad_deduction;
8405 Candidate.DeductionFailure =
8406 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8407 }
8408 return;
8409 }
8410
8411 // Add the function template specialization produced by template argument
8412 // deduction as a candidate.
8413 assert(Specialization && "Missing function template specialization?");
8414 S.AddOverloadCandidate(
8415 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8416 PartialOverloading, AllowExplicit,
8417 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8418 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8419 StrictPackMatch: Info.hasStrictPackMatch());
8420}
8421
8422void Sema::AddTemplateOverloadCandidate(
8423 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8424 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8425 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8426 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8427 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8428 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8429 return;
8430
8431 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8432
8433 if (ExplicitTemplateArgs ||
8434 !CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8435 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8436 DependentExplicitSpecifier)) {
8437
8438 AddTemplateOverloadCandidateImmediately(
8439 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8440 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8441 IsADLCandidate, PO, AggregateCandidateDeduction);
8442
8443 if (DependentExplicitSpecifier)
8444 CandidateSet.DisableResolutionByPerfectCandidate();
8445 return;
8446 }
8447
8448 CandidateSet.AddDeferredTemplateCandidate(
8449 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8450 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8451 AggregateCandidateDeduction);
8452}
8453
8454bool Sema::CheckNonDependentConversions(
8455 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8456 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8457 ConversionSequenceList &Conversions,
8458 CheckNonDependentConversionsFlag UserConversionFlag,
8459 CXXRecordDecl *ActingContext, QualType ObjectType,
8460 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8461 // FIXME: The cases in which we allow explicit conversions for constructor
8462 // arguments never consider calling a constructor template. It's not clear
8463 // that is correct.
8464 const bool AllowExplicit = false;
8465
8466 bool ForOverloadSetAddressResolution =
8467 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8468 auto *FD = FunctionTemplate->getTemplatedDecl();
8469 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8470 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8471 !isa<CXXConstructorDecl>(Val: Method);
8472 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8473
8474 if (Conversions.empty())
8475 Conversions =
8476 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8477
8478 // Overload resolution is always an unevaluated context.
8479 EnterExpressionEvaluationContext Unevaluated(
8480 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8481
8482 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8483 // require that, but this check should never result in a hard error, and
8484 // overload resolution is permitted to sidestep instantiations.
8485 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8486 !ObjectType.isNull()) {
8487 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8488 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8489 !ParamTypes[0]->isDependentType()) {
8490 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8491 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8492 Method, ActingContext, /*InOverloadResolution=*/true,
8493 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8494 : QualType());
8495 if (Conversions[ConvIdx].isBad())
8496 return true;
8497 }
8498 }
8499
8500 // A speculative workaround for self-dependent constraint bugs that manifest
8501 // after CWG2369.
8502 // FIXME: Add references to the standard once P3606 is adopted.
8503 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8504 QualType ArgType) {
8505 ParamType = ParamType.getNonReferenceType();
8506 ArgType = ArgType.getNonReferenceType();
8507 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8508 if (PointerConv) {
8509 ParamType = ParamType->getPointeeType();
8510 ArgType = ArgType->getPointeeType();
8511 }
8512
8513 if (auto *RD = ParamType->getAsCXXRecordDecl();
8514 RD && RD->hasDefinition() &&
8515 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8516 auto Info = getConstructorInfo(ND);
8517 if (!Info)
8518 return false;
8519 CXXConstructorDecl *Ctor = Info.Constructor;
8520 /// isConvertingConstructor takes copy/move constructors into
8521 /// account!
8522 return !Ctor->isCopyOrMoveConstructor() &&
8523 Ctor->isConvertingConstructor(
8524 /*AllowExplicit=*/true);
8525 }))
8526 return true;
8527 if (auto *RD = ArgType->getAsCXXRecordDecl();
8528 RD && RD->hasDefinition() &&
8529 !RD->getVisibleConversionFunctions().empty())
8530 return true;
8531
8532 return false;
8533 };
8534
8535 unsigned Offset =
8536 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8537 : 0;
8538
8539 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8540 I != N; ++I) {
8541 QualType ParamType = ParamTypes[I + Offset];
8542 if (!ParamType->isDependentType()) {
8543 unsigned ConvIdx;
8544 if (PO == OverloadCandidateParamOrder::Reversed) {
8545 ConvIdx = Args.size() - 1 - I;
8546 assert(Args.size() + ThisConversions == 2 &&
8547 "number of args (including 'this') must be exactly 2 for "
8548 "reversed order");
8549 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8550 // would also be 0. 'this' got ConvIdx = 1 previously.
8551 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8552 } else {
8553 // For members, 'this' got ConvIdx = 0 previously.
8554 ConvIdx = ThisConversions + I;
8555 }
8556 if (Conversions[ConvIdx].isInitialized())
8557 continue;
8558 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8559 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8560 continue;
8561 Conversions[ConvIdx] = TryCopyInitialization(
8562 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8563 /*InOverloadResolution=*/true,
8564 /*AllowObjCWritebackConversion=*/
8565 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8566 if (Conversions[ConvIdx].isBad())
8567 return true;
8568 }
8569 }
8570
8571 return false;
8572}
8573
8574/// Determine whether this is an allowable conversion from the result
8575/// of an explicit conversion operator to the expected type, per C++
8576/// [over.match.conv]p1 and [over.match.ref]p1.
8577///
8578/// \param ConvType The return type of the conversion function.
8579///
8580/// \param ToType The type we are converting to.
8581///
8582/// \param AllowObjCPointerConversion Allow a conversion from one
8583/// Objective-C pointer to another.
8584///
8585/// \returns true if the conversion is allowable, false otherwise.
8586static bool isAllowableExplicitConversion(Sema &S,
8587 QualType ConvType, QualType ToType,
8588 bool AllowObjCPointerConversion) {
8589 QualType ToNonRefType = ToType.getNonReferenceType();
8590
8591 // Easy case: the types are the same.
8592 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8593 return true;
8594
8595 // Allow qualification conversions.
8596 bool ObjCLifetimeConversion;
8597 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8598 ObjCLifetimeConversion))
8599 return true;
8600
8601 // If we're not allowed to consider Objective-C pointer conversions,
8602 // we're done.
8603 if (!AllowObjCPointerConversion)
8604 return false;
8605
8606 // Is this an Objective-C pointer conversion?
8607 bool IncompatibleObjC = false;
8608 QualType ConvertedType;
8609 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8610 IncompatibleObjC);
8611}
8612
8613void Sema::AddConversionCandidate(
8614 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8615 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8616 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8617 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8618 assert(!Conversion->getDescribedFunctionTemplate() &&
8619 "Conversion function templates use AddTemplateConversionCandidate");
8620 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8621 if (!CandidateSet.isNewCandidate(F: Conversion))
8622 return;
8623
8624 // If the conversion function has an undeduced return type, trigger its
8625 // deduction now.
8626 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8627 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8628 return;
8629 ConvType = Conversion->getConversionType().getNonReferenceType();
8630 }
8631
8632 // If we don't allow any conversion of the result type, ignore conversion
8633 // functions that don't convert to exactly (possibly cv-qualified) T.
8634 if (!AllowResultConversion &&
8635 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8636 return;
8637
8638 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8639 // operator is only a candidate if its return type is the target type or
8640 // can be converted to the target type with a qualification conversion.
8641 //
8642 // FIXME: Include such functions in the candidate list and explain why we
8643 // can't select them.
8644 if (Conversion->isExplicit() &&
8645 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8646 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8647 return;
8648
8649 // Overload resolution is always an unevaluated context.
8650 EnterExpressionEvaluationContext Unevaluated(
8651 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8652
8653 // Add this candidate
8654 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8655 Candidate.FoundDecl = FoundDecl;
8656 Candidate.Function = Conversion;
8657 Candidate.FinalConversion.setAsIdentityConversion();
8658 Candidate.FinalConversion.setFromType(ConvType);
8659 Candidate.FinalConversion.setAllToTypes(ToType);
8660 Candidate.HasFinalConversion = true;
8661 Candidate.Viable = true;
8662 Candidate.ExplicitCallArguments = 1;
8663 Candidate.StrictPackMatch = StrictPackMatch;
8664
8665 // Explicit functions are not actually candidates at all if we're not
8666 // allowing them in this context, but keep them around so we can point
8667 // to them in diagnostics.
8668 if (!AllowExplicit && Conversion->isExplicit()) {
8669 Candidate.Viable = false;
8670 Candidate.FailureKind = ovl_fail_explicit;
8671 return;
8672 }
8673
8674 // C++ [over.match.funcs]p4:
8675 // For conversion functions, the function is considered to be a member of
8676 // the class of the implicit implied object argument for the purpose of
8677 // defining the type of the implicit object parameter.
8678 //
8679 // Determine the implicit conversion sequence for the implicit
8680 // object parameter.
8681 QualType ObjectType = From->getType();
8682 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8683 ObjectType = FromPtrType->getPointeeType();
8684 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8685 // C++23 [over.best.ics.general]
8686 // However, if the target is [...]
8687 // - the object parameter of a user-defined conversion function
8688 // [...] user-defined conversion sequences are not considered.
8689 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8690 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8691 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8692 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8693 /*SuppressUserConversion*/ true);
8694
8695 if (Candidate.Conversions[0].isBad()) {
8696 Candidate.Viable = false;
8697 Candidate.FailureKind = ovl_fail_bad_conversion;
8698 return;
8699 }
8700
8701 if (Conversion->getTrailingRequiresClause()) {
8702 ConstraintSatisfaction Satisfaction;
8703 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8704 !Satisfaction.IsSatisfied) {
8705 Candidate.Viable = false;
8706 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8707 return;
8708 }
8709 }
8710
8711 // We won't go through a user-defined type conversion function to convert a
8712 // derived to base as such conversions are given Conversion Rank. They only
8713 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8714 QualType FromCanon
8715 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8716 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8717 if (FromCanon == ToCanon ||
8718 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8719 Candidate.Viable = false;
8720 Candidate.FailureKind = ovl_fail_trivial_conversion;
8721 return;
8722 }
8723
8724 // To determine what the conversion from the result of calling the
8725 // conversion function to the type we're eventually trying to
8726 // convert to (ToType), we need to synthesize a call to the
8727 // conversion function and attempt copy initialization from it. This
8728 // makes sure that we get the right semantics with respect to
8729 // lvalues/rvalues and the type. Fortunately, we can allocate this
8730 // call on the stack and we don't need its arguments to be
8731 // well-formed.
8732 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8733 VK_LValue, From->getBeginLoc());
8734 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8735 Context.getPointerType(T: Conversion->getType()),
8736 CK_FunctionToPointerDecay, &ConversionRef,
8737 VK_PRValue, FPOptionsOverride());
8738
8739 QualType ConversionType = Conversion->getConversionType();
8740 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8741 Candidate.Viable = false;
8742 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8743 return;
8744 }
8745
8746 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8747
8748 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8749
8750 // Introduce a temporary expression with the right type and value category
8751 // that we can use for deduction purposes.
8752 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8753
8754 ImplicitConversionSequence ICS =
8755 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8756 /*SuppressUserConversions=*/true,
8757 /*InOverloadResolution=*/false,
8758 /*AllowObjCWritebackConversion=*/false);
8759
8760 switch (ICS.getKind()) {
8761 case ImplicitConversionSequence::StandardConversion:
8762 Candidate.FinalConversion = ICS.Standard;
8763 Candidate.HasFinalConversion = true;
8764
8765 // C++ [over.ics.user]p3:
8766 // If the user-defined conversion is specified by a specialization of a
8767 // conversion function template, the second standard conversion sequence
8768 // shall have exact match rank.
8769 if (Conversion->getPrimaryTemplate() &&
8770 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8771 Candidate.Viable = false;
8772 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8773 return;
8774 }
8775
8776 // C++0x [dcl.init.ref]p5:
8777 // In the second case, if the reference is an rvalue reference and
8778 // the second standard conversion sequence of the user-defined
8779 // conversion sequence includes an lvalue-to-rvalue conversion, the
8780 // program is ill-formed.
8781 if (ToType->isRValueReferenceType() &&
8782 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8783 Candidate.Viable = false;
8784 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8785 return;
8786 }
8787 break;
8788
8789 case ImplicitConversionSequence::BadConversion:
8790 Candidate.Viable = false;
8791 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8792 return;
8793
8794 default:
8795 llvm_unreachable(
8796 "Can only end up with a standard conversion sequence or failure");
8797 }
8798
8799 if (EnableIfAttr *FailedAttr =
8800 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8801 Candidate.Viable = false;
8802 Candidate.FailureKind = ovl_fail_enable_if;
8803 Candidate.DeductionFailure.Data = FailedAttr;
8804 return;
8805 }
8806
8807 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8808 Candidate.Viable = false;
8809 Candidate.FailureKind = ovl_non_default_multiversion_function;
8810 }
8811}
8812
8813static void AddTemplateConversionCandidateImmediately(
8814 Sema &S, OverloadCandidateSet &CandidateSet,
8815 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8816 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8817 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8818 bool AllowResultConversion) {
8819
8820 // If the function template has a non-dependent explicit specification,
8821 // exclude it now if appropriate; we are not permitted to perform deduction
8822 // and substitution in this case.
8823 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8824 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8825 Candidate.FoundDecl = FoundDecl;
8826 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8827 Candidate.Viable = false;
8828 Candidate.FailureKind = ovl_fail_explicit;
8829 return;
8830 }
8831
8832 QualType ObjectType = From->getType();
8833 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8834
8835 TemplateDeductionInfo Info(CandidateSet.getLocation());
8836 CXXConversionDecl *Specialization = nullptr;
8837 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8838 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8839 Specialization, Info);
8840 Result != TemplateDeductionResult::Success) {
8841 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8842 Candidate.FoundDecl = FoundDecl;
8843 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8844 Candidate.Viable = false;
8845 Candidate.FailureKind = ovl_fail_bad_deduction;
8846 Candidate.ExplicitCallArguments = 1;
8847 Candidate.DeductionFailure =
8848 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8849 return;
8850 }
8851
8852 // Add the conversion function template specialization produced by
8853 // template argument deduction as a candidate.
8854 assert(Specialization && "Missing function template specialization?");
8855 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8856 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8857 AllowExplicit, AllowResultConversion,
8858 StrictPackMatch: Info.hasStrictPackMatch());
8859}
8860
8861void Sema::AddTemplateConversionCandidate(
8862 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8863 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8864 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8865 bool AllowExplicit, bool AllowResultConversion) {
8866 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8867 "Only conversion function templates permitted here");
8868
8869 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8870 return;
8871
8872 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(S: *this) ||
8873 CandidateSet.getKind() ==
8874 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8875 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8876 AddTemplateConversionCandidateImmediately(
8877 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8878 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8879 AllowResultConversion);
8880
8881 CandidateSet.DisableResolutionByPerfectCandidate();
8882 return;
8883 }
8884
8885 CandidateSet.AddDeferredConversionTemplateCandidate(
8886 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8887 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8888}
8889
8890void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8891 DeclAccessPair FoundDecl,
8892 CXXRecordDecl *ActingContext,
8893 const FunctionProtoType *Proto,
8894 Expr *Object,
8895 ArrayRef<Expr *> Args,
8896 OverloadCandidateSet& CandidateSet) {
8897 if (!CandidateSet.isNewCandidate(F: Conversion))
8898 return;
8899
8900 // Overload resolution is always an unevaluated context.
8901 EnterExpressionEvaluationContext Unevaluated(
8902 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8903
8904 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8905 Candidate.FoundDecl = FoundDecl;
8906 Candidate.Function = nullptr;
8907 Candidate.Surrogate = Conversion;
8908 Candidate.IsSurrogate = true;
8909 Candidate.Viable = true;
8910 Candidate.ExplicitCallArguments = Args.size();
8911
8912 // Determine the implicit conversion sequence for the implicit
8913 // object parameter.
8914 ImplicitConversionSequence ObjectInit;
8915 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8916 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8917 ToType: Conversion->getParamDecl(i: 0)->getType(),
8918 /*SuppressUserConversions=*/false,
8919 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8920 } else {
8921 ObjectInit = TryObjectArgumentInitialization(
8922 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8923 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8924 }
8925
8926 if (ObjectInit.isBad()) {
8927 Candidate.Viable = false;
8928 Candidate.FailureKind = ovl_fail_bad_conversion;
8929 Candidate.Conversions[0] = ObjectInit;
8930 return;
8931 }
8932
8933 // The first conversion is actually a user-defined conversion whose
8934 // first conversion is ObjectInit's standard conversion (which is
8935 // effectively a reference binding). Record it as such.
8936 Candidate.Conversions[0].setUserDefined();
8937 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8938 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8939 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8940 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8941 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8942 Candidate.Conversions[0].UserDefined.After
8943 = Candidate.Conversions[0].UserDefined.Before;
8944 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8945
8946 // Find the
8947 unsigned NumParams = Proto->getNumParams();
8948
8949 // (C++ 13.3.2p2): A candidate function having fewer than m
8950 // parameters is viable only if it has an ellipsis in its parameter
8951 // list (8.3.5).
8952 if (Args.size() > NumParams && !Proto->isVariadic()) {
8953 Candidate.Viable = false;
8954 Candidate.FailureKind = ovl_fail_too_many_arguments;
8955 return;
8956 }
8957
8958 // Function types don't have any default arguments, so just check if
8959 // we have enough arguments.
8960 if (Args.size() < NumParams) {
8961 // Not enough arguments.
8962 Candidate.Viable = false;
8963 Candidate.FailureKind = ovl_fail_too_few_arguments;
8964 return;
8965 }
8966
8967 // Determine the implicit conversion sequences for each of the
8968 // arguments.
8969 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8970 if (ArgIdx < NumParams) {
8971 // (C++ 13.3.2p3): for F to be a viable function, there shall
8972 // exist for each argument an implicit conversion sequence
8973 // (13.3.3.1) that converts that argument to the corresponding
8974 // parameter of F.
8975 QualType ParamType = Proto->getParamType(i: ArgIdx);
8976 Candidate.Conversions[ArgIdx + 1]
8977 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8978 /*SuppressUserConversions=*/false,
8979 /*InOverloadResolution=*/false,
8980 /*AllowObjCWritebackConversion=*/
8981 getLangOpts().ObjCAutoRefCount);
8982 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8983 Candidate.Viable = false;
8984 Candidate.FailureKind = ovl_fail_bad_conversion;
8985 return;
8986 }
8987 } else {
8988 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8989 // argument for which there is no corresponding parameter is
8990 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8991 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8992 }
8993 }
8994
8995 if (Conversion->getTrailingRequiresClause()) {
8996 ConstraintSatisfaction Satisfaction;
8997 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8998 /*ForOverloadResolution*/ true) ||
8999 !Satisfaction.IsSatisfied) {
9000 Candidate.Viable = false;
9001 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
9002 return;
9003 }
9004 }
9005
9006 if (EnableIfAttr *FailedAttr =
9007 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
9008 Candidate.Viable = false;
9009 Candidate.FailureKind = ovl_fail_enable_if;
9010 Candidate.DeductionFailure.Data = FailedAttr;
9011 return;
9012 }
9013}
9014
9015void Sema::AddNonMemberOperatorCandidates(
9016 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
9017 OverloadCandidateSet &CandidateSet,
9018 TemplateArgumentListInfo *ExplicitTemplateArgs) {
9019 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
9020 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
9021 ArrayRef<Expr *> FunctionArgs = Args;
9022
9023 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
9024 FunctionDecl *FD =
9025 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
9026
9027 // Don't consider rewritten functions if we're not rewriting.
9028 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
9029 continue;
9030
9031 assert(!isa<CXXMethodDecl>(FD) &&
9032 "unqualified operator lookup found a member function");
9033
9034 if (FunTmpl) {
9035 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
9036 Args: FunctionArgs, CandidateSet);
9037 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
9038
9039 // As template candidates are not deduced immediately,
9040 // persist the array in the overload set.
9041 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
9042 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
9043 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
9044 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
9045 IsADLCandidate: ADLCallKind::NotADL,
9046 PO: OverloadCandidateParamOrder::Reversed);
9047 }
9048 } else {
9049 if (ExplicitTemplateArgs)
9050 continue;
9051 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
9052 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
9053 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
9054 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9055 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
9056 PO: OverloadCandidateParamOrder::Reversed);
9057 }
9058 }
9059}
9060
9061void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
9062 SourceLocation OpLoc,
9063 ArrayRef<Expr *> Args,
9064 OverloadCandidateSet &CandidateSet,
9065 OverloadCandidateParamOrder PO) {
9066 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9067
9068 // C++ [over.match.oper]p3:
9069 // For a unary operator @ with an operand of a type whose
9070 // cv-unqualified version is T1, and for a binary operator @ with
9071 // a left operand of a type whose cv-unqualified version is T1 and
9072 // a right operand of a type whose cv-unqualified version is T2,
9073 // three sets of candidate functions, designated member
9074 // candidates, non-member candidates and built-in candidates, are
9075 // constructed as follows:
9076 QualType T1 = Args[0]->getType();
9077
9078 // -- If T1 is a complete class type or a class currently being
9079 // defined, the set of member candidates is the result of the
9080 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9081 // the set of member candidates is empty.
9082 if (T1->isRecordType()) {
9083 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
9084 auto *T1RD = T1->getAsCXXRecordDecl();
9085 // Complete the type if it can be completed.
9086 // If the type is neither complete nor being defined, bail out now.
9087 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9088 return;
9089
9090 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9091 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
9092 Operators.suppressAccessDiagnostics();
9093
9094 for (LookupResult::iterator Oper = Operators.begin(),
9095 OperEnd = Operators.end();
9096 Oper != OperEnd; ++Oper) {
9097 if (Oper->getAsFunction() &&
9098 PO == OverloadCandidateParamOrder::Reversed &&
9099 !CandidateSet.getRewriteInfo().shouldAddReversed(
9100 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
9101 continue;
9102 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
9103 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
9104 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
9105 }
9106 }
9107}
9108
9109void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
9110 OverloadCandidateSet& CandidateSet,
9111 bool IsAssignmentOperator,
9112 unsigned NumContextualBoolArguments) {
9113 // Overload resolution is always an unevaluated context.
9114 EnterExpressionEvaluationContext Unevaluated(
9115 *this, Sema::ExpressionEvaluationContext::Unevaluated);
9116
9117 // Add this candidate
9118 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
9119 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
9120 Candidate.Function = nullptr;
9121 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
9122
9123 // Determine the implicit conversion sequences for each of the
9124 // arguments.
9125 Candidate.Viable = true;
9126 Candidate.ExplicitCallArguments = Args.size();
9127 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9128 // C++ [over.match.oper]p4:
9129 // For the built-in assignment operators, conversions of the
9130 // left operand are restricted as follows:
9131 // -- no temporaries are introduced to hold the left operand, and
9132 // -- no user-defined conversions are applied to the left
9133 // operand to achieve a type match with the left-most
9134 // parameter of a built-in candidate.
9135 //
9136 // We block these conversions by turning off user-defined
9137 // conversions, since that is the only way that initialization of
9138 // a reference to a non-class type can occur from something that
9139 // is not of the same type.
9140 if (ArgIdx < NumContextualBoolArguments) {
9141 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9142 "Contextual conversion to bool requires bool type");
9143 Candidate.Conversions[ArgIdx]
9144 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9145 } else {
9146 Candidate.Conversions[ArgIdx]
9147 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9148 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9149 /*InOverloadResolution=*/false,
9150 /*AllowObjCWritebackConversion=*/
9151 getLangOpts().ObjCAutoRefCount);
9152 }
9153 if (Candidate.Conversions[ArgIdx].isBad()) {
9154 Candidate.Viable = false;
9155 Candidate.FailureKind = ovl_fail_bad_conversion;
9156 break;
9157 }
9158 }
9159}
9160
9161namespace {
9162
9163/// BuiltinCandidateTypeSet - A set of types that will be used for the
9164/// candidate operator functions for built-in operators (C++
9165/// [over.built]). The types are separated into pointer types and
9166/// enumeration types.
9167class BuiltinCandidateTypeSet {
9168 /// TypeSet - A set of types.
9169 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9170
9171 /// PointerTypes - The set of pointer types that will be used in the
9172 /// built-in candidates.
9173 TypeSet PointerTypes;
9174
9175 /// MemberPointerTypes - The set of member pointer types that will be
9176 /// used in the built-in candidates.
9177 TypeSet MemberPointerTypes;
9178
9179 /// EnumerationTypes - The set of enumeration types that will be
9180 /// used in the built-in candidates.
9181 TypeSet EnumerationTypes;
9182
9183 /// The set of vector types that will be used in the built-in
9184 /// candidates.
9185 TypeSet VectorTypes;
9186
9187 /// The set of matrix types that will be used in the built-in
9188 /// candidates.
9189 TypeSet MatrixTypes;
9190
9191 /// The set of _BitInt types that will be used in the built-in candidates.
9192 TypeSet BitIntTypes;
9193
9194 /// A flag indicating non-record types are viable candidates
9195 bool HasNonRecordTypes;
9196
9197 /// A flag indicating whether either arithmetic or enumeration types
9198 /// were present in the candidate set.
9199 bool HasArithmeticOrEnumeralTypes;
9200
9201 /// A flag indicating whether the candidate set has a type that might
9202 /// convert to a promoted arithmetic type or to a vector type. This is
9203 /// conservative: only scoped enumerations, pointers, member pointers,
9204 /// nullptr_t, and classes that convert to nothing else are known not to.
9205 bool MayConvertToArithmetic;
9206
9207 /// A flag indicating whether the nullptr type was present in the
9208 /// candidate set.
9209 bool HasNullPtrType;
9210
9211 /// A flag indicating whether the reflection type was present in the
9212 /// candidate set.
9213 bool HasReflectionType;
9214
9215 /// Sema - The semantic analysis instance where we are building the
9216 /// candidate type set.
9217 Sema &SemaRef;
9218
9219 /// Context - The AST context in which we will build the type sets.
9220 ASTContext &Context;
9221
9222 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9223 const Qualifiers &VisibleQuals);
9224 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9225
9226public:
9227 /// iterator - Iterates through the types that are part of the set.
9228 typedef TypeSet::iterator iterator;
9229
9230 BuiltinCandidateTypeSet(Sema &SemaRef)
9231 : HasNonRecordTypes(false), HasArithmeticOrEnumeralTypes(false),
9232 MayConvertToArithmetic(false), HasNullPtrType(false),
9233 HasReflectionType(false), SemaRef(SemaRef), Context(SemaRef.Context) {}
9234
9235 void AddTypesConvertedFrom(QualType Ty,
9236 SourceLocation Loc,
9237 bool AllowUserConversions,
9238 bool AllowExplicitConversions,
9239 const Qualifiers &VisibleTypeConversionsQuals);
9240
9241 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9242 llvm::iterator_range<iterator> member_pointer_types() {
9243 return MemberPointerTypes;
9244 }
9245 llvm::iterator_range<iterator> enumeration_types() {
9246 return EnumerationTypes;
9247 }
9248 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9249 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9250 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9251
9252 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9253 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9254 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9255 bool mayConvertToArithmetic() const { return MayConvertToArithmetic; }
9256 bool hasNullPtrType() const { return HasNullPtrType; }
9257 bool hasReflectionType() const { return HasReflectionType; }
9258};
9259
9260} // end anonymous namespace
9261
9262/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9263/// the set of pointer types along with any more-qualified variants of
9264/// that type. For example, if @p Ty is "int const *", this routine
9265/// will add "int const *", "int const volatile *", "int const
9266/// restrict *", and "int const volatile restrict *" to the set of
9267/// pointer types. Returns true if the add of @p Ty itself succeeded,
9268/// false otherwise.
9269///
9270/// FIXME: what to do about extended qualifiers?
9271bool
9272BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9273 const Qualifiers &VisibleQuals) {
9274
9275 // Insert this type.
9276 if (!PointerTypes.insert(X: Ty))
9277 return false;
9278
9279 QualType PointeeTy;
9280 const PointerType *PointerTy = Ty->getAs<PointerType>();
9281 bool buildObjCPtr = false;
9282 if (!PointerTy) {
9283 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9284 PointeeTy = PTy->getPointeeType();
9285 buildObjCPtr = true;
9286 } else {
9287 PointeeTy = PointerTy->getPointeeType();
9288 }
9289
9290 // Don't add qualified variants of arrays. For one, they're not allowed
9291 // (the qualifier would sink to the element type), and for another, the
9292 // only overload situation where it matters is subscript or pointer +- int,
9293 // and those shouldn't have qualifier variants anyway.
9294 if (PointeeTy->isArrayType())
9295 return true;
9296
9297 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9298 bool hasVolatile = VisibleQuals.hasVolatile();
9299 bool hasRestrict = VisibleQuals.hasRestrict();
9300
9301 // Iterate through all strict supersets of BaseCVR.
9302 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9303 if ((CVR | BaseCVR) != CVR) continue;
9304 // Skip over volatile if no volatile found anywhere in the types.
9305 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9306
9307 // Skip over restrict if no restrict found anywhere in the types, or if
9308 // the type cannot be restrict-qualified.
9309 if ((CVR & Qualifiers::Restrict) &&
9310 (!hasRestrict ||
9311 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9312 continue;
9313
9314 // Build qualified pointee type.
9315 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9316
9317 // Build qualified pointer type.
9318 QualType QPointerTy;
9319 if (!buildObjCPtr)
9320 QPointerTy = Context.getPointerType(T: QPointeeTy);
9321 else
9322 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9323
9324 // Insert qualified pointer type.
9325 PointerTypes.insert(X: QPointerTy);
9326 }
9327
9328 return true;
9329}
9330
9331/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9332/// to the set of pointer types along with any more-qualified variants of
9333/// that type. For example, if @p Ty is "int const *", this routine
9334/// will add "int const *", "int const volatile *", "int const
9335/// restrict *", and "int const volatile restrict *" to the set of
9336/// pointer types. Returns true if the add of @p Ty itself succeeded,
9337/// false otherwise.
9338///
9339/// FIXME: what to do about extended qualifiers?
9340bool
9341BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9342 QualType Ty) {
9343 // Insert this type.
9344 if (!MemberPointerTypes.insert(X: Ty))
9345 return false;
9346
9347 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9348 assert(PointerTy && "type was not a member pointer type!");
9349
9350 QualType PointeeTy = PointerTy->getPointeeType();
9351 // Don't add qualified variants of arrays. For one, they're not allowed
9352 // (the qualifier would sink to the element type), and for another, the
9353 // only overload situation where it matters is subscript or pointer +- int,
9354 // and those shouldn't have qualifier variants anyway.
9355 if (PointeeTy->isArrayType())
9356 return true;
9357 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9358
9359 // Iterate through all strict supersets of the pointee type's CVR
9360 // qualifiers.
9361 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9362 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9363 if ((CVR | BaseCVR) != CVR) continue;
9364
9365 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9366 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9367 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9368 }
9369
9370 return true;
9371}
9372
9373/// AddTypesConvertedFrom - Add each of the types to which the type @p
9374/// Ty can be implicit converted to the given set of @p Types. We're
9375/// primarily interested in pointer types and enumeration types. We also
9376/// take member pointer types, for the conditional operator.
9377/// AllowUserConversions is true if we should look at the conversion
9378/// functions of a class type, and AllowExplicitConversions if we
9379/// should also include the explicit conversion functions of a class
9380/// type.
9381void
9382BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9383 SourceLocation Loc,
9384 bool AllowUserConversions,
9385 bool AllowExplicitConversions,
9386 const Qualifiers &VisibleQuals) {
9387 // Only deal with canonical types.
9388 Ty = Context.getCanonicalType(T: Ty);
9389
9390 // Look through reference types; they aren't part of the type of an
9391 // expression for the purposes of conversions.
9392 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9393 Ty = RefTy->getPointeeType();
9394
9395 // If we're dealing with an array type, decay to the pointer.
9396 if (Ty->isArrayType())
9397 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9398
9399 // Otherwise, we don't care about qualifiers on the type.
9400 Ty = Ty.getLocalUnqualifiedType();
9401
9402 // Flag if we ever add a non-record type.
9403 bool TyIsRec = Ty->isRecordType();
9404 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9405
9406 // Flag if we encounter an arithmetic type.
9407 HasArithmeticOrEnumeralTypes =
9408 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9409
9410 // Flag if the type might convert to a promoted arithmetic or vector type.
9411 // For records, this is set below when visiting their conversion functions.
9412 MayConvertToArithmetic =
9413 MayConvertToArithmetic ||
9414 !(TyIsRec || Ty->isScopedEnumeralType() || Ty->isAnyPointerType() ||
9415 Ty->isMemberPointerType() || Ty->isNullPtrType());
9416
9417 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9418 PointerTypes.insert(X: Ty);
9419 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9420 // Insert our type, and its more-qualified variants, into the set
9421 // of types.
9422 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9423 return;
9424 } else if (Ty->isMemberPointerType()) {
9425 // Member pointers are far easier, since the pointee can't be converted.
9426 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9427 return;
9428 } else if (Ty->isEnumeralType()) {
9429 HasArithmeticOrEnumeralTypes = true;
9430 EnumerationTypes.insert(X: Ty);
9431 } else if (Ty->isBitIntType()) {
9432 HasArithmeticOrEnumeralTypes = true;
9433 BitIntTypes.insert(X: Ty);
9434 } else if (Ty->isVectorType()) {
9435 // We treat vector types as arithmetic types in many contexts as an
9436 // extension.
9437 HasArithmeticOrEnumeralTypes = true;
9438 VectorTypes.insert(X: Ty);
9439 } else if (Ty->isMatrixType()) {
9440 // Similar to vector types, we treat vector types as arithmetic types in
9441 // many contexts as an extension.
9442 HasArithmeticOrEnumeralTypes = true;
9443 MatrixTypes.insert(X: Ty);
9444 } else if (Ty->isNullPtrType()) {
9445 HasNullPtrType = true;
9446 } else if (Ty->isMetaInfoType()) {
9447 HasReflectionType = true;
9448 } else if (AllowUserConversions && TyIsRec) {
9449 // No conversion functions in incomplete types.
9450 if (!SemaRef.isCompleteType(Loc, T: Ty))
9451 return;
9452
9453 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9454 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9455 if (isa<UsingShadowDecl>(Val: D))
9456 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9457
9458 // Skip conversion function templates; they don't tell us anything
9459 // about which builtin types we can convert to.
9460 if (isa<FunctionTemplateDecl>(Val: D)) {
9461 MayConvertToArithmetic = true;
9462 continue;
9463 }
9464
9465 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9466 if (AllowExplicitConversions || !Conv->isExplicit()) {
9467 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9468 VisibleQuals);
9469 }
9470 }
9471 }
9472}
9473/// Helper function for adjusting address spaces for the pointer or reference
9474/// operands of builtin operators depending on the argument.
9475static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9476 Expr *Arg) {
9477 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9478}
9479
9480/// Helper function for AddBuiltinOperatorCandidates() that adds
9481/// the volatile- and non-volatile-qualified assignment operators for the
9482/// given type to the candidate set.
9483static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9484 QualType T,
9485 ArrayRef<Expr *> Args,
9486 OverloadCandidateSet &CandidateSet) {
9487 QualType ParamTypes[2];
9488
9489 // T& operator=(T&, T)
9490 ParamTypes[0] = S.Context.getLValueReferenceType(
9491 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9492 ParamTypes[1] = T;
9493 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9494 /*IsAssignmentOperator=*/true);
9495
9496 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9497 // volatile T& operator=(volatile T&, T)
9498 ParamTypes[0] = S.Context.getLValueReferenceType(
9499 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9500 Arg: Args[0]));
9501 ParamTypes[1] = T;
9502 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9503 /*IsAssignmentOperator=*/true);
9504 }
9505}
9506
9507/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9508/// if any, found in visible type conversion functions found in ArgExpr's type.
9509static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9510 Qualifiers VRQuals;
9511 CXXRecordDecl *ClassDecl;
9512 if (const MemberPointerType *RHSMPType =
9513 ArgExpr->getType()->getAs<MemberPointerType>())
9514 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9515 else
9516 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9517 if (!ClassDecl) {
9518 // Just to be safe, assume the worst case.
9519 VRQuals.addVolatile();
9520 VRQuals.addRestrict();
9521 return VRQuals;
9522 }
9523 if (!ClassDecl->hasDefinition())
9524 return VRQuals;
9525
9526 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9527 if (isa<UsingShadowDecl>(Val: D))
9528 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9529 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9530 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9531 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9532 CanTy = ResTypeRef->getPointeeType();
9533 // Need to go down the pointer/mempointer chain and add qualifiers
9534 // as see them.
9535 bool done = false;
9536 while (!done) {
9537 if (CanTy.isRestrictQualified())
9538 VRQuals.addRestrict();
9539 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9540 CanTy = ResTypePtr->getPointeeType();
9541 else if (const MemberPointerType *ResTypeMPtr =
9542 CanTy->getAs<MemberPointerType>())
9543 CanTy = ResTypeMPtr->getPointeeType();
9544 else
9545 done = true;
9546 if (CanTy.isVolatileQualified())
9547 VRQuals.addVolatile();
9548 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9549 return VRQuals;
9550 }
9551 }
9552 }
9553 return VRQuals;
9554}
9555
9556// Note: We're currently only handling qualifiers that are meaningful for the
9557// LHS of compound assignment overloading.
9558static void forAllQualifierCombinationsImpl(
9559 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9560 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9561 // _Atomic
9562 if (Available.hasAtomic()) {
9563 Available.removeAtomic();
9564 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9565 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9566 return;
9567 }
9568
9569 // volatile
9570 if (Available.hasVolatile()) {
9571 Available.removeVolatile();
9572 assert(!Applied.hasVolatile());
9573 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9574 Callback);
9575 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9576 return;
9577 }
9578
9579 Callback(Applied);
9580}
9581
9582static void forAllQualifierCombinations(
9583 QualifiersAndAtomic Quals,
9584 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9585 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9586 Callback);
9587}
9588
9589static QualType makeQualifiedLValueReferenceType(QualType Base,
9590 QualifiersAndAtomic Quals,
9591 Sema &S) {
9592 if (Quals.hasAtomic())
9593 Base = S.Context.getAtomicType(T: Base);
9594 if (Quals.hasVolatile())
9595 Base = S.Context.getVolatileType(T: Base);
9596 return S.Context.getLValueReferenceType(T: Base);
9597}
9598
9599namespace {
9600
9601/// Helper class to manage the addition of builtin operator overload
9602/// candidates. It provides shared state and utility methods used throughout
9603/// the process, as well as a helper method to add each group of builtin
9604/// operator overloads from the standard to a candidate set.
9605class BuiltinOperatorOverloadBuilder {
9606 // Common instance state available to all overload candidate addition methods.
9607 Sema &S;
9608 ArrayRef<Expr *> Args;
9609 QualifiersAndAtomic VisibleTypeConversionsQuals;
9610 // Whether a candidate whose parameters are all arithmetic, vector or matrix
9611 // types can be viable. It is viable if there is an arithmetic or enumeral
9612 // candidate type, and every argument might convert to such a type.
9613 bool ArithmeticCandidatesMayBeViable;
9614 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9615 OverloadCandidateSet &CandidateSet;
9616
9617 static constexpr int ArithmeticTypesCap = 26;
9618 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9619
9620 // Define some indices used to iterate over the arithmetic types in
9621 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9622 // types are that preserved by promotion (C++ [over.built]p2).
9623 unsigned FirstIntegralType,
9624 LastIntegralType;
9625 unsigned FirstPromotedIntegralType,
9626 LastPromotedIntegralType;
9627 unsigned FirstPromotedArithmeticType,
9628 LastPromotedArithmeticType;
9629 unsigned NumArithmeticTypes;
9630
9631 void InitArithmeticTypes() {
9632 // Start of promoted types.
9633 FirstPromotedArithmeticType = 0;
9634 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9635 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9636 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9637 if (S.Context.getTargetInfo().hasFloat128Type())
9638 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9639 if (S.Context.getTargetInfo().hasIbm128Type())
9640 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9641
9642 // Start of integral types.
9643 FirstIntegralType = ArithmeticTypes.size();
9644 FirstPromotedIntegralType = ArithmeticTypes.size();
9645 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9646 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9647 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9648 if (S.Context.getTargetInfo().hasInt128Type() ||
9649 (S.Context.getAuxTargetInfo() &&
9650 S.Context.getAuxTargetInfo()->hasInt128Type()))
9651 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9652 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9653 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9654 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9655 if (S.Context.getTargetInfo().hasInt128Type() ||
9656 (S.Context.getAuxTargetInfo() &&
9657 S.Context.getAuxTargetInfo()->hasInt128Type()))
9658 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9659
9660 /// We add candidates for the unique, unqualified _BitInt types present in
9661 /// the candidate type set. The candidate set already handled ensuring the
9662 /// type is unqualified and canonical, but because we're adding from N
9663 /// different sets, we need to do some extra work to unique things. Insert
9664 /// the candidates into a unique set, then move from that set into the list
9665 /// of arithmetic types.
9666 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9667 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9668 for (QualType BitTy : Candidate.bitint_types())
9669 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9670 }
9671 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9672 LastPromotedIntegralType = ArithmeticTypes.size();
9673 LastPromotedArithmeticType = ArithmeticTypes.size();
9674 // End of promoted types.
9675
9676 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9677 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9678 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9679 if (S.Context.getLangOpts().Char8)
9680 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9681 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9682 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9683 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9684 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9685 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9686 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9687 LastIntegralType = ArithmeticTypes.size();
9688 NumArithmeticTypes = ArithmeticTypes.size();
9689 // End of integral types.
9690 // FIXME: What about complex? What about half?
9691
9692 // We don't know for sure how many bit-precise candidates were involved, so
9693 // we subtract those from the total when testing whether we're under the
9694 // cap or not.
9695 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9696 ArithmeticTypesCap &&
9697 "Enough inline storage for all arithmetic types.");
9698 }
9699
9700 /// Helper method to factor out the common pattern of adding overloads
9701 /// for '++' and '--' builtin operators.
9702 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9703 bool HasVolatile,
9704 bool HasRestrict) {
9705 QualType ParamTypes[2] = {
9706 S.Context.getLValueReferenceType(T: CandidateTy),
9707 S.Context.IntTy
9708 };
9709
9710 // Non-volatile version.
9711 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9712
9713 // Use a heuristic to reduce number of builtin candidates in the set:
9714 // add volatile version only if there are conversions to a volatile type.
9715 if (HasVolatile) {
9716 ParamTypes[0] =
9717 S.Context.getLValueReferenceType(
9718 T: S.Context.getVolatileType(T: CandidateTy));
9719 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9720 }
9721
9722 // Add restrict version only if there are conversions to a restrict type
9723 // and our candidate type is a non-restrict-qualified pointer.
9724 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9725 !CandidateTy.isRestrictQualified()) {
9726 ParamTypes[0]
9727 = S.Context.getLValueReferenceType(
9728 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9729 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9730
9731 if (HasVolatile) {
9732 ParamTypes[0]
9733 = S.Context.getLValueReferenceType(
9734 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9735 CVR: (Qualifiers::Volatile |
9736 Qualifiers::Restrict)));
9737 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9738 }
9739 }
9740
9741 }
9742
9743 /// Helper to add an overload candidate for a binary builtin with types \p L
9744 /// and \p R.
9745 void AddCandidate(QualType L, QualType R) {
9746 QualType LandR[2] = {L, R};
9747 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9748 }
9749
9750public:
9751 BuiltinOperatorOverloadBuilder(
9752 Sema &S, ArrayRef<Expr *> Args,
9753 QualifiersAndAtomic VisibleTypeConversionsQuals,
9754 bool HasArithmeticOrEnumeralCandidateType,
9755 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9756 OverloadCandidateSet &CandidateSet)
9757 : S(S), Args(Args),
9758 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9759 ArithmeticCandidatesMayBeViable(
9760 HasArithmeticOrEnumeralCandidateType &&
9761 llvm::all_of(Range&: CandidateTypes,
9762 P: [](const BuiltinCandidateTypeSet &Types) {
9763 return Types.mayConvertToArithmetic();
9764 })),
9765 CandidateTypes(CandidateTypes), CandidateSet(CandidateSet) {
9766 InitArithmeticTypes();
9767 }
9768
9769 // Increment is deprecated for bool since C++17.
9770 //
9771 // C++ [over.built]p3:
9772 //
9773 // For every pair (T, VQ), where T is an arithmetic type other
9774 // than bool, and VQ is either volatile or empty, there exist
9775 // candidate operator functions of the form
9776 //
9777 // VQ T& operator++(VQ T&);
9778 // T operator++(VQ T&, int);
9779 //
9780 // C++ [over.built]p4:
9781 //
9782 // For every pair (T, VQ), where T is an arithmetic type other
9783 // than bool, and VQ is either volatile or empty, there exist
9784 // candidate operator functions of the form
9785 //
9786 // VQ T& operator--(VQ T&);
9787 // T operator--(VQ T&, int);
9788 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9789 if (!ArithmeticCandidatesMayBeViable)
9790 return;
9791
9792 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9793 const auto TypeOfT = ArithmeticTypes[Arith];
9794 if (TypeOfT == S.Context.BoolTy) {
9795 if (Op == OO_MinusMinus)
9796 continue;
9797 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9798 continue;
9799 }
9800 addPlusPlusMinusMinusStyleOverloads(
9801 CandidateTy: TypeOfT,
9802 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9803 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9804 }
9805 }
9806
9807 // C++ [over.built]p5:
9808 //
9809 // For every pair (T, VQ), where T is a cv-qualified or
9810 // cv-unqualified object type, and VQ is either volatile or
9811 // empty, there exist candidate operator functions of the form
9812 //
9813 // T*VQ& operator++(T*VQ&);
9814 // T*VQ& operator--(T*VQ&);
9815 // T* operator++(T*VQ&, int);
9816 // T* operator--(T*VQ&, int);
9817 void addPlusPlusMinusMinusPointerOverloads() {
9818 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9819 // Skip pointer types that aren't pointers to object types.
9820 if (!PtrTy->getPointeeType()->isObjectType())
9821 continue;
9822
9823 addPlusPlusMinusMinusStyleOverloads(
9824 CandidateTy: PtrTy,
9825 HasVolatile: (!PtrTy.isVolatileQualified() &&
9826 VisibleTypeConversionsQuals.hasVolatile()),
9827 HasRestrict: (!PtrTy.isRestrictQualified() &&
9828 VisibleTypeConversionsQuals.hasRestrict()));
9829 }
9830 }
9831
9832 // C++ [over.built]p6:
9833 // For every cv-qualified or cv-unqualified object type T, there
9834 // exist candidate operator functions of the form
9835 //
9836 // T& operator*(T*);
9837 //
9838 // C++ [over.built]p7:
9839 // For every function type T that does not have cv-qualifiers or a
9840 // ref-qualifier, there exist candidate operator functions of the form
9841 // T& operator*(T*);
9842 void addUnaryStarPointerOverloads() {
9843 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9844 QualType PointeeTy = ParamTy->getPointeeType();
9845 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9846 continue;
9847
9848 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9849 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9850 continue;
9851
9852 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9853 }
9854 }
9855
9856 // C++ [over.built]p9:
9857 // For every promoted arithmetic type T, there exist candidate
9858 // operator functions of the form
9859 //
9860 // T operator+(T);
9861 // T operator-(T);
9862 void addUnaryPlusOrMinusArithmeticOverloads() {
9863 if (!ArithmeticCandidatesMayBeViable)
9864 return;
9865
9866 for (unsigned Arith = FirstPromotedArithmeticType;
9867 Arith < LastPromotedArithmeticType; ++Arith) {
9868 QualType ArithTy = ArithmeticTypes[Arith];
9869 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9870 }
9871
9872 // Extension: We also add these operators for vector types.
9873 for (QualType VecTy : CandidateTypes[0].vector_types())
9874 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9875 }
9876
9877 // C++ [over.built]p8:
9878 // For every type T, there exist candidate operator functions of
9879 // the form
9880 //
9881 // T* operator+(T*);
9882 void addUnaryPlusPointerOverloads() {
9883 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9884 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9885 }
9886
9887 // C++ [over.built]p10:
9888 // For every promoted integral type T, there exist candidate
9889 // operator functions of the form
9890 //
9891 // T operator~(T);
9892 void addUnaryTildePromotedIntegralOverloads() {
9893 if (!ArithmeticCandidatesMayBeViable)
9894 return;
9895
9896 for (unsigned Int = FirstPromotedIntegralType;
9897 Int < LastPromotedIntegralType; ++Int) {
9898 QualType IntTy = ArithmeticTypes[Int];
9899 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9900 }
9901
9902 // Extension: We also add this operator for vector types.
9903 for (QualType VecTy : CandidateTypes[0].vector_types())
9904 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9905 }
9906
9907 // C++ [over.match.oper]p16:
9908 // For every pointer to member type T or type std::nullptr_t, there
9909 // exist candidate operator functions of the form
9910 //
9911 // bool operator==(T,T);
9912 // bool operator!=(T,T);
9913 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9914 /// Set of (canonical) types that we've already handled.
9915 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9916
9917 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9918 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9919 // Don't add the same builtin candidate twice.
9920 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9921 continue;
9922
9923 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9924 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9925 }
9926
9927 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9928 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9929 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9930 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9931 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9932 }
9933 }
9934
9935 if (CandidateTypes[ArgIdx].hasReflectionType()) {
9936 CanQualType MetaInfoTy = S.Context.MetaInfoTy;
9937 if (AddedTypes.insert(Ptr: MetaInfoTy).second) {
9938 QualType ParamTypes[2] = {MetaInfoTy, MetaInfoTy};
9939 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9940 }
9941 }
9942 }
9943 }
9944
9945 // C++ [over.built]p15:
9946 //
9947 // For every T, where T is an enumeration type or a pointer type,
9948 // there exist candidate operator functions of the form
9949 //
9950 // bool operator<(T, T);
9951 // bool operator>(T, T);
9952 // bool operator<=(T, T);
9953 // bool operator>=(T, T);
9954 // bool operator==(T, T);
9955 // bool operator!=(T, T);
9956 // R operator<=>(T, T)
9957 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9958 // C++ [over.match.oper]p3:
9959 // [...]the built-in candidates include all of the candidate operator
9960 // functions defined in 13.6 that, compared to the given operator, [...]
9961 // do not have the same parameter-type-list as any non-template non-member
9962 // candidate.
9963 //
9964 // Note that in practice, this only affects enumeration types because there
9965 // aren't any built-in candidates of record type, and a user-defined operator
9966 // must have an operand of record or enumeration type. Also, the only other
9967 // overloaded operator with enumeration arguments, operator=,
9968 // cannot be overloaded for enumeration types, so this is the only place
9969 // where we must suppress candidates like this.
9970 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9971 UserDefinedBinaryOperators;
9972
9973 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9974 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9975 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9976 CEnd = CandidateSet.end();
9977 C != CEnd; ++C) {
9978 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9979 continue;
9980
9981 if (C->Function->isFunctionTemplateSpecialization())
9982 continue;
9983
9984 // We interpret "same parameter-type-list" as applying to the
9985 // "synthesized candidate, with the order of the two parameters
9986 // reversed", not to the original function.
9987 bool Reversed = C->isReversed();
9988 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9989 ->getType()
9990 .getUnqualifiedType();
9991 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9992 ->getType()
9993 .getUnqualifiedType();
9994
9995 // Skip if either parameter isn't of enumeral type.
9996 if (!FirstParamType->isEnumeralType() ||
9997 !SecondParamType->isEnumeralType())
9998 continue;
9999
10000 // Add this operator to the set of known user-defined operators.
10001 UserDefinedBinaryOperators.insert(
10002 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
10003 y: S.Context.getCanonicalType(T: SecondParamType)));
10004 }
10005 }
10006 }
10007
10008 /// Set of (canonical) types that we've already handled.
10009 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10010
10011 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10012 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10013 // Don't add the same builtin candidate twice.
10014 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10015 continue;
10016 if (IsSpaceship && PtrTy->isFunctionPointerType())
10017 continue;
10018
10019 QualType ParamTypes[2] = {PtrTy, PtrTy};
10020 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10021 }
10022 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10023 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
10024
10025 // Don't add the same builtin candidate twice, or if a user defined
10026 // candidate exists.
10027 if (!AddedTypes.insert(Ptr: CanonType).second ||
10028 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
10029 y&: CanonType)))
10030 continue;
10031 QualType ParamTypes[2] = {EnumTy, EnumTy};
10032 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10033 }
10034 }
10035 }
10036
10037 // C++ [over.built]p13:
10038 //
10039 // For every cv-qualified or cv-unqualified object type T
10040 // there exist candidate operator functions of the form
10041 //
10042 // T* operator+(T*, ptrdiff_t);
10043 // T& operator[](T*, ptrdiff_t); [BELOW]
10044 // T* operator-(T*, ptrdiff_t);
10045 // T* operator+(ptrdiff_t, T*);
10046 // T& operator[](ptrdiff_t, T*); [BELOW]
10047 //
10048 // C++ [over.built]p14:
10049 //
10050 // For every T, where T is a pointer to object type, there
10051 // exist candidate operator functions of the form
10052 //
10053 // ptrdiff_t operator-(T, T);
10054 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
10055 /// Set of (canonical) types that we've already handled.
10056 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10057
10058 for (int Arg = 0; Arg < 2; ++Arg) {
10059 QualType AsymmetricParamTypes[2] = {
10060 S.Context.getPointerDiffType(),
10061 S.Context.getPointerDiffType(),
10062 };
10063 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
10064 QualType PointeeTy = PtrTy->getPointeeType();
10065 if (!PointeeTy->isObjectType())
10066 continue;
10067
10068 AsymmetricParamTypes[Arg] = PtrTy;
10069 if (Arg == 0 || Op == OO_Plus) {
10070 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
10071 // T* operator+(ptrdiff_t, T*);
10072 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
10073 }
10074 if (Op == OO_Minus) {
10075 // ptrdiff_t operator-(T, T);
10076 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10077 continue;
10078
10079 QualType ParamTypes[2] = {PtrTy, PtrTy};
10080 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10081 }
10082 }
10083 }
10084 }
10085
10086 // C++ [over.built]p12:
10087 //
10088 // For every pair of promoted arithmetic types L and R, there
10089 // exist candidate operator functions of the form
10090 //
10091 // LR operator*(L, R);
10092 // LR operator/(L, R);
10093 // LR operator+(L, R);
10094 // LR operator-(L, R);
10095 // bool operator<(L, R);
10096 // bool operator>(L, R);
10097 // bool operator<=(L, R);
10098 // bool operator>=(L, R);
10099 // bool operator==(L, R);
10100 // bool operator!=(L, R);
10101 //
10102 // where LR is the result of the usual arithmetic conversions
10103 // between types L and R.
10104 //
10105 // C++ [over.built]p24:
10106 //
10107 // For every pair of promoted arithmetic types L and R, there exist
10108 // candidate operator functions of the form
10109 //
10110 // LR operator?(bool, L, R);
10111 //
10112 // where LR is the result of the usual arithmetic conversions
10113 // between types L and R.
10114 // Our candidates ignore the first parameter.
10115 void addGenericBinaryArithmeticOverloads() {
10116 if (!ArithmeticCandidatesMayBeViable)
10117 return;
10118
10119 for (unsigned Left = FirstPromotedArithmeticType;
10120 Left < LastPromotedArithmeticType; ++Left) {
10121 for (unsigned Right = FirstPromotedArithmeticType;
10122 Right < LastPromotedArithmeticType; ++Right) {
10123 QualType LandR[2] = { ArithmeticTypes[Left],
10124 ArithmeticTypes[Right] };
10125 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10126 }
10127 }
10128
10129 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10130 // conditional operator for vector types.
10131 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10132 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10133 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10134 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10135 }
10136 }
10137
10138 /// Add binary operator overloads for each candidate matrix type M1, M2:
10139 /// * (M1, M1) -> M1
10140 /// * (M1, M1.getElementType()) -> M1
10141 /// * (M2.getElementType(), M2) -> M2
10142 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10143 void addMatrixBinaryArithmeticOverloads() {
10144 if (!ArithmeticCandidatesMayBeViable)
10145 return;
10146
10147 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10148 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
10149 AddCandidate(L: M1, R: M1);
10150 }
10151
10152 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10153 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
10154 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
10155 AddCandidate(L: M2, R: M2);
10156 }
10157 }
10158
10159 // C++2a [over.built]p14:
10160 //
10161 // For every integral type T there exists a candidate operator function
10162 // of the form
10163 //
10164 // std::strong_ordering operator<=>(T, T)
10165 //
10166 // C++2a [over.built]p15:
10167 //
10168 // For every pair of floating-point types L and R, there exists a candidate
10169 // operator function of the form
10170 //
10171 // std::partial_ordering operator<=>(L, R);
10172 //
10173 // FIXME: The current specification for integral types doesn't play nice with
10174 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10175 // comparisons. Under the current spec this can lead to ambiguity during
10176 // overload resolution. For example:
10177 //
10178 // enum A : int {a};
10179 // auto x = (a <=> (long)42);
10180 //
10181 // error: call is ambiguous for arguments 'A' and 'long'.
10182 // note: candidate operator<=>(int, int)
10183 // note: candidate operator<=>(long, long)
10184 //
10185 // To avoid this error, this function deviates from the specification and adds
10186 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10187 // arithmetic types (the same as the generic relational overloads).
10188 //
10189 // For now this function acts as a placeholder.
10190 void addThreeWayArithmeticOverloads() {
10191 addGenericBinaryArithmeticOverloads();
10192 }
10193
10194 // C++ [over.built]p17:
10195 //
10196 // For every pair of promoted integral types L and R, there
10197 // exist candidate operator functions of the form
10198 //
10199 // LR operator%(L, R);
10200 // LR operator&(L, R);
10201 // LR operator^(L, R);
10202 // LR operator|(L, R);
10203 // L operator<<(L, R);
10204 // L operator>>(L, R);
10205 //
10206 // where LR is the result of the usual arithmetic conversions
10207 // between types L and R.
10208 void addBinaryBitwiseArithmeticOverloads() {
10209 if (!ArithmeticCandidatesMayBeViable)
10210 return;
10211
10212 for (unsigned Left = FirstPromotedIntegralType;
10213 Left < LastPromotedIntegralType; ++Left) {
10214 for (unsigned Right = FirstPromotedIntegralType;
10215 Right < LastPromotedIntegralType; ++Right) {
10216 QualType LandR[2] = { ArithmeticTypes[Left],
10217 ArithmeticTypes[Right] };
10218 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10219 }
10220 }
10221 }
10222
10223 // C++ [over.built]p20:
10224 //
10225 // For every pair (T, VQ), where T is an enumeration or
10226 // pointer to member type and VQ is either volatile or
10227 // empty, there exist candidate operator functions of the form
10228 //
10229 // VQ T& operator=(VQ T&, T);
10230 void addAssignmentMemberPointerOrEnumeralOverloads() {
10231 /// Set of (canonical) types that we've already handled.
10232 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10233
10234 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10235 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10236 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10237 continue;
10238
10239 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10240 }
10241
10242 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10243 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10244 continue;
10245
10246 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10247 }
10248 }
10249 }
10250
10251 // C++ [over.built]p19:
10252 //
10253 // For every pair (T, VQ), where T is any type and VQ is either
10254 // volatile or empty, there exist candidate operator functions
10255 // of the form
10256 //
10257 // T*VQ& operator=(T*VQ&, T*);
10258 //
10259 // C++ [over.built]p21:
10260 //
10261 // For every pair (T, VQ), where T is a cv-qualified or
10262 // cv-unqualified object type and VQ is either volatile or
10263 // empty, there exist candidate operator functions of the form
10264 //
10265 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10266 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10267 void addAssignmentPointerOverloads(bool isEqualOp) {
10268 /// Set of (canonical) types that we've already handled.
10269 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10270
10271 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10272 // If this is operator=, keep track of the builtin candidates we added.
10273 if (isEqualOp)
10274 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10275 else if (!PtrTy->getPointeeType()->isObjectType())
10276 continue;
10277
10278 // non-volatile version
10279 QualType ParamTypes[2] = {
10280 S.Context.getLValueReferenceType(T: PtrTy),
10281 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10282 };
10283 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10284 /*IsAssignmentOperator=*/ isEqualOp);
10285
10286 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10287 VisibleTypeConversionsQuals.hasVolatile();
10288 if (NeedVolatile) {
10289 // volatile version
10290 ParamTypes[0] =
10291 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10292 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10293 /*IsAssignmentOperator=*/isEqualOp);
10294 }
10295
10296 if (!PtrTy.isRestrictQualified() &&
10297 VisibleTypeConversionsQuals.hasRestrict()) {
10298 // restrict version
10299 ParamTypes[0] =
10300 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10301 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10302 /*IsAssignmentOperator=*/isEqualOp);
10303
10304 if (NeedVolatile) {
10305 // volatile restrict version
10306 ParamTypes[0] =
10307 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10308 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10309 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10310 /*IsAssignmentOperator=*/isEqualOp);
10311 }
10312 }
10313 }
10314
10315 if (isEqualOp) {
10316 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10317 // Make sure we don't add the same candidate twice.
10318 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10319 continue;
10320
10321 QualType ParamTypes[2] = {
10322 S.Context.getLValueReferenceType(T: PtrTy),
10323 PtrTy,
10324 };
10325
10326 // non-volatile version
10327 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10328 /*IsAssignmentOperator=*/true);
10329
10330 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10331 VisibleTypeConversionsQuals.hasVolatile();
10332 if (NeedVolatile) {
10333 // volatile version
10334 ParamTypes[0] = S.Context.getLValueReferenceType(
10335 T: S.Context.getVolatileType(T: PtrTy));
10336 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10337 /*IsAssignmentOperator=*/true);
10338 }
10339
10340 if (!PtrTy.isRestrictQualified() &&
10341 VisibleTypeConversionsQuals.hasRestrict()) {
10342 // restrict version
10343 ParamTypes[0] = S.Context.getLValueReferenceType(
10344 T: S.Context.getRestrictType(T: PtrTy));
10345 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10346 /*IsAssignmentOperator=*/true);
10347
10348 if (NeedVolatile) {
10349 // volatile restrict version
10350 ParamTypes[0] =
10351 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10352 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10353 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10354 /*IsAssignmentOperator=*/true);
10355 }
10356 }
10357 }
10358 }
10359 }
10360
10361 // C++ [over.built]p18:
10362 //
10363 // For every triple (L, VQ, R), where L is an arithmetic type,
10364 // VQ is either volatile or empty, and R is a promoted
10365 // arithmetic type, there exist candidate operator functions of
10366 // the form
10367 //
10368 // VQ L& operator=(VQ L&, R);
10369 // VQ L& operator*=(VQ L&, R);
10370 // VQ L& operator/=(VQ L&, R);
10371 // VQ L& operator+=(VQ L&, R);
10372 // VQ L& operator-=(VQ L&, R);
10373 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10374 if (!ArithmeticCandidatesMayBeViable)
10375 return;
10376
10377 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10378 for (unsigned Right = FirstPromotedArithmeticType;
10379 Right < LastPromotedArithmeticType; ++Right) {
10380 QualType ParamTypes[2];
10381 ParamTypes[1] = ArithmeticTypes[Right];
10382 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10383 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10384
10385 forAllQualifierCombinations(
10386 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10387 ParamTypes[0] =
10388 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10389 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10390 /*IsAssignmentOperator=*/isEqualOp);
10391 });
10392 }
10393 }
10394
10395 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10396 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10397 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10398 QualType ParamTypes[2];
10399 ParamTypes[1] = Vec2Ty;
10400 // Add this built-in operator as a candidate (VQ is empty).
10401 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10402 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10403 /*IsAssignmentOperator=*/isEqualOp);
10404
10405 // Add this built-in operator as a candidate (VQ is 'volatile').
10406 if (VisibleTypeConversionsQuals.hasVolatile()) {
10407 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10408 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10409 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10410 /*IsAssignmentOperator=*/isEqualOp);
10411 }
10412 }
10413 }
10414
10415 // C++ [over.built]p22:
10416 //
10417 // For every triple (L, VQ, R), where L is an integral type, VQ
10418 // is either volatile or empty, and R is a promoted integral
10419 // type, there exist candidate operator functions of the form
10420 //
10421 // VQ L& operator%=(VQ L&, R);
10422 // VQ L& operator<<=(VQ L&, R);
10423 // VQ L& operator>>=(VQ L&, R);
10424 // VQ L& operator&=(VQ L&, R);
10425 // VQ L& operator^=(VQ L&, R);
10426 // VQ L& operator|=(VQ L&, R);
10427 void addAssignmentIntegralOverloads() {
10428 if (!ArithmeticCandidatesMayBeViable)
10429 return;
10430
10431 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10432 for (unsigned Right = FirstPromotedIntegralType;
10433 Right < LastPromotedIntegralType; ++Right) {
10434 QualType ParamTypes[2];
10435 ParamTypes[1] = ArithmeticTypes[Right];
10436 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10437 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10438
10439 forAllQualifierCombinations(
10440 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10441 ParamTypes[0] =
10442 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10443 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10444 });
10445 }
10446 }
10447 }
10448
10449 // C++ [over.operator]p23:
10450 //
10451 // There also exist candidate operator functions of the form
10452 //
10453 // bool operator!(bool);
10454 // bool operator&&(bool, bool);
10455 // bool operator||(bool, bool);
10456 void addExclaimOverload() {
10457 QualType ParamTy = S.Context.BoolTy;
10458 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10459 /*IsAssignmentOperator=*/false,
10460 /*NumContextualBoolArguments=*/1);
10461 }
10462 void addAmpAmpOrPipePipeOverload() {
10463 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10464 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10465 /*IsAssignmentOperator=*/false,
10466 /*NumContextualBoolArguments=*/2);
10467 }
10468
10469 // C++ [over.built]p13:
10470 //
10471 // For every cv-qualified or cv-unqualified object type T there
10472 // exist candidate operator functions of the form
10473 //
10474 // T* operator+(T*, ptrdiff_t); [ABOVE]
10475 // T& operator[](T*, ptrdiff_t);
10476 // T* operator-(T*, ptrdiff_t); [ABOVE]
10477 // T* operator+(ptrdiff_t, T*); [ABOVE]
10478 // T& operator[](ptrdiff_t, T*);
10479 void addSubscriptOverloads() {
10480 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10481 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10482 QualType PointeeType = PtrTy->getPointeeType();
10483 if (!PointeeType->isObjectType())
10484 continue;
10485
10486 // T& operator[](T*, ptrdiff_t)
10487 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10488 }
10489
10490 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10491 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10492 QualType PointeeType = PtrTy->getPointeeType();
10493 if (!PointeeType->isObjectType())
10494 continue;
10495
10496 // T& operator[](ptrdiff_t, T*)
10497 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10498 }
10499 }
10500
10501 // C++ [over.built]p11:
10502 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10503 // C1 is the same type as C2 or is a derived class of C2, T is an object
10504 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10505 // there exist candidate operator functions of the form
10506 //
10507 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10508 //
10509 // where CV12 is the union of CV1 and CV2.
10510 void addArrowStarOverloads() {
10511 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10512 QualType C1Ty = PtrTy;
10513 QualType C1;
10514 QualifierCollector Q1;
10515 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10516 if (!isa<RecordType>(Val: C1))
10517 continue;
10518 // heuristic to reduce number of builtin candidates in the set.
10519 // Add volatile/restrict version only if there are conversions to a
10520 // volatile/restrict type.
10521 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10522 continue;
10523 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10524 continue;
10525 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10526 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10527 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10528 *D2 = mptr->getMostRecentCXXRecordDecl();
10529 if (!declaresSameEntity(D1, D2) &&
10530 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10531 break;
10532 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10533 // build CV12 T&
10534 QualType T = mptr->getPointeeType();
10535 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10536 T.isVolatileQualified())
10537 continue;
10538 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10539 T.isRestrictQualified())
10540 continue;
10541 T = Q1.apply(Context: S.Context, QT: T);
10542 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10543 }
10544 }
10545 }
10546
10547 // Note that we don't consider the first argument, since it has been
10548 // contextually converted to bool long ago. The candidates below are
10549 // therefore added as binary.
10550 //
10551 // C++ [over.built]p25:
10552 // For every type T, where T is a pointer, pointer-to-member, or scoped
10553 // enumeration type, there exist candidate operator functions of the form
10554 //
10555 // T operator?(bool, T, T);
10556 //
10557 void addConditionalOperatorOverloads() {
10558 /// Set of (canonical) types that we've already handled.
10559 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10560
10561 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10562 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10563 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10564 continue;
10565
10566 QualType ParamTypes[2] = {PtrTy, PtrTy};
10567 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10568 }
10569
10570 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10571 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10572 continue;
10573
10574 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10575 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10576 }
10577
10578 if (S.getLangOpts().CPlusPlus11) {
10579 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10580 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10581 continue;
10582
10583 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10584 continue;
10585
10586 QualType ParamTypes[2] = {EnumTy, EnumTy};
10587 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10588 }
10589 }
10590 }
10591 }
10592};
10593
10594} // end anonymous namespace
10595
10596void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10597 SourceLocation OpLoc,
10598 ArrayRef<Expr *> Args,
10599 OverloadCandidateSet &CandidateSet) {
10600 // Find all of the types that the arguments can convert to, but only
10601 // if the operator we're looking at has built-in operator candidates
10602 // that make use of these types. Also record whether we encounter non-record
10603 // candidate types or either arithmetic or enumeral candidate types.
10604 QualifiersAndAtomic VisibleTypeConversionsQuals;
10605 VisibleTypeConversionsQuals.addConst();
10606 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10608 if (Args[ArgIdx]->getType()->isAtomicType())
10609 VisibleTypeConversionsQuals.addAtomic();
10610 }
10611
10612 bool HasNonRecordCandidateType = false;
10613 bool HasArithmeticOrEnumeralCandidateType = false;
10614 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10615 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10616 CandidateTypes.emplace_back(Args&: *this);
10617 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10618 Loc: OpLoc,
10619 AllowUserConversions: true,
10620 AllowExplicitConversions: (Op == OO_Exclaim ||
10621 Op == OO_AmpAmp ||
10622 Op == OO_PipePipe),
10623 VisibleQuals: VisibleTypeConversionsQuals);
10624 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10625 CandidateTypes[ArgIdx].hasNonRecordTypes();
10626 HasArithmeticOrEnumeralCandidateType =
10627 HasArithmeticOrEnumeralCandidateType ||
10628 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10629 }
10630
10631 // Exit early when no non-record types have been added to the candidate set
10632 // for any of the arguments to the operator.
10633 //
10634 // We can't exit early for !, ||, or &&, since there we have always have
10635 // 'bool' overloads.
10636 if (!HasNonRecordCandidateType &&
10637 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10638 return;
10639
10640 // Setup an object to manage the common state for building overloads.
10641 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10642 VisibleTypeConversionsQuals,
10643 HasArithmeticOrEnumeralCandidateType,
10644 CandidateTypes, CandidateSet);
10645
10646 // Dispatch over the operation to add in only those overloads which apply.
10647 switch (Op) {
10648 case OO_None:
10649 case NUM_OVERLOADED_OPERATORS:
10650 llvm_unreachable("Expected an overloaded operator");
10651
10652 case OO_New:
10653 case OO_Delete:
10654 case OO_Array_New:
10655 case OO_Array_Delete:
10656 case OO_Call:
10657 llvm_unreachable(
10658 "Special operators don't use AddBuiltinOperatorCandidates");
10659
10660 case OO_Comma:
10661 case OO_Arrow:
10662 case OO_Coawait:
10663 // C++ [over.match.oper]p3:
10664 // -- For the operator ',', the unary operator '&', the
10665 // operator '->', or the operator 'co_await', the
10666 // built-in candidates set is empty.
10667 break;
10668
10669 case OO_Plus: // '+' is either unary or binary
10670 if (Args.size() == 1)
10671 OpBuilder.addUnaryPlusPointerOverloads();
10672 [[fallthrough]];
10673
10674 case OO_Minus: // '-' is either unary or binary
10675 if (Args.size() == 1) {
10676 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10677 } else {
10678 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10679 OpBuilder.addGenericBinaryArithmeticOverloads();
10680 OpBuilder.addMatrixBinaryArithmeticOverloads();
10681 }
10682 break;
10683
10684 case OO_Star: // '*' is either unary or binary
10685 if (Args.size() == 1)
10686 OpBuilder.addUnaryStarPointerOverloads();
10687 else {
10688 OpBuilder.addGenericBinaryArithmeticOverloads();
10689 OpBuilder.addMatrixBinaryArithmeticOverloads();
10690 }
10691 break;
10692
10693 case OO_Slash:
10694 OpBuilder.addGenericBinaryArithmeticOverloads();
10695 break;
10696
10697 case OO_PlusPlus:
10698 case OO_MinusMinus:
10699 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10700 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10701 break;
10702
10703 case OO_EqualEqual:
10704 case OO_ExclaimEqual:
10705 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10706 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10707 OpBuilder.addGenericBinaryArithmeticOverloads();
10708 break;
10709
10710 case OO_Less:
10711 case OO_Greater:
10712 case OO_LessEqual:
10713 case OO_GreaterEqual:
10714 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10715 OpBuilder.addGenericBinaryArithmeticOverloads();
10716 break;
10717
10718 case OO_Spaceship:
10719 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10720 OpBuilder.addThreeWayArithmeticOverloads();
10721 break;
10722
10723 case OO_Percent:
10724 case OO_Caret:
10725 case OO_Pipe:
10726 case OO_LessLess:
10727 case OO_GreaterGreater:
10728 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10729 break;
10730
10731 case OO_Amp: // '&' is either unary or binary
10732 if (Args.size() == 1)
10733 // C++ [over.match.oper]p3:
10734 // -- For the operator ',', the unary operator '&', or the
10735 // operator '->', the built-in candidates set is empty.
10736 break;
10737
10738 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10739 break;
10740
10741 case OO_Tilde:
10742 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10743 break;
10744
10745 case OO_Equal:
10746 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10747 [[fallthrough]];
10748
10749 case OO_PlusEqual:
10750 case OO_MinusEqual:
10751 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10752 [[fallthrough]];
10753
10754 case OO_StarEqual:
10755 case OO_SlashEqual:
10756 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10757 break;
10758
10759 case OO_PercentEqual:
10760 case OO_LessLessEqual:
10761 case OO_GreaterGreaterEqual:
10762 case OO_AmpEqual:
10763 case OO_CaretEqual:
10764 case OO_PipeEqual:
10765 OpBuilder.addAssignmentIntegralOverloads();
10766 break;
10767
10768 case OO_Exclaim:
10769 OpBuilder.addExclaimOverload();
10770 break;
10771
10772 case OO_AmpAmp:
10773 case OO_PipePipe:
10774 OpBuilder.addAmpAmpOrPipePipeOverload();
10775 break;
10776
10777 case OO_Subscript:
10778 if (Args.size() == 2)
10779 OpBuilder.addSubscriptOverloads();
10780 break;
10781
10782 case OO_ArrowStar:
10783 OpBuilder.addArrowStarOverloads();
10784 break;
10785
10786 case OO_Conditional:
10787 OpBuilder.addConditionalOperatorOverloads();
10788 OpBuilder.addGenericBinaryArithmeticOverloads();
10789 break;
10790 }
10791}
10792
10793void
10794Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10795 SourceLocation Loc,
10796 ArrayRef<Expr *> Args,
10797 TemplateArgumentListInfo *ExplicitTemplateArgs,
10798 OverloadCandidateSet& CandidateSet,
10799 bool PartialOverloading) {
10800 ADLResult Fns;
10801
10802 // FIXME: This approach for uniquing ADL results (and removing
10803 // redundant candidates from the set) relies on pointer-equality,
10804 // which means we need to key off the canonical decl. However,
10805 // always going back to the canonical decl might not get us the
10806 // right set of default arguments. What default arguments are
10807 // we supposed to consider on ADL candidates, anyway?
10808
10809 // FIXME: Pass in the explicit template arguments?
10810 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10811
10812 ArrayRef<Expr *> ReversedArgs;
10813
10814 // Erase all of the candidates we already knew about.
10815 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10816 CandEnd = CandidateSet.end();
10817 Cand != CandEnd; ++Cand)
10818 if (Cand->Function) {
10819 FunctionDecl *Fn = Cand->Function;
10820 Fns.erase(D: Fn);
10821 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10822 Fns.erase(D: FunTmpl);
10823 }
10824
10825 // For each of the ADL candidates we found, add it to the overload
10826 // set.
10827 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10828 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10829
10830 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10831 if (ExplicitTemplateArgs)
10832 continue;
10833
10834 AddOverloadCandidate(
10835 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10836 PartialOverloading, /*AllowExplicit=*/true,
10837 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10838 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10839 AddOverloadCandidate(
10840 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10841 /*SuppressUserConversions=*/false, PartialOverloading,
10842 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10843 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10844 }
10845 } else {
10846 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10847 AddTemplateOverloadCandidate(
10848 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10849 /*SuppressUserConversions=*/false, PartialOverloading,
10850 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10851 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10852 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10853
10854 // As template candidates are not deduced immediately,
10855 // persist the array in the overload set.
10856 if (ReversedArgs.empty())
10857 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10858
10859 AddTemplateOverloadCandidate(
10860 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10861 /*SuppressUserConversions=*/false, PartialOverloading,
10862 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10863 PO: OverloadCandidateParamOrder::Reversed);
10864 }
10865 }
10866 }
10867}
10868
10869namespace {
10870enum class Comparison { Equal, Better, Worse };
10871}
10872
10873/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10874/// overload resolution.
10875///
10876/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10877/// Cand1's first N enable_if attributes have precisely the same conditions as
10878/// Cand2's first N enable_if attributes (where N = the number of enable_if
10879/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10880///
10881/// Note that you can have a pair of candidates such that Cand1's enable_if
10882/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10883/// worse than Cand1's.
10884static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10885 const FunctionDecl *Cand2) {
10886 // Common case: One (or both) decls don't have enable_if attrs.
10887 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10888 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10889 if (!Cand1Attr || !Cand2Attr) {
10890 if (Cand1Attr == Cand2Attr)
10891 return Comparison::Equal;
10892 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10893 }
10894
10895 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10896 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10897
10898 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10899 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10900 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10901 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10902
10903 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10904 // has fewer enable_if attributes than Cand2, and vice versa.
10905 if (!Cand1A)
10906 return Comparison::Worse;
10907 if (!Cand2A)
10908 return Comparison::Better;
10909
10910 Cand1ID.clear();
10911 Cand2ID.clear();
10912
10913 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10914 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10915 if (Cand1ID != Cand2ID)
10916 return Comparison::Worse;
10917 }
10918
10919 return Comparison::Equal;
10920}
10921
10922static Comparison
10923isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10924 const OverloadCandidate &Cand2) {
10925 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10926 !Cand2.Function->isMultiVersion())
10927 return Comparison::Equal;
10928
10929 // If both are invalid, they are equal. If one of them is invalid, the other
10930 // is better.
10931 if (Cand1.Function->isInvalidDecl()) {
10932 if (Cand2.Function->isInvalidDecl())
10933 return Comparison::Equal;
10934 return Comparison::Worse;
10935 }
10936 if (Cand2.Function->isInvalidDecl())
10937 return Comparison::Better;
10938
10939 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10940 // cpu_dispatch, else arbitrarily based on the identifiers.
10941 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10942 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10943 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10944 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10945
10946 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10947 return Comparison::Equal;
10948
10949 if (Cand1CPUDisp && !Cand2CPUDisp)
10950 return Comparison::Better;
10951 if (Cand2CPUDisp && !Cand1CPUDisp)
10952 return Comparison::Worse;
10953
10954 if (Cand1CPUSpec && Cand2CPUSpec) {
10955 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10956 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10957 ? Comparison::Better
10958 : Comparison::Worse;
10959
10960 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10961 FirstDiff = std::mismatch(
10962 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10963 first2: Cand2CPUSpec->cpus_begin(),
10964 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10965 return LHS->getName() == RHS->getName();
10966 });
10967
10968 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10969 "Two different cpu-specific versions should not have the same "
10970 "identifier list, otherwise they'd be the same decl!");
10971 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10972 ? Comparison::Better
10973 : Comparison::Worse;
10974 }
10975 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10976}
10977
10978/// Compute the type of the implicit object parameter for the given function,
10979/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10980/// null QualType if there is a 'matches anything' implicit object parameter.
10981static std::optional<QualType>
10982getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10983 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10984 return std::nullopt;
10985
10986 auto *M = cast<CXXMethodDecl>(Val: F);
10987 // Static member functions' object parameters match all types.
10988 if (M->isStatic())
10989 return QualType();
10990 return M->getFunctionObjectParameterReferenceType();
10991}
10992
10993// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10994// represent the same entity.
10995static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10996 const FunctionDecl *F2) {
10997 if (declaresSameEntity(D1: F1, D2: F2))
10998 return true;
10999 auto PT1 = F1->getPrimaryTemplate();
11000 auto PT2 = F2->getPrimaryTemplate();
11001 if (PT1 && PT2) {
11002 if (declaresSameEntity(D1: PT1, D2: PT2) ||
11003 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
11004 D2: PT2->getInstantiatedFromMemberTemplate()))
11005 return true;
11006 }
11007 // TODO: It is not clear whether comparing parameters is necessary (i.e.
11008 // different functions with same params). Consider removing this (as no test
11009 // fail w/o it).
11010 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
11011 if (First) {
11012 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
11013 return *T;
11014 }
11015 assert(I < F->getNumParams());
11016 return F->getParamDecl(i: I++)->getType();
11017 };
11018
11019 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
11020 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
11021
11022 if (F1NumParams != F2NumParams)
11023 return false;
11024
11025 unsigned I1 = 0, I2 = 0;
11026 for (unsigned I = 0; I != F1NumParams; ++I) {
11027 QualType T1 = NextParam(F1, I1, I == 0);
11028 QualType T2 = NextParam(F2, I2, I == 0);
11029 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
11030 if (!Context.hasSameUnqualifiedType(T1, T2))
11031 return false;
11032 }
11033 return true;
11034}
11035
11036/// We're allowed to use constraints partial ordering only if the candidates
11037/// have the same parameter types:
11038/// [over.match.best.general]p2.6
11039/// F1 and F2 are non-template functions with the same
11040/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
11041static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
11042 FunctionDecl *Fn2,
11043 bool IsFn1Reversed,
11044 bool IsFn2Reversed) {
11045 assert(Fn1 && Fn2);
11046 if (Fn1->isVariadic() != Fn2->isVariadic())
11047 return false;
11048
11049 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
11050 Reversed: IsFn1Reversed ^ IsFn2Reversed))
11051 return false;
11052
11053 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
11054 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
11055 if (Mem1 && Mem2) {
11056 // if they are member functions, both are direct members of the same class,
11057 // and
11058 if (Mem1->getParent() != Mem2->getParent())
11059 return false;
11060 // if both are non-static member functions, they have the same types for
11061 // their object parameters
11062 if (Mem1->isInstance() && Mem2->isInstance() &&
11063 !S.getASTContext().hasSameType(
11064 T1: Mem1->getFunctionObjectParameterReferenceType(),
11065 T2: Mem2->getFunctionObjectParameterReferenceType()))
11066 return false;
11067 }
11068 return true;
11069}
11070
11071static FunctionDecl *
11072getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
11073 bool IsFn1Reversed, bool IsFn2Reversed) {
11074 if (!Fn1 || !Fn2)
11075 return nullptr;
11076
11077 // C++ [temp.constr.order]:
11078 // A non-template function F1 is more partial-ordering-constrained than a
11079 // non-template function F2 if:
11080 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
11081 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11082
11083 if (Cand1IsSpecialization || Cand2IsSpecialization)
11084 return nullptr;
11085
11086 // - they have the same non-object-parameter-type-lists, and [...]
11087 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11088 IsFn2Reversed))
11089 return nullptr;
11090
11091 // - the declaration of F1 is more constrained than the declaration of F2.
11092 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
11093}
11094
11095/// isBetterOverloadCandidate - Determines whether the first overload
11096/// candidate is a better candidate than the second (C++ 13.3.3p1).
11097bool clang::isBetterOverloadCandidate(
11098 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11099 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
11100 bool PartialOverloading) {
11101 // Define viable functions to be better candidates than non-viable
11102 // functions.
11103 if (!Cand2.Viable)
11104 return Cand1.Viable;
11105 else if (!Cand1.Viable)
11106 return false;
11107
11108 // [CUDA] A function with 'never' preference is marked not viable, therefore
11109 // is never shown up here. The worst preference shown up here is 'wrong side',
11110 // e.g. an H function called by a HD function in device compilation. This is
11111 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11112 // function which is called only by an H function. A deferred diagnostic will
11113 // be triggered if it is emitted. However a wrong-sided function is still
11114 // a viable candidate here.
11115 //
11116 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11117 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11118 // can be emitted, Cand1 is not better than Cand2. This rule should have
11119 // precedence over other rules.
11120 //
11121 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11122 // other rules should be used to determine which is better. This is because
11123 // host/device based overloading resolution is mostly for determining
11124 // viability of a function. If two functions are both viable, other factors
11125 // should take precedence in preference, e.g. the standard-defined preferences
11126 // like argument conversion ranks or enable_if partial-ordering. The
11127 // preference for pass-object-size parameters is probably most similar to a
11128 // type-based-overloading decision and so should take priority.
11129 //
11130 // If other rules cannot determine which is better, CUDA preference will be
11131 // used again to determine which is better.
11132 //
11133 // TODO: Currently IdentifyPreference does not return correct values
11134 // for functions called in global variable initializers due to missing
11135 // correct context about device/host. Therefore we can only enforce this
11136 // rule when there is a caller. We should enforce this rule for functions
11137 // in global variable initializers once proper context is added.
11138 //
11139 // TODO: We can only enable the hostness based overloading resolution when
11140 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11141 // overloading resolution diagnostics.
11142 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11143 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11144 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11145 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
11146 bool IsCand1ImplicitHD =
11147 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
11148 bool IsCand2ImplicitHD =
11149 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
11150 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
11151 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11152 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11153 // The implicit HD function may be a function in a system header which
11154 // is forced by pragma. In device compilation, if we prefer HD candidates
11155 // over wrong-sided candidates, overloading resolution may change, which
11156 // may result in non-deferrable diagnostics. As a workaround, we let
11157 // implicit HD candidates take equal preference as wrong-sided candidates.
11158 // This will preserve the overloading resolution.
11159 // TODO: We still need special handling of implicit HD functions since
11160 // they may incur other diagnostics to be deferred. We should make all
11161 // host/device related diagnostics deferrable and remove special handling
11162 // of implicit HD functions.
11163 auto EmitThreshold =
11164 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11165 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11166 ? SemaCUDA::CFP_Never
11167 : SemaCUDA::CFP_WrongSide;
11168 auto Cand1Emittable = P1 > EmitThreshold;
11169 auto Cand2Emittable = P2 > EmitThreshold;
11170 if (Cand1Emittable && !Cand2Emittable)
11171 return true;
11172 if (!Cand1Emittable && Cand2Emittable)
11173 return false;
11174 }
11175 }
11176
11177 // C++ [over.match.best]p1: (Changed in C++23)
11178 //
11179 // -- if F is a static member function, ICS1(F) is defined such
11180 // that ICS1(F) is neither better nor worse than ICS1(G) for
11181 // any function G, and, symmetrically, ICS1(G) is neither
11182 // better nor worse than ICS1(F).
11183 unsigned StartArg = 0;
11184 if (!Cand1.TookAddressOfOverload &&
11185 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11186 StartArg = 1;
11187
11188 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11189 // We don't allow incompatible pointer conversions in C++.
11190 if (!S.getLangOpts().CPlusPlus)
11191 return ICS.isStandard() &&
11192 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11193
11194 // The only ill-formed conversion we allow in C++ is the string literal to
11195 // char* conversion, which is only considered ill-formed after C++11.
11196 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11197 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11198 };
11199
11200 // Define functions that don't require ill-formed conversions for a given
11201 // argument to be better candidates than functions that do.
11202 unsigned NumArgs = Cand1.Conversions.size();
11203 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11204 bool HasBetterConversion = false;
11205 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11206 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11207 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11208 if (Cand1Bad != Cand2Bad) {
11209 if (Cand1Bad)
11210 return false;
11211 HasBetterConversion = true;
11212 }
11213 }
11214
11215 if (HasBetterConversion)
11216 return true;
11217
11218 // C++ [over.match.best]p1:
11219 // A viable function F1 is defined to be a better function than another
11220 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11221 // conversion sequence than ICSi(F2), and then...
11222 bool HasWorseConversion = false;
11223 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11224 switch (CompareImplicitConversionSequences(S, Loc,
11225 ICS1: Cand1.Conversions[ArgIdx],
11226 ICS2: Cand2.Conversions[ArgIdx])) {
11227 case ImplicitConversionSequence::Better:
11228 // Cand1 has a better conversion sequence.
11229 HasBetterConversion = true;
11230 break;
11231
11232 case ImplicitConversionSequence::Worse:
11233 if (Cand1.Function && Cand2.Function &&
11234 Cand1.isReversed() != Cand2.isReversed() &&
11235 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11236 // Work around large-scale breakage caused by considering reversed
11237 // forms of operator== in C++20:
11238 //
11239 // When comparing a function against a reversed function, if we have a
11240 // better conversion for one argument and a worse conversion for the
11241 // other, the implicit conversion sequences are treated as being equally
11242 // good.
11243 //
11244 // This prevents a comparison function from being considered ambiguous
11245 // with a reversed form that is written in the same way.
11246 //
11247 // We diagnose this as an extension from CreateOverloadedBinOp.
11248 HasWorseConversion = true;
11249 break;
11250 }
11251
11252 // Cand1 can't be better than Cand2.
11253 return false;
11254
11255 case ImplicitConversionSequence::Indistinguishable:
11256 // Do nothing.
11257 break;
11258 }
11259 }
11260
11261 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11262 // ICSj(F2), or, if not that,
11263 if (HasBetterConversion && !HasWorseConversion)
11264 return true;
11265
11266 // -- the context is an initialization by user-defined conversion
11267 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11268 // from the return type of F1 to the destination type (i.e.,
11269 // the type of the entity being initialized) is a better
11270 // conversion sequence than the standard conversion sequence
11271 // from the return type of F2 to the destination type.
11272 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11273 Cand1.Function && Cand2.Function &&
11274 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11275 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11276
11277 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11278 // First check whether we prefer one of the conversion functions over the
11279 // other. This only distinguishes the results in non-standard, extension
11280 // cases such as the conversion from a lambda closure type to a function
11281 // pointer or block.
11282 ImplicitConversionSequence::CompareKind Result =
11283 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11284 if (Result == ImplicitConversionSequence::Indistinguishable)
11285 Result = CompareStandardConversionSequences(S, Loc,
11286 SCS1: Cand1.FinalConversion,
11287 SCS2: Cand2.FinalConversion);
11288
11289 if (Result != ImplicitConversionSequence::Indistinguishable)
11290 return Result == ImplicitConversionSequence::Better;
11291
11292 // FIXME: Compare kind of reference binding if conversion functions
11293 // convert to a reference type used in direct reference binding, per
11294 // C++14 [over.match.best]p1 section 2 bullet 3.
11295 }
11296
11297 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11298 // as combined with the resolution to CWG issue 243.
11299 //
11300 // When the context is initialization by constructor ([over.match.ctor] or
11301 // either phase of [over.match.list]), a constructor is preferred over
11302 // a conversion function.
11303 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11304 Cand1.Function && Cand2.Function &&
11305 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11306 isa<CXXConstructorDecl>(Val: Cand2.Function))
11307 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11308
11309 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11310 return Cand2.StrictPackMatch;
11311
11312 // -- F1 is a non-template function and F2 is a function template
11313 // specialization, or, if not that,
11314 bool Cand1IsSpecialization = Cand1.Function &&
11315 Cand1.Function->getPrimaryTemplate();
11316 bool Cand2IsSpecialization = Cand2.Function &&
11317 Cand2.Function->getPrimaryTemplate();
11318 if (Cand1IsSpecialization != Cand2IsSpecialization)
11319 return Cand2IsSpecialization;
11320
11321 // -- F1 and F2 are function template specializations, and the function
11322 // template for F1 is more specialized than the template for F2
11323 // according to the partial ordering rules described in 14.5.5.2, or,
11324 // if not that,
11325 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11326 const auto *Obj1Context =
11327 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11328 const auto *Obj2Context =
11329 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11330 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11331 FT1: Cand1.Function->getPrimaryTemplate(),
11332 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11333 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11334 : TPOC_Call,
11335 NumCallArguments1: Cand1.ExplicitCallArguments,
11336 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11337 : QualType{},
11338 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11339 : QualType{},
11340 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11341 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11342 }
11343 }
11344
11345 // -— F1 and F2 are non-template functions and F1 is more
11346 // partial-ordering-constrained than F2 [...],
11347 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11348 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11349 IsFn2Reversed: Cand2.isReversed());
11350 F && F == Cand1.Function)
11351 return true;
11352
11353 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11354 // class B of D, and for all arguments the corresponding parameters of
11355 // F1 and F2 have the same type.
11356 // FIXME: Implement the "all parameters have the same type" check.
11357 bool Cand1IsInherited =
11358 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11359 bool Cand2IsInherited =
11360 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11361 if (Cand1IsInherited != Cand2IsInherited)
11362 return Cand2IsInherited;
11363 else if (Cand1IsInherited) {
11364 assert(Cand2IsInherited);
11365 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11366 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11367 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11368 return true;
11369 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11370 return false;
11371 // Inherited from sibling base classes: still ambiguous.
11372 }
11373
11374 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11375 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11376 // with reversed order of parameters and F1 is not
11377 //
11378 // We rank reversed + different operator as worse than just reversed, but
11379 // that comparison can never happen, because we only consider reversing for
11380 // the maximally-rewritten operator (== or <=>).
11381 if (Cand1.RewriteKind != Cand2.RewriteKind)
11382 return Cand1.RewriteKind < Cand2.RewriteKind;
11383
11384 // Check C++17 tie-breakers for deduction guides.
11385 {
11386 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11387 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11388 if (Guide1 && Guide2) {
11389 // -- F1 is generated from a deduction-guide and F2 is not
11390 if (Guide1->isImplicit() != Guide2->isImplicit())
11391 return Guide2->isImplicit();
11392
11393 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11394 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11395 return true;
11396 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11397 return false;
11398
11399 // --F1 is generated from a non-template constructor and F2 is generated
11400 // from a constructor template
11401 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11402 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11403 if (Constructor1 && Constructor2) {
11404 bool isC1Templated = Constructor1->getTemplatedKind() !=
11405 FunctionDecl::TemplatedKind::TK_NonTemplate;
11406 bool isC2Templated = Constructor2->getTemplatedKind() !=
11407 FunctionDecl::TemplatedKind::TK_NonTemplate;
11408 if (isC1Templated != isC2Templated)
11409 return isC2Templated;
11410 }
11411 }
11412 }
11413
11414 // Check for enable_if value-based overload resolution.
11415 if (Cand1.Function && Cand2.Function) {
11416 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11417 if (Cmp != Comparison::Equal)
11418 return Cmp == Comparison::Better;
11419 }
11420
11421 bool HasPS1 = Cand1.Function != nullptr &&
11422 functionHasPassObjectSizeParams(FD: Cand1.Function);
11423 bool HasPS2 = Cand2.Function != nullptr &&
11424 functionHasPassObjectSizeParams(FD: Cand2.Function);
11425 if (HasPS1 != HasPS2 && HasPS1)
11426 return true;
11427
11428 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11429 if (MV == Comparison::Better)
11430 return true;
11431 if (MV == Comparison::Worse)
11432 return false;
11433
11434 // If other rules cannot determine which is better, CUDA preference is used
11435 // to determine which is better.
11436 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11437 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11438 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11439 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11440 }
11441
11442 // General member function overloading is handled above, so this only handles
11443 // constructors with address spaces.
11444 // This only handles address spaces since C++ has no other
11445 // qualifier that can be used with constructors.
11446 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11447 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11448 if (CD1 && CD2) {
11449 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11450 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11451 if (AS1 != AS2) {
11452 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11453 return true;
11454 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11455 return false;
11456 }
11457 }
11458
11459 return false;
11460}
11461
11462/// Determine whether two declarations are "equivalent" for the purposes of
11463/// name lookup and overload resolution. This applies when the same internal/no
11464/// linkage entity is defined by two modules (probably by textually including
11465/// the same header). In such a case, we don't consider the declarations to
11466/// declare the same entity, but we also don't want lookups with both
11467/// declarations visible to be ambiguous in some cases (this happens when using
11468/// a modularized libstdc++).
11469bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11470 const NamedDecl *B) {
11471 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11472 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11473 if (!VA || !VB)
11474 return false;
11475
11476 // The declarations must be declaring the same name as an internal linkage
11477 // entity in different modules.
11478 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11479 DC: VB->getDeclContext()->getRedeclContext()) ||
11480 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11481 VA->isExternallyVisible() || VB->isExternallyVisible())
11482 return false;
11483
11484 // Check that the declarations appear to be equivalent.
11485 //
11486 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11487 // For constants and functions, we should check the initializer or body is
11488 // the same. For non-constant variables, we shouldn't allow it at all.
11489 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11490 return true;
11491
11492 // Enum constants within unnamed enumerations will have different types, but
11493 // may still be similar enough to be interchangeable for our purposes.
11494 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11495 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11496 // Only handle anonymous enums. If the enumerations were named and
11497 // equivalent, they would have been merged to the same type.
11498 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11499 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11500 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11501 !Context.hasSameType(T1: EnumA->getIntegerType(),
11502 T2: EnumB->getIntegerType()))
11503 return false;
11504 // Allow this only if the value is the same for both enumerators.
11505 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11506 }
11507 }
11508
11509 // Nothing else is sufficiently similar.
11510 return false;
11511}
11512
11513void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11514 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11515 assert(D && "Unknown declaration");
11516 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11517
11518 Module *M = getOwningModule(Entity: D);
11519 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11520 << !M << (M ? M->getFullModuleName() : "");
11521
11522 for (auto *E : Equiv) {
11523 Module *M = getOwningModule(Entity: E);
11524 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11525 << !M << (M ? M->getFullModuleName() : "");
11526 }
11527}
11528
11529bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11530 return FailureKind == ovl_fail_bad_deduction &&
11531 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11532 TemplateDeductionResult::ConstraintsNotSatisfied &&
11533 static_cast<CNSInfo *>(DeductionFailure.Data)
11534 ->Satisfaction.ContainsErrors;
11535}
11536
11537void OverloadCandidateSet::AddDeferredTemplateCandidate(
11538 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11539 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11540 bool PartialOverloading, bool AllowExplicit,
11541 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11542 bool AggregateCandidateDeduction) {
11543
11544 auto *C =
11545 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11546
11547 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11548 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11549 /*AllowObjCConversionOnExplicit=*/false,
11550 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11551 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11552 .FunctionTemplate: FunctionTemplate,
11553 .FoundDecl: FoundDecl,
11554 .Args: Args,
11555 .IsADLCandidate: IsADLCandidate,
11556 .PO: PO};
11557
11558 HasDeferredTemplateConstructors |=
11559 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11560}
11561
11562void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11563 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11564 CXXRecordDecl *ActingContext, QualType ObjectType,
11565 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11566 bool SuppressUserConversions, bool PartialOverloading,
11567 OverloadCandidateParamOrder PO) {
11568
11569 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11570
11571 auto *C =
11572 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11573
11574 C = new (C) DeferredMethodTemplateOverloadCandidate{
11575 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11576 /*AllowObjCConversionOnExplicit=*/false,
11577 /*AllowResultConversion=*/false,
11578 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11579 /*AggregateCandidateDeduction=*/false},
11580 .FunctionTemplate: MethodTmpl,
11581 .FoundDecl: FoundDecl,
11582 .Args: Args,
11583 .ActingContext: ActingContext,
11584 .ObjectClassification: ObjectClassification,
11585 .ObjectType: ObjectType,
11586 .PO: PO};
11587}
11588
11589void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11590 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11591 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11592 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11593 bool AllowResultConversion) {
11594
11595 auto *C =
11596 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11597
11598 C = new (C) DeferredConversionTemplateOverloadCandidate{
11599 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11600 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11601 /*AllowExplicit=*/false,
11602 /*SuppressUserConversions=*/false,
11603 /*PartialOverloading*/ false,
11604 /*AggregateCandidateDeduction=*/false},
11605 .FunctionTemplate: FunctionTemplate,
11606 .FoundDecl: FoundDecl,
11607 .ActingContext: ActingContext,
11608 .From: From,
11609 .ToType: ToType};
11610}
11611
11612static void
11613AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11614 DeferredMethodTemplateOverloadCandidate &C) {
11615
11616 AddMethodTemplateCandidateImmediately(
11617 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11618 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11619 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11620}
11621
11622static void
11623AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11624 DeferredFunctionTemplateOverloadCandidate &C) {
11625 AddTemplateOverloadCandidateImmediately(
11626 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11627 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11628 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11629 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11630}
11631
11632static void
11633AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11634 DeferredConversionTemplateOverloadCandidate &C) {
11635 return AddTemplateConversionCandidateImmediately(
11636 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11637 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11638 AllowResultConversion: C.AllowResultConversion);
11639}
11640
11641void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11642 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11643 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11644 while (Cand) {
11645 switch (Cand->Kind) {
11646 case DeferredTemplateOverloadCandidate::Function:
11647 AddTemplateOverloadCandidate(
11648 S, CandidateSet&: *this,
11649 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11650 break;
11651 case DeferredTemplateOverloadCandidate::Method:
11652 AddTemplateOverloadCandidate(
11653 S, CandidateSet&: *this,
11654 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11655 break;
11656 case DeferredTemplateOverloadCandidate::Conversion:
11657 AddTemplateOverloadCandidate(
11658 S, CandidateSet&: *this,
11659 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11660 break;
11661 }
11662 Cand = Cand->Next;
11663 }
11664 FirstDeferredCandidate = nullptr;
11665 DeferredCandidatesCount = 0;
11666}
11667
11668OverloadingResult
11669OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11670 Best->Best = true;
11671 if (Best->Function && Best->Function->isDeleted())
11672 return OR_Deleted;
11673 return OR_Success;
11674}
11675
11676void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11677 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11678 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11679 // are accepted by both clang and NVCC. However, during a particular
11680 // compilation mode only one call variant is viable. We need to
11681 // exclude non-viable overload candidates from consideration based
11682 // only on their host/device attributes. Specifically, if one
11683 // candidate call is WrongSide and the other is SameSide, we ignore
11684 // the WrongSide candidate.
11685 // We only need to remove wrong-sided candidates here if
11686 // -fgpu-exclude-wrong-side-overloads is off. When
11687 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11688 // uniformly in isBetterOverloadCandidate.
11689 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11690 return;
11691 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11692
11693 bool ContainsSameSideCandidate =
11694 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11695 // Check viable function only.
11696 return Cand->Viable && Cand->Function &&
11697 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11698 SemaCUDA::CFP_SameSide;
11699 });
11700
11701 if (!ContainsSameSideCandidate)
11702 return;
11703
11704 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11705 // Check viable function only to avoid unnecessary data copying/moving.
11706 return Cand->Viable && Cand->Function &&
11707 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11708 SemaCUDA::CFP_WrongSide;
11709 };
11710 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11711}
11712
11713/// Computes the best viable function (C++ 13.3.3)
11714/// within an overload candidate set.
11715///
11716/// \param Loc The location of the function name (or operator symbol) for
11717/// which overload resolution occurs.
11718///
11719/// \param Best If overload resolution was successful or found a deleted
11720/// function, \p Best points to the candidate function found.
11721///
11722/// \returns The result of overload resolution.
11723OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11724 SourceLocation Loc,
11725 iterator &Best) {
11726
11727 assert((shouldDeferTemplateArgumentDeduction(S) ||
11728 DeferredCandidatesCount == 0) &&
11729 "Unexpected deferred template candidates");
11730
11731 bool TwoPhaseResolution =
11732 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11733
11734 if (TwoPhaseResolution) {
11735 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11736 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11737 if (!(HasDeferredTemplateConstructors &&
11738 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11739 return Res;
11740 }
11741 }
11742
11743 InjectNonDeducedTemplateCandidates(S);
11744 return BestViableFunctionImpl(S, Loc, Best);
11745}
11746
11747OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11748 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11749
11750 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11751 Candidates.reserve(N: this->Candidates.size());
11752 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11753 result: std::back_inserter(x&: Candidates),
11754 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11755
11756 if (S.getLangOpts().CUDA)
11757 CudaExcludeWrongSideCandidates(S, Candidates);
11758
11759 Best = end();
11760 for (auto *Cand : Candidates) {
11761 Cand->Best = false;
11762 if (Cand->Viable) {
11763 if (Best == end() ||
11764 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11765 Best = Cand;
11766 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11767 // This candidate has constraint that we were unable to evaluate because
11768 // it referenced an expression that contained an error. Rather than fall
11769 // back onto a potentially unintended candidate (made worse by
11770 // subsuming constraints), treat this as 'no viable candidate'.
11771 Best = end();
11772 return OR_No_Viable_Function;
11773 }
11774 }
11775
11776 // If we didn't find any viable functions, abort.
11777 if (Best == end())
11778 return OR_No_Viable_Function;
11779
11780 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11781 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11782 PendingBest.push_back(Elt: &*Best);
11783 Best->Best = true;
11784
11785 // Make sure that this function is better than every other viable
11786 // function. If not, we have an ambiguity.
11787 while (!PendingBest.empty()) {
11788 auto *Curr = PendingBest.pop_back_val();
11789 for (auto *Cand : Candidates) {
11790 if (Cand->Viable && !Cand->Best &&
11791 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11792 PendingBest.push_back(Elt: Cand);
11793 Cand->Best = true;
11794
11795 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11796 B: Curr->Function))
11797 EquivalentCands.push_back(Elt: Cand->Function);
11798 else
11799 Best = end();
11800 }
11801 }
11802 }
11803
11804 if (Best == end())
11805 return OR_Ambiguous;
11806
11807 OverloadingResult R = ResultForBestCandidate(Best);
11808
11809 if (!EquivalentCands.empty())
11810 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11811 Equiv: EquivalentCands);
11812 return R;
11813}
11814
11815namespace {
11816
11817enum OverloadCandidateKind {
11818 oc_function,
11819 oc_method,
11820 oc_reversed_binary_operator,
11821 oc_constructor,
11822 oc_implicit_default_constructor,
11823 oc_implicit_copy_constructor,
11824 oc_implicit_move_constructor,
11825 oc_implicit_copy_assignment,
11826 oc_implicit_move_assignment,
11827 oc_implicit_equality_comparison,
11828 oc_inherited_constructor
11829};
11830
11831enum OverloadCandidateSelect {
11832 ocs_non_template,
11833 ocs_template,
11834 ocs_described_template,
11835};
11836
11837static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11838ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11839 const FunctionDecl *Fn,
11840 OverloadCandidateRewriteKind CRK,
11841 std::string &Description) {
11842
11843 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11844 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11845 isTemplate = true;
11846 Description = S.getTemplateArgumentBindingsText(
11847 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11848 }
11849
11850 OverloadCandidateSelect Select = [&]() {
11851 if (!Description.empty())
11852 return ocs_described_template;
11853 return isTemplate ? ocs_template : ocs_non_template;
11854 }();
11855
11856 OverloadCandidateKind Kind = [&]() {
11857 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11858 return oc_implicit_equality_comparison;
11859
11860 if (CRK & CRK_Reversed)
11861 return oc_reversed_binary_operator;
11862
11863 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11864 if (!Ctor->isImplicit()) {
11865 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11866 return oc_inherited_constructor;
11867 else
11868 return oc_constructor;
11869 }
11870
11871 if (Ctor->isDefaultConstructor())
11872 return oc_implicit_default_constructor;
11873
11874 if (Ctor->isMoveConstructor())
11875 return oc_implicit_move_constructor;
11876
11877 assert(Ctor->isCopyConstructor() &&
11878 "unexpected sort of implicit constructor");
11879 return oc_implicit_copy_constructor;
11880 }
11881
11882 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11883 // This actually gets spelled 'candidate function' for now, but
11884 // it doesn't hurt to split it out.
11885 if (!Meth->isImplicit())
11886 return oc_method;
11887
11888 if (Meth->isMoveAssignmentOperator())
11889 return oc_implicit_move_assignment;
11890
11891 if (Meth->isCopyAssignmentOperator())
11892 return oc_implicit_copy_assignment;
11893
11894 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11895 return oc_method;
11896 }
11897
11898 return oc_function;
11899 }();
11900
11901 return std::make_pair(x&: Kind, y&: Select);
11902}
11903
11904void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11905 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11906 // set.
11907 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11908 S.Diag(Loc: FoundDecl->getLocation(),
11909 DiagID: diag::note_ovl_candidate_inherited_constructor)
11910 << Shadow->getNominatedBaseClass();
11911}
11912
11913} // end anonymous namespace
11914
11915static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11916 const FunctionDecl *FD) {
11917 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11918 bool AlwaysTrue;
11919 if (EnableIf->getCond()->isValueDependent() ||
11920 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11921 return false;
11922 if (!AlwaysTrue)
11923 return false;
11924 }
11925 return true;
11926}
11927
11928/// Returns true if we can take the address of the function.
11929///
11930/// \param Complain - If true, we'll emit a diagnostic
11931/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11932/// we in overload resolution?
11933/// \param Loc - The location of the statement we're complaining about. Ignored
11934/// if we're not complaining, or if we're in overload resolution.
11935static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11936 bool Complain,
11937 bool InOverloadResolution,
11938 SourceLocation Loc) {
11939 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11940 if (Complain) {
11941 if (InOverloadResolution)
11942 S.Diag(Loc: FD->getBeginLoc(),
11943 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11944 else
11945 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11946 }
11947 return false;
11948 }
11949
11950 if (FD->getTrailingRequiresClause()) {
11951 ConstraintSatisfaction Satisfaction;
11952 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11953 return false;
11954 if (!Satisfaction.IsSatisfied) {
11955 if (Complain) {
11956 if (InOverloadResolution) {
11957 SmallString<128> TemplateArgString;
11958 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11959 TemplateArgString += " ";
11960 TemplateArgString += S.getTemplateArgumentBindingsText(
11961 Params: FunTmpl->getTemplateParameters(),
11962 Args: *FD->getTemplateSpecializationArgs());
11963 }
11964
11965 S.Diag(Loc: FD->getBeginLoc(),
11966 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11967 << TemplateArgString;
11968 } else
11969 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11970 << FD;
11971 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11972 }
11973 return false;
11974 }
11975 }
11976
11977 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11978 return P->hasAttr<PassObjectSizeAttr>();
11979 });
11980 if (I == FD->param_end())
11981 return true;
11982
11983 if (Complain) {
11984 // Add one to ParamNo because it's user-facing
11985 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11986 if (InOverloadResolution)
11987 S.Diag(Loc: FD->getLocation(),
11988 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11989 << ParamNo;
11990 else
11991 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11992 << FD << ParamNo;
11993 }
11994 return false;
11995}
11996
11997static bool checkAddressOfCandidateIsAvailable(Sema &S,
11998 const FunctionDecl *FD) {
11999 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
12000 /*InOverloadResolution=*/true,
12001 /*Loc=*/SourceLocation());
12002}
12003
12004bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
12005 bool Complain,
12006 SourceLocation Loc) {
12007 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
12008 /*InOverloadResolution=*/false,
12009 Loc);
12010}
12011
12012// Don't print candidates other than the one that matches the calling
12013// convention of the call operator, since that is guaranteed to exist.
12014static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
12015 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
12016
12017 if (!ConvD)
12018 return false;
12019 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
12020 if (!RD->isLambda())
12021 return false;
12022
12023 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
12024 CallingConv CallOpCC =
12025 CallOp->getType()->castAs<FunctionType>()->getCallConv();
12026 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
12027 CallingConv ConvToCC =
12028 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
12029
12030 return ConvToCC != CallOpCC;
12031}
12032
12033// Notes the location of an overload candidate.
12034void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
12035 OverloadCandidateRewriteKind RewriteKind,
12036 QualType DestType, bool TakingAddress) {
12037 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
12038 return;
12039 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
12040 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
12041 return;
12042 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
12043 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
12044 return;
12045 if (shouldSkipNotingLambdaConversionDecl(Fn))
12046 return;
12047
12048 std::string FnDesc;
12049 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
12050 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
12051 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
12052 << (unsigned)KSPair.first << (unsigned)KSPair.second
12053 << Fn << FnDesc;
12054
12055 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
12056 Diag(Loc: Fn->getLocation(), PD);
12057 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
12058}
12059
12060static void
12061MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
12062 // Perhaps the ambiguity was caused by two atomic constraints that are
12063 // 'identical' but not equivalent:
12064 //
12065 // void foo() requires (sizeof(T) > 4) { } // #1
12066 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
12067 //
12068 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
12069 // #2 to subsume #1, but these constraint are not considered equivalent
12070 // according to the subsumption rules because they are not the same
12071 // source-level construct. This behavior is quite confusing and we should try
12072 // to help the user figure out what happened.
12073
12074 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
12075 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
12076 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12077 if (!I->Function)
12078 continue;
12079 SmallVector<AssociatedConstraint, 3> AC;
12080 if (auto *Template = I->Function->getPrimaryTemplate())
12081 Template->getAssociatedConstraints(AC);
12082 else
12083 I->Function->getAssociatedConstraints(ACs&: AC);
12084 if (AC.empty())
12085 continue;
12086 if (FirstCand == nullptr) {
12087 FirstCand = I->Function;
12088 FirstAC = AC;
12089 } else if (SecondCand == nullptr) {
12090 SecondCand = I->Function;
12091 SecondAC = AC;
12092 } else {
12093 // We have more than one pair of constrained functions - this check is
12094 // expensive and we'd rather not try to diagnose it.
12095 return;
12096 }
12097 }
12098 if (!SecondCand)
12099 return;
12100 // The diagnostic can only happen if there are associated constraints on
12101 // both sides (there needs to be some identical atomic constraint).
12102 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
12103 D2: SecondCand, AC2: SecondAC))
12104 // Just show the user one diagnostic, they'll probably figure it out
12105 // from here.
12106 return;
12107}
12108
12109// Notes the location of all overload candidates designated through
12110// OverloadedExpr
12111void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12112 bool TakingAddress) {
12113 assert(OverloadedExpr->getType() == Context.OverloadTy);
12114
12115 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
12116 OverloadExpr *OvlExpr = Ovl.Expression;
12117
12118 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12119 IEnd = OvlExpr->decls_end();
12120 I != IEnd; ++I) {
12121 if (FunctionTemplateDecl *FunTmpl =
12122 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12123 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
12124 TakingAddress);
12125 } else if (FunctionDecl *Fun
12126 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
12127 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
12128 }
12129 }
12130}
12131
12132/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12133/// "lead" diagnostic; it will be given two arguments, the source and
12134/// target types of the conversion.
12135void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
12136 Sema &S,
12137 SourceLocation CaretLoc,
12138 const PartialDiagnostic &PDiag) const {
12139 S.Diag(Loc: CaretLoc, PD: PDiag)
12140 << Ambiguous.getFromType() << Ambiguous.getToType();
12141 unsigned CandsShown = 0;
12142 AmbiguousConversionSequence::const_iterator I, E;
12143 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12144 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12145 break;
12146 ++CandsShown;
12147 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
12148 }
12149 S.Diags.overloadCandidatesShown(N: CandsShown);
12150 if (I != E)
12151 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
12152}
12153
12154static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
12155 unsigned I, bool TakingCandidateAddress) {
12156 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12157 assert(Conv.isBad());
12158 assert(Cand->Function && "for now, candidate must be a function");
12159 FunctionDecl *Fn = Cand->Function;
12160
12161 // There's a conversion slot for the object argument if this is a
12162 // non-constructor method. Note that 'I' corresponds the
12163 // conversion-slot index.
12164 bool isObjectArgument = false;
12165 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12166 !isa<CXXConstructorDecl>(Val: Fn)) {
12167 if (I == 0)
12168 isObjectArgument = true;
12169 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12170 I--;
12171 }
12172
12173 std::string FnDesc;
12174 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12175 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12176 Description&: FnDesc);
12177
12178 Expr *FromExpr = Conv.Bad.FromExpr;
12179 QualType FromTy = Conv.Bad.getFromType();
12180 QualType ToTy = Conv.Bad.getToType();
12181 SourceRange ToParamRange;
12182
12183 // FIXME: In presence of parameter packs we can't determine parameter range
12184 // reliably, as we don't have access to instantiation.
12185 bool HasParamPack =
12186 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12187 return Parm->isParameterPack();
12188 });
12189 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12190 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12191
12192 if (FromTy == S.Context.OverloadTy) {
12193 assert(FromExpr && "overload set argument came from implicit argument?");
12194 Expr *E = FromExpr->IgnoreParens();
12195 if (isa<UnaryOperator>(Val: E))
12196 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12197 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12198
12199 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12200 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12201 << ToParamRange << ToTy << Name << I + 1;
12202 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12203 return;
12204 }
12205
12206 // Do some hand-waving analysis to see if the non-viability is due
12207 // to a qualifier mismatch.
12208 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12209 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12210 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12211 CToTy = RT->getPointeeType();
12212 else {
12213 // TODO: detect and diagnose the full richness of const mismatches.
12214 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12215 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12216 CFromTy = FromPT->getPointeeType();
12217 CToTy = ToPT->getPointeeType();
12218 }
12219 }
12220
12221 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12222 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12223 Qualifiers FromQs = CFromTy.getQualifiers();
12224 Qualifiers ToQs = CToTy.getQualifiers();
12225
12226 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12227 if (isObjectArgument)
12228 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12230 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12231 else
12232 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12233 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12234 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12235 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12236 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12237 return;
12238 }
12239
12240 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12241 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12242 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12243 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12244 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12245 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12246 return;
12247 }
12248
12249 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12250 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12251 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12252 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12253 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12254 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12255 return;
12256 }
12257
12258 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12259 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12260 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12261 << FromTy << !!FromQs.getPointerAuth()
12262 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12263 << ToQs.getPointerAuth().getAsString() << I + 1
12264 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12265 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12266 return;
12267 }
12268
12269 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12270 assert(CVR && "expected qualifiers mismatch");
12271
12272 if (isObjectArgument) {
12273 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12274 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12275 << FromTy << (CVR - 1);
12276 } else {
12277 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12278 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12279 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12280 }
12281 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12282 return;
12283 }
12284
12285 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12286 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12287 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12288 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12289 << (unsigned)isObjectArgument << I + 1
12290 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12291 << ToParamRange;
12292 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12293 return;
12294 }
12295
12296 // Special diagnostic for failure to convert an initializer list, since
12297 // telling the user that it has type void is not useful.
12298 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12299 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12300 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12301 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12302 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12303 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12304 ? 2
12305 : 0);
12306 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12307 return;
12308 }
12309
12310 // Diagnose references or pointers to incomplete types differently,
12311 // since it's far from impossible that the incompleteness triggered
12312 // the failure.
12313 QualType TempFromTy = FromTy.getNonReferenceType();
12314 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12315 TempFromTy = PTy->getPointeeType();
12316 if (TempFromTy->isIncompleteType()) {
12317 // Emit the generic diagnostic and, optionally, add the hints to it.
12318 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12319 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12320 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12321 << (unsigned)(Cand->Fix.Kind);
12322
12323 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12324 return;
12325 }
12326
12327 // Diagnose base -> derived pointer conversions.
12328 unsigned BaseToDerivedConversion = 0;
12329 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12330 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12331 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12332 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12333 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12334 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12335 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12336 Base: FromPtrTy->getPointeeType()))
12337 BaseToDerivedConversion = 1;
12338 }
12339 } else if (const ObjCObjectPointerType *FromPtrTy
12340 = FromTy->getAs<ObjCObjectPointerType>()) {
12341 if (const ObjCObjectPointerType *ToPtrTy
12342 = ToTy->getAs<ObjCObjectPointerType>())
12343 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12344 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12345 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12346 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12347 FromIface->isSuperClassOf(I: ToIface))
12348 BaseToDerivedConversion = 2;
12349 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12350 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12351 Ctx: S.getASTContext()) &&
12352 !FromTy->isIncompleteType() &&
12353 !ToRefTy->getPointeeType()->isIncompleteType() &&
12354 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12355 BaseToDerivedConversion = 3;
12356 }
12357 }
12358
12359 if (BaseToDerivedConversion) {
12360 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12361 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12362 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12363 << I + 1;
12364 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12365 return;
12366 }
12367
12368 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12369 isa<PointerType>(Val: CToTy)) {
12370 Qualifiers FromQs = CFromTy.getQualifiers();
12371 Qualifiers ToQs = CToTy.getQualifiers();
12372 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12373 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12374 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12375 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12376 << I + 1;
12377 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12378 return;
12379 }
12380 }
12381
12382 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12383 return;
12384
12385 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12386 // although this is almost always an error and we advise against it.
12387 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12388 ToTy == S.Context.getLogicalOperationType()) {
12389 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12390 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12391 << Conv.Bad.FromExpr << ToTy;
12392 return;
12393 }
12394
12395 // Emit the generic diagnostic and, optionally, add the hints to it.
12396 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12397 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12398 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12399 << (unsigned)(Cand->Fix.Kind);
12400
12401 // Check that location of Fn is not in system header.
12402 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12403 // If we can fix the conversion, suggest the FixIts.
12404 for (const FixItHint &HI : Cand->Fix.Hints)
12405 FDiag << HI;
12406 }
12407
12408 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12409
12410 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12411}
12412
12413/// Additional arity mismatch diagnosis specific to a function overload
12414/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12415/// over a candidate in any candidate set.
12416static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12417 unsigned NumArgs, bool IsAddressOf = false) {
12418 assert(Cand->Function && "Candidate is required to be a function.");
12419 FunctionDecl *Fn = Cand->Function;
12420 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12421 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12422
12423 // With invalid overloaded operators, it's possible that we think we
12424 // have an arity mismatch when in fact it looks like we have the
12425 // right number of arguments, because only overloaded operators have
12426 // the weird behavior of overloading member and non-member functions.
12427 // Just don't report anything.
12428 if (Fn->isInvalidDecl() &&
12429 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12430 return true;
12431
12432 if (NumArgs < MinParams) {
12433 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12434 (Cand->FailureKind == ovl_fail_bad_deduction &&
12435 Cand->DeductionFailure.getResult() ==
12436 TemplateDeductionResult::TooFewArguments));
12437 } else {
12438 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12439 (Cand->FailureKind == ovl_fail_bad_deduction &&
12440 Cand->DeductionFailure.getResult() ==
12441 TemplateDeductionResult::TooManyArguments));
12442 }
12443
12444 return false;
12445}
12446
12447/// General arity mismatch diagnosis over a candidate in a candidate set.
12448static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12449 unsigned NumFormalArgs,
12450 bool IsAddressOf = false) {
12451 assert(isa<FunctionDecl>(D) &&
12452 "The templated declaration should at least be a function"
12453 " when diagnosing bad template argument deduction due to too many"
12454 " or too few arguments");
12455
12456 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12457
12458 // TODO: treat calls to a missing default constructor as a special case
12459 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12460 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12461 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12462
12463 // at least / at most / exactly
12464 bool HasExplicitObjectParam =
12465 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12466
12467 unsigned ParamCount =
12468 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12469 unsigned mode, modeCount;
12470
12471 if (NumFormalArgs < MinParams) {
12472 if (MinParams != ParamCount || FnTy->isVariadic() ||
12473 FnTy->isTemplateVariadic())
12474 mode = 0; // "at least"
12475 else
12476 mode = 2; // "exactly"
12477 modeCount = MinParams;
12478 } else {
12479 if (MinParams != ParamCount)
12480 mode = 1; // "at most"
12481 else
12482 mode = 2; // "exactly"
12483 modeCount = ParamCount;
12484 }
12485
12486 std::string Description;
12487 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12488 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12489
12490 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12491 if (modeCount == 1 && !IsAddressOf &&
12492 FirstNonObjectParamIdx < Fn->getNumParams() &&
12493 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12494 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12495 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12496 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12497 << NumFormalArgs << HasExplicitObjectParam
12498 << Fn->getParametersSourceRange();
12499 else
12500 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12501 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12502 << Description << mode << modeCount << NumFormalArgs
12503 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12504
12505 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12506}
12507
12508/// Arity mismatch diagnosis specific to a function overload candidate.
12509static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12510 unsigned NumFormalArgs) {
12511 assert(Cand->Function && "Candidate must be a function");
12512 FunctionDecl *Fn = Cand->Function;
12513 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12514 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12515 IsAddressOf: Cand->TookAddressOfOverload);
12516}
12517
12518static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12519 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12520 return TD;
12521 llvm_unreachable("Unsupported: Getting the described template declaration"
12522 " for bad deduction diagnosis");
12523}
12524
12525/// Diagnose a failed template-argument deduction.
12526static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12527 DeductionFailureInfo &DeductionFailure,
12528 unsigned NumArgs, bool TakingCandidateAddress,
12529 TemplateSpecCandidateSetKind CandidateSetKind =
12530 TemplateSpecCandidateSetKind::Normal) {
12531 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12532 NamedDecl *ParamD = dyn_cast_if_present<TemplateTypeParmDecl *>(Val&: Param);
12533 if (!ParamD)
12534 ParamD = dyn_cast_if_present<NonTypeTemplateParmDecl *>(Val&: Param);
12535 if (!ParamD)
12536 ParamD = dyn_cast_if_present<TemplateTemplateParmDecl *>(Val&: Param);
12537 switch (DeductionFailure.getResult()) {
12538 case TemplateDeductionResult::Success:
12539 llvm_unreachable(
12540 "TemplateDeductionResult::Success while diagnosing bad deduction");
12541 case TemplateDeductionResult::NonDependentConversionFailure:
12542 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12543 "while diagnosing bad deduction");
12544 case TemplateDeductionResult::Invalid:
12545 case TemplateDeductionResult::AlreadyDiagnosed:
12546 return;
12547
12548 case TemplateDeductionResult::Incomplete: {
12549 assert(ParamD && "no parameter found for incomplete deduction result");
12550 S.Diag(Loc: Templated->getLocation(),
12551 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12552 << ParamD->getDeclName();
12553 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12554 return;
12555 }
12556
12557 case TemplateDeductionResult::IncompletePack: {
12558 assert(ParamD && "no parameter found for incomplete deduction result");
12559 S.Diag(Loc: Templated->getLocation(),
12560 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12561 << ParamD->getDeclName()
12562 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12563 << *DeductionFailure.getFirstArg();
12564 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12565 return;
12566 }
12567
12568 case TemplateDeductionResult::Underqualified: {
12569 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12570 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12571
12572 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12573
12574 // Param will have been canonicalized, but it should just be a
12575 // qualified version of ParamD, so move the qualifiers to that.
12576 QualifierCollector Qs;
12577 Qs.strip(type: Param);
12578 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12579 assert(S.Context.hasSameType(Param, NonCanonParam));
12580
12581 // Arg has also been canonicalized, but there's nothing we can do
12582 // about that. It also doesn't matter as much, because it won't
12583 // have any template parameters in it (because deduction isn't
12584 // done on dependent types).
12585 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12586
12587 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12588 << ParamD->getDeclName() << Arg << NonCanonParam;
12589 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12590 return;
12591 }
12592
12593 case TemplateDeductionResult::Inconsistent: {
12594 assert(ParamD && "no parameter found for inconsistent deduction result");
12595 int which = 0;
12596 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12597 which = 0;
12598 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12599 // Deduction might have failed because we deduced arguments of two
12600 // different types for a non-type template parameter.
12601 // FIXME: Use a different TDK value for this.
12602 QualType T1 =
12603 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12604 QualType T2 =
12605 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12606 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12607 S.Diag(Loc: Templated->getLocation(),
12608 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12609 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12610 << *DeductionFailure.getSecondArg() << T2;
12611 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12612 return;
12613 }
12614
12615 which = 1;
12616 } else {
12617 which = 2;
12618 }
12619
12620 // Tweak the diagnostic if the problem is that we deduced packs of
12621 // different arities. We'll print the actual packs anyway in case that
12622 // includes additional useful information.
12623 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12624 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12625 DeductionFailure.getFirstArg()->pack_size() !=
12626 DeductionFailure.getSecondArg()->pack_size()) {
12627 which = 3;
12628 }
12629
12630 S.Diag(Loc: Templated->getLocation(),
12631 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12632 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12633 << *DeductionFailure.getSecondArg();
12634 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12635 return;
12636 }
12637
12638 case TemplateDeductionResult::InvalidExplicitArguments: {
12639 assert(ParamD && "no parameter found for invalid explicit arguments");
12640
12641 auto Diag = S.Diag(Loc: Templated->getLocation(),
12642 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch);
12643 if (ParamD->getDeclName())
12644 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12645 else
12646 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12647 << (getDepthAndIndex(ND: ParamD).second + 1);
12648 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12649 SmallString<128> DiagContent;
12650 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: DiagContent);
12651 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12652 } else {
12653 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12654 }
12655
12656 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12657 return;
12658 }
12659 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12660 // Format the template argument list into the argument string.
12661 SmallString<128> TemplateArgString;
12662 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12663 TemplateArgString = " ";
12664 TemplateArgString += S.getTemplateArgumentBindingsText(
12665 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12666 if (TemplateArgString.size() == 1)
12667 TemplateArgString.clear();
12668 S.Diag(Loc: Templated->getLocation(),
12669 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12670 << TemplateArgString;
12671
12672 S.DiagnoseUnsatisfiedConstraint(
12673 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12674 return;
12675 }
12676 case TemplateDeductionResult::TooManyArguments:
12677 case TemplateDeductionResult::TooFewArguments:
12678 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12679 return;
12680
12681 case TemplateDeductionResult::InstantiationDepth:
12682 S.Diag(Loc: Templated->getLocation(),
12683 DiagID: diag::note_ovl_candidate_instantiation_depth);
12684 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12685 return;
12686
12687 case TemplateDeductionResult::SubstitutionFailure: {
12688 // Format the template argument list into the argument string.
12689 SmallString<128> TemplateArgString;
12690 if (TemplateArgumentList *Args =
12691 DeductionFailure.getTemplateArgumentList()) {
12692 TemplateArgString = " ";
12693 TemplateArgString += S.getTemplateArgumentBindingsText(
12694 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12695 if (TemplateArgString.size() == 1)
12696 TemplateArgString.clear();
12697 }
12698
12699 // If this candidate was disabled by enable_if, say so.
12700 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12701 if (PDiag && PDiag->second.getDiagID() ==
12702 diag::err_typename_nested_not_found_enable_if) {
12703 // FIXME: Use the source range of the condition, and the fully-qualified
12704 // name of the enable_if template. These are both present in PDiag.
12705 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12706 << "'enable_if'" << TemplateArgString;
12707 return;
12708 }
12709
12710 // We found a specific requirement that disabled the enable_if.
12711 if (PDiag && PDiag->second.getDiagID() ==
12712 diag::err_typename_nested_not_found_requirement) {
12713 S.Diag(Loc: Templated->getLocation(),
12714 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12715 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12716 return;
12717 }
12718
12719 // Format the SFINAE diagnostic into the argument string.
12720 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12721 // formatted message in another diagnostic.
12722 SmallString<128> SFINAEArgString;
12723 SourceRange R;
12724 if (PDiag) {
12725 SFINAEArgString = ": ";
12726 R = SourceRange(PDiag->first, PDiag->first);
12727 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12728 }
12729
12730 S.Diag(Loc: Templated->getLocation(),
12731 DiagID: diag::note_ovl_candidate_substitution_failure)
12732 << TemplateArgString << SFINAEArgString << R;
12733 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12734 return;
12735 }
12736
12737 case TemplateDeductionResult::DeducedMismatch:
12738 case TemplateDeductionResult::DeducedMismatchNested: {
12739 // Format the template argument list into the argument string.
12740 SmallString<128> TemplateArgString;
12741 if (TemplateArgumentList *Args =
12742 DeductionFailure.getTemplateArgumentList()) {
12743 TemplateArgString = " ";
12744 TemplateArgString += S.getTemplateArgumentBindingsText(
12745 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12746 if (TemplateArgString.size() == 1)
12747 TemplateArgString.clear();
12748 }
12749
12750 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12751 << (*DeductionFailure.getCallArgIndex() + 1)
12752 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12753 << TemplateArgString
12754 << (DeductionFailure.getResult() ==
12755 TemplateDeductionResult::DeducedMismatchNested);
12756 break;
12757 }
12758
12759 case TemplateDeductionResult::NonDeducedMismatch: {
12760 // FIXME: Provide a source location to indicate what we couldn't match.
12761 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12762 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12763 if (FirstTA.getKind() == TemplateArgument::Template &&
12764 SecondTA.getKind() == TemplateArgument::Template) {
12765 TemplateName FirstTN = FirstTA.getAsTemplate();
12766 TemplateName SecondTN = SecondTA.getAsTemplate();
12767 if (FirstTN.getKind() == TemplateName::Template &&
12768 SecondTN.getKind() == TemplateName::Template) {
12769 if (FirstTN.getAsTemplateDecl()->getName() ==
12770 SecondTN.getAsTemplateDecl()->getName()) {
12771 // FIXME: This fixes a bad diagnostic where both templates are named
12772 // the same. This particular case is a bit difficult since:
12773 // 1) It is passed as a string to the diagnostic printer.
12774 // 2) The diagnostic printer only attempts to find a better
12775 // name for types, not decls.
12776 // Ideally, this should folded into the diagnostic printer.
12777 S.Diag(Loc: Templated->getLocation(),
12778 DiagID: CandidateSetKind ==
12779 TemplateSpecCandidateSetKind::FriendTemplate
12780 ? diag::note_friend_template_non_deduced_mismatch_qualified
12781 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12782 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12783 return;
12784 }
12785 }
12786 }
12787
12788 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12789 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12790 return;
12791
12792 // FIXME: For generic lambda parameters, check if the function is a lambda
12793 // call operator, and if so, emit a prettier and more informative
12794 // diagnostic that mentions 'auto' and lambda in addition to
12795 // (or instead of?) the canonical template type parameters.
12796 S.Diag(Loc: Templated->getLocation(),
12797 DiagID: CandidateSetKind == TemplateSpecCandidateSetKind::FriendTemplate
12798 ? diag::note_friend_template_non_deduced_mismatch
12799 : diag::note_ovl_candidate_non_deduced_mismatch)
12800 << FirstTA << SecondTA;
12801 return;
12802 }
12803 // TODO: diagnose these individually, then kill off
12804 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12805 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12806 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12807 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12808 return;
12809 case TemplateDeductionResult::CUDATargetMismatch:
12810 S.Diag(Loc: Templated->getLocation(),
12811 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12812 return;
12813 }
12814}
12815
12816/// Diagnose a failed template-argument deduction, for function calls.
12817static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12818 unsigned NumArgs,
12819 bool TakingCandidateAddress) {
12820 assert(Cand->Function && "Candidate must be a function");
12821 FunctionDecl *Fn = Cand->Function;
12822 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12823 if (TDK == TemplateDeductionResult::TooFewArguments ||
12824 TDK == TemplateDeductionResult::TooManyArguments) {
12825 if (CheckArityMismatch(S, Cand, NumArgs))
12826 return;
12827 }
12828 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12829 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12830}
12831
12832/// CUDA: diagnose an invalid call across targets.
12833static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12834 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12835 assert(Cand->Function && "Candidate must be a Function.");
12836 FunctionDecl *Callee = Cand->Function;
12837
12838 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12839 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12840
12841 std::string FnDesc;
12842 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12843 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12844 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12845
12846 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12847 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12848 << FnDesc /* Ignored */
12849 << CalleeTarget << CallerTarget;
12850
12851 // This could be an implicit constructor for which we could not infer the
12852 // target due to a collsion. Diagnose that case.
12853 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12854 if (Meth != nullptr && Meth->isImplicit()) {
12855 CXXRecordDecl *ParentClass = Meth->getParent();
12856 CXXSpecialMemberKind CSM;
12857
12858 switch (FnKindPair.first) {
12859 default:
12860 return;
12861 case oc_implicit_default_constructor:
12862 CSM = CXXSpecialMemberKind::DefaultConstructor;
12863 break;
12864 case oc_implicit_copy_constructor:
12865 CSM = CXXSpecialMemberKind::CopyConstructor;
12866 break;
12867 case oc_implicit_move_constructor:
12868 CSM = CXXSpecialMemberKind::MoveConstructor;
12869 break;
12870 case oc_implicit_copy_assignment:
12871 CSM = CXXSpecialMemberKind::CopyAssignment;
12872 break;
12873 case oc_implicit_move_assignment:
12874 CSM = CXXSpecialMemberKind::MoveAssignment;
12875 break;
12876 };
12877
12878 bool ConstRHS = false;
12879 if (Meth->getNumParams()) {
12880 if (const ReferenceType *RT =
12881 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12882 ConstRHS = RT->getPointeeType().isConstQualified();
12883 }
12884 }
12885
12886 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12887 /* ConstRHS */ ConstRHS,
12888 /* Diagnose */ true);
12889 }
12890}
12891
12892static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12893 assert(Cand->Function && "Candidate must be a function");
12894 FunctionDecl *Callee = Cand->Function;
12895 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12896
12897 S.Diag(Loc: Callee->getLocation(),
12898 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12899 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12900}
12901
12902static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12903 assert(Cand->Function && "Candidate must be a function");
12904 FunctionDecl *Fn = Cand->Function;
12905 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12906 assert(ES.isExplicit() && "not an explicit candidate");
12907
12908 unsigned Kind;
12909 switch (Fn->getDeclKind()) {
12910 case Decl::Kind::CXXConstructor:
12911 Kind = 0;
12912 break;
12913 case Decl::Kind::CXXConversion:
12914 Kind = 1;
12915 break;
12916 case Decl::Kind::CXXDeductionGuide:
12917 Kind = Fn->isImplicit() ? 0 : 2;
12918 break;
12919 default:
12920 llvm_unreachable("invalid Decl");
12921 }
12922
12923 // Note the location of the first (in-class) declaration; a redeclaration
12924 // (particularly an out-of-class definition) will typically lack the
12925 // 'explicit' specifier.
12926 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12927 FunctionDecl *First = Fn->getFirstDecl();
12928 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12929 First = Pattern->getFirstDecl();
12930
12931 S.Diag(Loc: First->getLocation(),
12932 DiagID: diag::note_ovl_candidate_explicit)
12933 << Kind << (ES.getExpr() ? 1 : 0)
12934 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12935}
12936
12937static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12938 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12939 if (!DG)
12940 return;
12941 TemplateDecl *OriginTemplate =
12942 DG->getDeclName().getCXXDeductionGuideTemplate();
12943 // We want to always print synthesized deduction guides for type aliases.
12944 // They would retain the explicit bit of the corresponding constructor.
12945 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12946 return;
12947 std::string FunctionProto;
12948 llvm::raw_string_ostream OS(FunctionProto);
12949 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12950 if (!Template) {
12951 // This also could be an instantiation. Find out the primary template.
12952 FunctionDecl *Pattern =
12953 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12954 if (!Pattern) {
12955 // The implicit deduction guide is built on an explicit non-template
12956 // deduction guide. Currently, this might be the case only for type
12957 // aliases.
12958 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12959 // gets merged.
12960 assert(OriginTemplate->isTypeAlias() &&
12961 "Non-template implicit deduction guides are only possible for "
12962 "type aliases");
12963 DG->print(Out&: OS);
12964 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12965 << FunctionProto;
12966 return;
12967 }
12968 Template = Pattern->getDescribedFunctionTemplate();
12969 assert(Template && "Cannot find the associated function template of "
12970 "CXXDeductionGuideDecl?");
12971 }
12972 Template->print(Out&: OS);
12973 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12974 << FunctionProto;
12975}
12976
12977/// Generates a 'note' diagnostic for an overload candidate. We've
12978/// already generated a primary error at the call site.
12979///
12980/// It really does need to be a single diagnostic with its caret
12981/// pointed at the candidate declaration. Yes, this creates some
12982/// major challenges of technical writing. Yes, this makes pointing
12983/// out problems with specific arguments quite awkward. It's still
12984/// better than generating twenty screens of text for every failed
12985/// overload.
12986///
12987/// It would be great to be able to express per-candidate problems
12988/// more richly for those diagnostic clients that cared, but we'd
12989/// still have to be just as careful with the default diagnostics.
12990/// \param CtorDestAS Addr space of object being constructed (for ctor
12991/// candidates only).
12992static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12993 unsigned NumArgs,
12994 bool TakingCandidateAddress,
12995 LangAS CtorDestAS = LangAS::Default) {
12996 assert(Cand->Function && "Candidate must be a function");
12997 FunctionDecl *Fn = Cand->Function;
12998 if (shouldSkipNotingLambdaConversionDecl(Fn))
12999 return;
13000
13001 // There is no physical candidate declaration to point to for OpenCL builtins.
13002 // Except for failed conversions, the notes are identical for each candidate,
13003 // so do not generate such notes.
13004 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
13005 Cand->FailureKind != ovl_fail_bad_conversion)
13006 return;
13007
13008 // Skip implicit member functions when trying to resolve
13009 // the address of a an overload set for a function pointer.
13010 if (Cand->TookAddressOfOverload &&
13011 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
13012 return;
13013
13014 // Note deleted candidates, but only if they're viable.
13015 if (Cand->Viable) {
13016 if (Fn->isDeleted()) {
13017 std::string FnDesc;
13018 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13019 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
13020 CRK: Cand->getRewriteKind(), Description&: FnDesc);
13021
13022 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
13023 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
13024 << (Fn->isDeleted()
13025 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
13026 : 0);
13027 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13028 return;
13029 }
13030
13031 // We don't really have anything else to say about viable candidates.
13032 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13033 return;
13034 }
13035
13036 // If this is a synthesized deduction guide we're deducing against, add a note
13037 // for it. These deduction guides are not explicitly spelled in the source
13038 // code, so simply printing a deduction failure note mentioning synthesized
13039 // template parameters or pointing to the header of the surrounding RecordDecl
13040 // would be confusing.
13041 //
13042 // We prefer adding such notes at the end of the deduction failure because
13043 // duplicate code snippets appearing in the diagnostic would likely become
13044 // noisy.
13045 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
13046
13047 switch (Cand->FailureKind) {
13048 case ovl_fail_too_many_arguments:
13049 case ovl_fail_too_few_arguments:
13050 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
13051
13052 case ovl_fail_bad_deduction:
13053 return DiagnoseBadDeduction(S, Cand, NumArgs,
13054 TakingCandidateAddress);
13055
13056 case ovl_fail_illegal_constructor: {
13057 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
13058 << (Fn->getPrimaryTemplate() ? 1 : 0);
13059 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13060 return;
13061 }
13062
13063 case ovl_fail_object_addrspace_mismatch: {
13064 Qualifiers QualsForPrinting;
13065 QualsForPrinting.setAddressSpace(CtorDestAS);
13066 S.Diag(Loc: Fn->getLocation(),
13067 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
13068 << QualsForPrinting;
13069 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13070 return;
13071 }
13072
13073 case ovl_fail_trivial_conversion:
13074 case ovl_fail_bad_final_conversion:
13075 case ovl_fail_final_conversion_not_exact:
13076 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13077
13078 case ovl_fail_bad_conversion: {
13079 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
13080 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
13081 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
13082 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13083
13084 // FIXME: this currently happens when we're called from SemaInit
13085 // when user-conversion overload fails. Figure out how to handle
13086 // those conditions and diagnose them well.
13087 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
13088 }
13089
13090 case ovl_fail_bad_target:
13091 return DiagnoseBadTarget(S, Cand);
13092
13093 case ovl_fail_enable_if:
13094 return DiagnoseFailedEnableIfAttr(S, Cand);
13095
13096 case ovl_fail_explicit:
13097 return DiagnoseFailedExplicitSpec(S, Cand);
13098
13099 case ovl_fail_inhctor_slice:
13100 // It's generally not interesting to note copy/move constructors here.
13101 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
13102 return;
13103 S.Diag(Loc: Fn->getLocation(),
13104 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
13105 << (Fn->getPrimaryTemplate() ? 1 : 0)
13106 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
13107 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
13108 return;
13109
13110 case ovl_fail_addr_not_available: {
13111 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
13112 (void)Available;
13113 assert(!Available);
13114 break;
13115 }
13116 case ovl_non_default_multiversion_function:
13117 // Do nothing, these should simply be ignored.
13118 break;
13119
13120 case ovl_fail_constraints_not_satisfied: {
13121 std::string FnDesc;
13122 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13123 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
13124 CRK: Cand->getRewriteKind(), Description&: FnDesc);
13125
13126 S.Diag(Loc: Fn->getLocation(),
13127 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
13128 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13129 << FnDesc /* Ignored */;
13130 ConstraintSatisfaction Satisfaction;
13131 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
13132 /*ForOverloadResolution=*/true))
13133 break;
13134 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13135 }
13136 }
13137}
13138
13139static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
13140 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
13141 return;
13142
13143 // Desugar the type of the surrogate down to a function type,
13144 // retaining as many typedefs as possible while still showing
13145 // the function type (and, therefore, its parameter types).
13146 QualType FnType = Cand->Surrogate->getConversionType();
13147 bool isLValueReference = false;
13148 bool isRValueReference = false;
13149 bool isPointer = false;
13150 if (const LValueReferenceType *FnTypeRef =
13151 FnType->getAs<LValueReferenceType>()) {
13152 FnType = FnTypeRef->getPointeeType();
13153 isLValueReference = true;
13154 } else if (const RValueReferenceType *FnTypeRef =
13155 FnType->getAs<RValueReferenceType>()) {
13156 FnType = FnTypeRef->getPointeeType();
13157 isRValueReference = true;
13158 }
13159 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13160 FnType = FnTypePtr->getPointeeType();
13161 isPointer = true;
13162 }
13163 // Desugar down to a function type.
13164 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13165 // Reconstruct the pointer/reference as appropriate.
13166 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
13167 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13168 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13169
13170 if (!Cand->Viable &&
13171 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13172 S.Diag(Loc: Cand->Surrogate->getLocation(),
13173 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13174 << Cand->Surrogate;
13175 ConstraintSatisfaction Satisfaction;
13176 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13177 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13178 } else {
13179 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13180 << FnType;
13181 }
13182}
13183
13184static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13185 SourceLocation OpLoc,
13186 OverloadCandidate *Cand) {
13187 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13188 std::string TypeStr("operator");
13189 TypeStr += Opc;
13190 TypeStr += "(";
13191 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13192 if (Cand->Conversions.size() == 1) {
13193 TypeStr += ")";
13194 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13195 } else {
13196 TypeStr += ", ";
13197 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13198 TypeStr += ")";
13199 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13200 }
13201}
13202
13203static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13204 OverloadCandidate *Cand) {
13205 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13206 if (ICS.isBad()) break; // all meaningless after first invalid
13207 if (!ICS.isAmbiguous()) continue;
13208
13209 ICS.DiagnoseAmbiguousConversion(
13210 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13211 }
13212}
13213
13214static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13215 if (Cand->Function)
13216 return Cand->Function->getLocation();
13217 if (Cand->IsSurrogate)
13218 return Cand->Surrogate->getLocation();
13219 return SourceLocation();
13220}
13221
13222static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13223 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13224 case TemplateDeductionResult::Success:
13225 case TemplateDeductionResult::NonDependentConversionFailure:
13226 case TemplateDeductionResult::AlreadyDiagnosed:
13227 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13228
13229 case TemplateDeductionResult::Invalid:
13230 case TemplateDeductionResult::Incomplete:
13231 case TemplateDeductionResult::IncompletePack:
13232 return 1;
13233
13234 case TemplateDeductionResult::Underqualified:
13235 case TemplateDeductionResult::Inconsistent:
13236 return 2;
13237
13238 case TemplateDeductionResult::SubstitutionFailure:
13239 case TemplateDeductionResult::DeducedMismatch:
13240 case TemplateDeductionResult::ConstraintsNotSatisfied:
13241 case TemplateDeductionResult::DeducedMismatchNested:
13242 case TemplateDeductionResult::NonDeducedMismatch:
13243 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13244 case TemplateDeductionResult::CUDATargetMismatch:
13245 return 3;
13246
13247 case TemplateDeductionResult::InstantiationDepth:
13248 return 4;
13249
13250 case TemplateDeductionResult::InvalidExplicitArguments:
13251 return 5;
13252
13253 case TemplateDeductionResult::TooManyArguments:
13254 case TemplateDeductionResult::TooFewArguments:
13255 return 6;
13256 }
13257 llvm_unreachable("Unhandled deduction result");
13258}
13259
13260namespace {
13261
13262struct CompareOverloadCandidatesForDisplay {
13263 Sema &S;
13264 SourceLocation Loc;
13265 size_t NumArgs;
13266 OverloadCandidateSet::CandidateSetKind CSK;
13267
13268 CompareOverloadCandidatesForDisplay(
13269 Sema &S, SourceLocation Loc, size_t NArgs,
13270 OverloadCandidateSet::CandidateSetKind CSK)
13271 : S(S), NumArgs(NArgs), CSK(CSK) {}
13272
13273 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13274 // If there are too many or too few arguments, that's the high-order bit we
13275 // want to sort by, even if the immediate failure kind was something else.
13276 if (C->FailureKind == ovl_fail_too_many_arguments ||
13277 C->FailureKind == ovl_fail_too_few_arguments)
13278 return static_cast<OverloadFailureKind>(C->FailureKind);
13279
13280 if (C->Function) {
13281 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13282 return ovl_fail_too_many_arguments;
13283 if (NumArgs < C->Function->getMinRequiredArguments())
13284 return ovl_fail_too_few_arguments;
13285 }
13286
13287 return static_cast<OverloadFailureKind>(C->FailureKind);
13288 }
13289
13290 bool operator()(const OverloadCandidate *L,
13291 const OverloadCandidate *R) {
13292 // Fast-path this check.
13293 if (L == R) return false;
13294
13295 // Order first by viability.
13296 if (L->Viable) {
13297 if (!R->Viable) return true;
13298
13299 if (int Ord = CompareConversions(L: *L, R: *R))
13300 return Ord < 0;
13301 // Use other tie breakers.
13302 } else if (R->Viable)
13303 return false;
13304
13305 assert(L->Viable == R->Viable);
13306
13307 // Criteria by which we can sort non-viable candidates:
13308 if (!L->Viable) {
13309 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13310 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13311
13312 // 1. Arity mismatches come after other candidates.
13313 if (LFailureKind == ovl_fail_too_many_arguments ||
13314 LFailureKind == ovl_fail_too_few_arguments) {
13315 if (RFailureKind == ovl_fail_too_many_arguments ||
13316 RFailureKind == ovl_fail_too_few_arguments) {
13317 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13318 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13319 if (LDist == RDist) {
13320 if (LFailureKind == RFailureKind)
13321 // Sort non-surrogates before surrogates.
13322 return !L->IsSurrogate && R->IsSurrogate;
13323 // Sort candidates requiring fewer parameters than there were
13324 // arguments given after candidates requiring more parameters
13325 // than there were arguments given.
13326 return LFailureKind == ovl_fail_too_many_arguments;
13327 }
13328 return LDist < RDist;
13329 }
13330 return false;
13331 }
13332 if (RFailureKind == ovl_fail_too_many_arguments ||
13333 RFailureKind == ovl_fail_too_few_arguments)
13334 return true;
13335
13336 // 2. Bad conversions come first and are ordered by the number
13337 // of bad conversions and quality of good conversions.
13338 if (LFailureKind == ovl_fail_bad_conversion) {
13339 if (RFailureKind != ovl_fail_bad_conversion)
13340 return true;
13341
13342 // The conversion that can be fixed with a smaller number of changes,
13343 // comes first.
13344 unsigned numLFixes = L->Fix.NumConversionsFixed;
13345 unsigned numRFixes = R->Fix.NumConversionsFixed;
13346 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13347 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13348 if (numLFixes != numRFixes) {
13349 return numLFixes < numRFixes;
13350 }
13351
13352 // If there's any ordering between the defined conversions...
13353 if (int Ord = CompareConversions(L: *L, R: *R))
13354 return Ord < 0;
13355 } else if (RFailureKind == ovl_fail_bad_conversion)
13356 return false;
13357
13358 if (LFailureKind == ovl_fail_bad_deduction) {
13359 if (RFailureKind != ovl_fail_bad_deduction)
13360 return true;
13361
13362 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13363 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13364 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13365 if (LRank != RRank)
13366 return LRank < RRank;
13367 }
13368 } else if (RFailureKind == ovl_fail_bad_deduction)
13369 return false;
13370
13371 // TODO: others?
13372 }
13373
13374 // Sort everything else by location.
13375 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13376 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13377
13378 // Put candidates without locations (e.g. builtins) at the end.
13379 if (LLoc.isValid() && RLoc.isValid())
13380 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13381 if (LLoc.isValid() && !RLoc.isValid())
13382 return true;
13383 if (RLoc.isValid() && !LLoc.isValid())
13384 return false;
13385 assert(!LLoc.isValid() && !RLoc.isValid());
13386 // For builtins and other functions without locations, fallback to the order
13387 // in which they were added into the candidate set.
13388 return L < R;
13389 }
13390
13391private:
13392 struct ConversionSignals {
13393 unsigned KindRank = 0;
13394 ImplicitConversionRank Rank = ICR_Exact_Match;
13395
13396 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13397 ConversionSignals Sig;
13398 Sig.KindRank = Seq.getKindRank();
13399 if (Seq.isStandard())
13400 Sig.Rank = Seq.Standard.getRank();
13401 else if (Seq.isUserDefined())
13402 Sig.Rank = Seq.UserDefined.After.getRank();
13403 // We intend StaticObjectArgumentConversion to compare the same as
13404 // StandardConversion with ICR_ExactMatch rank.
13405 return Sig;
13406 }
13407
13408 static ConversionSignals ForObjectArgument() {
13409 // We intend StaticObjectArgumentConversion to compare the same as
13410 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13411 return {};
13412 }
13413 };
13414
13415 // Returns -1 if conversions in L are considered better.
13416 // 0 if they are considered indistinguishable.
13417 // 1 if conversions in R are better.
13418 int CompareConversions(const OverloadCandidate &L,
13419 const OverloadCandidate &R) {
13420 // We cannot use `isBetterOverloadCandidate` because it is defined
13421 // according to the C++ standard and provides a partial order, but we need
13422 // a total order as this function is used in sort.
13423 assert(L.Conversions.size() == R.Conversions.size());
13424 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13425 auto LS = L.IgnoreObjectArgument && I == 0
13426 ? ConversionSignals::ForObjectArgument()
13427 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13428 auto RS = R.IgnoreObjectArgument
13429 ? ConversionSignals::ForObjectArgument()
13430 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13431 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13432 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13433 ? -1
13434 : 1;
13435 }
13436 // FIXME: find a way to compare templates for being more or less
13437 // specialized that provides a strict weak ordering.
13438 return 0;
13439 }
13440};
13441}
13442
13443/// CompleteNonViableCandidate - Normally, overload resolution only
13444/// computes up to the first bad conversion. Produces the FixIt set if
13445/// possible.
13446static void
13447CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13448 ArrayRef<Expr *> Args,
13449 OverloadCandidateSet::CandidateSetKind CSK) {
13450 assert(!Cand->Viable);
13451
13452 // Don't do anything on failures other than bad conversion.
13453 if (Cand->FailureKind != ovl_fail_bad_conversion)
13454 return;
13455
13456 // We only want the FixIts if all the arguments can be corrected.
13457 bool Unfixable = false;
13458 // Use a implicit copy initialization to check conversion fixes.
13459 Cand->Fix.setConversionChecker(TryCopyInitialization);
13460
13461 // Attempt to fix the bad conversion.
13462 unsigned ConvCount = Cand->Conversions.size();
13463 for (unsigned ConvIdx =
13464 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13465 : 0);
13466 /**/; ++ConvIdx) {
13467 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13468 if (Cand->Conversions[ConvIdx].isInitialized() &&
13469 Cand->Conversions[ConvIdx].isBad()) {
13470 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13471 break;
13472 }
13473 }
13474
13475 // FIXME: this should probably be preserved from the overload
13476 // operation somehow.
13477 bool SuppressUserConversions = false;
13478
13479 unsigned ConvIdx = 0;
13480 unsigned ArgIdx = 0;
13481 ArrayRef<QualType> ParamTypes;
13482 bool Reversed = Cand->isReversed();
13483
13484 if (Cand->IsSurrogate) {
13485 QualType ConvType
13486 = Cand->Surrogate->getConversionType().getNonReferenceType();
13487 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13488 ConvType = ConvPtrType->getPointeeType();
13489 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13490 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13491 ConvIdx = 1;
13492 } else if (Cand->Function) {
13493 ParamTypes =
13494 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13495 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13496 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13497 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13498 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13499 ConvIdx = 1;
13500 if (CSK == OverloadCandidateSet::CSK_Operator &&
13501 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13502 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13503 OO_Subscript)
13504 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13505 ArgIdx = 1;
13506 }
13507 } else {
13508 // Builtin operator.
13509 assert(ConvCount <= 3);
13510 ParamTypes = Cand->BuiltinParamTypes;
13511 }
13512
13513 // Fill in the rest of the conversions.
13514 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13515 ConvIdx != ConvCount && ArgIdx < Args.size();
13516 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13517 if (Cand->Conversions[ConvIdx].isInitialized()) {
13518 // We've already checked this conversion.
13519 } else if (ParamIdx < ParamTypes.size()) {
13520 if (ParamTypes[ParamIdx]->isDependentType())
13521 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13522 Args[ArgIdx]->getType());
13523 else {
13524 Cand->Conversions[ConvIdx] =
13525 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13526 SuppressUserConversions,
13527 /*InOverloadResolution=*/true,
13528 /*AllowObjCWritebackConversion=*/
13529 S.getLangOpts().ObjCAutoRefCount);
13530 // Store the FixIt in the candidate if it exists.
13531 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13532 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13533 }
13534 } else
13535 Cand->Conversions[ConvIdx].setEllipsis();
13536 }
13537}
13538
13539SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13540 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13541 SourceLocation OpLoc,
13542 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13543
13544 InjectNonDeducedTemplateCandidates(S);
13545
13546 // Sort the candidates by viability and position. Sorting directly would
13547 // be prohibitive, so we make a set of pointers and sort those.
13548 SmallVector<OverloadCandidate*, 32> Cands;
13549 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13550 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13551 Cand != LastCand; ++Cand) {
13552 if (!Filter(*Cand))
13553 continue;
13554 switch (OCD) {
13555 case OCD_AllCandidates:
13556 if (!Cand->Viable) {
13557 if (!Cand->Function && !Cand->IsSurrogate) {
13558 // This a non-viable builtin candidate. We do not, in general,
13559 // want to list every possible builtin candidate.
13560 continue;
13561 }
13562 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13563 }
13564 break;
13565
13566 case OCD_ViableCandidates:
13567 if (!Cand->Viable)
13568 continue;
13569 break;
13570
13571 case OCD_AmbiguousCandidates:
13572 if (!Cand->Best)
13573 continue;
13574 break;
13575 }
13576
13577 Cands.push_back(Elt: Cand);
13578 }
13579
13580 llvm::stable_sort(
13581 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13582
13583 return Cands;
13584}
13585
13586bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13587 SourceLocation OpLoc) {
13588 bool DeferHint = false;
13589 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13590 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13591 // host device candidates.
13592 auto WrongSidedCands =
13593 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13594 return (Cand.Viable == false &&
13595 Cand.FailureKind == ovl_fail_bad_target) ||
13596 (Cand.Function &&
13597 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13598 Cand.Function->template hasAttr<CUDADeviceAttr>());
13599 });
13600 DeferHint = !WrongSidedCands.empty();
13601 }
13602 return DeferHint;
13603}
13604
13605/// When overload resolution fails, prints diagnostic messages containing the
13606/// candidates in the candidate set.
13607void OverloadCandidateSet::NoteCandidates(
13608 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13609 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13610 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13611
13612 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13613
13614 {
13615 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13616 S.Diag(Loc: PD.first, PD: PD.second);
13617 }
13618
13619 // In WebAssembly we don't want to emit further diagnostics if a table is
13620 // passed as an argument to a function.
13621 bool NoteCands = true;
13622 for (const Expr *Arg : Args) {
13623 if (Arg->getType()->isWebAssemblyTableType())
13624 NoteCands = false;
13625 }
13626
13627 if (NoteCands)
13628 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13629
13630 if (OCD == OCD_AmbiguousCandidates)
13631 MaybeDiagnoseAmbiguousConstraints(S,
13632 Cands: {Candidates.begin(), Candidates.end()});
13633}
13634
13635void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13636 ArrayRef<OverloadCandidate *> Cands,
13637 StringRef Opc, SourceLocation OpLoc) {
13638 bool ReportedAmbiguousConversions = false;
13639
13640 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13641 unsigned CandsShown = 0;
13642 auto I = Cands.begin(), E = Cands.end();
13643 for (; I != E; ++I) {
13644 OverloadCandidate *Cand = *I;
13645
13646 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13647 ShowOverloads == Ovl_Best) {
13648 break;
13649 }
13650 ++CandsShown;
13651
13652 if (Cand->Function)
13653 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13654 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13655 else if (Cand->IsSurrogate)
13656 NoteSurrogateCandidate(S, Cand);
13657 else {
13658 assert(Cand->Viable &&
13659 "Non-viable built-in candidates are not added to Cands.");
13660 // Generally we only see ambiguities including viable builtin
13661 // operators if overload resolution got screwed up by an
13662 // ambiguous user-defined conversion.
13663 //
13664 // FIXME: It's quite possible for different conversions to see
13665 // different ambiguities, though.
13666 if (!ReportedAmbiguousConversions) {
13667 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13668 ReportedAmbiguousConversions = true;
13669 }
13670
13671 // If this is a viable builtin, print it.
13672 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13673 }
13674 }
13675
13676 // Inform S.Diags that we've shown an overload set with N elements. This may
13677 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13678 S.Diags.overloadCandidatesShown(N: CandsShown);
13679
13680 if (I != E) {
13681 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13682 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13683 }
13684}
13685
13686bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
13687 const Sema &S) const {
13688 if (S.getLangOpts().CUDA) {
13689 auto *Caller = S.getCurFunctionDecl(AllowLambda: true);
13690 // Overloading based on __host__ and __device__ attributes takes
13691 // higher priority, HD functions may favor template candidates even when a
13692 // non-template candidate would be a perfect match.
13693 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13694 Caller->hasAttr<CUDADeviceAttr>())
13695 return false;
13696 }
13697
13698 return
13699 // For user defined conversion we need to check against different
13700 // combination of CV qualifiers and look at any explicit specifier, so
13701 // always deduce template candidates.
13702 Kind != CSK_InitByUserDefinedConversion
13703 // When doing code completion, we want to see all the
13704 // viable candidates.
13705 && Kind != CSK_CodeCompletion;
13706}
13707
13708static SourceLocation
13709GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13710 return Cand->Specialization ? Cand->Specialization->getLocation()
13711 : SourceLocation();
13712}
13713
13714namespace {
13715struct CompareTemplateSpecCandidatesForDisplay {
13716 Sema &S;
13717 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13718
13719 bool operator()(const TemplateSpecCandidate *L,
13720 const TemplateSpecCandidate *R) {
13721 // Fast-path this check.
13722 if (L == R)
13723 return false;
13724
13725 // Assuming that both candidates are not matches...
13726
13727 // Sort by the ranking of deduction failures.
13728 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13729 return RankDeductionFailure(DFI: L->DeductionFailure) <
13730 RankDeductionFailure(DFI: R->DeductionFailure);
13731
13732 // Sort everything else by location.
13733 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13734 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13735
13736 // Put candidates without locations (e.g. builtins) at the end.
13737 if (LLoc.isInvalid())
13738 return false;
13739 if (RLoc.isInvalid())
13740 return true;
13741
13742 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13743 }
13744};
13745}
13746
13747/// Diagnose a template argument deduction failure.
13748/// We are treating these failures as overload failures due to bad
13749/// deductions.
13750void TemplateSpecCandidate::NoteDeductionFailure(
13751 Sema &S, bool ForTakingAddress,
13752 TemplateSpecCandidateSetKind CandidateSetKind) {
13753 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13754 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress,
13755 CandidateSetKind);
13756}
13757
13758void TemplateSpecCandidateSet::destroyCandidates() {
13759 for (iterator i = begin(), e = end(); i != e; ++i) {
13760 i->DeductionFailure.Destroy();
13761 }
13762}
13763
13764void TemplateSpecCandidateSet::clear() {
13765 destroyCandidates();
13766 Candidates.clear();
13767}
13768
13769/// NoteCandidates - When no template specialization match is found, prints
13770/// diagnostic messages containing the non-matching specializations that form
13771/// the candidate set.
13772/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13773/// OCD == OCD_AllCandidates and Cand->Viable == false.
13774void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13775 // Sort the candidates by position (assuming no candidate is a match).
13776 // Sorting directly would be prohibitive, so we make a set of pointers
13777 // and sort those.
13778 SmallVector<TemplateSpecCandidate *, 32> Cands;
13779 Cands.reserve(N: size());
13780 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13781 if (Cand->Specialization)
13782 Cands.push_back(Elt: Cand);
13783 // Otherwise, this is a non-matching builtin candidate. We do not,
13784 // in general, want to list every possible builtin candidate.
13785 }
13786
13787 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13788
13789 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13790 // for generalization purposes (?).
13791 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13792
13793 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13794 unsigned CandsShown = 0;
13795 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13796 TemplateSpecCandidate *Cand = *I;
13797
13798 // Set an arbitrary limit on the number of candidates we'll spam
13799 // the user with. FIXME: This limit should depend on details of the
13800 // candidate list.
13801 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13802 break;
13803 ++CandsShown;
13804
13805 assert(Cand->Specialization &&
13806 "Non-matching built-in candidates are not added to Cands.");
13807 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13808 }
13809
13810 if (I != E)
13811 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13812}
13813
13814// [PossiblyAFunctionType] --> [Return]
13815// NonFunctionType --> NonFunctionType
13816// R (A) --> R(A)
13817// R (*)(A) --> R (A)
13818// R (&)(A) --> R (A)
13819// R (S::*)(A) --> R (A)
13820QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13821 QualType Ret = PossiblyAFunctionType;
13822 if (const PointerType *ToTypePtr =
13823 PossiblyAFunctionType->getAs<PointerType>())
13824 Ret = ToTypePtr->getPointeeType();
13825 else if (const ReferenceType *ToTypeRef =
13826 PossiblyAFunctionType->getAs<ReferenceType>())
13827 Ret = ToTypeRef->getPointeeType();
13828 else if (const MemberPointerType *MemTypePtr =
13829 PossiblyAFunctionType->getAs<MemberPointerType>())
13830 Ret = MemTypePtr->getPointeeType();
13831 Ret =
13832 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13833 return Ret;
13834}
13835
13836static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13837 bool Complain = true) {
13838 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13839 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13840 return true;
13841
13842 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13843 if (S.getLangOpts().CPlusPlus17 &&
13844 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13845 !S.ResolveExceptionSpec(Loc, FPT))
13846 return true;
13847
13848 return false;
13849}
13850
13851namespace {
13852// A helper class to help with address of function resolution
13853// - allows us to avoid passing around all those ugly parameters
13854class AddressOfFunctionResolver {
13855 Sema& S;
13856 Expr* SourceExpr;
13857 const QualType& TargetType;
13858 QualType TargetFunctionType; // Extracted function type from target type
13859
13860 bool Complain;
13861 //DeclAccessPair& ResultFunctionAccessPair;
13862 ASTContext& Context;
13863
13864 bool TargetTypeIsNonStaticMemberFunction;
13865 bool FoundNonTemplateFunction;
13866 bool StaticMemberFunctionFromBoundPointer;
13867 bool HasComplained;
13868
13869 OverloadExpr::FindResult OvlExprInfo;
13870 OverloadExpr *OvlExpr;
13871 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13872 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13873 TemplateSpecCandidateSet FailedCandidates;
13874
13875public:
13876 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13877 const QualType &TargetType, bool Complain)
13878 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13879 Complain(Complain), Context(S.getASTContext()),
13880 TargetTypeIsNonStaticMemberFunction(
13881 !!TargetType->getAs<MemberPointerType>()),
13882 FoundNonTemplateFunction(false),
13883 StaticMemberFunctionFromBoundPointer(false),
13884 HasComplained(false),
13885 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13886 OvlExpr(OvlExprInfo.Expression),
13887 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13888 ExtractUnqualifiedFunctionTypeFromTargetType();
13889
13890 if (TargetFunctionType->isFunctionType()) {
13891 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13892 if (!UME->isImplicitAccess() &&
13893 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13894 StaticMemberFunctionFromBoundPointer = true;
13895 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13896 DeclAccessPair dap;
13897 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13898 ovl: OvlExpr, Complain: false, Found: &dap)) {
13899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13900 if (!Method->isStatic()) {
13901 // If the target type is a non-function type and the function found
13902 // is a non-static member function, pretend as if that was the
13903 // target, it's the only possible type to end up with.
13904 TargetTypeIsNonStaticMemberFunction = true;
13905
13906 // And skip adding the function if its not in the proper form.
13907 // We'll diagnose this due to an empty set of functions.
13908 if (!OvlExprInfo.HasFormOfMemberPointer)
13909 return;
13910 }
13911
13912 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13913 }
13914 return;
13915 }
13916
13917 if (OvlExpr->hasExplicitTemplateArgs())
13918 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13919
13920 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13921 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13922 EliminateSuboptimalCudaMatches();
13923
13924 // C++ [over.over]p4:
13925 // If more than one function is selected, [...]
13926 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13927 if (FoundNonTemplateFunction) {
13928 EliminateAllTemplateMatches();
13929 EliminateLessPartialOrderingConstrainedMatches();
13930 } else
13931 EliminateAllExceptMostSpecializedTemplate();
13932 }
13933 }
13934 }
13935
13936 bool hasComplained() const { return HasComplained; }
13937
13938private:
13939 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13940 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13941 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13942 }
13943
13944 /// \return true if A is considered a better overload candidate for the
13945 /// desired type than B.
13946 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13947 // If A doesn't have exactly the correct type, we don't want to classify it
13948 // as "better" than anything else. This way, the user is required to
13949 // disambiguate for us if there are multiple candidates and no exact match.
13950 return candidateHasExactlyCorrectType(FD: A) &&
13951 (!candidateHasExactlyCorrectType(FD: B) ||
13952 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13953 }
13954
13955 /// \return true if we were able to eliminate all but one overload candidate,
13956 /// false otherwise.
13957 bool eliminiateSuboptimalOverloadCandidates() {
13958 // Same algorithm as overload resolution -- one pass to pick the "best",
13959 // another pass to be sure that nothing is better than the best.
13960 auto Best = Matches.begin();
13961 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13962 if (isBetterCandidate(A: I->second, B: Best->second))
13963 Best = I;
13964
13965 const FunctionDecl *BestFn = Best->second;
13966 auto IsBestOrInferiorToBest = [this, BestFn](
13967 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13968 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13969 };
13970
13971 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13972 // option, so we can potentially give the user a better error
13973 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13974 return false;
13975 Matches[0] = *Best;
13976 Matches.resize(N: 1);
13977 return true;
13978 }
13979
13980 bool isTargetTypeAFunction() const {
13981 return TargetFunctionType->isFunctionType();
13982 }
13983
13984 // [ToType] [Return]
13985
13986 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13987 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13988 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13989 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13990 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13991 }
13992
13993 // return true if any matching specializations were found
13994 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13995 const DeclAccessPair& CurAccessFunPair) {
13996 if (CXXMethodDecl *Method
13997 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13998 // Skip non-static function templates when converting to pointer, and
13999 // static when converting to member pointer.
14000 bool CanConvertToFunctionPointer =
14001 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14002 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14003 return false;
14004 }
14005 else if (TargetTypeIsNonStaticMemberFunction)
14006 return false;
14007
14008 // C++ [over.over]p2:
14009 // If the name is a function template, template argument deduction is
14010 // done (14.8.2.2), and if the argument deduction succeeds, the
14011 // resulting template argument list is used to generate a single
14012 // function template specialization, which is added to the set of
14013 // overloaded functions considered.
14014 FunctionDecl *Specialization = nullptr;
14015 TemplateDeductionInfo Info(FailedCandidates.getLocation());
14016 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
14017 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
14018 Specialization, Info, /*IsAddressOfFunction*/ true);
14019 Result != TemplateDeductionResult::Success) {
14020 // Make a note of the failed deduction for diagnostics.
14021 FailedCandidates.addCandidate()
14022 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
14023 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14024 return false;
14025 }
14026
14027 // Template argument deduction ensures that we have an exact match or
14028 // compatible pointer-to-function arguments that would be adjusted by ICS.
14029 // This function template specicalization works.
14030 assert(S.isSameOrCompatibleFunctionType(
14031 Context.getCanonicalType(Specialization->getType()),
14032 Context.getCanonicalType(TargetFunctionType)));
14033
14034 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
14035 return false;
14036
14037 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
14038 return true;
14039 }
14040
14041 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
14042 const DeclAccessPair& CurAccessFunPair) {
14043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
14044 // Skip non-static functions when converting to pointer, and static
14045 // when converting to member pointer.
14046 bool CanConvertToFunctionPointer =
14047 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14048 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14049 return false;
14050 }
14051 else if (TargetTypeIsNonStaticMemberFunction)
14052 return false;
14053
14054 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
14055 if (S.getLangOpts().CUDA) {
14056 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
14057 if (!(Caller && Caller->isImplicit()) &&
14058 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
14059 return false;
14060 }
14061 if (FunDecl->isMultiVersion()) {
14062 const auto *TA = FunDecl->getAttr<TargetAttr>();
14063 if (TA && !TA->isDefaultVersion())
14064 return false;
14065 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
14066 if (TVA && !TVA->isDefaultVersion())
14067 return false;
14068 }
14069
14070 // If any candidate has a placeholder return type, trigger its deduction
14071 // now.
14072 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
14073 Complain)) {
14074 HasComplained |= Complain;
14075 return false;
14076 }
14077
14078 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
14079 return false;
14080
14081 // If we're in C, we need to support types that aren't exactly identical.
14082 if (!S.getLangOpts().CPlusPlus ||
14083 candidateHasExactlyCorrectType(FD: FunDecl)) {
14084 Matches.push_back(Elt: std::make_pair(
14085 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
14086 FoundNonTemplateFunction = true;
14087 return true;
14088 }
14089 }
14090
14091 return false;
14092 }
14093
14094 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14095 bool Ret = false;
14096
14097 // If the overload expression doesn't have the form of a pointer to
14098 // member, don't try to convert it to a pointer-to-member type.
14099 if (IsInvalidFormOfPointerToMemberFunction())
14100 return false;
14101
14102 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14103 E = OvlExpr->decls_end();
14104 I != E; ++I) {
14105 // Look through any using declarations to find the underlying function.
14106 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14107
14108 // C++ [over.over]p3:
14109 // Non-member functions and static member functions match
14110 // targets of type "pointer-to-function" or "reference-to-function."
14111 // Nonstatic member functions match targets of
14112 // type "pointer-to-member-function."
14113 // Note that according to DR 247, the containing class does not matter.
14114 if (FunctionTemplateDecl *FunctionTemplate
14115 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
14116 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
14117 Ret = true;
14118 }
14119 // If we have explicit template arguments supplied, skip non-templates.
14120 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14121 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
14122 Ret = true;
14123 }
14124 assert(Ret || Matches.empty());
14125 return Ret;
14126 }
14127
14128 void EliminateAllExceptMostSpecializedTemplate() {
14129 // [...] and any given function template specialization F1 is
14130 // eliminated if the set contains a second function template
14131 // specialization whose function template is more specialized
14132 // than the function template of F1 according to the partial
14133 // ordering rules of 14.5.5.2.
14134
14135 // The algorithm specified above is quadratic. We instead use a
14136 // two-pass algorithm (similar to the one used to identify the
14137 // best viable function in an overload set) that identifies the
14138 // best function template (if it exists).
14139
14140 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14141 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14142 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
14143
14144 // TODO: It looks like FailedCandidates does not serve much purpose
14145 // here, since the no_viable diagnostic has index 0.
14146 UnresolvedSetIterator Result = S.getMostSpecialized(
14147 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
14148 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
14149 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
14150 << Matches[0].second->getDeclName(),
14151 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
14152 << (unsigned)oc_function << (unsigned)ocs_described_template,
14153 Complain, TargetType: TargetFunctionType);
14154
14155 if (Result != MatchesCopy.end()) {
14156 // Make it the first and only element
14157 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14158 Matches[0].second = cast<FunctionDecl>(Val: *Result);
14159 Matches.resize(N: 1);
14160 } else
14161 HasComplained |= Complain;
14162 }
14163
14164 void EliminateAllTemplateMatches() {
14165 // [...] any function template specializations in the set are
14166 // eliminated if the set also contains a non-template function, [...]
14167 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14168 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14169 ++I;
14170 else {
14171 Matches[I] = Matches[--N];
14172 Matches.resize(N);
14173 }
14174 }
14175 }
14176
14177 void EliminateLessPartialOrderingConstrainedMatches() {
14178 // C++ [over.over]p5:
14179 // [...] Any given non-template function F0 is eliminated if the set
14180 // contains a second non-template function that is more
14181 // partial-ordering-constrained than F0. [...]
14182 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14183 "Call EliminateAllTemplateMatches() first");
14184 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14185 Results.push_back(Elt: Matches[0]);
14186 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14187 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14188 FunctionDecl *F = getMorePartialOrderingConstrained(
14189 S, Fn1: Matches[I].second, Fn2: Results[0].second,
14190 /*IsFn1Reversed=*/false,
14191 /*IsFn2Reversed=*/false);
14192 if (!F) {
14193 Results.push_back(Elt: Matches[I]);
14194 continue;
14195 }
14196 if (F == Matches[I].second) {
14197 Results.clear();
14198 Results.push_back(Elt: Matches[I]);
14199 }
14200 }
14201 std::swap(LHS&: Matches, RHS&: Results);
14202 }
14203
14204 void EliminateSuboptimalCudaMatches() {
14205 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14206 Matches);
14207 }
14208
14209public:
14210 void ComplainNoMatchesFound() const {
14211 assert(Matches.empty());
14212 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14213 << OvlExpr->getName() << TargetFunctionType
14214 << OvlExpr->getSourceRange();
14215 if (FailedCandidates.empty())
14216 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14217 /*TakingAddress=*/true);
14218 else {
14219 // We have some deduction failure messages. Use them to diagnose
14220 // the function templates, and diagnose the non-template candidates
14221 // normally.
14222 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14223 IEnd = OvlExpr->decls_end();
14224 I != IEnd; ++I)
14225 if (FunctionDecl *Fun =
14226 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14227 if (!functionHasPassObjectSizeParams(FD: Fun))
14228 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14229 /*TakingAddress=*/true);
14230 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14231 }
14232 }
14233
14234 bool IsInvalidFormOfPointerToMemberFunction() const {
14235 return TargetTypeIsNonStaticMemberFunction &&
14236 !OvlExprInfo.HasFormOfMemberPointer;
14237 }
14238
14239 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14240 // TODO: Should we condition this on whether any functions might
14241 // have matched, or is it more appropriate to do that in callers?
14242 // TODO: a fixit wouldn't hurt.
14243 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14244 << TargetType << OvlExpr->getSourceRange();
14245 }
14246
14247 bool IsStaticMemberFunctionFromBoundPointer() const {
14248 return StaticMemberFunctionFromBoundPointer;
14249 }
14250
14251 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14252 S.Diag(Loc: OvlExpr->getBeginLoc(),
14253 DiagID: diag::err_invalid_form_pointer_member_function)
14254 << OvlExpr->getSourceRange();
14255 }
14256
14257 void ComplainOfInvalidConversion() const {
14258 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14259 << OvlExpr->getName() << TargetType;
14260 }
14261
14262 void ComplainMultipleMatchesFound() const {
14263 assert(Matches.size() > 1);
14264 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14265 << OvlExpr->getName() << OvlExpr->getSourceRange();
14266 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14267 /*TakingAddress=*/true);
14268 }
14269
14270 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14271
14272 int getNumMatches() const { return Matches.size(); }
14273
14274 FunctionDecl* getMatchingFunctionDecl() const {
14275 if (Matches.size() != 1) return nullptr;
14276 return Matches[0].second;
14277 }
14278
14279 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14280 if (Matches.size() != 1) return nullptr;
14281 return &Matches[0].first;
14282 }
14283};
14284}
14285
14286FunctionDecl *
14287Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14288 QualType TargetType,
14289 bool Complain,
14290 DeclAccessPair &FoundResult,
14291 bool *pHadMultipleCandidates) {
14292 assert(AddressOfExpr->getType() == Context.OverloadTy);
14293
14294 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14295 Complain);
14296 int NumMatches = Resolver.getNumMatches();
14297 FunctionDecl *Fn = nullptr;
14298 bool ShouldComplain = Complain && !Resolver.hasComplained();
14299 if (NumMatches == 0 && ShouldComplain) {
14300 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14301 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14302 else
14303 Resolver.ComplainNoMatchesFound();
14304 }
14305 else if (NumMatches > 1 && ShouldComplain)
14306 Resolver.ComplainMultipleMatchesFound();
14307 else if (NumMatches == 1) {
14308 Fn = Resolver.getMatchingFunctionDecl();
14309 assert(Fn);
14310 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14311 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14312 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14313 if (Complain) {
14314 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14315 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14316 else
14317 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14318 }
14319 }
14320
14321 if (pHadMultipleCandidates)
14322 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14323 return Fn;
14324}
14325
14326FunctionDecl *
14327Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14328 OverloadExpr::FindResult R = OverloadExpr::find(E);
14329 OverloadExpr *Ovl = R.Expression;
14330 bool IsResultAmbiguous = false;
14331 FunctionDecl *Result = nullptr;
14332 DeclAccessPair DAP;
14333 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14334
14335 // Return positive for better, negative for worse, 0 for equal preference.
14336 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14337 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14338 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14339 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14340 };
14341
14342 // Don't use the AddressOfResolver because we're specifically looking for
14343 // cases where we have one overload candidate that lacks
14344 // enable_if/pass_object_size/...
14345 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14346 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14347 if (!FD)
14348 return nullptr;
14349
14350 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14351 continue;
14352
14353 // If we found a better result, update Result.
14354 auto FoundBetter = [&]() {
14355 IsResultAmbiguous = false;
14356 DAP = I.getPair();
14357 Result = FD;
14358 };
14359
14360 // We have more than one result - see if it is more
14361 // partial-ordering-constrained than the previous one.
14362 if (Result) {
14363 // Check CUDA preference first. If the candidates have differennt CUDA
14364 // preference, choose the one with higher CUDA preference. Otherwise,
14365 // choose the one with more constraints.
14366 if (getLangOpts().CUDA) {
14367 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14368 // FD has different preference than Result.
14369 if (PreferenceByCUDA != 0) {
14370 // FD is more preferable than Result.
14371 if (PreferenceByCUDA > 0)
14372 FoundBetter();
14373 continue;
14374 }
14375 }
14376 // FD has the same CUDA preference than Result. Continue to check
14377 // constraints.
14378
14379 // C++ [over.over]p5:
14380 // [...] If more than one function in the set remains, all function
14381 // template specializations in the set are eliminated if the set also
14382 // contains a function that is not a function template specialization.
14383 // [...]
14384 if (Result->isFunctionTemplateSpecialization() !=
14385 FD->isFunctionTemplateSpecialization()) {
14386 if (!FD->isFunctionTemplateSpecialization())
14387 FoundBetter();
14388 continue;
14389 }
14390
14391 // C++ [over.over]p5:
14392 // [...] Any given non-template function F0 is eliminated if the set
14393 // contains a second non-template function that is more
14394 // partial-ordering-constrained than F0 [...]
14395 FunctionDecl *MoreConstrained =
14396 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14397 /*IsFn1Reversed=*/false,
14398 /*IsFn2Reversed=*/false);
14399 if (MoreConstrained != FD) {
14400 if (!MoreConstrained) {
14401 IsResultAmbiguous = true;
14402 AmbiguousDecls.push_back(Elt: FD);
14403 }
14404 continue;
14405 }
14406 // FD is more constrained - replace Result with it.
14407 }
14408 FoundBetter();
14409 }
14410
14411 if (IsResultAmbiguous)
14412 return nullptr;
14413
14414 if (Result) {
14415 // We skipped over some ambiguous declarations which might be ambiguous with
14416 // the selected result.
14417 for (FunctionDecl *Skipped : AmbiguousDecls) {
14418 // If skipped candidate has different CUDA preference than the result,
14419 // there is no ambiguity. Otherwise check whether they have different
14420 // constraints.
14421 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14422 continue;
14423 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14424 return nullptr;
14425 }
14426 Pair = DAP;
14427 }
14428 return Result;
14429}
14430
14431bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14432 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14433 Expr *E = SrcExpr.get();
14434 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14435
14436 DeclAccessPair DAP;
14437 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14438 if (!Found || Found->isCPUDispatchMultiVersion() ||
14439 Found->isCPUSpecificMultiVersion())
14440 return false;
14441
14442 // Emitting multiple diagnostics for a function that is both inaccessible and
14443 // unavailable is consistent with our behavior elsewhere. So, always check
14444 // for both.
14445 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14446 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14447 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14448 if (Res.isInvalid())
14449 return false;
14450 Expr *Fixed = Res.get();
14451 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14452 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14453 else
14454 SrcExpr = Fixed;
14455 return true;
14456}
14457
14458FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14459 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14460 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14461 // C++ [over.over]p1:
14462 // [...] [Note: any redundant set of parentheses surrounding the
14463 // overloaded function name is ignored (5.1). ]
14464 // C++ [over.over]p1:
14465 // [...] The overloaded function name can be preceded by the &
14466 // operator.
14467
14468 // If we didn't actually find any template-ids, we're done.
14469 if (!ovl->hasExplicitTemplateArgs())
14470 return nullptr;
14471
14472 TemplateArgumentListInfo ExplicitTemplateArgs;
14473 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14474
14475 // Look through all of the overloaded functions, searching for one
14476 // whose type matches exactly.
14477 FunctionDecl *Matched = nullptr;
14478 for (UnresolvedSetIterator I = ovl->decls_begin(),
14479 E = ovl->decls_end(); I != E; ++I) {
14480 // C++0x [temp.arg.explicit]p3:
14481 // [...] In contexts where deduction is done and fails, or in contexts
14482 // where deduction is not done, if a template argument list is
14483 // specified and it, along with any default template arguments,
14484 // identifies a single function template specialization, then the
14485 // template-id is an lvalue for the function template specialization.
14486 FunctionTemplateDecl *FunctionTemplate =
14487 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14488 if (!FunctionTemplate)
14489 continue;
14490
14491 // C++ [over.over]p2:
14492 // If the name is a function template, template argument deduction is
14493 // done (14.8.2.2), and if the argument deduction succeeds, the
14494 // resulting template argument list is used to generate a single
14495 // function template specialization, which is added to the set of
14496 // overloaded functions considered.
14497 FunctionDecl *Specialization = nullptr;
14498 TemplateDeductionInfo Info(ovl->getNameLoc());
14499 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14500 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14501 /*IsAddressOfFunction*/ true);
14502 Result != TemplateDeductionResult::Success) {
14503 // Make a note of the failed deduction for diagnostics.
14504 if (FailedTSC)
14505 FailedTSC->addCandidate().set(
14506 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14507 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14508 continue;
14509 }
14510
14511 assert(Specialization && "no specialization and no error?");
14512
14513 // C++ [temp.deduct.call]p6:
14514 // [...] If all successful deductions yield the same deduced A, that
14515 // deduced A is the result of deduction; otherwise, the parameter is
14516 // treated as a non-deduced context.
14517 if (Matched) {
14518 if (ForTypeDeduction &&
14519 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14520 Arg: Specialization->getType()))
14521 continue;
14522 // Multiple matches; we can't resolve to a single declaration.
14523 if (Complain) {
14524 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14525 << ovl->getName();
14526 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14527 }
14528 return nullptr;
14529 }
14530
14531 Matched = Specialization;
14532 if (FoundResult) *FoundResult = I.getPair();
14533 }
14534
14535 if (Matched &&
14536 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14537 return nullptr;
14538
14539 return Matched;
14540}
14541
14542bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14543 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14544 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14545 unsigned DiagIDForComplaining) {
14546 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14547
14548 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14549
14550 DeclAccessPair found;
14551 ExprResult SingleFunctionExpression;
14552 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14553 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14554 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14555 SrcExpr = ExprError();
14556 return true;
14557 }
14558
14559 // It is only correct to resolve to an instance method if we're
14560 // resolving a form that's permitted to be a pointer to member.
14561 // Otherwise we'll end up making a bound member expression, which
14562 // is illegal in all the contexts we resolve like this.
14563 if (!ovl.HasFormOfMemberPointer &&
14564 isa<CXXMethodDecl>(Val: fn) &&
14565 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14566 if (!complain) return false;
14567
14568 Diag(Loc: ovl.Expression->getExprLoc(),
14569 DiagID: diag::err_bound_member_function)
14570 << 0 << ovl.Expression->getSourceRange();
14571
14572 // TODO: I believe we only end up here if there's a mix of
14573 // static and non-static candidates (otherwise the expression
14574 // would have 'bound member' type, not 'overload' type).
14575 // Ideally we would note which candidate was chosen and why
14576 // the static candidates were rejected.
14577 SrcExpr = ExprError();
14578 return true;
14579 }
14580
14581 // Fix the expression to refer to 'fn'.
14582 SingleFunctionExpression =
14583 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14584
14585 // If desired, do function-to-pointer decay.
14586 if (doFunctionPointerConversion) {
14587 SingleFunctionExpression =
14588 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14589 if (SingleFunctionExpression.isInvalid()) {
14590 SrcExpr = ExprError();
14591 return true;
14592 }
14593 }
14594 }
14595
14596 if (!SingleFunctionExpression.isUsable()) {
14597 if (complain) {
14598 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14599 << ovl.Expression->getName()
14600 << DestTypeForComplaining
14601 << OpRangeForComplaining
14602 << ovl.Expression->getQualifierLoc().getSourceRange();
14603 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14604
14605 SrcExpr = ExprError();
14606 return true;
14607 }
14608
14609 return false;
14610 }
14611
14612 SrcExpr = SingleFunctionExpression;
14613 return true;
14614}
14615
14616/// Add a single candidate to the overload set.
14617static void AddOverloadedCallCandidate(Sema &S,
14618 DeclAccessPair FoundDecl,
14619 TemplateArgumentListInfo *ExplicitTemplateArgs,
14620 ArrayRef<Expr *> Args,
14621 OverloadCandidateSet &CandidateSet,
14622 bool PartialOverloading,
14623 bool KnownValid) {
14624 NamedDecl *Callee = FoundDecl.getDecl();
14625 if (isa<UsingShadowDecl>(Val: Callee))
14626 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14627
14628 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14629 if (ExplicitTemplateArgs) {
14630 assert(!KnownValid && "Explicit template arguments?");
14631 return;
14632 }
14633 // Prevent ill-formed function decls to be added as overload candidates.
14634 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14635 return;
14636
14637 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14638 /*SuppressUserConversions=*/false,
14639 PartialOverloading);
14640 return;
14641 }
14642
14643 if (FunctionTemplateDecl *FuncTemplate
14644 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14645 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14646 ExplicitTemplateArgs, Args, CandidateSet,
14647 /*SuppressUserConversions=*/false,
14648 PartialOverloading);
14649 return;
14650 }
14651
14652 assert(!KnownValid && "unhandled case in overloaded call candidate");
14653}
14654
14655void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14656 ArrayRef<Expr *> Args,
14657 OverloadCandidateSet &CandidateSet,
14658 bool PartialOverloading) {
14659
14660#ifndef NDEBUG
14661 // Verify that ArgumentDependentLookup is consistent with the rules
14662 // in C++0x [basic.lookup.argdep]p3:
14663 //
14664 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14665 // and let Y be the lookup set produced by argument dependent
14666 // lookup (defined as follows). If X contains
14667 //
14668 // -- a declaration of a class member, or
14669 //
14670 // -- a block-scope function declaration that is not a
14671 // using-declaration, or
14672 //
14673 // -- a declaration that is neither a function or a function
14674 // template
14675 //
14676 // then Y is empty.
14677
14678 if (ULE->requiresADL()) {
14679 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14680 E = ULE->decls_end(); I != E; ++I) {
14681 assert(!(*I)->getDeclContext()->isRecord());
14682 assert(isa<UsingShadowDecl>(*I) ||
14683 !(*I)->getDeclContext()->isFunctionOrMethod());
14684 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14685 }
14686 }
14687#endif
14688
14689 // It would be nice to avoid this copy.
14690 TemplateArgumentListInfo TABuffer;
14691 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14692 if (ULE->hasExplicitTemplateArgs()) {
14693 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14694 ExplicitTemplateArgs = &TABuffer;
14695 }
14696
14697 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14698 E = ULE->decls_end(); I != E; ++I)
14699 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14700 CandidateSet, PartialOverloading,
14701 /*KnownValid*/ true);
14702
14703 if (ULE->requiresADL())
14704 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14705 Args, ExplicitTemplateArgs,
14706 CandidateSet, PartialOverloading);
14707}
14708
14709void Sema::AddOverloadedCallCandidates(
14710 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14711 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14712 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14713 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14714 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14715}
14716
14717/// Determine whether a declaration with the specified name could be moved into
14718/// a different namespace.
14719static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14720 switch (Name.getCXXOverloadedOperator()) {
14721 case OO_New: case OO_Array_New:
14722 case OO_Delete: case OO_Array_Delete:
14723 return false;
14724
14725 default:
14726 return true;
14727 }
14728}
14729
14730/// Attempt to recover from an ill-formed use of a non-dependent name in a
14731/// template, where the non-dependent name was declared after the template
14732/// was defined. This is common in code written for compilers which do not
14733/// correctly implement two-stage name lookup.
14734///
14735/// Returns true if a viable candidate was found and a diagnostic was issued.
14736static bool DiagnoseTwoPhaseLookup(
14737 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14738 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14739 const OverloadCandidateSet &ResolvedCandidates,
14740 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14741 CXXRecordDecl **FoundInClass = nullptr) {
14742 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14743 return false;
14744
14745 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14746 if (DC->isTransparentContext())
14747 continue;
14748
14749 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14750
14751 if (!R.empty()) {
14752 R.suppressDiagnostics();
14753
14754 OverloadCandidateSet Candidates(FnLoc, CSK);
14755 // We have performed a BestViableFunction over these candidates, so
14756 // exclude them.
14757 for (auto &Cand : ResolvedCandidates) {
14758 if (Cand.Function)
14759 Candidates.exclude(F: Cand.Function);
14760 else if (Cand.IsSurrogate)
14761 Candidates.exclude(F: Cand.Surrogate);
14762 }
14763 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14764 CandidateSet&: Candidates);
14765
14766 OverloadCandidateSet::iterator Best;
14767 OverloadingResult OR =
14768 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14769
14770 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14771 // We either found non-function declarations or a best viable function
14772 // at class scope. A class-scope lookup result disables ADL. Don't
14773 // look past this, but let the caller know that we found something that
14774 // either is, or might be, usable in this class.
14775 if (FoundInClass) {
14776 *FoundInClass = RD;
14777 if (OR == OR_Success) {
14778 R.clear();
14779 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14780 R.resolveKind();
14781 }
14782 }
14783 return false;
14784 }
14785
14786 if (OR != OR_Success) {
14787 // There wasn't a unique best function or function template.
14788 return false;
14789 }
14790
14791 // Find the namespaces where ADL would have looked, and suggest
14792 // declaring the function there instead.
14793 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14794 Sema::AssociatedClassSet AssociatedClasses;
14795 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14796 AssociatedNamespaces,
14797 AssociatedClasses);
14798 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14799 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14800 DeclContext *Std = SemaRef.getStdNamespace();
14801 for (Sema::AssociatedNamespaceSet::iterator
14802 it = AssociatedNamespaces.begin(),
14803 end = AssociatedNamespaces.end(); it != end; ++it) {
14804 // Never suggest declaring a function within namespace 'std'.
14805 if (Std && Std->Encloses(DC: *it))
14806 continue;
14807
14808 // Never suggest declaring a function within a namespace with a
14809 // reserved name, like __gnu_cxx.
14810 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14811 if (NS &&
14812 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14813 continue;
14814
14815 SuggestedNamespaces.insert(X: *it);
14816 }
14817 }
14818
14819 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14820 << R.getLookupName();
14821 if (SuggestedNamespaces.empty()) {
14822 SemaRef.Diag(Loc: Best->Function->getLocation(),
14823 DiagID: diag::note_not_found_by_two_phase_lookup)
14824 << R.getLookupName() << 0;
14825 } else if (SuggestedNamespaces.size() == 1) {
14826 SemaRef.Diag(Loc: Best->Function->getLocation(),
14827 DiagID: diag::note_not_found_by_two_phase_lookup)
14828 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14829 } else {
14830 // FIXME: It would be useful to list the associated namespaces here,
14831 // but the diagnostics infrastructure doesn't provide a way to produce
14832 // a localized representation of a list of items.
14833 SemaRef.Diag(Loc: Best->Function->getLocation(),
14834 DiagID: diag::note_not_found_by_two_phase_lookup)
14835 << R.getLookupName() << 2;
14836 }
14837
14838 // Try to recover by calling this function.
14839 return true;
14840 }
14841
14842 R.clear();
14843 }
14844
14845 return false;
14846}
14847
14848/// Attempt to recover from ill-formed use of a non-dependent operator in a
14849/// template, where the non-dependent operator was declared after the template
14850/// was defined.
14851///
14852/// Returns true if a viable candidate was found and a diagnostic was issued.
14853static bool DiagnoseTwoPhaseOperatorLookup(
14854 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14855 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14856 DeclarationName OpName =
14857 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14858 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14859 return DiagnoseTwoPhaseLookup(
14860 SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R, CSK: OverloadCandidateSet::CSK_Operator,
14861 ResolvedCandidates: ResolvedCandidateSet,
14862 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14863}
14864
14865namespace {
14866class BuildRecoveryCallExprRAII {
14867 Sema &SemaRef;
14868 Sema::SatisfactionStackResetRAII SatStack;
14869
14870public:
14871 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14872 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14873 SemaRef.IsBuildingRecoveryCallExpr = true;
14874 }
14875
14876 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14877};
14878}
14879
14880/// Attempts to recover from a call where no functions were found.
14881///
14882/// This function will do one of three things:
14883/// * Diagnose, recover, and return a recovery expression.
14884/// * Diagnose, fail to recover, and return ExprError().
14885/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14886/// expected to diagnose as appropriate.
14887static ExprResult
14888BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14889 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14890 MutableArrayRef<Expr *> Args, SourceLocation RParenLoc,
14891 const OverloadCandidateSet &ResolvedCandidateSet,
14892 bool AllowTypoCorrection) {
14893 // Do not try to recover if it is already building a recovery call.
14894 // This stops infinite loops for template instantiations like
14895 //
14896 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14897 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14898 if (SemaRef.IsBuildingRecoveryCallExpr)
14899 return ExprResult();
14900 BuildRecoveryCallExprRAII RCE(SemaRef);
14901
14902 CXXScopeSpec SS;
14903 SS.Adopt(Other: ULE->getQualifierLoc());
14904 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14905
14906 TemplateArgumentListInfo TABuffer;
14907 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14908 if (ULE->hasExplicitTemplateArgs()) {
14909 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14910 ExplicitTemplateArgs = &TABuffer;
14911 }
14912
14913 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14914 Sema::LookupOrdinaryName);
14915 CXXRecordDecl *FoundInClass = nullptr;
14916 if (DiagnoseTwoPhaseLookup(
14917 SemaRef, FnLoc: Fn->getExprLoc(), SS, R, CSK: OverloadCandidateSet::CSK_Normal,
14918 ResolvedCandidates: ResolvedCandidateSet, ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14919 // OK, diagnosed a two-phase lookup issue.
14920 } else if (ResolvedCandidateSet.empty()) {
14921 // Try to recover from an empty lookup with typo correction.
14922 R.clear();
14923 NoTypoCorrectionCCC NoTypoValidator{};
14924 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14925 ExplicitTemplateArgs != nullptr,
14926 dyn_cast<MemberExpr>(Val: Fn));
14927 CorrectionCandidateCallback &Validator =
14928 AllowTypoCorrection
14929 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14930 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14931 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14932 Args))
14933 return ExprError();
14934 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14935 // We found a usable declaration of the name in a dependent base of some
14936 // enclosing class.
14937 // FIXME: We should also explain why the candidates found by name lookup
14938 // were not viable.
14939 if (SemaRef.DiagnoseDependentMemberLookup(R))
14940 return ExprError();
14941 } else {
14942 // We had viable candidates and couldn't recover; let the caller diagnose
14943 // this.
14944 return ExprResult();
14945 }
14946
14947 // If we get here, we should have issued a diagnostic and formed a recovery
14948 // lookup result.
14949 assert(!R.empty() && "lookup results empty despite recovery");
14950
14951 // If recovery created an ambiguity, just bail out.
14952 if (R.isAmbiguous()) {
14953 R.suppressDiagnostics();
14954 return ExprError();
14955 }
14956
14957 // Build an implicit member call if appropriate. Just drop the
14958 // casts and such from the call, we don't really care.
14959 ExprResult NewFn = ExprError();
14960 if ((*R.begin())->isCXXClassMember())
14961 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14962 TemplateArgs: ExplicitTemplateArgs, S);
14963 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14964 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14965 TemplateArgs: ExplicitTemplateArgs);
14966 else
14967 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14968
14969 if (NewFn.isInvalid())
14970 return ExprError();
14971
14972 // This shouldn't cause an infinite loop because we're giving it
14973 // an expression with viable lookup results, which should never
14974 // end up here.
14975 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14976 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14977 RParenLoc);
14978}
14979
14980bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14981 UnresolvedLookupExpr *ULE,
14982 MultiExprArg Args,
14983 SourceLocation RParenLoc,
14984 OverloadCandidateSet *CandidateSet,
14985 ExprResult *Result) {
14986#ifndef NDEBUG
14987 if (ULE->requiresADL()) {
14988 // To do ADL, we must have found an unqualified name.
14989 assert(!ULE->getQualifier() && "qualified name with ADL");
14990
14991 // We don't perform ADL for implicit declarations of builtins.
14992 // Verify that this was correctly set up.
14993 FunctionDecl *F;
14994 if (ULE->decls_begin() != ULE->decls_end() &&
14995 ULE->decls_begin() + 1 == ULE->decls_end() &&
14996 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14997 F->getBuiltinID() && F->isImplicit())
14998 llvm_unreachable("performing ADL for builtin");
14999
15000 // We don't perform ADL in C.
15001 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
15002 }
15003#endif
15004
15005 UnbridgedCastsSet UnbridgedCasts;
15006 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
15007 *Result = ExprError();
15008 return true;
15009 }
15010
15011 // Add the functions denoted by the callee to the set of candidate
15012 // functions, including those from argument-dependent lookup.
15013 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
15014
15015 if (getLangOpts().MSVCCompat &&
15016 CurContext->isDependentContext() && !isSFINAEContext() &&
15017 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
15018
15019 OverloadCandidateSet::iterator Best;
15020 if (CandidateSet->empty() ||
15021 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
15022 OR_No_Viable_Function) {
15023 // In Microsoft mode, if we are inside a template class member function
15024 // then create a type dependent CallExpr. The goal is to postpone name
15025 // lookup to instantiation time to be able to search into type dependent
15026 // base classes.
15027 CallExpr *CE =
15028 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
15029 RParenLoc, FPFeatures: CurFPFeatureOverrides());
15030 CE->markDependentForPostponedNameLookup();
15031 *Result = CE;
15032 return true;
15033 }
15034 }
15035
15036 if (CandidateSet->empty())
15037 return false;
15038
15039 UnbridgedCasts.restore();
15040 return false;
15041}
15042
15043// Guess at what the return type for an unresolvable overload should be.
15044static QualType chooseRecoveryType(OverloadCandidateSet &CS,
15045 OverloadCandidateSet::iterator *Best) {
15046 std::optional<QualType> Result;
15047 // Adjust Type after seeing a candidate.
15048 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
15049 if (!Candidate.Function)
15050 return;
15051 if (Candidate.Function->isInvalidDecl())
15052 return;
15053 QualType T = Candidate.Function->getReturnType();
15054 if (T.isNull())
15055 return;
15056 if (!Result)
15057 Result = T;
15058 else if (Result != T)
15059 Result = QualType();
15060 };
15061
15062 // Look for an unambiguous type from a progressively larger subset.
15063 // e.g. if types disagree, but all *viable* overloads return int, choose int.
15064 //
15065 // First, consider only the best candidate.
15066 if (Best && *Best != CS.end())
15067 ConsiderCandidate(**Best);
15068 // Next, consider only viable candidates.
15069 if (!Result)
15070 for (const auto &C : CS)
15071 if (C.Viable)
15072 ConsiderCandidate(C);
15073 // Finally, consider all candidates.
15074 if (!Result)
15075 for (const auto &C : CS)
15076 ConsiderCandidate(C);
15077
15078 if (!Result)
15079 return QualType();
15080 auto Value = *Result;
15081 if (Value.isNull() || Value->isUndeducedType())
15082 return QualType();
15083 return Value;
15084}
15085
15086/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
15087/// the completed call expression. If overload resolution fails, emits
15088/// diagnostics and returns ExprError()
15089static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
15090 UnresolvedLookupExpr *ULE,
15091 SourceLocation LParenLoc,
15092 MultiExprArg Args,
15093 SourceLocation RParenLoc,
15094 Expr *ExecConfig,
15095 OverloadCandidateSet *CandidateSet,
15096 OverloadCandidateSet::iterator *Best,
15097 OverloadingResult OverloadResult,
15098 bool AllowTypoCorrection) {
15099 switch (OverloadResult) {
15100 case OR_Success: {
15101 FunctionDecl *FDecl = (*Best)->Function;
15102 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
15103 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
15104 return ExprError();
15105 ExprResult Res =
15106 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15107 if (Res.isInvalid())
15108 return ExprError();
15109 return SemaRef.BuildResolvedCallExpr(
15110 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15111 /*IsExecConfig=*/false,
15112 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15113 }
15114
15115 case OR_No_Viable_Function: {
15116 if (*Best != CandidateSet->end() &&
15117 CandidateSet->getKind() ==
15118 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
15119 if (CXXMethodDecl *M =
15120 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
15121 M && M->isImplicitObjectMemberFunction()) {
15122 CandidateSet->NoteCandidates(
15123 PD: PartialDiagnosticAt(
15124 Fn->getBeginLoc(),
15125 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
15126 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15127 return ExprError();
15128 }
15129 }
15130
15131 // Try to recover by looking for viable functions which the user might
15132 // have meant to call.
15133 ExprResult Recovery =
15134 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15135 ResolvedCandidateSet: *CandidateSet, AllowTypoCorrection);
15136 if (Recovery.isInvalid() || Recovery.isUsable())
15137 return Recovery;
15138
15139 // If the user passes in a function that we can't take the address of, we
15140 // generally end up emitting really bad error messages. Here, we attempt to
15141 // emit better ones.
15142 for (const Expr *Arg : Args) {
15143 if (!Arg->getType()->isFunctionType())
15144 continue;
15145 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
15146 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
15147 if (FD &&
15148 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
15149 Loc: Arg->getExprLoc()))
15150 return ExprError();
15151 }
15152 }
15153
15154 CandidateSet->NoteCandidates(
15155 PD: PartialDiagnosticAt(
15156 Fn->getBeginLoc(),
15157 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
15158 << ULE->getName() << Fn->getSourceRange()),
15159 S&: SemaRef, OCD: OCD_AllCandidates, Args);
15160 break;
15161 }
15162
15163 case OR_Ambiguous:
15164 CandidateSet->NoteCandidates(
15165 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
15166 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
15167 << ULE->getName() << Fn->getSourceRange()),
15168 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
15169 break;
15170
15171 case OR_Deleted: {
15172 FunctionDecl *FDecl = (*Best)->Function;
15173 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
15174 Range: Fn->getSourceRange(), Name: ULE->getName(),
15175 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
15176
15177 // We emitted an error for the unavailable/deleted function call but keep
15178 // the call in the AST.
15179 ExprResult Res =
15180 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
15181 if (Res.isInvalid())
15182 return ExprError();
15183 return SemaRef.BuildResolvedCallExpr(
15184 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
15185 /*IsExecConfig=*/false,
15186 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15187 }
15188 }
15189
15190 // Overload resolution failed, try to recover.
15191 SmallVector<Expr *, 8> SubExprs = {Fn};
15192 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
15193 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
15194 T: chooseRecoveryType(CS&: *CandidateSet, Best));
15195}
15196
15197static void markUnaddressableCandidatesUnviable(Sema &S,
15198 OverloadCandidateSet &CS) {
15199 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15200 if (I->Viable &&
15201 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
15202 I->Viable = false;
15203 I->FailureKind = ovl_fail_addr_not_available;
15204 }
15205 }
15206}
15207
15208ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
15209 UnresolvedLookupExpr *ULE,
15210 SourceLocation LParenLoc,
15211 MultiExprArg Args,
15212 SourceLocation RParenLoc,
15213 Expr *ExecConfig,
15214 bool AllowTypoCorrection,
15215 bool CalleesAddressIsTaken) {
15216
15217 OverloadCandidateSet::CandidateSetKind CSK =
15218 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15219 : OverloadCandidateSet::CSK_Normal;
15220
15221 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15222 ExprResult result;
15223
15224 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15225 Result: &result))
15226 return result;
15227
15228 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15229 // functions that aren't addressible are considered unviable.
15230 if (CalleesAddressIsTaken)
15231 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15232
15233 OverloadCandidateSet::iterator Best;
15234 OverloadingResult OverloadResult =
15235 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15236
15237 // [C++23][over.call.func]
15238 // if overload resolution selects a non-static member function,
15239 // the call is ill-formed;
15240 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15241 Best != CandidateSet.end()) {
15242 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15243 M && M->isImplicitObjectMemberFunction()) {
15244 OverloadResult = OR_No_Viable_Function;
15245 }
15246 }
15247
15248 // Model the case with a call to a templated function whose definition
15249 // encloses the call and whose return type contains a placeholder type as if
15250 // the UnresolvedLookupExpr was type-dependent.
15251 if (OverloadResult == OR_Success) {
15252 const FunctionDecl *FDecl = Best->Function;
15253 if (LangOpts.CUDA)
15254 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15255 if (FDecl && FDecl->isTemplateInstantiation() &&
15256 FDecl->getReturnType()->isUndeducedType()) {
15257
15258 // Creating dependent CallExpr is not okay if the enclosing context itself
15259 // is not dependent. This situation notably arises if a non-dependent
15260 // member function calls the later-defined overloaded static function.
15261 //
15262 // For example, in
15263 // class A {
15264 // void c() { callee(1); }
15265 // static auto callee(auto x) { }
15266 // };
15267 //
15268 // Here callee(1) is unresolved at the call site, but is not inside a
15269 // dependent context. There will be no further attempt to resolve this
15270 // call if it is made dependent.
15271
15272 if (const auto *TP =
15273 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15274 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15275 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15276 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15277 }
15278 }
15279 }
15280
15281 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15282 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15283 OverloadResult, AllowTypoCorrection);
15284}
15285
15286ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15287 NestedNameSpecifierLoc NNSLoc,
15288 DeclarationNameInfo DNI,
15289 const UnresolvedSetImpl &Fns,
15290 bool PerformADL) {
15291 return UnresolvedLookupExpr::Create(
15292 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15293 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15294}
15295
15296ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15297 CXXConversionDecl *Method,
15298 bool HadMultipleCandidates) {
15299 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15300 // the FoundDecl as it impedes TransformMemberExpr.
15301 // We go a bit further here: if there's no difference in UnderlyingDecl,
15302 // then using FoundDecl vs Method shouldn't make a difference either.
15303 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15304 FoundDecl = Method;
15305 // Convert the expression to match the conversion function's implicit object
15306 // parameter.
15307 ExprResult Exp;
15308 if (Method->isExplicitObjectMemberFunction())
15309 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15310 else
15311 Exp = PerformImplicitObjectArgumentInitialization(
15312 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15313 if (Exp.isInvalid())
15314 return true;
15315
15316 if (Method->getParent()->isLambda() &&
15317 Method->getConversionType()->isBlockPointerType()) {
15318 // This is a lambda conversion to block pointer; check if the argument
15319 // was a LambdaExpr.
15320 Expr *SubE = E;
15321 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15322 if (CE && CE->getCastKind() == CK_NoOp)
15323 SubE = CE->getSubExpr();
15324 SubE = SubE->IgnoreParens();
15325 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15326 SubE = BE->getSubExpr();
15327 if (isa<LambdaExpr>(Val: SubE)) {
15328 // For the conversion to block pointer on a lambda expression, we
15329 // construct a special BlockLiteral instead; this doesn't really make
15330 // a difference in ARC, but outside of ARC the resulting block literal
15331 // follows the normal lifetime rules for block literals instead of being
15332 // autoreleased.
15333 PushExpressionEvaluationContext(
15334 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15335 ExprResult BlockExp = BuildBlockForLambdaConversion(
15336 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15337 PopExpressionEvaluationContext();
15338
15339 // FIXME: This note should be produced by a CodeSynthesisContext.
15340 if (BlockExp.isInvalid())
15341 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15342 return BlockExp;
15343 }
15344 }
15345 CallExpr *CE;
15346 QualType ResultType = Method->getReturnType();
15347 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15348 ResultType = ResultType.getNonLValueExprType(Context);
15349 if (Method->isExplicitObjectMemberFunction()) {
15350 ExprResult FnExpr =
15351 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15352 HadMultipleCandidates, Loc: E->getBeginLoc());
15353 if (FnExpr.isInvalid())
15354 return ExprError();
15355 Expr *ObjectParam = Exp.get();
15356 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15357 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15358 FPFeatures: CurFPFeatureOverrides());
15359 CE->setUsesMemberSyntax(true);
15360 } else {
15361 MemberExpr *ME =
15362 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15363 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15364 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15365 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15366 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15367
15368 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15369 RP: Exp.get()->getEndLoc(),
15370 FPFeatures: CurFPFeatureOverrides());
15371 }
15372
15373 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15374 Proto: Method->getType()->castAs<FunctionProtoType>()))
15375 return ExprError();
15376
15377 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15378}
15379
15380void Sema::LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
15381 OverloadedOperatorKind Op,
15382 const UnresolvedSetImpl &Fns,
15383 ArrayRef<Expr *> Args, bool PerformADL) {
15384 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15385
15386 SourceLocation OpLoc = CandidateSet.getLocation();
15387 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15388
15389 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15390 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15391 if (PerformADL)
15392 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15393 /*ExplicitTemplateArgs*/ nullptr,
15394 CandidateSet);
15395 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15396}
15397
15398ExprResult
15399Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15400 const UnresolvedSetImpl &Fns,
15401 Expr *Input, bool PerformADL) {
15402 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15403 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15404 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15405 // TODO: provide better source location info.
15406 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15407
15408 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15409 return ExprError();
15410
15411 Expr *Args[2] = { Input, nullptr };
15412 unsigned NumArgs = 1;
15413
15414 // For post-increment and post-decrement, add the implicit '0' as
15415 // the second argument, so that we know this is a post-increment or
15416 // post-decrement.
15417 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15418 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15419 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15420 l: SourceLocation());
15421 NumArgs = 2;
15422 }
15423
15424 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15425
15426 if (Input->isTypeDependent()) {
15427 ExprValueKind VK = ExprValueKind::VK_PRValue;
15428 // [C++26][expr.unary.op][expr.pre.incr]
15429 // The * operator yields an lvalue of type
15430 // The pre/post increment operators yied an lvalue.
15431 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15432 VK = VK_LValue;
15433
15434 if (Fns.empty())
15435 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15436 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15437 FPFeatures: CurFPFeatureOverrides());
15438
15439 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15440 ExprResult Fn = CreateUnresolvedLookupExpr(
15441 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15442 if (Fn.isInvalid())
15443 return ExprError();
15444 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15445 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15446 FPFeatures: CurFPFeatureOverrides());
15447 }
15448
15449 // Build an empty overload set.
15450 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15451 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, Args: ArgsArray, PerformADL);
15452
15453 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15454
15455 // Perform overload resolution.
15456 OverloadCandidateSet::iterator Best;
15457 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15458 case OR_Success: {
15459 // We found a built-in operator or an overloaded operator.
15460 FunctionDecl *FnDecl = Best->Function;
15461
15462 if (FnDecl) {
15463 Expr *Base = nullptr;
15464 // We matched an overloaded operator. Build a call to that
15465 // operator.
15466
15467 // Convert the arguments.
15468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15469 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15470
15471 ExprResult InputInit;
15472 if (Method->isExplicitObjectMemberFunction())
15473 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15474 else
15475 InputInit = PerformImplicitObjectArgumentInitialization(
15476 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15477 if (InputInit.isInvalid())
15478 return ExprError();
15479 Base = Input = InputInit.get();
15480 } else {
15481 // Convert the arguments.
15482 ExprResult InputInit
15483 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15484 Context,
15485 Parm: FnDecl->getParamDecl(i: 0)),
15486 EqualLoc: SourceLocation(),
15487 Init: Input);
15488 if (InputInit.isInvalid())
15489 return ExprError();
15490 Input = InputInit.get();
15491 }
15492
15493 // Build the actual expression node.
15494 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15495 Base, HadMultipleCandidates,
15496 Loc: OpLoc);
15497 if (FnExpr.isInvalid())
15498 return ExprError();
15499
15500 // Determine the result type.
15501 QualType ResultTy = FnDecl->getReturnType();
15502 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15503 ResultTy = ResultTy.getNonLValueExprType(Context);
15504
15505 Args[0] = Input;
15506 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15507 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15508 FPFeatures: CurFPFeatureOverrides(),
15509 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15510
15511 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15512 return ExprError();
15513
15514 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15515 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15516 return ExprError();
15517 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15518 } else {
15519 // We matched a built-in operator. Convert the arguments, then
15520 // break out so that we will build the appropriate built-in
15521 // operator node.
15522 ExprResult InputRes = PerformImplicitConversion(
15523 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15524 Action: AssignmentAction::Passing,
15525 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15526 if (InputRes.isInvalid())
15527 return ExprError();
15528 Input = InputRes.get();
15529 break;
15530 }
15531 }
15532
15533 case OR_No_Viable_Function:
15534 // This is an erroneous use of an operator which can be overloaded by
15535 // a non-member function. Check for non-member operators which were
15536 // defined too late to be candidates.
15537 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray,
15538 ResolvedCandidateSet: CandidateSet))
15539 // FIXME: Recover by calling the found function.
15540 return ExprError();
15541
15542 // No viable function; fall through to handling this as a
15543 // built-in operator, which will produce an error message for us.
15544 break;
15545
15546 case OR_Ambiguous:
15547 CandidateSet.NoteCandidates(
15548 PD: PartialDiagnosticAt(OpLoc,
15549 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15550 << UnaryOperator::getOpcodeStr(Op: Opc)
15551 << Input->getType() << Input->getSourceRange()),
15552 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15553 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15554 return ExprError();
15555
15556 case OR_Deleted: {
15557 // A defaulted postfix increment or decrement operator that was implicitly
15558 // defined as deleted. Explain why it was deleted.
15559 if (FunctionDecl *DeletedFD = Best->Function;
15560 DeletedFD->isDefaulted() &&
15561 DeletedFD->getDefaultedFunctionKind().isPostfixOperator()) {
15562 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_postfix_operator)
15563 << Input->getType()
15564 << (int)DeletedFD->getDefaultedFunctionKind().asPostfixOperator()
15565 << Input->getSourceRange();
15566 NoteDeletedFunction(FD: DeletedFD);
15567 return ExprError();
15568 }
15569
15570 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15571 // object whose method was called. Later in NoteCandidates size of ArgsArray
15572 // is passed further and it eventually ends up compared to number of
15573 // function candidate parameters which never includes the object parameter,
15574 // so slice ArgsArray to make sure apples are compared to apples.
15575 StringLiteral *Msg = Best->Function->getDeletedMessage();
15576 CandidateSet.NoteCandidates(
15577 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15578 << UnaryOperator::getOpcodeStr(Op: Opc)
15579 << (Msg != nullptr)
15580 << (Msg ? Msg->getString() : StringRef())
15581 << Input->getSourceRange()),
15582 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15583 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15584 return ExprError();
15585 }
15586 }
15587
15588 // Either we found no viable overloaded operator or we matched a
15589 // built-in operator. In either case, fall through to trying to
15590 // build a built-in operation.
15591 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15592}
15593
15594void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15595 OverloadedOperatorKind Op,
15596 const UnresolvedSetImpl &Fns,
15597 ArrayRef<Expr *> Args, bool PerformADL) {
15598 SourceLocation OpLoc = CandidateSet.getLocation();
15599
15600 OverloadedOperatorKind ExtraOp =
15601 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15602 ? getRewrittenOverloadedOperator(Kind: Op)
15603 : OO_None;
15604
15605 // Add the candidates from the given function set. This also adds the
15606 // rewritten candidates using these functions if necessary.
15607 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15608
15609 // As template candidates are not deduced immediately,
15610 // persist the array in the overload set.
15611 ArrayRef<Expr *> ReversedArgs;
15612 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15613 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15614 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15615
15616 // Add operator candidates that are member functions.
15617 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15618 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15619 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15620 PO: OverloadCandidateParamOrder::Reversed);
15621
15622 // In C++20, also add any rewritten member candidates.
15623 if (ExtraOp) {
15624 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15625 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15626 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15627 PO: OverloadCandidateParamOrder::Reversed);
15628 }
15629
15630 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15631 // performed for an assignment operator (nor for operator[] nor operator->,
15632 // which don't get here).
15633 if (Op != OO_Equal && PerformADL) {
15634 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15635 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15636 /*ExplicitTemplateArgs*/ nullptr,
15637 CandidateSet);
15638 if (ExtraOp) {
15639 DeclarationName ExtraOpName =
15640 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15641 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15642 /*ExplicitTemplateArgs*/ nullptr,
15643 CandidateSet);
15644 }
15645 }
15646
15647 // Add builtin operator candidates.
15648 //
15649 // FIXME: We don't add any rewritten candidates here. This is strictly
15650 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15651 // resulting in our selecting a rewritten builtin candidate. For example:
15652 //
15653 // enum class E { e };
15654 // bool operator!=(E, E) requires false;
15655 // bool k = E::e != E::e;
15656 //
15657 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15658 // it seems unreasonable to consider rewritten builtin candidates. A core
15659 // issue has been filed proposing to removed this requirement.
15660 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15661}
15662
15663ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15664 BinaryOperatorKind Opc,
15665 const UnresolvedSetImpl &Fns, Expr *LHS,
15666 Expr *RHS, bool PerformADL,
15667 bool AllowRewrittenCandidates,
15668 FunctionDecl *DefaultedFn) {
15669 Expr *Args[2] = { LHS, RHS };
15670 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15671
15672 if (!getLangOpts().CPlusPlus20)
15673 AllowRewrittenCandidates = false;
15674
15675 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15676
15677 // If either side is type-dependent, create an appropriate dependent
15678 // expression.
15679 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15680 if (Fns.empty()) {
15681 // If there are no functions to store, just build a dependent
15682 // BinaryOperator or CompoundAssignment.
15683 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15684 return CompoundAssignOperator::Create(
15685 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15686 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15687 CompResultType: Context.DependentTy);
15688 return BinaryOperator::Create(
15689 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15690 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15691 }
15692
15693 // FIXME: save results of ADL from here?
15694 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15695 // TODO: provide better source location info in DNLoc component.
15696 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15697 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15698 ExprResult Fn = CreateUnresolvedLookupExpr(
15699 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15700 if (Fn.isInvalid())
15701 return ExprError();
15702 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15703 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15704 FPFeatures: CurFPFeatureOverrides());
15705 }
15706
15707 // If this is the .* operator, which is not overloadable, just
15708 // create a built-in binary operator.
15709 if (Opc == BO_PtrMemD) {
15710 auto CheckPlaceholder = [&](Expr *&Arg) {
15711 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15712 if (Res.isUsable())
15713 Arg = Res.get();
15714 return !Res.isUsable();
15715 };
15716
15717 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15718 // expression that contains placeholders (in either the LHS or RHS).
15719 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15720 return ExprError();
15721 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15722 }
15723
15724 // Always do placeholder-like conversions on the RHS.
15725 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15726 return ExprError();
15727
15728 // Do placeholder-like conversion on the LHS; note that we should
15729 // not get here with a PseudoObject LHS.
15730 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15731 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15732 return ExprError();
15733
15734 // If this is the assignment operator, we only perform overload resolution
15735 // if the left-hand side is a class or enumeration type. This is actually
15736 // a hack. The standard requires that we do overload resolution between the
15737 // various built-in candidates, but as DR507 points out, this can lead to
15738 // problems. So we do it this way, which pretty much follows what GCC does.
15739 // Note that we go the traditional code path for compound assignment forms.
15740 // In HLSL, user-defined structs/classes do not have constructors or
15741 // overloadable assignment operators, so we can take this shortcut too.
15742 const Type *LHSTy = Args[0]->getType().getTypePtr();
15743 if (Opc == BO_Assign &&
15744 (!LHSTy->isOverloadableType() ||
15745 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15746 !LHSTy->getAsCXXRecordDecl()->isHLSLBuiltinRecord())))
15747 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15748
15749 // Build the overload set.
15750 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15751 OverloadCandidateSet::OperatorRewriteInfo(
15752 Op, OpLoc, AllowRewrittenCandidates));
15753 if (DefaultedFn)
15754 CandidateSet.exclude(F: DefaultedFn);
15755 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15756
15757 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15758
15759 // Perform overload resolution.
15760 OverloadCandidateSet::iterator Best;
15761 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15762 case OR_Success: {
15763 // We found a built-in operator or an overloaded operator.
15764 FunctionDecl *FnDecl = Best->Function;
15765
15766 bool IsReversed = Best->isReversed();
15767 if (IsReversed)
15768 std::swap(a&: Args[0], b&: Args[1]);
15769
15770 if (FnDecl) {
15771
15772 if (FnDecl->isInvalidDecl())
15773 return ExprError();
15774
15775 Expr *Base = nullptr;
15776 // We matched an overloaded operator. Build a call to that
15777 // operator.
15778
15779 OverloadedOperatorKind ChosenOp =
15780 FnDecl->getDeclName().getCXXOverloadedOperator();
15781
15782 // C++2a [over.match.oper]p9:
15783 // If a rewritten operator== candidate is selected by overload
15784 // resolution for an operator@, its return type shall be cv bool
15785 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15786 !FnDecl->getReturnType()->isBooleanType()) {
15787 bool IsExtension =
15788 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15789 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15790 : diag::err_ovl_rewrite_equalequal_not_bool)
15791 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15792 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15793 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15794 if (!IsExtension)
15795 return ExprError();
15796 }
15797
15798 if (AllowRewrittenCandidates && !IsReversed &&
15799 CandidateSet.getRewriteInfo().isReversible()) {
15800 // We could have reversed this operator, but didn't. Check if some
15801 // reversed form was a viable candidate, and if so, if it had a
15802 // better conversion for either parameter. If so, this call is
15803 // formally ambiguous, and allowing it is an extension.
15804 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15805 for (OverloadCandidate &Cand : CandidateSet) {
15806 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15807 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15808 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15809 if (CompareImplicitConversionSequences(
15810 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15811 ICS2: Best->Conversions[ArgIdx]) ==
15812 ImplicitConversionSequence::Better) {
15813 AmbiguousWith.push_back(Elt: Cand.Function);
15814 break;
15815 }
15816 }
15817 }
15818 }
15819
15820 if (!AmbiguousWith.empty()) {
15821 bool AmbiguousWithSelf =
15822 AmbiguousWith.size() == 1 &&
15823 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15824 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15825 << BinaryOperator::getOpcodeStr(Op: Opc)
15826 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15827 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15828 if (AmbiguousWithSelf) {
15829 Diag(Loc: FnDecl->getLocation(),
15830 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15831 // Mark member== const or provide matching != to disallow reversed
15832 // args. Eg.
15833 // struct S { bool operator==(const S&); };
15834 // S()==S();
15835 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15836 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15837 !MD->isConst() &&
15838 !MD->hasCXXExplicitFunctionObjectParameter() &&
15839 Context.hasSameUnqualifiedType(
15840 T1: MD->getFunctionObjectParameterType(),
15841 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15842 Context.hasSameUnqualifiedType(
15843 T1: MD->getFunctionObjectParameterType(),
15844 T2: Args[0]->getType()) &&
15845 Context.hasSameUnqualifiedType(
15846 T1: MD->getFunctionObjectParameterType(),
15847 T2: Args[1]->getType()))
15848 Diag(Loc: FnDecl->getLocation(),
15849 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15850 } else {
15851 Diag(Loc: FnDecl->getLocation(),
15852 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15853 for (auto *F : AmbiguousWith)
15854 Diag(Loc: F->getLocation(),
15855 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15856 }
15857 }
15858 }
15859
15860 // Check for nonnull = nullable.
15861 // This won't be caught in the arg's initialization: the parameter to
15862 // the assignment operator is not marked nonnull.
15863 if (Op == OO_Equal)
15864 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15865 SrcType: Args[1]->getType(), Loc: OpLoc);
15866
15867 // Convert the arguments.
15868 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15869 // Best->Access is only meaningful for class members.
15870 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15871
15872 ExprResult Arg0, Arg1;
15873 unsigned ParamIdx = 0;
15874 if (Method->isExplicitObjectMemberFunction()) {
15875 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15876 ParamIdx = 1;
15877 } else {
15878 Arg0 = PerformImplicitObjectArgumentInitialization(
15879 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15880 }
15881 Arg1 = PerformCopyInitialization(
15882 Entity: InitializedEntity::InitializeParameter(
15883 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15884 EqualLoc: SourceLocation(), Init: Args[1]);
15885 if (Arg0.isInvalid() || Arg1.isInvalid())
15886 return ExprError();
15887
15888 Base = Args[0] = Arg0.getAs<Expr>();
15889 Args[1] = RHS = Arg1.getAs<Expr>();
15890 } else {
15891 // Convert the arguments.
15892 ExprResult Arg0 = PerformCopyInitialization(
15893 Entity: InitializedEntity::InitializeParameter(Context,
15894 Parm: FnDecl->getParamDecl(i: 0)),
15895 EqualLoc: SourceLocation(), Init: Args[0]);
15896 if (Arg0.isInvalid())
15897 return ExprError();
15898
15899 ExprResult Arg1 =
15900 PerformCopyInitialization(
15901 Entity: InitializedEntity::InitializeParameter(Context,
15902 Parm: FnDecl->getParamDecl(i: 1)),
15903 EqualLoc: SourceLocation(), Init: Args[1]);
15904 if (Arg1.isInvalid())
15905 return ExprError();
15906 Args[0] = LHS = Arg0.getAs<Expr>();
15907 Args[1] = RHS = Arg1.getAs<Expr>();
15908 }
15909
15910 // Build the actual expression node.
15911 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15912 FoundDecl: Best->FoundDecl, Base,
15913 HadMultipleCandidates, Loc: OpLoc);
15914 if (FnExpr.isInvalid())
15915 return ExprError();
15916
15917 if (auto *Pattern = FnDecl->getInstantiatedFromMemberFunction();
15918 Pattern && Pattern->getOverloadedOperator() == OO_Spaceship)
15919 Pattern->setIsUsed();
15920
15921 // Determine the result type.
15922 QualType ResultTy = FnDecl->getReturnType();
15923 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15924 ResultTy = ResultTy.getNonLValueExprType(Context);
15925
15926 CallExpr *TheCall;
15927 ArrayRef<const Expr *> ArgsArray(Args, 2);
15928 const Expr *ImplicitThis = nullptr;
15929
15930 // We always create a CXXOperatorCallExpr, even for explicit object
15931 // members; CodeGen should take care not to emit the this pointer.
15932 TheCall = CXXOperatorCallExpr::Create(
15933 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15934 FPFeatures: CurFPFeatureOverrides(),
15935 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15936 IsReversed);
15937
15938 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15939 Method && Method->isImplicitObjectMemberFunction()) {
15940 // Cut off the implicit 'this'.
15941 ImplicitThis = ArgsArray[0];
15942 ArgsArray = ArgsArray.slice(N: 1);
15943 }
15944
15945 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15946 FD: FnDecl))
15947 return ExprError();
15948
15949 if (Op == OO_Equal) {
15950 // Check for a self move.
15951 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15952 // lifetime check.
15953 checkAssignmentLifetime(
15954 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15955 Init: Args[1]);
15956 }
15957 if (ImplicitThis) {
15958 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15959 QualType ThisTypeFromDecl = Context.getPointerType(
15960 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15961
15962 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15963 ParamTy: ThisTypeFromDecl);
15964 }
15965
15966 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15967 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15968 CallType: VariadicCallType::DoesNotApply);
15969
15970 ExprResult R = MaybeBindToTemporary(E: TheCall);
15971 if (R.isInvalid())
15972 return ExprError();
15973
15974 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15975 if (R.isInvalid())
15976 return ExprError();
15977
15978 // For a rewritten candidate, we've already reversed the arguments
15979 // if needed. Perform the rest of the rewrite now.
15980 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15981 (Op == OO_Spaceship && IsReversed)) {
15982 if (Op == OO_ExclaimEqual) {
15983 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15984 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15985 } else {
15986 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15987 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15988 Expr *ZeroLiteral =
15989 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15990
15991 Sema::CodeSynthesisContext Ctx;
15992 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15993 Ctx.Entity = FnDecl;
15994 pushCodeSynthesisContext(Ctx);
15995
15996 R = CreateOverloadedBinOp(
15997 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15998 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15999 /*AllowRewrittenCandidates=*/false);
16000
16001 popCodeSynthesisContext();
16002 }
16003 if (R.isInvalid())
16004 return ExprError();
16005 } else {
16006 assert(ChosenOp == Op && "unexpected operator name");
16007 }
16008
16009 // Make a note in the AST if we did any rewriting.
16010 if (Best->RewriteKind != CRK_None)
16011 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
16012
16013 return R;
16014 } else {
16015 // We matched a built-in operator. Convert the arguments, then
16016 // break out so that we will build the appropriate built-in
16017 // operator node.
16018 ExprResult ArgsRes0 = PerformImplicitConversion(
16019 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16020 Action: AssignmentAction::Passing,
16021 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16022 if (ArgsRes0.isInvalid())
16023 return ExprError();
16024 Args[0] = ArgsRes0.get();
16025
16026 ExprResult ArgsRes1 = PerformImplicitConversion(
16027 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16028 Action: AssignmentAction::Passing,
16029 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16030 if (ArgsRes1.isInvalid())
16031 return ExprError();
16032 Args[1] = ArgsRes1.get();
16033 break;
16034 }
16035 }
16036
16037 case OR_No_Viable_Function: {
16038 // C++ [over.match.oper]p9:
16039 // If the operator is the operator , [...] and there are no
16040 // viable functions, then the operator is assumed to be the
16041 // built-in operator and interpreted according to clause 5.
16042 if (Opc == BO_Comma)
16043 break;
16044
16045 // When defaulting an 'operator<=>', we can try to synthesize a three-way
16046 // compare result using '==' and '<'.
16047 if (DefaultedFn && Opc == BO_Cmp) {
16048 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
16049 RHS: Args[1], DefaultedFn);
16050 if (E.isInvalid() || E.isUsable())
16051 return E;
16052 }
16053
16054 // For class as left operand for assignment or compound assignment
16055 // operator do not fall through to handling in built-in, but report that
16056 // no overloaded assignment operator found
16057 ExprResult Result = ExprError();
16058 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
16059 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
16060 Args, OpLoc);
16061 DeferDiagsRAII DDR(*this,
16062 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
16063 if (Args[0]->getType()->isRecordType() &&
16064 Opc >= BO_Assign && Opc <= BO_OrAssign) {
16065 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16066 << BinaryOperator::getOpcodeStr(Op: Opc)
16067 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16068 if (Args[0]->getType()->isIncompleteType()) {
16069 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
16070 << Args[0]->getType()
16071 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16072 }
16073 } else {
16074 // This is an erroneous use of an operator which can be overloaded by
16075 // a non-member function. Check for non-member operators which were
16076 // defined too late to be candidates.
16077 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args,
16078 ResolvedCandidateSet: CandidateSet))
16079 // FIXME: Recover by calling the found function.
16080 return ExprError();
16081
16082 // No viable function; try to create a built-in operation, which will
16083 // produce an error. Then, show the non-viable candidates.
16084 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
16085 }
16086 assert(Result.isInvalid() &&
16087 "C++ binary operator overloading is missing candidates!");
16088 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
16089 return Result;
16090 }
16091
16092 case OR_Ambiguous:
16093 CandidateSet.NoteCandidates(
16094 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16095 << BinaryOperator::getOpcodeStr(Op: Opc)
16096 << Args[0]->getType()
16097 << Args[1]->getType()
16098 << Args[0]->getSourceRange()
16099 << Args[1]->getSourceRange()),
16100 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
16101 OpLoc);
16102 return ExprError();
16103
16104 case OR_Deleted: {
16105 if (isImplicitlyDeleted(FD: Best->Function)) {
16106 FunctionDecl *DeletedFD = Best->Function;
16107 FunctionDecl::DefaultedFunctionKind DFK =
16108 DeletedFD->getDefaultedFunctionKind();
16109 if (DFK.isSpecialMember()) {
16110 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
16111 << Args[0]->getType() << DFK.asSpecialMember();
16112 } else {
16113 assert(DFK.isComparison());
16114 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
16115 << Args[0]->getType() << DeletedFD;
16116 }
16117
16118 // The user probably meant to call this special member. Just
16119 // explain why it's deleted.
16120 NoteDeletedFunction(FD: DeletedFD);
16121 return ExprError();
16122 }
16123
16124 StringLiteral *Msg = Best->Function->getDeletedMessage();
16125 CandidateSet.NoteCandidates(
16126 PD: PartialDiagnosticAt(
16127 OpLoc,
16128 PDiag(DiagID: diag::err_ovl_deleted_oper)
16129 << getOperatorSpelling(Operator: Best->Function->getDeclName()
16130 .getCXXOverloadedOperator())
16131 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16132 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16133 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
16134 OpLoc);
16135 return ExprError();
16136 }
16137 }
16138
16139 // We matched a built-in operator; build it.
16140 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
16141}
16142
16143ExprResult Sema::BuildSynthesizedThreeWayComparison(
16144 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16145 FunctionDecl *DefaultedFn) {
16146 const ComparisonCategoryInfo *Info =
16147 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
16148 // If we're not producing a known comparison category type, we can't
16149 // synthesize a three-way comparison. Let the caller diagnose this.
16150 if (!Info)
16151 return ExprResult((Expr*)nullptr);
16152
16153 // If we ever want to perform this synthesis more generally, we will need to
16154 // apply the temporary materialization conversion to the operands.
16155 assert(LHS->isGLValue() && RHS->isGLValue() &&
16156 "cannot use prvalue expressions more than once");
16157 Expr *OrigLHS = LHS;
16158 Expr *OrigRHS = RHS;
16159
16160 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16161 // each of them multiple times below.
16162 LHS = new (Context)
16163 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16164 LHS->getObjectKind(), LHS);
16165 RHS = new (Context)
16166 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16167 RHS->getObjectKind(), RHS);
16168
16169 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
16170 DefaultedFn);
16171 if (Eq.isInvalid())
16172 return ExprError();
16173
16174 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
16175 AllowRewrittenCandidates: true, DefaultedFn);
16176 if (Less.isInvalid())
16177 return ExprError();
16178
16179 ExprResult Greater;
16180 if (Info->isPartial()) {
16181 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
16182 DefaultedFn);
16183 if (Greater.isInvalid())
16184 return ExprError();
16185 }
16186
16187 // Form the list of comparisons we're going to perform.
16188 struct Comparison {
16189 ExprResult Cmp;
16190 ComparisonCategoryResult Result;
16191 } Comparisons[4] =
16192 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
16193 : ComparisonCategoryResult::Equivalent},
16194 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
16195 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
16196 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
16197 };
16198
16199 int I = Info->isPartial() ? 3 : 2;
16200
16201 // Combine the comparisons with suitable conditional expressions.
16202 ExprResult Result;
16203 for (; I >= 0; --I) {
16204 // Build a reference to the comparison category constant.
16205 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
16206 // FIXME: Missing a constant for a comparison category. Diagnose this?
16207 if (!VI)
16208 return ExprResult((Expr*)nullptr);
16209 ExprResult ThisResult =
16210 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
16211 if (ThisResult.isInvalid())
16212 return ExprError();
16213
16214 // Build a conditional unless this is the final case.
16215 if (Result.get()) {
16216 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
16217 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
16218 if (Result.isInvalid())
16219 return ExprError();
16220 } else {
16221 Result = ThisResult;
16222 }
16223 }
16224
16225 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16226 // bind the OpaqueValueExprs before they're (repeatedly) used.
16227 Expr *SyntacticForm = BinaryOperator::Create(
16228 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
16229 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
16230 FPFeatures: CurFPFeatureOverrides());
16231 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16232 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
16233}
16234
16235static bool PrepareArgumentsForCallToObjectOfClassType(
16236 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16237 MultiExprArg Args, SourceLocation LParenLoc) {
16238
16239 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16240 unsigned NumParams = Proto->getNumParams();
16241 unsigned NumArgsSlots =
16242 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16243 // Build the full argument list for the method call (the implicit object
16244 // parameter is placed at the beginning of the list).
16245 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16246 bool IsError = false;
16247 // Initialize the implicit object parameter.
16248 // Check the argument types.
16249 for (unsigned i = 0; i != NumParams; i++) {
16250 Expr *Arg;
16251 if (i < Args.size()) {
16252 Arg = Args[i];
16253 ExprResult InputInit =
16254 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16255 Context&: S.Context, Parm: Method->getParamDecl(i)),
16256 EqualLoc: SourceLocation(), Init: Arg);
16257 IsError |= InputInit.isInvalid();
16258 Arg = InputInit.getAs<Expr>();
16259 } else {
16260 ExprResult DefArg =
16261 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16262 if (DefArg.isInvalid()) {
16263 IsError = true;
16264 break;
16265 }
16266 Arg = DefArg.getAs<Expr>();
16267 }
16268
16269 MethodArgs.push_back(Elt: Arg);
16270 }
16271 return IsError;
16272}
16273
16274ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16275 SourceLocation RLoc,
16276 Expr *Base,
16277 MultiExprArg ArgExpr) {
16278 SmallVector<Expr *, 2> Args;
16279 Args.push_back(Elt: Base);
16280 for (auto *e : ArgExpr) {
16281 Args.push_back(Elt: e);
16282 }
16283 DeclarationName OpName =
16284 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16285
16286 SourceRange Range = ArgExpr.empty()
16287 ? SourceRange{}
16288 : SourceRange(ArgExpr.front()->getBeginLoc(),
16289 ArgExpr.back()->getEndLoc());
16290
16291 // If either side is type-dependent, create an appropriate dependent
16292 // expression.
16293 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16294
16295 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16296 // CHECKME: no 'operator' keyword?
16297 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16298 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16299 ExprResult Fn = CreateUnresolvedLookupExpr(
16300 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16301 if (Fn.isInvalid())
16302 return ExprError();
16303 // Can't add any actual overloads yet
16304
16305 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16306 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16307 FPFeatures: CurFPFeatureOverrides());
16308 }
16309
16310 // Handle placeholders
16311 UnbridgedCastsSet UnbridgedCasts;
16312 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16313 return ExprError();
16314 }
16315 // Build an empty overload set.
16316 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16317
16318 // Subscript can only be overloaded as a member function.
16319
16320 // Add operator candidates that are member functions.
16321 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16322
16323 // Add builtin operator candidates.
16324 if (Args.size() == 2)
16325 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16326
16327 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16328
16329 // Perform overload resolution.
16330 OverloadCandidateSet::iterator Best;
16331 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16332 case OR_Success: {
16333 // We found a built-in operator or an overloaded operator.
16334 FunctionDecl *FnDecl = Best->Function;
16335
16336 if (FnDecl) {
16337 // We matched an overloaded operator. Build a call to that
16338 // operator.
16339
16340 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16341
16342 // Convert the arguments.
16343 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16344 SmallVector<Expr *, 2> MethodArgs;
16345
16346 // Initialize the object parameter.
16347 if (Method->isExplicitObjectMemberFunction()) {
16348 ExprResult Res =
16349 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16350 if (Res.isInvalid())
16351 return ExprError();
16352 Args[0] = Res.get();
16353 ArgExpr = Args;
16354 } else {
16355 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16356 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16357 if (Arg0.isInvalid())
16358 return ExprError();
16359
16360 MethodArgs.push_back(Elt: Arg0.get());
16361 }
16362
16363 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16364 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16365 if (IsError)
16366 return ExprError();
16367
16368 // Build the actual expression node.
16369 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16370 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16371 ExprResult FnExpr =
16372 CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base,
16373 HadMultipleCandidates, NameInfo: OpLocInfo);
16374 if (FnExpr.isInvalid())
16375 return ExprError();
16376
16377 // Determine the result type
16378 QualType ResultTy = FnDecl->getReturnType();
16379 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16380 ResultTy = ResultTy.getNonLValueExprType(Context);
16381
16382 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16383 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16384 FPFeatures: CurFPFeatureOverrides());
16385
16386 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16387 return ExprError();
16388
16389 if (CheckFunctionCall(FDecl: Method, TheCall,
16390 Proto: Method->getType()->castAs<FunctionProtoType>()))
16391 return ExprError();
16392
16393 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16394 Decl: FnDecl);
16395 } else {
16396 // We matched a built-in operator. Convert the arguments, then
16397 // break out so that we will build the appropriate built-in
16398 // operator node.
16399 ExprResult ArgsRes0 = PerformImplicitConversion(
16400 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16401 Action: AssignmentAction::Passing,
16402 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16403 if (ArgsRes0.isInvalid())
16404 return ExprError();
16405 Args[0] = ArgsRes0.get();
16406
16407 ExprResult ArgsRes1 = PerformImplicitConversion(
16408 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16409 Action: AssignmentAction::Passing,
16410 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16411 if (ArgsRes1.isInvalid())
16412 return ExprError();
16413 Args[1] = ArgsRes1.get();
16414
16415 break;
16416 }
16417 }
16418
16419 case OR_No_Viable_Function: {
16420 PartialDiagnostic PD =
16421 CandidateSet.empty()
16422 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16423 << Args[0]->getType() << /*subscript*/ 0
16424 << Args[0]->getSourceRange() << Range)
16425 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16426 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16427 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16428 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16429 return ExprError();
16430 }
16431
16432 case OR_Ambiguous:
16433 if (Args.size() == 2) {
16434 CandidateSet.NoteCandidates(
16435 PD: PartialDiagnosticAt(
16436 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16437 << "[]" << Args[0]->getType() << Args[1]->getType()
16438 << Args[0]->getSourceRange() << Range),
16439 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16440 } else {
16441 CandidateSet.NoteCandidates(
16442 PD: PartialDiagnosticAt(LLoc,
16443 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16444 << Args[0]->getType()
16445 << Args[0]->getSourceRange() << Range),
16446 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16447 }
16448 return ExprError();
16449
16450 case OR_Deleted: {
16451 StringLiteral *Msg = Best->Function->getDeletedMessage();
16452 CandidateSet.NoteCandidates(
16453 PD: PartialDiagnosticAt(LLoc,
16454 PDiag(DiagID: diag::err_ovl_deleted_oper)
16455 << "[]" << (Msg != nullptr)
16456 << (Msg ? Msg->getString() : StringRef())
16457 << Args[0]->getSourceRange() << Range),
16458 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16459 return ExprError();
16460 }
16461 }
16462
16463 // We matched a built-in operator; build it.
16464 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16465}
16466
16467ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16468 SourceLocation LParenLoc,
16469 MultiExprArg Args,
16470 SourceLocation RParenLoc,
16471 Expr *ExecConfig, bool IsExecConfig,
16472 bool AllowRecovery) {
16473 assert(MemExprE->getType() == Context.BoundMemberTy ||
16474 MemExprE->getType() == Context.OverloadTy);
16475
16476 // Dig out the member expression. This holds both the object
16477 // argument and the member function we're referring to.
16478 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16479
16480 // Determine whether this is a call to a pointer-to-member function.
16481 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16482 assert(op->getType() == Context.BoundMemberTy);
16483 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16484
16485 QualType fnType =
16486 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16487
16488 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16489 QualType resultType = proto->getCallResultType(Context);
16490 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16491
16492 // Check that the object type isn't more qualified than the
16493 // member function we're calling.
16494 Qualifiers funcQuals = proto->getMethodQuals();
16495
16496 QualType objectType = op->getLHS()->getType();
16497 if (op->getOpcode() == BO_PtrMemI)
16498 objectType = objectType->castAs<PointerType>()->getPointeeType();
16499 Qualifiers objectQuals = objectType.getQualifiers();
16500
16501 Qualifiers difference = objectQuals - funcQuals;
16502 difference.removeObjCGCAttr();
16503 difference.removeAddressSpace();
16504 if (difference) {
16505 std::string qualsString = difference.getAsString();
16506 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16507 << fnType.getUnqualifiedType()
16508 << qualsString
16509 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16510 }
16511
16512 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16513 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16514 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16515
16516 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16517 CE: call, FD: nullptr))
16518 return ExprError();
16519
16520 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16521 return ExprError();
16522
16523 if (CheckOtherCall(TheCall: call, Proto: proto))
16524 return ExprError();
16525
16526 return MaybeBindToTemporary(E: call);
16527 }
16528
16529 // We only try to build a recovery expr at this level if we can preserve
16530 // the return type, otherwise we return ExprError() and let the caller
16531 // recover.
16532 auto BuildRecoveryExpr = [&](QualType Type) {
16533 if (!AllowRecovery)
16534 return ExprError();
16535 std::vector<Expr *> SubExprs = {MemExprE};
16536 llvm::append_range(C&: SubExprs, R&: Args);
16537 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16538 T: Type);
16539 };
16540 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16541 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16542 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16543
16544 UnbridgedCastsSet UnbridgedCasts;
16545 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16546 return ExprError();
16547
16548 MemberExpr *MemExpr;
16549 CXXMethodDecl *Method = nullptr;
16550 bool HadMultipleCandidates = false;
16551 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16552 NestedNameSpecifier Qualifier = std::nullopt;
16553 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16554 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16555 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16556 FoundDecl = MemExpr->getFoundDecl();
16557 Qualifier = MemExpr->getQualifier();
16558 UnbridgedCasts.restore();
16559 } else {
16560 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16561 Qualifier = UnresExpr->getQualifier();
16562
16563 QualType ObjectType = UnresExpr->getBaseType();
16564 Expr::Classification ObjectClassification
16565 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16566 : UnresExpr->getBase()->Classify(Ctx&: Context);
16567
16568 // Add overload candidates
16569 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16570 OverloadCandidateSet::CSK_Normal);
16571
16572 // FIXME: avoid copy.
16573 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16574 if (UnresExpr->hasExplicitTemplateArgs()) {
16575 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16576 TemplateArgs = &TemplateArgsBuffer;
16577 }
16578
16579 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16580 E = UnresExpr->decls_end(); I != E; ++I) {
16581
16582 QualType ExplicitObjectType = ObjectType;
16583
16584 NamedDecl *Func = *I;
16585 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16586 if (isa<UsingShadowDecl>(Val: Func))
16587 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16588
16589 bool HasExplicitParameter = false;
16590 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16591 M && M->hasCXXExplicitFunctionObjectParameter())
16592 HasExplicitParameter = true;
16593 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16594 M &&
16595 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16596 HasExplicitParameter = true;
16597
16598 if (HasExplicitParameter)
16599 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16600
16601 // Microsoft supports direct constructor calls.
16602 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16603 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16604 CandidateSet,
16605 /*SuppressUserConversions*/ false);
16606 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16607 // If explicit template arguments were provided, we can't call a
16608 // non-template member function.
16609 if (TemplateArgs)
16610 continue;
16611
16612 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16613 ObjectClassification, Args, CandidateSet,
16614 /*SuppressUserConversions=*/false);
16615 } else {
16616 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16617 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16618 ObjectType: ExplicitObjectType, ObjectClassification,
16619 Args, CandidateSet,
16620 /*SuppressUserConversions=*/false);
16621 }
16622 }
16623
16624 HadMultipleCandidates = (CandidateSet.size() > 1);
16625
16626 DeclarationName DeclName = UnresExpr->getMemberName();
16627
16628 UnbridgedCasts.restore();
16629
16630 OverloadCandidateSet::iterator Best;
16631 bool Succeeded = false;
16632 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16633 Best)) {
16634 case OR_Success:
16635 Method = cast<CXXMethodDecl>(Val: Best->Function);
16636 FoundDecl = Best->FoundDecl;
16637 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16638 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16639 break;
16640 // If FoundDecl is different from Method (such as if one is a template
16641 // and the other a specialization), make sure DiagnoseUseOfDecl is
16642 // called on both.
16643 // FIXME: This would be more comprehensively addressed by modifying
16644 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16645 // being used.
16646 if (Method != FoundDecl.getDecl() &&
16647 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16648 break;
16649 Succeeded = true;
16650 break;
16651
16652 case OR_No_Viable_Function:
16653 CandidateSet.NoteCandidates(
16654 PD: PartialDiagnosticAt(
16655 UnresExpr->getMemberLoc(),
16656 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16657 << DeclName << MemExprE->getSourceRange()),
16658 S&: *this, OCD: OCD_AllCandidates, Args);
16659 break;
16660 case OR_Ambiguous:
16661 CandidateSet.NoteCandidates(
16662 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16663 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16664 << DeclName << MemExprE->getSourceRange()),
16665 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16666 break;
16667 case OR_Deleted:
16668 DiagnoseUseOfDeletedFunction(
16669 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16670 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16671 break;
16672 }
16673 // Overload resolution fails, try to recover.
16674 if (!Succeeded)
16675 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16676
16677 ExprResult Res =
16678 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16679 if (Res.isInvalid())
16680 return ExprError();
16681 MemExprE = Res.get();
16682
16683 // If overload resolution picked a static member
16684 // build a non-member call based on that function.
16685 if (Method->isStatic()) {
16686 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16687 Config: ExecConfig, IsExecConfig);
16688 }
16689
16690 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16691 }
16692
16693 QualType ResultType = Method->getReturnType();
16694 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16695 ResultType = ResultType.getNonLValueExprType(Context);
16696
16697 assert(Method && "Member call to something that isn't a method?");
16698 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16699
16700 CallExpr *TheCall = nullptr;
16701 llvm::SmallVector<Expr *, 8> NewArgs;
16702 if (Method->isExplicitObjectMemberFunction()) {
16703 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16704 NewArgs))
16705 return ExprError();
16706
16707 // FIXME: avoid copy.
16708 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16709 if (MemExpr->hasExplicitTemplateArgs()) {
16710 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16711 TemplateArgs = &TemplateArgsBuffer;
16712 }
16713
16714 // Build the actual expression node.
16715 ExprResult FnExpr = CreateFunctionRefExpr(
16716 S&: *this, QualifierLoc: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(),
16717 Fn: Method, FoundDecl, Base: MemExpr, HadMultipleCandidates,
16718 NameInfo: MemExpr->getMemberNameInfo(), TemplateArgs);
16719 if (FnExpr.isInvalid())
16720 return ExprError();
16721
16722 TheCall =
16723 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16724 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16725 TheCall->setUsesMemberSyntax(true);
16726 } else {
16727 // Convert the object argument (for a non-static member function call).
16728 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16729 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16730 if (ObjectArg.isInvalid())
16731 return ExprError();
16732 MemExpr->setBase(ObjectArg.get());
16733 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16734 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16735 MinNumArgs: Proto->getNumParams());
16736 }
16737
16738 // Check for a valid return type.
16739 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16740 CE: TheCall, FD: Method))
16741 return BuildRecoveryExpr(ResultType);
16742
16743 // Convert the rest of the arguments
16744 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16745 RParenLoc))
16746 return BuildRecoveryExpr(ResultType);
16747
16748 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16749
16750 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16751 return ExprError();
16752
16753 // In the case the method to call was not selected by the overloading
16754 // resolution process, we still need to handle the enable_if attribute. Do
16755 // that here, so it will not hide previous -- and more relevant -- errors.
16756 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16757 if (const EnableIfAttr *Attr =
16758 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16759 Diag(Loc: MemE->getMemberLoc(),
16760 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16761 << Method << Method->getSourceRange();
16762 Diag(Loc: Method->getLocation(),
16763 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16764 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16765 return ExprError();
16766 }
16767 }
16768
16769 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16770 TheCall->getDirectCallee()->isPureVirtual()) {
16771 const FunctionDecl *MD = TheCall->getDirectCallee();
16772
16773 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16774 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16775 Diag(Loc: MemExpr->getBeginLoc(),
16776 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16777 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16778 << MD->getParent();
16779
16780 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16781 if (getLangOpts().AppleKext)
16782 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16783 << MD->getParent() << MD->getDeclName();
16784 }
16785 }
16786
16787 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16788 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16789 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16790 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16791 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16792 DtorLoc: MemExpr->getMemberLoc());
16793 }
16794
16795 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16796 Decl: TheCall->getDirectCallee());
16797}
16798
16799ExprResult
16800Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16801 SourceLocation LParenLoc,
16802 MultiExprArg Args,
16803 SourceLocation RParenLoc) {
16804 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16805 return ExprError();
16806 ExprResult Object = Obj;
16807
16808 UnbridgedCastsSet UnbridgedCasts;
16809 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16810 return ExprError();
16811
16812 assert(Object.get()->getType()->isRecordType() &&
16813 "Requires object type argument");
16814
16815 // C++ [over.call.object]p1:
16816 // If the primary-expression E in the function call syntax
16817 // evaluates to a class object of type "cv T", then the set of
16818 // candidate functions includes at least the function call
16819 // operators of T. The function call operators of T are obtained by
16820 // ordinary lookup of the name operator() in the context of
16821 // (E).operator().
16822 OverloadCandidateSet CandidateSet(LParenLoc,
16823 OverloadCandidateSet::CSK_Operator);
16824 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16825
16826 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16827 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16828 return true;
16829
16830 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16831 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16832 LookupQualifiedName(R, LookupCtx: Record);
16833 R.suppressAccessDiagnostics();
16834
16835 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16836 Oper != OperEnd; ++Oper) {
16837 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16838 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16839 /*SuppressUserConversion=*/SuppressUserConversions: false);
16840 }
16841
16842 // When calling a lambda, both the call operator, and
16843 // the conversion operator to function pointer
16844 // are considered. But when constraint checking
16845 // on the call operator fails, it will also fail on the
16846 // conversion operator as the constraints are always the same.
16847 // As the user probably does not intend to perform a surrogate call,
16848 // we filter them out to produce better error diagnostics, ie to avoid
16849 // showing 2 failed overloads instead of one.
16850 bool IgnoreSurrogateFunctions = false;
16851 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16852 const OverloadCandidate &Candidate = *CandidateSet.begin();
16853 if (!Candidate.Viable &&
16854 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16855 IgnoreSurrogateFunctions = true;
16856 }
16857
16858 // C++ [over.call.object]p2:
16859 // In addition, for each (non-explicit in C++0x) conversion function
16860 // declared in T of the form
16861 //
16862 // operator conversion-type-id () cv-qualifier;
16863 //
16864 // where cv-qualifier is the same cv-qualification as, or a
16865 // greater cv-qualification than, cv, and where conversion-type-id
16866 // denotes the type "pointer to function of (P1,...,Pn) returning
16867 // R", or the type "reference to pointer to function of
16868 // (P1,...,Pn) returning R", or the type "reference to function
16869 // of (P1,...,Pn) returning R", a surrogate call function [...]
16870 // is also considered as a candidate function. Similarly,
16871 // surrogate call functions are added to the set of candidate
16872 // functions for each conversion function declared in an
16873 // accessible base class provided the function is not hidden
16874 // within T by another intervening declaration.
16875 const auto &Conversions = Record->getVisibleConversionFunctions();
16876 for (auto I = Conversions.begin(), E = Conversions.end();
16877 !IgnoreSurrogateFunctions && I != E; ++I) {
16878 NamedDecl *D = *I;
16879 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16880 if (isa<UsingShadowDecl>(Val: D))
16881 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16882
16883 // Skip over templated conversion functions; they aren't
16884 // surrogates.
16885 if (isa<FunctionTemplateDecl>(Val: D))
16886 continue;
16887
16888 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16889 if (!Conv->isExplicit()) {
16890 // Strip the reference type (if any) and then the pointer type (if
16891 // any) to get down to what might be a function type.
16892 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16893 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16894 ConvType = ConvPtrType->getPointeeType();
16895
16896 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16897 {
16898 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16899 Object: Object.get(), Args, CandidateSet);
16900 }
16901 }
16902 }
16903
16904 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16905
16906 // Perform overload resolution.
16907 OverloadCandidateSet::iterator Best;
16908 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16909 Best)) {
16910 case OR_Success:
16911 // Overload resolution succeeded; we'll build the appropriate call
16912 // below.
16913 break;
16914
16915 case OR_No_Viable_Function: {
16916 PartialDiagnostic PD =
16917 CandidateSet.empty()
16918 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16919 << Object.get()->getType() << /*call*/ 1
16920 << Object.get()->getSourceRange())
16921 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16922 << Object.get()->getType() << Object.get()->getSourceRange());
16923 CandidateSet.NoteCandidates(
16924 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16925 OCD: OCD_AllCandidates, Args);
16926 break;
16927 }
16928 case OR_Ambiguous:
16929 if (!R.isAmbiguous())
16930 CandidateSet.NoteCandidates(
16931 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16932 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16933 << Object.get()->getType()
16934 << Object.get()->getSourceRange()),
16935 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16936 break;
16937
16938 case OR_Deleted: {
16939 // FIXME: Is this diagnostic here really necessary? It seems that
16940 // 1. we don't have any tests for this diagnostic, and
16941 // 2. we already issue err_deleted_function_use for this later on anyway.
16942 StringLiteral *Msg = Best->Function->getDeletedMessage();
16943 CandidateSet.NoteCandidates(
16944 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16945 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16946 << Object.get()->getType() << (Msg != nullptr)
16947 << (Msg ? Msg->getString() : StringRef())
16948 << Object.get()->getSourceRange()),
16949 S&: *this, OCD: OCD_AllCandidates, Args);
16950 break;
16951 }
16952 }
16953
16954 if (Best == CandidateSet.end())
16955 return true;
16956
16957 UnbridgedCasts.restore();
16958
16959 if (Best->Function == nullptr) {
16960 // Since there is no function declaration, this is one of the
16961 // surrogate candidates. Dig out the conversion function.
16962 CXXConversionDecl *Conv
16963 = cast<CXXConversionDecl>(
16964 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16965
16966 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16967 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16968 "Found Decl & conversion-to-functionptr should be same, right?!");
16969 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16970 FoundDecl: Best->FoundDecl);
16971 if (DiagnoseUseOfDecl(D: Conv, Locs: LParenLoc))
16972 return ExprError();
16973 // We selected one of the surrogate functions that converts the
16974 // object parameter to a function pointer. Perform the conversion
16975 // on the object argument, then let BuildCallExpr finish the job.
16976
16977 // Create an implicit member expr to refer to the conversion operator.
16978 // and then call it.
16979 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16980 Method: Conv, HadMultipleCandidates);
16981 if (Call.isInvalid())
16982 return ExprError();
16983 // Record usage of conversion in an implicit cast.
16984 Call = ImplicitCastExpr::Create(
16985 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16986 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16987
16988 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16989 }
16990
16991 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16992
16993 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16994 // that calls this method, using Object for the implicit object
16995 // parameter and passing along the remaining arguments.
16996 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16997
16998 // An error diagnostic has already been printed when parsing the declaration.
16999 if (Method->isInvalidDecl())
17000 return ExprError();
17001
17002 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
17003 unsigned NumParams = Proto->getNumParams();
17004
17005 DeclarationNameInfo OpLocInfo(
17006 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
17007 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
17008 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl, Base: Obj,
17009 HadMultipleCandidates, NameInfo: OpLocInfo);
17010 if (NewFn.isInvalid())
17011 return true;
17012
17013 SmallVector<Expr *, 8> MethodArgs;
17014 MethodArgs.reserve(N: NumParams + 1);
17015
17016 bool IsError = false;
17017
17018 // Initialize the object parameter.
17019 llvm::SmallVector<Expr *, 8> NewArgs;
17020 if (Method->isExplicitObjectMemberFunction()) {
17021 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
17022 } else {
17023 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
17024 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
17025 if (ObjRes.isInvalid())
17026 IsError = true;
17027 else
17028 Object = ObjRes;
17029 MethodArgs.push_back(Elt: Object.get());
17030 }
17031
17032 IsError |= PrepareArgumentsForCallToObjectOfClassType(
17033 S&: *this, MethodArgs, Method, Args, LParenLoc);
17034
17035 // If this is a variadic call, handle args passed through "...".
17036 if (Proto->isVariadic()) {
17037 // Promote the arguments (C99 6.5.2.2p7).
17038 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
17039 ExprResult Arg = DefaultVariadicArgumentPromotion(
17040 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
17041 IsError |= Arg.isInvalid();
17042 MethodArgs.push_back(Elt: Arg.get());
17043 }
17044 }
17045
17046 if (IsError)
17047 return true;
17048
17049 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
17050
17051 // Once we've built TheCall, all of the expressions are properly owned.
17052 QualType ResultTy = Method->getReturnType();
17053 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17054 ResultTy = ResultTy.getNonLValueExprType(Context);
17055
17056 CallExpr *TheCall = CXXOperatorCallExpr::Create(
17057 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
17058 FPFeatures: CurFPFeatureOverrides());
17059
17060 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
17061 return true;
17062
17063 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
17064 return true;
17065
17066 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17067}
17068
17069ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
17070 SourceLocation OpLoc,
17071 bool *NoArrowOperatorFound) {
17072 assert(Base->getType()->isRecordType() &&
17073 "left-hand side must have class type");
17074
17075 if (checkPlaceholderForOverload(S&: *this, E&: Base))
17076 return ExprError();
17077
17078 SourceLocation Loc = Base->getExprLoc();
17079
17080 // C++ [over.ref]p1:
17081 //
17082 // [...] An expression x->m is interpreted as (x.operator->())->m
17083 // for a class object x of type T if T::operator->() exists and if
17084 // the operator is selected as the best match function by the
17085 // overload resolution mechanism (13.3).
17086 DeclarationName OpName =
17087 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
17088 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
17089
17090 if (RequireCompleteType(Loc, T: Base->getType(),
17091 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
17092 return ExprError();
17093
17094 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
17095 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
17096 R.suppressAccessDiagnostics();
17097
17098 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
17099 Oper != OperEnd; ++Oper) {
17100 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
17101 Args: {}, CandidateSet,
17102 /*SuppressUserConversion=*/SuppressUserConversions: false);
17103 }
17104
17105 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17106
17107 // Perform overload resolution.
17108 OverloadCandidateSet::iterator Best;
17109 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
17110 case OR_Success:
17111 // Overload resolution succeeded; we'll build the call below.
17112 break;
17113
17114 case OR_No_Viable_Function: {
17115 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
17116 if (CandidateSet.empty()) {
17117 QualType BaseType = Base->getType();
17118 if (NoArrowOperatorFound) {
17119 // Report this specific error to the caller instead of emitting a
17120 // diagnostic, as requested.
17121 *NoArrowOperatorFound = true;
17122 return ExprError();
17123 }
17124 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
17125 << BaseType << Base->getSourceRange();
17126 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17127 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
17128 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
17129 }
17130 } else
17131 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
17132 << "operator->" << Base->getSourceRange();
17133 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
17134 return ExprError();
17135 }
17136 case OR_Ambiguous:
17137 if (!R.isAmbiguous())
17138 CandidateSet.NoteCandidates(
17139 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
17140 << "->" << Base->getType()
17141 << Base->getSourceRange()),
17142 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
17143 return ExprError();
17144
17145 case OR_Deleted: {
17146 StringLiteral *Msg = Best->Function->getDeletedMessage();
17147 CandidateSet.NoteCandidates(
17148 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
17149 << "->" << (Msg != nullptr)
17150 << (Msg ? Msg->getString() : StringRef())
17151 << Base->getSourceRange()),
17152 S&: *this, OCD: OCD_AllCandidates, Args: Base);
17153 return ExprError();
17154 }
17155 }
17156
17157 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
17158
17159 // Convert the object parameter.
17160 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
17161
17162 if (Method->isExplicitObjectMemberFunction()) {
17163 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
17164 if (R.isInvalid())
17165 return ExprError();
17166 Base = R.get();
17167 } else {
17168 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
17169 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
17170 if (BaseResult.isInvalid())
17171 return ExprError();
17172 Base = BaseResult.get();
17173 }
17174
17175 // Build the operator call.
17176 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
17177 Base, HadMultipleCandidates, Loc: OpLoc);
17178 if (FnExpr.isInvalid())
17179 return ExprError();
17180
17181 QualType ResultTy = Method->getReturnType();
17182 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17183 ResultTy = ResultTy.getNonLValueExprType(Context);
17184
17185 CallExpr *TheCall =
17186 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
17187 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
17188
17189 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
17190 return ExprError();
17191
17192 if (CheckFunctionCall(FDecl: Method, TheCall,
17193 Proto: Method->getType()->castAs<FunctionProtoType>()))
17194 return ExprError();
17195
17196 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
17197}
17198
17199ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
17200 DeclarationNameInfo &SuffixInfo,
17201 ArrayRef<Expr*> Args,
17202 SourceLocation LitEndLoc,
17203 TemplateArgumentListInfo *TemplateArgs) {
17204 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17205
17206 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17207 OverloadCandidateSet::CSK_Normal);
17208 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
17209 ExplicitTemplateArgs: TemplateArgs);
17210
17211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17212
17213 // Perform overload resolution. This will usually be trivial, but might need
17214 // to perform substitutions for a literal operator template.
17215 OverloadCandidateSet::iterator Best;
17216 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
17217 case OR_Success:
17218 case OR_Deleted:
17219 break;
17220
17221 case OR_No_Viable_Function:
17222 CandidateSet.NoteCandidates(
17223 PD: PartialDiagnosticAt(UDSuffixLoc,
17224 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
17225 << R.getLookupName()),
17226 S&: *this, OCD: OCD_AllCandidates, Args);
17227 return ExprError();
17228
17229 case OR_Ambiguous:
17230 CandidateSet.NoteCandidates(
17231 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
17232 << R.getLookupName()),
17233 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
17234 return ExprError();
17235 }
17236
17237 FunctionDecl *FD = Best->Function;
17238 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl, Base: nullptr,
17239 HadMultipleCandidates, NameInfo: SuffixInfo);
17240 if (Fn.isInvalid())
17241 return true;
17242
17243 // Check the argument types. This should almost always be a no-op, except
17244 // that array-to-pointer decay is applied to string literals.
17245 Expr *ConvArgs[2];
17246 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17247 ExprResult InputInit = PerformCopyInitialization(
17248 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17249 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17250 if (InputInit.isInvalid())
17251 return true;
17252 ConvArgs[ArgIdx] = InputInit.get();
17253 }
17254
17255 QualType ResultTy = FD->getReturnType();
17256 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17257 ResultTy = ResultTy.getNonLValueExprType(Context);
17258
17259 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17260 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17261 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17262
17263 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17264 return ExprError();
17265
17266 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17267 return ExprError();
17268
17269 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17270}
17271
17272Sema::ForRangeStatus
17273Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17274 SourceLocation RangeLoc,
17275 const DeclarationNameInfo &NameInfo,
17276 LookupResult &MemberLookup,
17277 OverloadCandidateSet *CandidateSet,
17278 Expr *Range, ExprResult *CallExpr) {
17279 Scope *S = nullptr;
17280
17281 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17282 if (!MemberLookup.empty()) {
17283 ExprResult MemberRef =
17284 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17285 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17286 /*TemplateKWLoc=*/SourceLocation(),
17287 /*FirstQualifierInScope=*/nullptr,
17288 R&: MemberLookup,
17289 /*TemplateArgs=*/nullptr, S);
17290 if (MemberRef.isInvalid()) {
17291 *CallExpr = ExprError();
17292 return FRS_DiagnosticIssued;
17293 }
17294 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17295 if (CallExpr->isInvalid()) {
17296 *CallExpr = ExprError();
17297 return FRS_DiagnosticIssued;
17298 }
17299 } else {
17300 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17301 NNSLoc: NestedNameSpecifierLoc(),
17302 DNI: NameInfo, Fns: UnresolvedSet<0>());
17303 if (FnR.isInvalid())
17304 return FRS_DiagnosticIssued;
17305 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17306
17307 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17308 CandidateSet, Result: CallExpr);
17309 if (CandidateSet->empty() || CandidateSetError) {
17310 *CallExpr = ExprError();
17311 return FRS_NoViableFunction;
17312 }
17313 OverloadCandidateSet::iterator Best;
17314 OverloadingResult OverloadResult =
17315 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17316
17317 if (OverloadResult == OR_No_Viable_Function) {
17318 *CallExpr = ExprError();
17319 return FRS_NoViableFunction;
17320 }
17321 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17322 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17323 OverloadResult,
17324 /*AllowTypoCorrection=*/false);
17325 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17326 *CallExpr = ExprError();
17327 return FRS_DiagnosticIssued;
17328 }
17329 }
17330 return FRS_Success;
17331}
17332
17333ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17334 FunctionDecl *Fn) {
17335 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17336 ExprResult SubExpr =
17337 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17338 if (SubExpr.isInvalid())
17339 return ExprError();
17340 if (SubExpr.get() == PE->getSubExpr())
17341 return PE;
17342
17343 return new (Context)
17344 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17345 }
17346
17347 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17348 ExprResult SubExpr =
17349 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17350 if (SubExpr.isInvalid())
17351 return ExprError();
17352 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17353 SubExpr.get()->getType()) &&
17354 "Implicit cast type cannot be determined from overload");
17355 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17356 if (SubExpr.get() == ICE->getSubExpr())
17357 return ICE;
17358
17359 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17360 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17361 FPO: CurFPFeatureOverrides());
17362 }
17363
17364 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17365 if (!GSE->isResultDependent()) {
17366 ExprResult SubExpr =
17367 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17368 if (SubExpr.isInvalid())
17369 return ExprError();
17370 if (SubExpr.get() == GSE->getResultExpr())
17371 return GSE;
17372
17373 // Replace the resulting type information before rebuilding the generic
17374 // selection expression.
17375 ArrayRef<Expr *> A = GSE->getAssocExprs();
17376 SmallVector<Expr *, 4> AssocExprs(A);
17377 unsigned ResultIdx = GSE->getResultIndex();
17378 AssocExprs[ResultIdx] = SubExpr.get();
17379
17380 if (GSE->isExprPredicate())
17381 return GenericSelectionExpr::Create(
17382 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17383 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17384 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17385 ResultIndex: ResultIdx);
17386 return GenericSelectionExpr::Create(
17387 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17388 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17389 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17390 ResultIndex: ResultIdx);
17391 }
17392 // Rather than fall through to the unreachable, return the original generic
17393 // selection expression.
17394 return GSE;
17395 }
17396
17397 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17398 assert(UnOp->getOpcode() == UO_AddrOf &&
17399 "Can only take the address of an overloaded function");
17400 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17401 if (!Method->isImplicitObjectMemberFunction()) {
17402 // Do nothing: the address of static and
17403 // explicit object member functions is a (non-member) function pointer.
17404 } else {
17405 // Fix the subexpression, which really has to be an
17406 // UnresolvedLookupExpr holding an overloaded member function
17407 // or template.
17408 ExprResult SubExpr =
17409 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17410 if (SubExpr.isInvalid())
17411 return ExprError();
17412 if (SubExpr.get() == UnOp->getSubExpr())
17413 return UnOp;
17414
17415 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17416 Op: SubExpr.get(), MD: Method))
17417 return ExprError();
17418
17419 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17420 "fixed to something other than a decl ref");
17421 NestedNameSpecifier Qualifier =
17422 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17423 assert(Qualifier &&
17424 "fixed to a member ref with no nested name qualifier");
17425
17426 // We have taken the address of a pointer to member
17427 // function. Perform the computation here so that we get the
17428 // appropriate pointer to member type.
17429 QualType MemPtrType = Context.getMemberPointerType(
17430 T: Fn->getType(), Qualifier,
17431 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17432 // Under the MS ABI, lock down the inheritance model now.
17433 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17434 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17435
17436 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17437 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17438 l: UnOp->getOperatorLoc(), CanOverflow: false,
17439 FPFeatures: CurFPFeatureOverrides());
17440 }
17441 }
17442 ExprResult SubExpr =
17443 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17444 if (SubExpr.isInvalid())
17445 return ExprError();
17446 if (SubExpr.get() == UnOp->getSubExpr())
17447 return UnOp;
17448
17449 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17450 InputExpr: SubExpr.get());
17451 }
17452
17453 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17454 if (Found.getAccess() == AS_none) {
17455 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17456 }
17457 // FIXME: avoid copy.
17458 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17459 if (ULE->hasExplicitTemplateArgs()) {
17460 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17461 TemplateArgs = &TemplateArgsBuffer;
17462 }
17463
17464 QualType Type = Fn->getType();
17465 ExprValueKind ValueKind =
17466 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17467 ? VK_LValue
17468 : VK_PRValue;
17469
17470 // FIXME: Duplicated from BuildDeclarationNameExpr.
17471 if (unsigned BID = Fn->getBuiltinID()) {
17472 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17473 Type = Context.BuiltinFnTy;
17474 ValueKind = VK_PRValue;
17475 }
17476 }
17477
17478 DeclRefExpr *DRE = BuildDeclRefExpr(
17479 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17480 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17481 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17482 return DRE;
17483 }
17484
17485 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17486 // FIXME: avoid copy.
17487 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17488 if (MemExpr->hasExplicitTemplateArgs()) {
17489 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17490 TemplateArgs = &TemplateArgsBuffer;
17491 }
17492
17493 Expr *Base;
17494
17495 // If we're filling in a static method where we used to have an
17496 // implicit member access, rewrite to a simple decl ref.
17497 if (MemExpr->isImplicitAccess()) {
17498 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17499 DeclRefExpr *DRE = BuildDeclRefExpr(
17500 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17501 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17502 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17503 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17504 return DRE;
17505 } else {
17506 SourceLocation Loc = MemExpr->getMemberLoc();
17507 if (MemExpr->getQualifier())
17508 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17509 Base =
17510 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17511 }
17512 } else
17513 Base = MemExpr->getBase();
17514
17515 ExprValueKind valueKind;
17516 QualType type;
17517 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17518 valueKind = VK_LValue;
17519 type = Fn->getType();
17520 } else {
17521 valueKind = VK_PRValue;
17522 type = Context.BoundMemberTy;
17523 }
17524
17525 return BuildMemberExpr(
17526 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17527 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17528 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17529 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17530 }
17531
17532 llvm_unreachable("Invalid reference to overloaded function");
17533}
17534
17535ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17536 DeclAccessPair Found,
17537 FunctionDecl *Fn) {
17538 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17539}
17540
17541bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17542 FunctionDecl *Function) {
17543 if (!PartialOverloading || !Function)
17544 return true;
17545 if (Function->isVariadic())
17546 return false;
17547 if (const auto *Proto =
17548 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17549 if (Proto->isTemplateVariadic())
17550 return false;
17551 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17552 if (const auto *Proto =
17553 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17554 if (Proto->isTemplateVariadic())
17555 return false;
17556 return true;
17557}
17558
17559void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17560 DeclarationName Name,
17561 OverloadCandidateSet &CandidateSet,
17562 FunctionDecl *Fn, MultiExprArg Args,
17563 bool IsMember) {
17564 StringLiteral *Msg = Fn->getDeletedMessage();
17565 CandidateSet.NoteCandidates(
17566 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17567 << IsMember << Name << (Msg != nullptr)
17568 << (Msg ? Msg->getString() : StringRef())
17569 << Range),
17570 S&: *this, OCD: OCD_AllCandidates, Args);
17571}
17572