Bug Summary

File:build/source/clang/lib/Sema/SemaOverload.cpp
Warning:line 14067, column 21
Although the value stored to 'LHS' is used in the enclosing expression, the value is never actually read from 'LHS'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaOverload.cpp
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 "clang/AST/ASTContext.h"
14#include "clang/AST/CXXInheritance.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DependenceFlags.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/Type.h"
22#include "clang/AST/TypeOrdering.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/DiagnosticOptions.h"
25#include "clang/Basic/OperatorKinds.h"
26#include "clang/Basic/PartialDiagnostic.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/Template.h"
35#include "clang/Sema/TemplateDeduction.h"
36#include "llvm/ADT/DenseSet.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/Support/Casting.h"
41#include <algorithm>
42#include <cstdlib>
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48using AllowedExplicit = Sema::AllowedExplicit;
49
50static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
51 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
52 return P->hasAttr<PassObjectSizeAttr>();
53 });
54}
55
56/// A convenience routine for creating a decayed reference to a function.
57static ExprResult CreateFunctionRefExpr(
58 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
59 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
60 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
61 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
62 return ExprError();
63 // If FoundDecl is different from Fn (such as if one is a template
64 // and the other a specialization), make sure DiagnoseUseOfDecl is
65 // called on both.
66 // FIXME: This would be more comprehensively addressed by modifying
67 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
68 // being used.
69 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
70 return ExprError();
71 DeclRefExpr *DRE = new (S.Context)
72 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
73 if (HadMultipleCandidates)
74 DRE->setHadMultipleCandidates(true);
75
76 S.MarkDeclRefReferenced(DRE, Base);
77 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
78 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
79 S.ResolveExceptionSpec(Loc, FPT);
80 DRE->setType(Fn->getType());
81 }
82 }
83 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
84 CK_FunctionToPointerDecay);
85}
86
87static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
88 bool InOverloadResolution,
89 StandardConversionSequence &SCS,
90 bool CStyle,
91 bool AllowObjCWritebackConversion);
92
93static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
94 QualType &ToType,
95 bool InOverloadResolution,
96 StandardConversionSequence &SCS,
97 bool CStyle);
98static OverloadingResult
99IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
100 UserDefinedConversionSequence& User,
101 OverloadCandidateSet& Conversions,
102 AllowedExplicit AllowExplicit,
103 bool AllowObjCConversionOnExplicit);
104
105static ImplicitConversionSequence::CompareKind
106CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
110static ImplicitConversionSequence::CompareKind
111CompareQualificationConversions(Sema &S,
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
115static ImplicitConversionSequence::CompareKind
116CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
120/// GetConversionRank - Retrieve the implicit conversion rank
121/// corresponding to the given implicit conversion kind.
122ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
123 static const ImplicitConversionRank
124 Rank[] = {
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Promotion,
132 ICR_Promotion,
133 ICR_Promotion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_OCL_Scalar_Widening,
147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_Writeback_Conversion,
151 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
152 // it was omitted by the patch that added
153 // ICK_Zero_Event_Conversion
154 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Queue_Conversion
157 ICR_C_Conversion,
158 ICR_C_Conversion_Extension
159 };
160 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
161 return Rank[(int)Kind];
162}
163
164/// GetImplicitConversionName - Return the name of this kind of
165/// implicit conversion.
166static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
167 static const char* const Name[] = {
168 "No conversion",
169 "Lvalue-to-rvalue",
170 "Array-to-pointer",
171 "Function-to-pointer",
172 "Function pointer conversion",
173 "Qualification",
174 "Integral promotion",
175 "Floating point promotion",
176 "Complex promotion",
177 "Integral conversion",
178 "Floating conversion",
179 "Complex conversion",
180 "Floating-integral conversion",
181 "Pointer conversion",
182 "Pointer-to-member conversion",
183 "Boolean conversion",
184 "Compatible-types conversion",
185 "Derived-to-base conversion",
186 "Vector conversion",
187 "SVE Vector conversion",
188 "RVV Vector conversion",
189 "Vector splat",
190 "Complex-real conversion",
191 "Block Pointer conversion",
192 "Transparent Union Conversion",
193 "Writeback conversion",
194 "OpenCL Zero Event Conversion",
195 "OpenCL Zero Queue Conversion",
196 "C specific type conversion",
197 "Incompatible pointer conversion"
198 };
199 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
200 return Name[Kind];
201}
202
203/// StandardConversionSequence - Set the standard conversion
204/// sequence to the identity conversion.
205void StandardConversionSequence::setAsIdentityConversion() {
206 First = ICK_Identity;
207 Second = ICK_Identity;
208 Third = ICK_Identity;
209 DeprecatedStringLiteralToCharPtr = false;
210 QualificationIncludesObjCLifetime = false;
211 ReferenceBinding = false;
212 DirectBinding = false;
213 IsLvalueReference = true;
214 BindsToFunctionLvalue = false;
215 BindsToRvalue = false;
216 BindsImplicitObjectArgumentWithoutRefQualifier = false;
217 ObjCLifetimeConversionBinding = false;
218 CopyConstructor = nullptr;
219}
220
221/// getRank - Retrieve the rank of this standard conversion sequence
222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223/// implicit conversions.
224ImplicitConversionRank StandardConversionSequence::getRank() const {
225 ImplicitConversionRank Rank = ICR_Exact_Match;
226 if (GetConversionRank(First) > Rank)
227 Rank = GetConversionRank(First);
228 if (GetConversionRank(Second) > Rank)
229 Rank = GetConversionRank(Second);
230 if (GetConversionRank(Third) > Rank)
231 Rank = GetConversionRank(Third);
232 return Rank;
233}
234
235/// isPointerConversionToBool - Determines whether this conversion is
236/// a conversion of a pointer or pointer-to-member to bool. This is
237/// used as part of the ranking of standard conversion sequences
238/// (C++ 13.3.3.2p4).
239bool StandardConversionSequence::isPointerConversionToBool() const {
240 // Note that FromType has not necessarily been transformed by the
241 // array-to-pointer or function-to-pointer implicit conversions, so
242 // check for their presence as well as checking whether FromType is
243 // a pointer.
244 if (getToType(1)->isBooleanType() &&
245 (getFromType()->isPointerType() ||
246 getFromType()->isMemberPointerType() ||
247 getFromType()->isObjCObjectPointerType() ||
248 getFromType()->isBlockPointerType() ||
249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250 return true;
251
252 return false;
253}
254
255/// isPointerConversionToVoidPointer - Determines whether this
256/// conversion is a conversion of a pointer to a void pointer. This is
257/// used as part of the ranking of standard conversion sequences (C++
258/// 13.3.3.2p4).
259bool
260StandardConversionSequence::
261isPointerConversionToVoidPointer(ASTContext& Context) const {
262 QualType FromType = getFromType();
263 QualType ToType = getToType(1);
264
265 // Note that FromType has not necessarily been transformed by the
266 // array-to-pointer implicit conversion, so check for its presence
267 // and redo the conversion to get a pointer.
268 if (First == ICK_Array_To_Pointer)
269 FromType = Context.getArrayDecayedType(FromType);
270
271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
273 return ToPtrType->getPointeeType()->isVoidType();
274
275 return false;
276}
277
278/// Skip any implicit casts which could be either part of a narrowing conversion
279/// or after one in an implicit conversion.
280static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
281 const Expr *Converted) {
282 // We can have cleanups wrapping the converted expression; these need to be
283 // preserved so that destructors run if necessary.
284 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
285 Expr *Inner =
286 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
287 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
288 EWC->getObjects());
289 }
290
291 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
292 switch (ICE->getCastKind()) {
293 case CK_NoOp:
294 case CK_IntegralCast:
295 case CK_IntegralToBoolean:
296 case CK_IntegralToFloating:
297 case CK_BooleanToSignedIntegral:
298 case CK_FloatingToIntegral:
299 case CK_FloatingToBoolean:
300 case CK_FloatingCast:
301 Converted = ICE->getSubExpr();
302 continue;
303
304 default:
305 return Converted;
306 }
307 }
308
309 return Converted;
310}
311
312/// Check if this standard conversion sequence represents a narrowing
313/// conversion, according to C++11 [dcl.init.list]p7.
314///
315/// \param Ctx The AST context.
316/// \param Converted The result of applying this standard conversion sequence.
317/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
318/// value of the expression prior to the narrowing conversion.
319/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
320/// type of the expression prior to the narrowing conversion.
321/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
322/// from floating point types to integral types should be ignored.
323NarrowingKind StandardConversionSequence::getNarrowingKind(
324 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
325 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
326 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus &&
"narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "clang/lib/Sema/SemaOverload.cpp", 326, __extension__ __PRETTY_FUNCTION__
))
;
327
328 // C++11 [dcl.init.list]p7:
329 // A narrowing conversion is an implicit conversion ...
330 QualType FromType = getToType(0);
331 QualType ToType = getToType(1);
332
333 // A conversion to an enumeration type is narrowing if the conversion to
334 // the underlying type is narrowing. This only arises for expressions of
335 // the form 'Enum{init}'.
336 if (auto *ET = ToType->getAs<EnumType>())
337 ToType = ET->getDecl()->getIntegerType();
338
339 switch (Second) {
340 // 'bool' is an integral type; dispatch to the right place to handle it.
341 case ICK_Boolean_Conversion:
342 if (FromType->isRealFloatingType())
343 goto FloatingIntegralConversion;
344 if (FromType->isIntegralOrUnscopedEnumerationType())
345 goto IntegralConversion;
346 // -- from a pointer type or pointer-to-member type to bool, or
347 return NK_Type_Narrowing;
348
349 // -- from a floating-point type to an integer type, or
350 //
351 // -- from an integer type or unscoped enumeration type to a floating-point
352 // type, except where the source is a constant expression and the actual
353 // value after conversion will fit into the target type and will produce
354 // the original value when converted back to the original type, or
355 case ICK_Floating_Integral:
356 FloatingIntegralConversion:
357 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
358 return NK_Type_Narrowing;
359 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
360 ToType->isRealFloatingType()) {
361 if (IgnoreFloatToIntegralConversion)
362 return NK_Not_Narrowing;
363 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
364 assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "clang/lib/Sema/SemaOverload.cpp", 364, __extension__ __PRETTY_FUNCTION__
))
;
365
366 // If it's value-dependent, we can't tell whether it's narrowing.
367 if (Initializer->isValueDependent())
368 return NK_Dependent_Narrowing;
369
370 if (std::optional<llvm::APSInt> IntConstantValue =
371 Initializer->getIntegerConstantExpr(Ctx)) {
372 // Convert the integer to the floating type.
373 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
374 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
375 llvm::APFloat::rmNearestTiesToEven);
376 // And back.
377 llvm::APSInt ConvertedValue = *IntConstantValue;
378 bool ignored;
379 Result.convertToInteger(ConvertedValue,
380 llvm::APFloat::rmTowardZero, &ignored);
381 // If the resulting value is different, this was a narrowing conversion.
382 if (*IntConstantValue != ConvertedValue) {
383 ConstantValue = APValue(*IntConstantValue);
384 ConstantType = Initializer->getType();
385 return NK_Constant_Narrowing;
386 }
387 } else {
388 // Variables are always narrowings.
389 return NK_Variable_Narrowing;
390 }
391 }
392 return NK_Not_Narrowing;
393
394 // -- from long double to double or float, or from double to float, except
395 // where the source is a constant expression and the actual value after
396 // conversion is within the range of values that can be represented (even
397 // if it cannot be represented exactly), or
398 case ICK_Floating_Conversion:
399 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
400 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
401 // FromType is larger than ToType.
402 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
403
404 // If it's value-dependent, we can't tell whether it's narrowing.
405 if (Initializer->isValueDependent())
406 return NK_Dependent_Narrowing;
407
408 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
409 // Constant!
410 assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "clang/lib/Sema/SemaOverload.cpp"
, 410, __extension__ __PRETTY_FUNCTION__))
;
411 llvm::APFloat FloatVal = ConstantValue.getFloat();
412 // Convert the source value into the target type.
413 bool ignored;
414 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
415 Ctx.getFloatTypeSemantics(ToType),
416 llvm::APFloat::rmNearestTiesToEven, &ignored);
417 // If there was no overflow, the source value is within the range of
418 // values that can be represented.
419 if (ConvertStatus & llvm::APFloat::opOverflow) {
420 ConstantType = Initializer->getType();
421 return NK_Constant_Narrowing;
422 }
423 } else {
424 return NK_Variable_Narrowing;
425 }
426 }
427 return NK_Not_Narrowing;
428
429 // -- from an integer type or unscoped enumeration type to an integer type
430 // that cannot represent all the values of the original type, except where
431 // the source is a constant expression and the actual value after
432 // conversion will fit into the target type and will produce the original
433 // value when converted back to the original type.
434 case ICK_Integral_Conversion:
435 IntegralConversion: {
436 assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 436, __extension__ __PRETTY_FUNCTION__
))
;
437 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaOverload.cpp", 437, __extension__ __PRETTY_FUNCTION__
))
;
438 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
439 const unsigned FromWidth = Ctx.getIntWidth(FromType);
440 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
441 const unsigned ToWidth = Ctx.getIntWidth(ToType);
442
443 if (FromWidth > ToWidth ||
444 (FromWidth == ToWidth && FromSigned != ToSigned) ||
445 (FromSigned && !ToSigned)) {
446 // Not all values of FromType can be represented in ToType.
447 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
448
449 // If it's value-dependent, we can't tell whether it's narrowing.
450 if (Initializer->isValueDependent())
451 return NK_Dependent_Narrowing;
452
453 std::optional<llvm::APSInt> OptInitializerValue;
454 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
455 // Such conversions on variables are always narrowing.
456 return NK_Variable_Narrowing;
457 }
458 llvm::APSInt &InitializerValue = *OptInitializerValue;
459 bool Narrowing = false;
460 if (FromWidth < ToWidth) {
461 // Negative -> unsigned is narrowing. Otherwise, more bits is never
462 // narrowing.
463 if (InitializerValue.isSigned() && InitializerValue.isNegative())
464 Narrowing = true;
465 } else {
466 // Add a bit to the InitializerValue so we don't have to worry about
467 // signed vs. unsigned comparisons.
468 InitializerValue = InitializerValue.extend(
469 InitializerValue.getBitWidth() + 1);
470 // Convert the initializer to and from the target width and signed-ness.
471 llvm::APSInt ConvertedValue = InitializerValue;
472 ConvertedValue = ConvertedValue.trunc(ToWidth);
473 ConvertedValue.setIsSigned(ToSigned);
474 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
475 ConvertedValue.setIsSigned(InitializerValue.isSigned());
476 // If the result is different, this was a narrowing conversion.
477 if (ConvertedValue != InitializerValue)
478 Narrowing = true;
479 }
480 if (Narrowing) {
481 ConstantType = Initializer->getType();
482 ConstantValue = APValue(InitializerValue);
483 return NK_Constant_Narrowing;
484 }
485 }
486 return NK_Not_Narrowing;
487 }
488
489 default:
490 // Other kinds of conversions are not narrowings.
491 return NK_Not_Narrowing;
492 }
493}
494
495/// dump - Print this standard conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
498 raw_ostream &OS = llvm::errs();
499 bool PrintedSomething = false;
500 if (First != ICK_Identity) {
501 OS << GetImplicitConversionName(First);
502 PrintedSomething = true;
503 }
504
505 if (Second != ICK_Identity) {
506 if (PrintedSomething) {
507 OS << " -> ";
508 }
509 OS << GetImplicitConversionName(Second);
510
511 if (CopyConstructor) {
512 OS << " (by copy constructor)";
513 } else if (DirectBinding) {
514 OS << " (direct reference binding)";
515 } else if (ReferenceBinding) {
516 OS << " (reference binding)";
517 }
518 PrintedSomething = true;
519 }
520
521 if (Third != ICK_Identity) {
522 if (PrintedSomething) {
523 OS << " -> ";
524 }
525 OS << GetImplicitConversionName(Third);
526 PrintedSomething = true;
527 }
528
529 if (!PrintedSomething) {
530 OS << "No conversions required";
531 }
532}
533
534/// dump - Print this user-defined conversion sequence to standard
535/// error. Useful for debugging overloading issues.
536void UserDefinedConversionSequence::dump() const {
537 raw_ostream &OS = llvm::errs();
538 if (Before.First || Before.Second || Before.Third) {
539 Before.dump();
540 OS << " -> ";
541 }
542 if (ConversionFunction)
543 OS << '\'' << *ConversionFunction << '\'';
544 else
545 OS << "aggregate initialization";
546 if (After.First || After.Second || After.Third) {
547 OS << " -> ";
548 After.dump();
549 }
550}
551
552/// dump - Print this implicit conversion sequence to standard
553/// error. Useful for debugging overloading issues.
554void ImplicitConversionSequence::dump() const {
555 raw_ostream &OS = llvm::errs();
556 if (hasInitializerListContainerType())
557 OS << "Worst list element conversion: ";
558 switch (ConversionKind) {
559 case StandardConversion:
560 OS << "Standard conversion: ";
561 Standard.dump();
562 break;
563 case UserDefinedConversion:
564 OS << "User-defined conversion: ";
565 UserDefined.dump();
566 break;
567 case EllipsisConversion:
568 OS << "Ellipsis conversion";
569 break;
570 case AmbiguousConversion:
571 OS << "Ambiguous conversion";
572 break;
573 case BadConversion:
574 OS << "Bad conversion";
575 break;
576 }
577
578 OS << "\n";
579}
580
581void AmbiguousConversionSequence::construct() {
582 new (&conversions()) ConversionSet();
583}
584
585void AmbiguousConversionSequence::destruct() {
586 conversions().~ConversionSet();
587}
588
589void
590AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
591 FromTypePtr = O.FromTypePtr;
592 ToTypePtr = O.ToTypePtr;
593 new (&conversions()) ConversionSet(O.conversions());
594}
595
596namespace {
597 // Structure used by DeductionFailureInfo to store
598 // template argument information.
599 struct DFIArguments {
600 TemplateArgument FirstArg;
601 TemplateArgument SecondArg;
602 };
603 // Structure used by DeductionFailureInfo to store
604 // template parameter and template argument information.
605 struct DFIParamWithArguments : DFIArguments {
606 TemplateParameter Param;
607 };
608 // Structure used by DeductionFailureInfo to store template argument
609 // information and the index of the problematic call argument.
610 struct DFIDeducedMismatchArgs : DFIArguments {
611 TemplateArgumentList *TemplateArgs;
612 unsigned CallArgIndex;
613 };
614 // Structure used by DeductionFailureInfo to store information about
615 // unsatisfied constraints.
616 struct CNSInfo {
617 TemplateArgumentList *TemplateArgs;
618 ConstraintSatisfaction Satisfaction;
619 };
620}
621
622/// Convert from Sema's representation of template deduction information
623/// to the form used in overload-candidate information.
624DeductionFailureInfo
625clang::MakeDeductionFailureInfo(ASTContext &Context,
626 Sema::TemplateDeductionResult TDK,
627 TemplateDeductionInfo &Info) {
628 DeductionFailureInfo Result;
629 Result.Result = static_cast<unsigned>(TDK);
630 Result.HasDiagnostic = false;
631 switch (TDK) {
632 case Sema::TDK_Invalid:
633 case Sema::TDK_InstantiationDepth:
634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
636 case Sema::TDK_MiscellaneousDeductionFailure:
637 case Sema::TDK_CUDATargetMismatch:
638 Result.Data = nullptr;
639 break;
640
641 case Sema::TDK_Incomplete:
642 case Sema::TDK_InvalidExplicitArguments:
643 Result.Data = Info.Param.getOpaqueValue();
644 break;
645
646 case Sema::TDK_DeducedMismatch:
647 case Sema::TDK_DeducedMismatchNested: {
648 // FIXME: Should allocate from normal heap so that we can free this later.
649 auto *Saved = new (Context) DFIDeducedMismatchArgs;
650 Saved->FirstArg = Info.FirstArg;
651 Saved->SecondArg = Info.SecondArg;
652 Saved->TemplateArgs = Info.takeSugared();
653 Saved->CallArgIndex = Info.CallArgIndex;
654 Result.Data = Saved;
655 break;
656 }
657
658 case Sema::TDK_NonDeducedMismatch: {
659 // FIXME: Should allocate from normal heap so that we can free this later.
660 DFIArguments *Saved = new (Context) DFIArguments;
661 Saved->FirstArg = Info.FirstArg;
662 Saved->SecondArg = Info.SecondArg;
663 Result.Data = Saved;
664 break;
665 }
666
667 case Sema::TDK_IncompletePack:
668 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
669 case Sema::TDK_Inconsistent:
670 case Sema::TDK_Underqualified: {
671 // FIXME: Should allocate from normal heap so that we can free this later.
672 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
673 Saved->Param = Info.Param;
674 Saved->FirstArg = Info.FirstArg;
675 Saved->SecondArg = Info.SecondArg;
676 Result.Data = Saved;
677 break;
678 }
679
680 case Sema::TDK_SubstitutionFailure:
681 Result.Data = Info.takeSugared();
682 if (Info.hasSFINAEDiagnostic()) {
683 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
684 SourceLocation(), PartialDiagnostic::NullDiagnostic());
685 Info.takeSFINAEDiagnostic(*Diag);
686 Result.HasDiagnostic = true;
687 }
688 break;
689
690 case Sema::TDK_ConstraintsNotSatisfied: {
691 CNSInfo *Saved = new (Context) CNSInfo;
692 Saved->TemplateArgs = Info.takeSugared();
693 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
694 Result.Data = Saved;
695 break;
696 }
697
698 case Sema::TDK_Success:
699 case Sema::TDK_NonDependentConversionFailure:
700 case Sema::TDK_AlreadyDiagnosed:
701 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "clang/lib/Sema/SemaOverload.cpp"
, 701)
;
702 }
703
704 return Result;
705}
706
707void DeductionFailureInfo::Destroy() {
708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709 case Sema::TDK_Success:
710 case Sema::TDK_Invalid:
711 case Sema::TDK_InstantiationDepth:
712 case Sema::TDK_Incomplete:
713 case Sema::TDK_TooManyArguments:
714 case Sema::TDK_TooFewArguments:
715 case Sema::TDK_InvalidExplicitArguments:
716 case Sema::TDK_CUDATargetMismatch:
717 case Sema::TDK_NonDependentConversionFailure:
718 break;
719
720 case Sema::TDK_IncompletePack:
721 case Sema::TDK_Inconsistent:
722 case Sema::TDK_Underqualified:
723 case Sema::TDK_DeducedMismatch:
724 case Sema::TDK_DeducedMismatchNested:
725 case Sema::TDK_NonDeducedMismatch:
726 // FIXME: Destroy the data?
727 Data = nullptr;
728 break;
729
730 case Sema::TDK_SubstitutionFailure:
731 // FIXME: Destroy the template argument list?
732 Data = nullptr;
733 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
734 Diag->~PartialDiagnosticAt();
735 HasDiagnostic = false;
736 }
737 break;
738
739 case Sema::TDK_ConstraintsNotSatisfied:
740 // FIXME: Destroy the template argument list?
741 Data = nullptr;
742 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
743 Diag->~PartialDiagnosticAt();
744 HasDiagnostic = false;
745 }
746 break;
747
748 // Unhandled
749 case Sema::TDK_MiscellaneousDeductionFailure:
750 case Sema::TDK_AlreadyDiagnosed:
751 break;
752 }
753}
754
755PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
756 if (HasDiagnostic)
757 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
758 return nullptr;
759}
760
761TemplateParameter DeductionFailureInfo::getTemplateParameter() {
762 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
763 case Sema::TDK_Success:
764 case Sema::TDK_Invalid:
765 case Sema::TDK_InstantiationDepth:
766 case Sema::TDK_TooManyArguments:
767 case Sema::TDK_TooFewArguments:
768 case Sema::TDK_SubstitutionFailure:
769 case Sema::TDK_DeducedMismatch:
770 case Sema::TDK_DeducedMismatchNested:
771 case Sema::TDK_NonDeducedMismatch:
772 case Sema::TDK_CUDATargetMismatch:
773 case Sema::TDK_NonDependentConversionFailure:
774 case Sema::TDK_ConstraintsNotSatisfied:
775 return TemplateParameter();
776
777 case Sema::TDK_Incomplete:
778 case Sema::TDK_InvalidExplicitArguments:
779 return TemplateParameter::getFromOpaqueValue(Data);
780
781 case Sema::TDK_IncompletePack:
782 case Sema::TDK_Inconsistent:
783 case Sema::TDK_Underqualified:
784 return static_cast<DFIParamWithArguments*>(Data)->Param;
785
786 // Unhandled
787 case Sema::TDK_MiscellaneousDeductionFailure:
788 case Sema::TDK_AlreadyDiagnosed:
789 break;
790 }
791
792 return TemplateParameter();
793}
794
795TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
796 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
797 case Sema::TDK_Success:
798 case Sema::TDK_Invalid:
799 case Sema::TDK_InstantiationDepth:
800 case Sema::TDK_TooManyArguments:
801 case Sema::TDK_TooFewArguments:
802 case Sema::TDK_Incomplete:
803 case Sema::TDK_IncompletePack:
804 case Sema::TDK_InvalidExplicitArguments:
805 case Sema::TDK_Inconsistent:
806 case Sema::TDK_Underqualified:
807 case Sema::TDK_NonDeducedMismatch:
808 case Sema::TDK_CUDATargetMismatch:
809 case Sema::TDK_NonDependentConversionFailure:
810 return nullptr;
811
812 case Sema::TDK_DeducedMismatch:
813 case Sema::TDK_DeducedMismatchNested:
814 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
815
816 case Sema::TDK_SubstitutionFailure:
817 return static_cast<TemplateArgumentList*>(Data);
818
819 case Sema::TDK_ConstraintsNotSatisfied:
820 return static_cast<CNSInfo*>(Data)->TemplateArgs;
821
822 // Unhandled
823 case Sema::TDK_MiscellaneousDeductionFailure:
824 case Sema::TDK_AlreadyDiagnosed:
825 break;
826 }
827
828 return nullptr;
829}
830
831const TemplateArgument *DeductionFailureInfo::getFirstArg() {
832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833 case Sema::TDK_Success:
834 case Sema::TDK_Invalid:
835 case Sema::TDK_InstantiationDepth:
836 case Sema::TDK_Incomplete:
837 case Sema::TDK_TooManyArguments:
838 case Sema::TDK_TooFewArguments:
839 case Sema::TDK_InvalidExplicitArguments:
840 case Sema::TDK_SubstitutionFailure:
841 case Sema::TDK_CUDATargetMismatch:
842 case Sema::TDK_NonDependentConversionFailure:
843 case Sema::TDK_ConstraintsNotSatisfied:
844 return nullptr;
845
846 case Sema::TDK_IncompletePack:
847 case Sema::TDK_Inconsistent:
848 case Sema::TDK_Underqualified:
849 case Sema::TDK_DeducedMismatch:
850 case Sema::TDK_DeducedMismatchNested:
851 case Sema::TDK_NonDeducedMismatch:
852 return &static_cast<DFIArguments*>(Data)->FirstArg;
853
854 // Unhandled
855 case Sema::TDK_MiscellaneousDeductionFailure:
856 case Sema::TDK_AlreadyDiagnosed:
857 break;
858 }
859
860 return nullptr;
861}
862
863const TemplateArgument *DeductionFailureInfo::getSecondArg() {
864 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
865 case Sema::TDK_Success:
866 case Sema::TDK_Invalid:
867 case Sema::TDK_InstantiationDepth:
868 case Sema::TDK_Incomplete:
869 case Sema::TDK_IncompletePack:
870 case Sema::TDK_TooManyArguments:
871 case Sema::TDK_TooFewArguments:
872 case Sema::TDK_InvalidExplicitArguments:
873 case Sema::TDK_SubstitutionFailure:
874 case Sema::TDK_CUDATargetMismatch:
875 case Sema::TDK_NonDependentConversionFailure:
876 case Sema::TDK_ConstraintsNotSatisfied:
877 return nullptr;
878
879 case Sema::TDK_Inconsistent:
880 case Sema::TDK_Underqualified:
881 case Sema::TDK_DeducedMismatch:
882 case Sema::TDK_DeducedMismatchNested:
883 case Sema::TDK_NonDeducedMismatch:
884 return &static_cast<DFIArguments*>(Data)->SecondArg;
885
886 // Unhandled
887 case Sema::TDK_MiscellaneousDeductionFailure:
888 case Sema::TDK_AlreadyDiagnosed:
889 break;
890 }
891
892 return nullptr;
893}
894
895std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
896 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
897 case Sema::TDK_DeducedMismatch:
898 case Sema::TDK_DeducedMismatchNested:
899 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
900
901 default:
902 return std::nullopt;
903 }
904}
905
906static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
907 const FunctionDecl *Y) {
908 if (!X || !Y)
909 return false;
910 if (X->getNumParams() != Y->getNumParams())
911 return false;
912 for (unsigned I = 0; I < X->getNumParams(); ++I)
913 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
914 Y->getParamDecl(I)->getType()))
915 return false;
916 if (auto *FTX = X->getDescribedFunctionTemplate()) {
917 auto *FTY = Y->getDescribedFunctionTemplate();
918 if (!FTY)
919 return false;
920 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
921 FTY->getTemplateParameters()))
922 return false;
923 }
924 return true;
925}
926
927static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
928 Expr *FirstOperand, FunctionDecl *EqFD) {
929 assert(EqFD->getOverloadedOperator() ==(static_cast <bool> (EqFD->getOverloadedOperator() ==
OverloadedOperatorKind::OO_EqualEqual) ? void (0) : __assert_fail
("EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual"
, "clang/lib/Sema/SemaOverload.cpp", 930, __extension__ __PRETTY_FUNCTION__
))
930 OverloadedOperatorKind::OO_EqualEqual)(static_cast <bool> (EqFD->getOverloadedOperator() ==
OverloadedOperatorKind::OO_EqualEqual) ? void (0) : __assert_fail
("EqFD->getOverloadedOperator() == OverloadedOperatorKind::OO_EqualEqual"
, "clang/lib/Sema/SemaOverload.cpp", 930, __extension__ __PRETTY_FUNCTION__
))
;
931 // C++2a [over.match.oper]p4:
932 // A non-template function or function template F named operator== is a
933 // rewrite target with first operand o unless a search for the name operator!=
934 // in the scope S from the instantiation context of the operator expression
935 // finds a function or function template that would correspond
936 // ([basic.scope.scope]) to F if its name were operator==, where S is the
937 // scope of the class type of o if F is a class member, and the namespace
938 // scope of which F is a member otherwise. A function template specialization
939 // named operator== is a rewrite target if its function template is a rewrite
940 // target.
941 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
942 OverloadedOperatorKind::OO_ExclaimEqual);
943 if (isa<CXXMethodDecl>(EqFD)) {
944 // If F is a class member, search scope is class type of first operand.
945 QualType RHS = FirstOperand->getType();
946 auto *RHSRec = RHS->getAs<RecordType>();
947 if (!RHSRec)
948 return true;
949 LookupResult Members(S, NotEqOp, OpLoc,
950 Sema::LookupNameKind::LookupMemberName);
951 S.LookupQualifiedName(Members, RHSRec->getDecl());
952 Members.suppressDiagnostics();
953 for (NamedDecl *Op : Members)
954 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
955 return false;
956 return true;
957 }
958 // Otherwise the search scope is the namespace scope of which F is a member.
959 LookupResult NonMembers(S, NotEqOp, OpLoc,
960 Sema::LookupNameKind::LookupOperatorName);
961 S.LookupName(NonMembers,
962 S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
963 NonMembers.suppressDiagnostics();
964 for (NamedDecl *Op : NonMembers) {
965 auto *FD = Op->getAsFunction();
966 if(auto* UD = dyn_cast<UsingShadowDecl>(Op))
967 FD = UD->getUnderlyingDecl()->getAsFunction();
968 if (FunctionsCorrespond(S.Context, EqFD, FD) &&
969 declaresSameEntity(cast<Decl>(EqFD->getDeclContext()),
970 cast<Decl>(Op->getDeclContext())))
971 return false;
972 }
973 return true;
974}
975
976bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
977 OverloadedOperatorKind Op) {
978 if (!AllowRewrittenCandidates)
979 return false;
980 return Op == OO_EqualEqual || Op == OO_Spaceship;
981}
982
983bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
984 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
985 auto Op = FD->getOverloadedOperator();
986 if (!allowsReversed(Op))
987 return false;
988 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
989 assert(OriginalArgs.size() == 2)(static_cast <bool> (OriginalArgs.size() == 2) ? void (
0) : __assert_fail ("OriginalArgs.size() == 2", "clang/lib/Sema/SemaOverload.cpp"
, 989, __extension__ __PRETTY_FUNCTION__))
;
990 if (!shouldAddReversedEqEq(
991 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
992 return false;
993 }
994 // Don't bother adding a reversed candidate that can never be a better
995 // match than the non-reversed version.
996 return FD->getNumParams() != 2 ||
997 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
998 FD->getParamDecl(1)->getType()) ||
999 FD->hasAttr<EnableIfAttr>();
1000}
1001
1002void OverloadCandidateSet::destroyCandidates() {
1003 for (iterator i = begin(), e = end(); i != e; ++i) {
1004 for (auto &C : i->Conversions)
1005 C.~ImplicitConversionSequence();
1006 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1007 i->DeductionFailure.Destroy();
1008 }
1009}
1010
1011void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1012 destroyCandidates();
1013 SlabAllocator.Reset();
1014 NumInlineBytesUsed = 0;
1015 Candidates.clear();
1016 Functions.clear();
1017 Kind = CSK;
1018}
1019
1020namespace {
1021 class UnbridgedCastsSet {
1022 struct Entry {
1023 Expr **Addr;
1024 Expr *Saved;
1025 };
1026 SmallVector<Entry, 2> Entries;
1027
1028 public:
1029 void save(Sema &S, Expr *&E) {
1030 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "clang/lib/Sema/SemaOverload.cpp", 1030, __extension__ __PRETTY_FUNCTION__
))
;
1031 Entry entry = { &E, E };
1032 Entries.push_back(entry);
1033 E = S.stripARCUnbridgedCast(E);
1034 }
1035
1036 void restore() {
1037 for (SmallVectorImpl<Entry>::iterator
1038 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1039 *i->Addr = i->Saved;
1040 }
1041 };
1042}
1043
1044/// checkPlaceholderForOverload - Do any interesting placeholder-like
1045/// preprocessing on the given expression.
1046///
1047/// \param unbridgedCasts a collection to which to add unbridged casts;
1048/// without this, they will be immediately diagnosed as errors
1049///
1050/// Return true on unrecoverable error.
1051static bool
1052checkPlaceholderForOverload(Sema &S, Expr *&E,
1053 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1054 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1055 // We can't handle overloaded expressions here because overload
1056 // resolution might reasonably tweak them.
1057 if (placeholder->getKind() == BuiltinType::Overload) return false;
1058
1059 // If the context potentially accepts unbridged ARC casts, strip
1060 // the unbridged cast and add it to the collection for later restoration.
1061 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1062 unbridgedCasts) {
1063 unbridgedCasts->save(S, E);
1064 return false;
1065 }
1066
1067 // Go ahead and check everything else.
1068 ExprResult result = S.CheckPlaceholderExpr(E);
1069 if (result.isInvalid())
1070 return true;
1071
1072 E = result.get();
1073 return false;
1074 }
1075
1076 // Nothing to do.
1077 return false;
1078}
1079
1080/// checkArgPlaceholdersForOverload - Check a set of call operands for
1081/// placeholders.
1082static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1083 UnbridgedCastsSet &unbridged) {
1084 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1085 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1086 return true;
1087
1088 return false;
1089}
1090
1091/// Determine whether the given New declaration is an overload of the
1092/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1093/// New and Old cannot be overloaded, e.g., if New has the same signature as
1094/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1095/// functions (or function templates) at all. When it does return Ovl_Match or
1096/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1097/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1098/// declaration.
1099///
1100/// Example: Given the following input:
1101///
1102/// void f(int, float); // #1
1103/// void f(int, int); // #2
1104/// int f(int, int); // #3
1105///
1106/// When we process #1, there is no previous declaration of "f", so IsOverload
1107/// will not be used.
1108///
1109/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1110/// the parameter types, we see that #1 and #2 are overloaded (since they have
1111/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1112/// unchanged.
1113///
1114/// When we process #3, Old is an overload set containing #1 and #2. We compare
1115/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1116/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1117/// functions are not part of the signature), IsOverload returns Ovl_Match and
1118/// MatchedDecl will be set to point to the FunctionDecl for #2.
1119///
1120/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1121/// by a using declaration. The rules for whether to hide shadow declarations
1122/// ignore some properties which otherwise figure into a function template's
1123/// signature.
1124Sema::OverloadKind
1125Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1126 NamedDecl *&Match, bool NewIsUsingDecl) {
1127 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1128 I != E; ++I) {
1129 NamedDecl *OldD = *I;
1130
1131 bool OldIsUsingDecl = false;
1132 if (isa<UsingShadowDecl>(OldD)) {
1133 OldIsUsingDecl = true;
1134
1135 // We can always introduce two using declarations into the same
1136 // context, even if they have identical signatures.
1137 if (NewIsUsingDecl) continue;
1138
1139 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1140 }
1141
1142 // A using-declaration does not conflict with another declaration
1143 // if one of them is hidden.
1144 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1145 continue;
1146
1147 // If either declaration was introduced by a using declaration,
1148 // we'll need to use slightly different rules for matching.
1149 // Essentially, these rules are the normal rules, except that
1150 // function templates hide function templates with different
1151 // return types or template parameter lists.
1152 bool UseMemberUsingDeclRules =
1153 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1154 !New->getFriendObjectKind();
1155
1156 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1157 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1158 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1159 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1160 continue;
1161 }
1162
1163 if (!isa<FunctionTemplateDecl>(OldD) &&
1164 !shouldLinkPossiblyHiddenDecl(*I, New))
1165 continue;
1166
1167 Match = *I;
1168 return Ovl_Match;
1169 }
1170
1171 // Builtins that have custom typechecking or have a reference should
1172 // not be overloadable or redeclarable.
1173 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1174 Match = *I;
1175 return Ovl_NonFunction;
1176 }
1177 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1178 // We can overload with these, which can show up when doing
1179 // redeclaration checks for UsingDecls.
1180 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "clang/lib/Sema/SemaOverload.cpp", 1180, __extension__ __PRETTY_FUNCTION__
))
;
1181 } else if (isa<TagDecl>(OldD)) {
1182 // We can always overload with tags by hiding them.
1183 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1184 // Optimistically assume that an unresolved using decl will
1185 // overload; if it doesn't, we'll have to diagnose during
1186 // template instantiation.
1187 //
1188 // Exception: if the scope is dependent and this is not a class
1189 // member, the using declaration can only introduce an enumerator.
1190 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1191 Match = *I;
1192 return Ovl_NonFunction;
1193 }
1194 } else {
1195 // (C++ 13p1):
1196 // Only function declarations can be overloaded; object and type
1197 // declarations cannot be overloaded.
1198 Match = *I;
1199 return Ovl_NonFunction;
1200 }
1201 }
1202
1203 // C++ [temp.friend]p1:
1204 // For a friend function declaration that is not a template declaration:
1205 // -- if the name of the friend is a qualified or unqualified template-id,
1206 // [...], otherwise
1207 // -- if the name of the friend is a qualified-id and a matching
1208 // non-template function is found in the specified class or namespace,
1209 // the friend declaration refers to that function, otherwise,
1210 // -- if the name of the friend is a qualified-id and a matching function
1211 // template is found in the specified class or namespace, the friend
1212 // declaration refers to the deduced specialization of that function
1213 // template, otherwise
1214 // -- the name shall be an unqualified-id [...]
1215 // If we get here for a qualified friend declaration, we've just reached the
1216 // third bullet. If the type of the friend is dependent, skip this lookup
1217 // until instantiation.
1218 if (New->getFriendObjectKind() && New->getQualifier() &&
1219 !New->getDescribedFunctionTemplate() &&
1220 !New->getDependentSpecializationInfo() &&
1221 !New->getType()->isDependentType()) {
1222 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1223 TemplateSpecResult.addAllDecls(Old);
1224 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1225 /*QualifiedFriend*/true)) {
1226 New->setInvalidDecl();
1227 return Ovl_Overload;
1228 }
1229
1230 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1231 return Ovl_Match;
1232 }
1233
1234 return Ovl_Overload;
1235}
1236
1237bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1238 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1239 bool ConsiderRequiresClauses) {
1240 // C++ [basic.start.main]p2: This function shall not be overloaded.
1241 if (New->isMain())
1242 return false;
1243
1244 // MSVCRT user defined entry points cannot be overloaded.
1245 if (New->isMSVCRTEntryPoint())
1246 return false;
1247
1248 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1249 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1250
1251 // C++ [temp.fct]p2:
1252 // A function template can be overloaded with other function templates
1253 // and with normal (non-template) functions.
1254 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1255 return true;
1256
1257 // Is the function New an overload of the function Old?
1258 QualType OldQType = Context.getCanonicalType(Old->getType());
1259 QualType NewQType = Context.getCanonicalType(New->getType());
1260
1261 // Compare the signatures (C++ 1.3.10) of the two functions to
1262 // determine whether they are overloads. If we find any mismatch
1263 // in the signature, they are overloads.
1264
1265 // If either of these functions is a K&R-style function (no
1266 // prototype), then we consider them to have matching signatures.
1267 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1268 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1269 return false;
1270
1271 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1272 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1273
1274 // The signature of a function includes the types of its
1275 // parameters (C++ 1.3.10), which includes the presence or absence
1276 // of the ellipsis; see C++ DR 357).
1277 if (OldQType != NewQType &&
1278 (OldType->getNumParams() != NewType->getNumParams() ||
1279 OldType->isVariadic() != NewType->isVariadic() ||
1280 !FunctionParamTypesAreEqual(OldType, NewType)))
1281 return true;
1282
1283 // For member-like friends, the enclosing class is part of the signature.
1284 if ((New->isMemberLikeConstrainedFriend() ||
1285 Old->isMemberLikeConstrainedFriend()) &&
1286 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1287 return true;
1288
1289 if (NewTemplate) {
1290 // C++ [temp.over.link]p4:
1291 // The signature of a function template consists of its function
1292 // signature, its return type and its template parameter list. The names
1293 // of the template parameters are significant only for establishing the
1294 // relationship between the template parameters and the rest of the
1295 // signature.
1296 //
1297 // We check the return type and template parameter lists for function
1298 // templates first; the remaining checks follow.
1299 bool SameTemplateParameterList = TemplateParameterListsAreEqual(
1300 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1301 OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
1302 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
1303 New->getDeclaredReturnType());
1304 // FIXME(GH58571): Match template parameter list even for non-constrained
1305 // template heads. This currently ensures that the code prior to C++20 is
1306 // not newly broken.
1307 bool ConstraintsInTemplateHead =
1308 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1309 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1310 // C++ [namespace.udecl]p11:
1311 // The set of declarations named by a using-declarator that inhabits a
1312 // class C does not include member functions and member function
1313 // templates of a base class that "correspond" to (and thus would
1314 // conflict with) a declaration of a function or function template in
1315 // C.
1316 // Comparing return types is not required for the "correspond" check to
1317 // decide whether a member introduced by a shadow declaration is hidden.
1318 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1319 !SameTemplateParameterList)
1320 return true;
1321 if (!UseMemberUsingDeclRules &&
1322 (!SameTemplateParameterList || !SameReturnType))
1323 return true;
1324 }
1325
1326 if (ConsiderRequiresClauses) {
1327 Expr *NewRC = New->getTrailingRequiresClause(),
1328 *OldRC = Old->getTrailingRequiresClause();
1329 if ((NewRC != nullptr) != (OldRC != nullptr))
1330 return true;
1331
1332 if (NewRC && !AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1333 return true;
1334 }
1335
1336 // If the function is a class member, its signature includes the
1337 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1338 //
1339 // As part of this, also check whether one of the member functions
1340 // is static, in which case they are not overloads (C++
1341 // 13.1p2). While not part of the definition of the signature,
1342 // this check is important to determine whether these functions
1343 // can be overloaded.
1344 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1345 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1346 if (OldMethod && NewMethod &&
1347 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1348 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1349 if (!UseMemberUsingDeclRules &&
1350 (OldMethod->getRefQualifier() == RQ_None ||
1351 NewMethod->getRefQualifier() == RQ_None)) {
1352 // C++20 [over.load]p2:
1353 // - Member function declarations with the same name, the same
1354 // parameter-type-list, and the same trailing requires-clause (if
1355 // any), as well as member function template declarations with the
1356 // same name, the same parameter-type-list, the same trailing
1357 // requires-clause (if any), and the same template-head, cannot be
1358 // overloaded if any of them, but not all, have a ref-qualifier.
1359 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1360 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1361 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1362 }
1363 return true;
1364 }
1365
1366 // We may not have applied the implicit const for a constexpr member
1367 // function yet (because we haven't yet resolved whether this is a static
1368 // or non-static member function). Add it now, on the assumption that this
1369 // is a redeclaration of OldMethod.
1370 auto OldQuals = OldMethod->getMethodQualifiers();
1371 auto NewQuals = NewMethod->getMethodQualifiers();
1372 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1373 !isa<CXXConstructorDecl>(NewMethod))
1374 NewQuals.addConst();
1375 // We do not allow overloading based off of '__restrict'.
1376 OldQuals.removeRestrict();
1377 NewQuals.removeRestrict();
1378 if (OldQuals != NewQuals)
1379 return true;
1380 }
1381
1382 // Though pass_object_size is placed on parameters and takes an argument, we
1383 // consider it to be a function-level modifier for the sake of function
1384 // identity. Either the function has one or more parameters with
1385 // pass_object_size or it doesn't.
1386 if (functionHasPassObjectSizeParams(New) !=
1387 functionHasPassObjectSizeParams(Old))
1388 return true;
1389
1390 // enable_if attributes are an order-sensitive part of the signature.
1391 for (specific_attr_iterator<EnableIfAttr>
1392 NewI = New->specific_attr_begin<EnableIfAttr>(),
1393 NewE = New->specific_attr_end<EnableIfAttr>(),
1394 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1395 OldE = Old->specific_attr_end<EnableIfAttr>();
1396 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1397 if (NewI == NewE || OldI == OldE)
1398 return true;
1399 llvm::FoldingSetNodeID NewID, OldID;
1400 NewI->getCond()->Profile(NewID, Context, true);
1401 OldI->getCond()->Profile(OldID, Context, true);
1402 if (NewID != OldID)
1403 return true;
1404 }
1405
1406 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1407 // Don't allow overloading of destructors. (In theory we could, but it
1408 // would be a giant change to clang.)
1409 if (!isa<CXXDestructorDecl>(New)) {
1410 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1411 OldTarget = IdentifyCUDATarget(Old);
1412 if (NewTarget != CFT_InvalidTarget) {
1413 assert((OldTarget != CFT_InvalidTarget) &&(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1414, __extension__ __PRETTY_FUNCTION__
))
1414 "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "clang/lib/Sema/SemaOverload.cpp", 1414, __extension__ __PRETTY_FUNCTION__
))
;
1415
1416 // Allow overloading of functions with same signature and different CUDA
1417 // target attributes.
1418 if (NewTarget != OldTarget)
1419 return true;
1420 }
1421 }
1422 }
1423
1424 // The signatures match; this is not an overload.
1425 return false;
1426}
1427
1428/// Tries a user-defined conversion from From to ToType.
1429///
1430/// Produces an implicit conversion sequence for when a standard conversion
1431/// is not an option. See TryImplicitConversion for more information.
1432static ImplicitConversionSequence
1433TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1434 bool SuppressUserConversions,
1435 AllowedExplicit AllowExplicit,
1436 bool InOverloadResolution,
1437 bool CStyle,
1438 bool AllowObjCWritebackConversion,
1439 bool AllowObjCConversionOnExplicit) {
1440 ImplicitConversionSequence ICS;
1441
1442 if (SuppressUserConversions) {
1443 // We're not in the case above, so there is no conversion that
1444 // we can perform.
1445 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1446 return ICS;
1447 }
1448
1449 // Attempt user-defined conversion.
1450 OverloadCandidateSet Conversions(From->getExprLoc(),
1451 OverloadCandidateSet::CSK_Normal);
1452 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1453 Conversions, AllowExplicit,
1454 AllowObjCConversionOnExplicit)) {
1455 case OR_Success:
1456 case OR_Deleted:
1457 ICS.setUserDefined();
1458 // C++ [over.ics.user]p4:
1459 // A conversion of an expression of class type to the same class
1460 // type is given Exact Match rank, and a conversion of an
1461 // expression of class type to a base class of that type is
1462 // given Conversion rank, in spite of the fact that a copy
1463 // constructor (i.e., a user-defined conversion function) is
1464 // called for those cases.
1465 if (CXXConstructorDecl *Constructor
1466 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1467 QualType FromCanon
1468 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1469 QualType ToCanon
1470 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1471 if (Constructor->isCopyConstructor() &&
1472 (FromCanon == ToCanon ||
1473 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1474 // Turn this into a "standard" conversion sequence, so that it
1475 // gets ranked with standard conversion sequences.
1476 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1477 ICS.setStandard();
1478 ICS.Standard.setAsIdentityConversion();
1479 ICS.Standard.setFromType(From->getType());
1480 ICS.Standard.setAllToTypes(ToType);
1481 ICS.Standard.CopyConstructor = Constructor;
1482 ICS.Standard.FoundCopyConstructor = Found;
1483 if (ToCanon != FromCanon)
1484 ICS.Standard.Second = ICK_Derived_To_Base;
1485 }
1486 }
1487 break;
1488
1489 case OR_Ambiguous:
1490 ICS.setAmbiguous();
1491 ICS.Ambiguous.setFromType(From->getType());
1492 ICS.Ambiguous.setToType(ToType);
1493 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1494 Cand != Conversions.end(); ++Cand)
1495 if (Cand->Best)
1496 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1497 break;
1498
1499 // Fall through.
1500 case OR_No_Viable_Function:
1501 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1502 break;
1503 }
1504
1505 return ICS;
1506}
1507
1508/// TryImplicitConversion - Attempt to perform an implicit conversion
1509/// from the given expression (Expr) to the given type (ToType). This
1510/// function returns an implicit conversion sequence that can be used
1511/// to perform the initialization. Given
1512///
1513/// void f(float f);
1514/// void g(int i) { f(i); }
1515///
1516/// this routine would produce an implicit conversion sequence to
1517/// describe the initialization of f from i, which will be a standard
1518/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1519/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1520//
1521/// Note that this routine only determines how the conversion can be
1522/// performed; it does not actually perform the conversion. As such,
1523/// it will not produce any diagnostics if no conversion is available,
1524/// but will instead return an implicit conversion sequence of kind
1525/// "BadConversion".
1526///
1527/// If @p SuppressUserConversions, then user-defined conversions are
1528/// not permitted.
1529/// If @p AllowExplicit, then explicit user-defined conversions are
1530/// permitted.
1531///
1532/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1533/// writeback conversion, which allows __autoreleasing id* parameters to
1534/// be initialized with __strong id* or __weak id* arguments.
1535static ImplicitConversionSequence
1536TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1537 bool SuppressUserConversions,
1538 AllowedExplicit AllowExplicit,
1539 bool InOverloadResolution,
1540 bool CStyle,
1541 bool AllowObjCWritebackConversion,
1542 bool AllowObjCConversionOnExplicit) {
1543 ImplicitConversionSequence ICS;
1544 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1545 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1546 ICS.setStandard();
1547 return ICS;
1548 }
1549
1550 if (!S.getLangOpts().CPlusPlus) {
1551 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1552 return ICS;
1553 }
1554
1555 // C++ [over.ics.user]p4:
1556 // A conversion of an expression of class type to the same class
1557 // type is given Exact Match rank, and a conversion of an
1558 // expression of class type to a base class of that type is
1559 // given Conversion rank, in spite of the fact that a copy/move
1560 // constructor (i.e., a user-defined conversion function) is
1561 // called for those cases.
1562 QualType FromType = From->getType();
1563 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1564 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1565 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1566 ICS.setStandard();
1567 ICS.Standard.setAsIdentityConversion();
1568 ICS.Standard.setFromType(FromType);
1569 ICS.Standard.setAllToTypes(ToType);
1570
1571 // We don't actually check at this point whether there is a valid
1572 // copy/move constructor, since overloading just assumes that it
1573 // exists. When we actually perform initialization, we'll find the
1574 // appropriate constructor to copy the returned object, if needed.
1575 ICS.Standard.CopyConstructor = nullptr;
1576
1577 // Determine whether this is considered a derived-to-base conversion.
1578 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1579 ICS.Standard.Second = ICK_Derived_To_Base;
1580
1581 return ICS;
1582 }
1583
1584 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1585 AllowExplicit, InOverloadResolution, CStyle,
1586 AllowObjCWritebackConversion,
1587 AllowObjCConversionOnExplicit);
1588}
1589
1590ImplicitConversionSequence
1591Sema::TryImplicitConversion(Expr *From, QualType ToType,
1592 bool SuppressUserConversions,
1593 AllowedExplicit AllowExplicit,
1594 bool InOverloadResolution,
1595 bool CStyle,
1596 bool AllowObjCWritebackConversion) {
1597 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1598 AllowExplicit, InOverloadResolution, CStyle,
1599 AllowObjCWritebackConversion,
1600 /*AllowObjCConversionOnExplicit=*/false);
1601}
1602
1603/// PerformImplicitConversion - Perform an implicit conversion of the
1604/// expression From to the type ToType. Returns the
1605/// converted expression. Flavor is the kind of conversion we're
1606/// performing, used in the error message. If @p AllowExplicit,
1607/// explicit user-defined conversions are permitted.
1608ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1609 AssignmentAction Action,
1610 bool AllowExplicit) {
1611 if (checkPlaceholderForOverload(*this, From))
1612 return ExprError();
1613
1614 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1615 bool AllowObjCWritebackConversion
1616 = getLangOpts().ObjCAutoRefCount &&
1617 (Action == AA_Passing || Action == AA_Sending);
1618 if (getLangOpts().ObjC)
1619 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1620 From->getType(), From);
1621 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1622 *this, From, ToType,
1623 /*SuppressUserConversions=*/false,
1624 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1625 /*InOverloadResolution=*/false,
1626 /*CStyle=*/false, AllowObjCWritebackConversion,
1627 /*AllowObjCConversionOnExplicit=*/false);
1628 return PerformImplicitConversion(From, ToType, ICS, Action);
1629}
1630
1631/// Determine whether the conversion from FromType to ToType is a valid
1632/// conversion that strips "noexcept" or "noreturn" off the nested function
1633/// type.
1634bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1635 QualType &ResultTy) {
1636 if (Context.hasSameUnqualifiedType(FromType, ToType))
1637 return false;
1638
1639 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1640 // or F(t noexcept) -> F(t)
1641 // where F adds one of the following at most once:
1642 // - a pointer
1643 // - a member pointer
1644 // - a block pointer
1645 // Changes here need matching changes in FindCompositePointerType.
1646 CanQualType CanTo = Context.getCanonicalType(ToType);
1647 CanQualType CanFrom = Context.getCanonicalType(FromType);
1648 Type::TypeClass TyClass = CanTo->getTypeClass();
1649 if (TyClass != CanFrom->getTypeClass()) return false;
1650 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1651 if (TyClass == Type::Pointer) {
1652 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1653 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1654 } else if (TyClass == Type::BlockPointer) {
1655 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1656 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1657 } else if (TyClass == Type::MemberPointer) {
1658 auto ToMPT = CanTo.castAs<MemberPointerType>();
1659 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1660 // A function pointer conversion cannot change the class of the function.
1661 if (ToMPT->getClass() != FromMPT->getClass())
1662 return false;
1663 CanTo = ToMPT->getPointeeType();
1664 CanFrom = FromMPT->getPointeeType();
1665 } else {
1666 return false;
1667 }
1668
1669 TyClass = CanTo->getTypeClass();
1670 if (TyClass != CanFrom->getTypeClass()) return false;
1671 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1672 return false;
1673 }
1674
1675 const auto *FromFn = cast<FunctionType>(CanFrom);
1676 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1677
1678 const auto *ToFn = cast<FunctionType>(CanTo);
1679 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1680
1681 bool Changed = false;
1682
1683 // Drop 'noreturn' if not present in target type.
1684 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1685 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1686 Changed = true;
1687 }
1688
1689 // Drop 'noexcept' if not present in target type.
1690 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1691 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1692 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1693 FromFn = cast<FunctionType>(
1694 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1695 EST_None)
1696 .getTypePtr());
1697 Changed = true;
1698 }
1699
1700 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1701 // only if the ExtParameterInfo lists of the two function prototypes can be
1702 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1703 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1704 bool CanUseToFPT, CanUseFromFPT;
1705 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1706 CanUseFromFPT, NewParamInfos) &&
1707 CanUseToFPT && !CanUseFromFPT) {
1708 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1709 ExtInfo.ExtParameterInfos =
1710 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1711 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1712 FromFPT->getParamTypes(), ExtInfo);
1713 FromFn = QT->getAs<FunctionType>();
1714 Changed = true;
1715 }
1716 }
1717
1718 if (!Changed)
1719 return false;
1720
1721 assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "clang/lib/Sema/SemaOverload.cpp", 1721, __extension__ __PRETTY_FUNCTION__
))
;
1722 if (QualType(FromFn, 0) != CanTo) return false;
1723
1724 ResultTy = ToType;
1725 return true;
1726}
1727
1728/// Determine whether the conversion from FromType to ToType is a valid
1729/// vector conversion.
1730///
1731/// \param ICK Will be set to the vector conversion kind, if this is a vector
1732/// conversion.
1733static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1734 ImplicitConversionKind &ICK, Expr *From,
1735 bool InOverloadResolution, bool CStyle) {
1736 // We need at least one of these types to be a vector type to have a vector
1737 // conversion.
1738 if (!ToType->isVectorType() && !FromType->isVectorType())
1739 return false;
1740
1741 // Identical types require no conversions.
1742 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1743 return false;
1744
1745 // There are no conversions between extended vector types, only identity.
1746 if (ToType->isExtVectorType()) {
1747 // There are no conversions between extended vector types other than the
1748 // identity conversion.
1749 if (FromType->isExtVectorType())
1750 return false;
1751
1752 // Vector splat from any arithmetic type to a vector.
1753 if (FromType->isArithmeticType()) {
1754 ICK = ICK_Vector_Splat;
1755 return true;
1756 }
1757 }
1758
1759 if (ToType->isSVESizelessBuiltinType() ||
1760 FromType->isSVESizelessBuiltinType())
1761 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1762 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1763 ICK = ICK_SVE_Vector_Conversion;
1764 return true;
1765 }
1766
1767 if (ToType->isRVVSizelessBuiltinType() ||
1768 FromType->isRVVSizelessBuiltinType())
1769 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
1770 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
1771 ICK = ICK_RVV_Vector_Conversion;
1772 return true;
1773 }
1774
1775 // We can perform the conversion between vector types in the following cases:
1776 // 1)vector types are equivalent AltiVec and GCC vector types
1777 // 2)lax vector conversions are permitted and the vector types are of the
1778 // same size
1779 // 3)the destination type does not have the ARM MVE strict-polymorphism
1780 // attribute, which inhibits lax vector conversion for overload resolution
1781 // only
1782 if (ToType->isVectorType() && FromType->isVectorType()) {
1783 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1784 (S.isLaxVectorConversion(FromType, ToType) &&
1785 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1786 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
1787 S.isLaxVectorConversion(FromType, ToType) &&
1788 S.anyAltivecTypes(FromType, ToType) &&
1789 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
1790 !InOverloadResolution && !CStyle) {
1791 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1792 << FromType << ToType;
1793 }
1794 ICK = ICK_Vector_Conversion;
1795 return true;
1796 }
1797 }
1798
1799 return false;
1800}
1801
1802static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1803 bool InOverloadResolution,
1804 StandardConversionSequence &SCS,
1805 bool CStyle);
1806
1807/// IsStandardConversion - Determines whether there is a standard
1808/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1809/// expression From to the type ToType. Standard conversion sequences
1810/// only consider non-class types; for conversions that involve class
1811/// types, use TryImplicitConversion. If a conversion exists, SCS will
1812/// contain the standard conversion sequence required to perform this
1813/// conversion and this routine will return true. Otherwise, this
1814/// routine will return false and the value of SCS is unspecified.
1815static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1816 bool InOverloadResolution,
1817 StandardConversionSequence &SCS,
1818 bool CStyle,
1819 bool AllowObjCWritebackConversion) {
1820 QualType FromType = From->getType();
1821
1822 // Standard conversions (C++ [conv])
1823 SCS.setAsIdentityConversion();
1824 SCS.IncompatibleObjC = false;
1825 SCS.setFromType(FromType);
1826 SCS.CopyConstructor = nullptr;
1827
1828 // There are no standard conversions for class types in C++, so
1829 // abort early. When overloading in C, however, we do permit them.
1830 if (S.getLangOpts().CPlusPlus &&
1831 (FromType->isRecordType() || ToType->isRecordType()))
1832 return false;
1833
1834 // The first conversion can be an lvalue-to-rvalue conversion,
1835 // array-to-pointer conversion, or function-to-pointer conversion
1836 // (C++ 4p1).
1837
1838 if (FromType == S.Context.OverloadTy) {
1839 DeclAccessPair AccessPair;
1840 if (FunctionDecl *Fn
1841 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1842 AccessPair)) {
1843 // We were able to resolve the address of the overloaded function,
1844 // so we can convert to the type of that function.
1845 FromType = Fn->getType();
1846 SCS.setFromType(FromType);
1847
1848 // we can sometimes resolve &foo<int> regardless of ToType, so check
1849 // if the type matches (identity) or we are converting to bool
1850 if (!S.Context.hasSameUnqualifiedType(
1851 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1852 QualType resultTy;
1853 // if the function type matches except for [[noreturn]], it's ok
1854 if (!S.IsFunctionConversion(FromType,
1855 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1856 // otherwise, only a boolean conversion is standard
1857 if (!ToType->isBooleanType())
1858 return false;
1859 }
1860
1861 // Check if the "from" expression is taking the address of an overloaded
1862 // function and recompute the FromType accordingly. Take advantage of the
1863 // fact that non-static member functions *must* have such an address-of
1864 // expression.
1865 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1866 if (Method && !Method->isStatic()) {
1867 assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1868, __extension__ __PRETTY_FUNCTION__
))
1868 "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1868, __extension__ __PRETTY_FUNCTION__
))
;
1869 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1871, __extension__ __PRETTY_FUNCTION__
))
1870 == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1871, __extension__ __PRETTY_FUNCTION__
))
1871 "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "clang/lib/Sema/SemaOverload.cpp", 1871, __extension__ __PRETTY_FUNCTION__
))
;
1872 const Type *ClassType
1873 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1874 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1875 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1876 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1878, __extension__ __PRETTY_FUNCTION__
))
1877 UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1878, __extension__ __PRETTY_FUNCTION__
))
1878 "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "clang/lib/Sema/SemaOverload.cpp", 1878, __extension__ __PRETTY_FUNCTION__
))
;
1879 FromType = S.Context.getPointerType(FromType);
1880 }
1881 } else {
1882 return false;
1883 }
1884 }
1885 // Lvalue-to-rvalue conversion (C++11 4.1):
1886 // A glvalue (3.10) of a non-function, non-array type T can
1887 // be converted to a prvalue.
1888 bool argIsLValue = From->isGLValue();
1889 if (argIsLValue &&
1890 !FromType->isFunctionType() && !FromType->isArrayType() &&
1891 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1892 SCS.First = ICK_Lvalue_To_Rvalue;
1893
1894 // C11 6.3.2.1p2:
1895 // ... if the lvalue has atomic type, the value has the non-atomic version
1896 // of the type of the lvalue ...
1897 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1898 FromType = Atomic->getValueType();
1899
1900 // If T is a non-class type, the type of the rvalue is the
1901 // cv-unqualified version of T. Otherwise, the type of the rvalue
1902 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1903 // just strip the qualifiers because they don't matter.
1904 FromType = FromType.getUnqualifiedType();
1905 } else if (FromType->isArrayType()) {
1906 // Array-to-pointer conversion (C++ 4.2)
1907 SCS.First = ICK_Array_To_Pointer;
1908
1909 // An lvalue or rvalue of type "array of N T" or "array of unknown
1910 // bound of T" can be converted to an rvalue of type "pointer to
1911 // T" (C++ 4.2p1).
1912 FromType = S.Context.getArrayDecayedType(FromType);
1913
1914 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1915 // This conversion is deprecated in C++03 (D.4)
1916 SCS.DeprecatedStringLiteralToCharPtr = true;
1917
1918 // For the purpose of ranking in overload resolution
1919 // (13.3.3.1.1), this conversion is considered an
1920 // array-to-pointer conversion followed by a qualification
1921 // conversion (4.4). (C++ 4.2p2)
1922 SCS.Second = ICK_Identity;
1923 SCS.Third = ICK_Qualification;
1924 SCS.QualificationIncludesObjCLifetime = false;
1925 SCS.setAllToTypes(FromType);
1926 return true;
1927 }
1928 } else if (FromType->isFunctionType() && argIsLValue) {
1929 // Function-to-pointer conversion (C++ 4.3).
1930 SCS.First = ICK_Function_To_Pointer;
1931
1932 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1933 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1934 if (!S.checkAddressOfFunctionIsAvailable(FD))
1935 return false;
1936
1937 // An lvalue of function type T can be converted to an rvalue of
1938 // type "pointer to T." The result is a pointer to the
1939 // function. (C++ 4.3p1).
1940 FromType = S.Context.getPointerType(FromType);
1941 } else {
1942 // We don't require any conversions for the first step.
1943 SCS.First = ICK_Identity;
1944 }
1945 SCS.setToType(0, FromType);
1946
1947 // The second conversion can be an integral promotion, floating
1948 // point promotion, integral conversion, floating point conversion,
1949 // floating-integral conversion, pointer conversion,
1950 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1951 // For overloading in C, this can also be a "compatible-type"
1952 // conversion.
1953 bool IncompatibleObjC = false;
1954 ImplicitConversionKind SecondICK = ICK_Identity;
1955 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1956 // The unqualified versions of the types are the same: there's no
1957 // conversion to do.
1958 SCS.Second = ICK_Identity;
1959 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1960 // Integral promotion (C++ 4.5).
1961 SCS.Second = ICK_Integral_Promotion;
1962 FromType = ToType.getUnqualifiedType();
1963 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1964 // Floating point promotion (C++ 4.6).
1965 SCS.Second = ICK_Floating_Promotion;
1966 FromType = ToType.getUnqualifiedType();
1967 } else if (S.IsComplexPromotion(FromType, ToType)) {
1968 // Complex promotion (Clang extension)
1969 SCS.Second = ICK_Complex_Promotion;
1970 FromType = ToType.getUnqualifiedType();
1971 } else if (ToType->isBooleanType() &&
1972 (FromType->isArithmeticType() ||
1973 FromType->isAnyPointerType() ||
1974 FromType->isBlockPointerType() ||
1975 FromType->isMemberPointerType())) {
1976 // Boolean conversions (C++ 4.12).
1977 SCS.Second = ICK_Boolean_Conversion;
1978 FromType = S.Context.BoolTy;
1979 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1980 ToType->isIntegralType(S.Context)) {
1981 // Integral conversions (C++ 4.7).
1982 SCS.Second = ICK_Integral_Conversion;
1983 FromType = ToType.getUnqualifiedType();
1984 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1985 // Complex conversions (C99 6.3.1.6)
1986 SCS.Second = ICK_Complex_Conversion;
1987 FromType = ToType.getUnqualifiedType();
1988 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1989 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1990 // Complex-real conversions (C99 6.3.1.7)
1991 SCS.Second = ICK_Complex_Real;
1992 FromType = ToType.getUnqualifiedType();
1993 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1994 // FIXME: disable conversions between long double, __ibm128 and __float128
1995 // if their representation is different until there is back end support
1996 // We of course allow this conversion if long double is really double.
1997
1998 // Conversions between bfloat and other floats are not permitted.
1999 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
2000 return false;
2001
2002 // Conversions between IEEE-quad and IBM-extended semantics are not
2003 // permitted.
2004 const llvm::fltSemantics &FromSem =
2005 S.Context.getFloatTypeSemantics(FromType);
2006 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2007 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2008 &ToSem == &llvm::APFloat::IEEEquad()) ||
2009 (&FromSem == &llvm::APFloat::IEEEquad() &&
2010 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2011 return false;
2012
2013 // Floating point conversions (C++ 4.8).
2014 SCS.Second = ICK_Floating_Conversion;
2015 FromType = ToType.getUnqualifiedType();
2016 } else if ((FromType->isRealFloatingType() &&
2017 ToType->isIntegralType(S.Context)) ||
2018 (FromType->isIntegralOrUnscopedEnumerationType() &&
2019 ToType->isRealFloatingType())) {
2020 // Conversions between bfloat and int are not permitted.
2021 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
2022 return false;
2023
2024 // Floating-integral conversions (C++ 4.9).
2025 SCS.Second = ICK_Floating_Integral;
2026 FromType = ToType.getUnqualifiedType();
2027 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2028 SCS.Second = ICK_Block_Pointer_Conversion;
2029 } else if (AllowObjCWritebackConversion &&
2030 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2031 SCS.Second = ICK_Writeback_Conversion;
2032 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2033 FromType, IncompatibleObjC)) {
2034 // Pointer conversions (C++ 4.10).
2035 SCS.Second = ICK_Pointer_Conversion;
2036 SCS.IncompatibleObjC = IncompatibleObjC;
2037 FromType = FromType.getUnqualifiedType();
2038 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2039 InOverloadResolution, FromType)) {
2040 // Pointer to member conversions (4.11).
2041 SCS.Second = ICK_Pointer_Member;
2042 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2043 InOverloadResolution, CStyle)) {
2044 SCS.Second = SecondICK;
2045 FromType = ToType.getUnqualifiedType();
2046 } else if (!S.getLangOpts().CPlusPlus &&
2047 S.Context.typesAreCompatible(ToType, FromType)) {
2048 // Compatible conversions (Clang extension for C function overloading)
2049 SCS.Second = ICK_Compatible_Conversion;
2050 FromType = ToType.getUnqualifiedType();
2051 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2052 InOverloadResolution,
2053 SCS, CStyle)) {
2054 SCS.Second = ICK_TransparentUnionConversion;
2055 FromType = ToType;
2056 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2057 CStyle)) {
2058 // tryAtomicConversion has updated the standard conversion sequence
2059 // appropriately.
2060 return true;
2061 } else if (ToType->isEventT() &&
2062 From->isIntegerConstantExpr(S.getASTContext()) &&
2063 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2064 SCS.Second = ICK_Zero_Event_Conversion;
2065 FromType = ToType;
2066 } else if (ToType->isQueueT() &&
2067 From->isIntegerConstantExpr(S.getASTContext()) &&
2068 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2069 SCS.Second = ICK_Zero_Queue_Conversion;
2070 FromType = ToType;
2071 } else if (ToType->isSamplerT() &&
2072 From->isIntegerConstantExpr(S.getASTContext())) {
2073 SCS.Second = ICK_Compatible_Conversion;
2074 FromType = ToType;
2075 } else {
2076 // No second conversion required.
2077 SCS.Second = ICK_Identity;
2078 }
2079 SCS.setToType(1, FromType);
2080
2081 // The third conversion can be a function pointer conversion or a
2082 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2083 bool ObjCLifetimeConversion;
2084 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2085 // Function pointer conversions (removing 'noexcept') including removal of
2086 // 'noreturn' (Clang extension).
2087 SCS.Third = ICK_Function_Conversion;
2088 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2089 ObjCLifetimeConversion)) {
2090 SCS.Third = ICK_Qualification;
2091 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2092 FromType = ToType;
2093 } else {
2094 // No conversion required
2095 SCS.Third = ICK_Identity;
2096 }
2097
2098 // C++ [over.best.ics]p6:
2099 // [...] Any difference in top-level cv-qualification is
2100 // subsumed by the initialization itself and does not constitute
2101 // a conversion. [...]
2102 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2103 QualType CanonTo = S.Context.getCanonicalType(ToType);
2104 if (CanonFrom.getLocalUnqualifiedType()
2105 == CanonTo.getLocalUnqualifiedType() &&
2106 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2107 FromType = ToType;
2108 CanonFrom = CanonTo;
2109 }
2110
2111 SCS.setToType(2, FromType);
2112
2113 if (CanonFrom == CanonTo)
2114 return true;
2115
2116 // If we have not converted the argument type to the parameter type,
2117 // this is a bad conversion sequence, unless we're resolving an overload in C.
2118 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2119 return false;
2120
2121 ExprResult ER = ExprResult{From};
2122 Sema::AssignConvertType Conv =
2123 S.CheckSingleAssignmentConstraints(ToType, ER,
2124 /*Diagnose=*/false,
2125 /*DiagnoseCFAudited=*/false,
2126 /*ConvertRHS=*/false);
2127 ImplicitConversionKind SecondConv;
2128 switch (Conv) {
2129 case Sema::Compatible:
2130 SecondConv = ICK_C_Only_Conversion;
2131 break;
2132 // For our purposes, discarding qualifiers is just as bad as using an
2133 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2134 // qualifiers, as well.
2135 case Sema::CompatiblePointerDiscardsQualifiers:
2136 case Sema::IncompatiblePointer:
2137 case Sema::IncompatiblePointerSign:
2138 SecondConv = ICK_Incompatible_Pointer_Conversion;
2139 break;
2140 default:
2141 return false;
2142 }
2143
2144 // First can only be an lvalue conversion, so we pretend that this was the
2145 // second conversion. First should already be valid from earlier in the
2146 // function.
2147 SCS.Second = SecondConv;
2148 SCS.setToType(1, ToType);
2149
2150 // Third is Identity, because Second should rank us worse than any other
2151 // conversion. This could also be ICK_Qualification, but it's simpler to just
2152 // lump everything in with the second conversion, and we don't gain anything
2153 // from making this ICK_Qualification.
2154 SCS.Third = ICK_Identity;
2155 SCS.setToType(2, ToType);
2156 return true;
2157}
2158
2159static bool
2160IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2161 QualType &ToType,
2162 bool InOverloadResolution,
2163 StandardConversionSequence &SCS,
2164 bool CStyle) {
2165
2166 const RecordType *UT = ToType->getAsUnionType();
2167 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2168 return false;
2169 // The field to initialize within the transparent union.
2170 RecordDecl *UD = UT->getDecl();
2171 // It's compatible if the expression matches any of the fields.
2172 for (const auto *it : UD->fields()) {
2173 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2174 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2175 ToType = it->getType();
2176 return true;
2177 }
2178 }
2179 return false;
2180}
2181
2182/// IsIntegralPromotion - Determines whether the conversion from the
2183/// expression From (whose potentially-adjusted type is FromType) to
2184/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2185/// sets PromotedType to the promoted type.
2186bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2187 const BuiltinType *To = ToType->getAs<BuiltinType>();
2188 // All integers are built-in.
2189 if (!To) {
2190 return false;
2191 }
2192
2193 // An rvalue of type char, signed char, unsigned char, short int, or
2194 // unsigned short int can be converted to an rvalue of type int if
2195 // int can represent all the values of the source type; otherwise,
2196 // the source rvalue can be converted to an rvalue of type unsigned
2197 // int (C++ 4.5p1).
2198 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2199 !FromType->isEnumeralType()) {
2200 if ( // We can promote any signed, promotable integer type to an int
2201 (FromType->isSignedIntegerType() ||
2202 // We can promote any unsigned integer type whose size is
2203 // less than int to an int.
2204 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2205 return To->getKind() == BuiltinType::Int;
2206 }
2207
2208 return To->getKind() == BuiltinType::UInt;
2209 }
2210
2211 // C++11 [conv.prom]p3:
2212 // A prvalue of an unscoped enumeration type whose underlying type is not
2213 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2214 // following types that can represent all the values of the enumeration
2215 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2216 // unsigned int, long int, unsigned long int, long long int, or unsigned
2217 // long long int. If none of the types in that list can represent all the
2218 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2219 // type can be converted to an rvalue a prvalue of the extended integer type
2220 // with lowest integer conversion rank (4.13) greater than the rank of long
2221 // long in which all the values of the enumeration can be represented. If
2222 // there are two such extended types, the signed one is chosen.
2223 // C++11 [conv.prom]p4:
2224 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2225 // can be converted to a prvalue of its underlying type. Moreover, if
2226 // integral promotion can be applied to its underlying type, a prvalue of an
2227 // unscoped enumeration type whose underlying type is fixed can also be
2228 // converted to a prvalue of the promoted underlying type.
2229 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2230 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2231 // provided for a scoped enumeration.
2232 if (FromEnumType->getDecl()->isScoped())
2233 return false;
2234
2235 // We can perform an integral promotion to the underlying type of the enum,
2236 // even if that's not the promoted type. Note that the check for promoting
2237 // the underlying type is based on the type alone, and does not consider
2238 // the bitfield-ness of the actual source expression.
2239 if (FromEnumType->getDecl()->isFixed()) {
2240 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2241 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2242 IsIntegralPromotion(nullptr, Underlying, ToType);
2243 }
2244
2245 // We have already pre-calculated the promotion type, so this is trivial.
2246 if (ToType->isIntegerType() &&
2247 isCompleteType(From->getBeginLoc(), FromType))
2248 return Context.hasSameUnqualifiedType(
2249 ToType, FromEnumType->getDecl()->getPromotionType());
2250
2251 // C++ [conv.prom]p5:
2252 // If the bit-field has an enumerated type, it is treated as any other
2253 // value of that type for promotion purposes.
2254 //
2255 // ... so do not fall through into the bit-field checks below in C++.
2256 if (getLangOpts().CPlusPlus)
2257 return false;
2258 }
2259
2260 // C++0x [conv.prom]p2:
2261 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2262 // to an rvalue a prvalue of the first of the following types that can
2263 // represent all the values of its underlying type: int, unsigned int,
2264 // long int, unsigned long int, long long int, or unsigned long long int.
2265 // If none of the types in that list can represent all the values of its
2266 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2267 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2268 // type.
2269 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2270 ToType->isIntegerType()) {
2271 // Determine whether the type we're converting from is signed or
2272 // unsigned.
2273 bool FromIsSigned = FromType->isSignedIntegerType();
2274 uint64_t FromSize = Context.getTypeSize(FromType);
2275
2276 // The types we'll try to promote to, in the appropriate
2277 // order. Try each of these types.
2278 QualType PromoteTypes[6] = {
2279 Context.IntTy, Context.UnsignedIntTy,
2280 Context.LongTy, Context.UnsignedLongTy ,
2281 Context.LongLongTy, Context.UnsignedLongLongTy
2282 };
2283 for (int Idx = 0; Idx < 6; ++Idx) {
2284 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2285 if (FromSize < ToSize ||
2286 (FromSize == ToSize &&
2287 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2288 // We found the type that we can promote to. If this is the
2289 // type we wanted, we have a promotion. Otherwise, no
2290 // promotion.
2291 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2292 }
2293 }
2294 }
2295
2296 // An rvalue for an integral bit-field (9.6) can be converted to an
2297 // rvalue of type int if int can represent all the values of the
2298 // bit-field; otherwise, it can be converted to unsigned int if
2299 // unsigned int can represent all the values of the bit-field. If
2300 // the bit-field is larger yet, no integral promotion applies to
2301 // it. If the bit-field has an enumerated type, it is treated as any
2302 // other value of that type for promotion purposes (C++ 4.5p3).
2303 // FIXME: We should delay checking of bit-fields until we actually perform the
2304 // conversion.
2305 //
2306 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2307 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2308 // bit-fields and those whose underlying type is larger than int) for GCC
2309 // compatibility.
2310 if (From) {
2311 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2312 std::optional<llvm::APSInt> BitWidth;
2313 if (FromType->isIntegralType(Context) &&
2314 (BitWidth =
2315 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2316 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2317 ToSize = Context.getTypeSize(ToType);
2318
2319 // Are we promoting to an int from a bitfield that fits in an int?
2320 if (*BitWidth < ToSize ||
2321 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2322 return To->getKind() == BuiltinType::Int;
2323 }
2324
2325 // Are we promoting to an unsigned int from an unsigned bitfield
2326 // that fits into an unsigned int?
2327 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2328 return To->getKind() == BuiltinType::UInt;
2329 }
2330
2331 return false;
2332 }
2333 }
2334 }
2335
2336 // An rvalue of type bool can be converted to an rvalue of type int,
2337 // with false becoming zero and true becoming one (C++ 4.5p4).
2338 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2339 return true;
2340 }
2341
2342 return false;
2343}
2344
2345/// IsFloatingPointPromotion - Determines whether the conversion from
2346/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2347/// returns true and sets PromotedType to the promoted type.
2348bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2349 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2350 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2351 /// An rvalue of type float can be converted to an rvalue of type
2352 /// double. (C++ 4.6p1).
2353 if (FromBuiltin->getKind() == BuiltinType::Float &&
2354 ToBuiltin->getKind() == BuiltinType::Double)
2355 return true;
2356
2357 // C99 6.3.1.5p1:
2358 // When a float is promoted to double or long double, or a
2359 // double is promoted to long double [...].
2360 if (!getLangOpts().CPlusPlus &&
2361 (FromBuiltin->getKind() == BuiltinType::Float ||
2362 FromBuiltin->getKind() == BuiltinType::Double) &&
2363 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2364 ToBuiltin->getKind() == BuiltinType::Float128 ||
2365 ToBuiltin->getKind() == BuiltinType::Ibm128))
2366 return true;
2367
2368 // Half can be promoted to float.
2369 if (!getLangOpts().NativeHalfType &&
2370 FromBuiltin->getKind() == BuiltinType::Half &&
2371 ToBuiltin->getKind() == BuiltinType::Float)
2372 return true;
2373 }
2374
2375 return false;
2376}
2377
2378/// Determine if a conversion is a complex promotion.
2379///
2380/// A complex promotion is defined as a complex -> complex conversion
2381/// where the conversion between the underlying real types is a
2382/// floating-point or integral promotion.
2383bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2384 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2385 if (!FromComplex)
2386 return false;
2387
2388 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2389 if (!ToComplex)
2390 return false;
2391
2392 return IsFloatingPointPromotion(FromComplex->getElementType(),
2393 ToComplex->getElementType()) ||
2394 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2395 ToComplex->getElementType());
2396}
2397
2398/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2399/// the pointer type FromPtr to a pointer to type ToPointee, with the
2400/// same type qualifiers as FromPtr has on its pointee type. ToType,
2401/// if non-empty, will be a pointer to ToType that may or may not have
2402/// the right set of qualifiers on its pointee.
2403///
2404static QualType
2405BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2406 QualType ToPointee, QualType ToType,
2407 ASTContext &Context,
2408 bool StripObjCLifetime = false) {
2409 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2411, __extension__ __PRETTY_FUNCTION__
))
2410 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2411, __extension__ __PRETTY_FUNCTION__
))
2411 "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "clang/lib/Sema/SemaOverload.cpp", 2411, __extension__ __PRETTY_FUNCTION__
))
;
2412
2413 /// Conversions to 'id' subsume cv-qualifier conversions.
2414 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2415 return ToType.getUnqualifiedType();
2416
2417 QualType CanonFromPointee
2418 = Context.getCanonicalType(FromPtr->getPointeeType());
2419 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2420 Qualifiers Quals = CanonFromPointee.getQualifiers();
2421
2422 if (StripObjCLifetime)
2423 Quals.removeObjCLifetime();
2424
2425 // Exact qualifier match -> return the pointer type we're converting to.
2426 if (CanonToPointee.getLocalQualifiers() == Quals) {
2427 // ToType is exactly what we need. Return it.
2428 if (!ToType.isNull())
2429 return ToType.getUnqualifiedType();
2430
2431 // Build a pointer to ToPointee. It has the right qualifiers
2432 // already.
2433 if (isa<ObjCObjectPointerType>(ToType))
2434 return Context.getObjCObjectPointerType(ToPointee);
2435 return Context.getPointerType(ToPointee);
2436 }
2437
2438 // Just build a canonical type that has the right qualifiers.
2439 QualType QualifiedCanonToPointee
2440 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2441
2442 if (isa<ObjCObjectPointerType>(ToType))
2443 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2444 return Context.getPointerType(QualifiedCanonToPointee);
2445}
2446
2447static bool isNullPointerConstantForConversion(Expr *Expr,
2448 bool InOverloadResolution,
2449 ASTContext &Context) {
2450 // Handle value-dependent integral null pointer constants correctly.
2451 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2452 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2453 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2454 return !InOverloadResolution;
2455
2456 return Expr->isNullPointerConstant(Context,
2457 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2458 : Expr::NPC_ValueDependentIsNull);
2459}
2460
2461/// IsPointerConversion - Determines whether the conversion of the
2462/// expression From, which has the (possibly adjusted) type FromType,
2463/// can be converted to the type ToType via a pointer conversion (C++
2464/// 4.10). If so, returns true and places the converted type (that
2465/// might differ from ToType in its cv-qualifiers at some level) into
2466/// ConvertedType.
2467///
2468/// This routine also supports conversions to and from block pointers
2469/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2470/// pointers to interfaces. FIXME: Once we've determined the
2471/// appropriate overloading rules for Objective-C, we may want to
2472/// split the Objective-C checks into a different routine; however,
2473/// GCC seems to consider all of these conversions to be pointer
2474/// conversions, so for now they live here. IncompatibleObjC will be
2475/// set if the conversion is an allowed Objective-C conversion that
2476/// should result in a warning.
2477bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2478 bool InOverloadResolution,
2479 QualType& ConvertedType,
2480 bool &IncompatibleObjC) {
2481 IncompatibleObjC = false;
2482 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2483 IncompatibleObjC))
2484 return true;
2485
2486 // Conversion from a null pointer constant to any Objective-C pointer type.
2487 if (ToType->isObjCObjectPointerType() &&
2488 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2489 ConvertedType = ToType;
2490 return true;
2491 }
2492
2493 // Blocks: Block pointers can be converted to void*.
2494 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2495 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2496 ConvertedType = ToType;
2497 return true;
2498 }
2499 // Blocks: A null pointer constant can be converted to a block
2500 // pointer type.
2501 if (ToType->isBlockPointerType() &&
2502 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2503 ConvertedType = ToType;
2504 return true;
2505 }
2506
2507 // If the left-hand-side is nullptr_t, the right side can be a null
2508 // pointer constant.
2509 if (ToType->isNullPtrType() &&
2510 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2511 ConvertedType = ToType;
2512 return true;
2513 }
2514
2515 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2516 if (!ToTypePtr)
2517 return false;
2518
2519 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2520 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2521 ConvertedType = ToType;
2522 return true;
2523 }
2524
2525 // Beyond this point, both types need to be pointers
2526 // , including objective-c pointers.
2527 QualType ToPointeeType = ToTypePtr->getPointeeType();
2528 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2529 !getLangOpts().ObjCAutoRefCount) {
2530 ConvertedType = BuildSimilarlyQualifiedPointerType(
2531 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2532 Context);
2533 return true;
2534 }
2535 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2536 if (!FromTypePtr)
2537 return false;
2538
2539 QualType FromPointeeType = FromTypePtr->getPointeeType();
2540
2541 // If the unqualified pointee types are the same, this can't be a
2542 // pointer conversion, so don't do all of the work below.
2543 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2544 return false;
2545
2546 // An rvalue of type "pointer to cv T," where T is an object type,
2547 // can be converted to an rvalue of type "pointer to cv void" (C++
2548 // 4.10p2).
2549 if (FromPointeeType->isIncompleteOrObjectType() &&
2550 ToPointeeType->isVoidType()) {
2551 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2552 ToPointeeType,
2553 ToType, Context,
2554 /*StripObjCLifetime=*/true);
2555 return true;
2556 }
2557
2558 // MSVC allows implicit function to void* type conversion.
2559 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2560 ToPointeeType->isVoidType()) {
2561 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2562 ToPointeeType,
2563 ToType, Context);
2564 return true;
2565 }
2566
2567 // When we're overloading in C, we allow a special kind of pointer
2568 // conversion for compatible-but-not-identical pointee types.
2569 if (!getLangOpts().CPlusPlus &&
2570 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2571 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2572 ToPointeeType,
2573 ToType, Context);
2574 return true;
2575 }
2576
2577 // C++ [conv.ptr]p3:
2578 //
2579 // An rvalue of type "pointer to cv D," where D is a class type,
2580 // can be converted to an rvalue of type "pointer to cv B," where
2581 // B is a base class (clause 10) of D. If B is an inaccessible
2582 // (clause 11) or ambiguous (10.2) base class of D, a program that
2583 // necessitates this conversion is ill-formed. The result of the
2584 // conversion is a pointer to the base class sub-object of the
2585 // derived class object. The null pointer value is converted to
2586 // the null pointer value of the destination type.
2587 //
2588 // Note that we do not check for ambiguity or inaccessibility
2589 // here. That is handled by CheckPointerConversion.
2590 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2591 ToPointeeType->isRecordType() &&
2592 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2593 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2594 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2595 ToPointeeType,
2596 ToType, Context);
2597 return true;
2598 }
2599
2600 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2601 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2602 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2603 ToPointeeType,
2604 ToType, Context);
2605 return true;
2606 }
2607
2608 return false;
2609}
2610
2611/// Adopt the given qualifiers for the given type.
2612static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2613 Qualifiers TQs = T.getQualifiers();
2614
2615 // Check whether qualifiers already match.
2616 if (TQs == Qs)
2617 return T;
2618
2619 if (Qs.compatiblyIncludes(TQs))
2620 return Context.getQualifiedType(T, Qs);
2621
2622 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2623}
2624
2625/// isObjCPointerConversion - Determines whether this is an
2626/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2627/// with the same arguments and return values.
2628bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2629 QualType& ConvertedType,
2630 bool &IncompatibleObjC) {
2631 if (!getLangOpts().ObjC)
2632 return false;
2633
2634 // The set of qualifiers on the type we're converting from.
2635 Qualifiers FromQualifiers = FromType.getQualifiers();
2636
2637 // First, we handle all conversions on ObjC object pointer types.
2638 const ObjCObjectPointerType* ToObjCPtr =
2639 ToType->getAs<ObjCObjectPointerType>();
2640 const ObjCObjectPointerType *FromObjCPtr =
2641 FromType->getAs<ObjCObjectPointerType>();
2642
2643 if (ToObjCPtr && FromObjCPtr) {
2644 // If the pointee types are the same (ignoring qualifications),
2645 // then this is not a pointer conversion.
2646 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2647 FromObjCPtr->getPointeeType()))
2648 return false;
2649
2650 // Conversion between Objective-C pointers.
2651 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2652 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2653 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2654 if (getLangOpts().CPlusPlus && LHS && RHS &&
2655 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2656 FromObjCPtr->getPointeeType()))
2657 return false;
2658 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2659 ToObjCPtr->getPointeeType(),
2660 ToType, Context);
2661 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2662 return true;
2663 }
2664
2665 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2666 // Okay: this is some kind of implicit downcast of Objective-C
2667 // interfaces, which is permitted. However, we're going to
2668 // complain about it.
2669 IncompatibleObjC = true;
2670 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2671 ToObjCPtr->getPointeeType(),
2672 ToType, Context);
2673 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2674 return true;
2675 }
2676 }
2677 // Beyond this point, both types need to be C pointers or block pointers.
2678 QualType ToPointeeType;
2679 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2680 ToPointeeType = ToCPtr->getPointeeType();
2681 else if (const BlockPointerType *ToBlockPtr =
2682 ToType->getAs<BlockPointerType>()) {
2683 // Objective C++: We're able to convert from a pointer to any object
2684 // to a block pointer type.
2685 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2686 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2687 return true;
2688 }
2689 ToPointeeType = ToBlockPtr->getPointeeType();
2690 }
2691 else if (FromType->getAs<BlockPointerType>() &&
2692 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2693 // Objective C++: We're able to convert from a block pointer type to a
2694 // pointer to any object.
2695 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2696 return true;
2697 }
2698 else
2699 return false;
2700
2701 QualType FromPointeeType;
2702 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2703 FromPointeeType = FromCPtr->getPointeeType();
2704 else if (const BlockPointerType *FromBlockPtr =
2705 FromType->getAs<BlockPointerType>())
2706 FromPointeeType = FromBlockPtr->getPointeeType();
2707 else
2708 return false;
2709
2710 // If we have pointers to pointers, recursively check whether this
2711 // is an Objective-C conversion.
2712 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2713 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2714 IncompatibleObjC)) {
2715 // We always complain about this conversion.
2716 IncompatibleObjC = true;
2717 ConvertedType = Context.getPointerType(ConvertedType);
2718 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2719 return true;
2720 }
2721 // Allow conversion of pointee being objective-c pointer to another one;
2722 // as in I* to id.
2723 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2724 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2725 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2726 IncompatibleObjC)) {
2727
2728 ConvertedType = Context.getPointerType(ConvertedType);
2729 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2730 return true;
2731 }
2732
2733 // If we have pointers to functions or blocks, check whether the only
2734 // differences in the argument and result types are in Objective-C
2735 // pointer conversions. If so, we permit the conversion (but
2736 // complain about it).
2737 const FunctionProtoType *FromFunctionType
2738 = FromPointeeType->getAs<FunctionProtoType>();
2739 const FunctionProtoType *ToFunctionType
2740 = ToPointeeType->getAs<FunctionProtoType>();
2741 if (FromFunctionType && ToFunctionType) {
2742 // If the function types are exactly the same, this isn't an
2743 // Objective-C pointer conversion.
2744 if (Context.getCanonicalType(FromPointeeType)
2745 == Context.getCanonicalType(ToPointeeType))
2746 return false;
2747
2748 // Perform the quick checks that will tell us whether these
2749 // function types are obviously different.
2750 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2751 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2752 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2753 return false;
2754
2755 bool HasObjCConversion = false;
2756 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2757 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2758 // Okay, the types match exactly. Nothing to do.
2759 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2760 ToFunctionType->getReturnType(),
2761 ConvertedType, IncompatibleObjC)) {
2762 // Okay, we have an Objective-C pointer conversion.
2763 HasObjCConversion = true;
2764 } else {
2765 // Function types are too different. Abort.
2766 return false;
2767 }
2768
2769 // Check argument types.
2770 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2771 ArgIdx != NumArgs; ++ArgIdx) {
2772 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2773 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2774 if (Context.getCanonicalType(FromArgType)
2775 == Context.getCanonicalType(ToArgType)) {
2776 // Okay, the types match exactly. Nothing to do.
2777 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2778 ConvertedType, IncompatibleObjC)) {
2779 // Okay, we have an Objective-C pointer conversion.
2780 HasObjCConversion = true;
2781 } else {
2782 // Argument types are too different. Abort.
2783 return false;
2784 }
2785 }
2786
2787 if (HasObjCConversion) {
2788 // We had an Objective-C conversion. Allow this pointer
2789 // conversion, but complain about it.
2790 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2791 IncompatibleObjC = true;
2792 return true;
2793 }
2794 }
2795
2796 return false;
2797}
2798
2799/// Determine whether this is an Objective-C writeback conversion,
2800/// used for parameter passing when performing automatic reference counting.
2801///
2802/// \param FromType The type we're converting form.
2803///
2804/// \param ToType The type we're converting to.
2805///
2806/// \param ConvertedType The type that will be produced after applying
2807/// this conversion.
2808bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2809 QualType &ConvertedType) {
2810 if (!getLangOpts().ObjCAutoRefCount ||
2811 Context.hasSameUnqualifiedType(FromType, ToType))
2812 return false;
2813
2814 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2815 QualType ToPointee;
2816 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2817 ToPointee = ToPointer->getPointeeType();
2818 else
2819 return false;
2820
2821 Qualifiers ToQuals = ToPointee.getQualifiers();
2822 if (!ToPointee->isObjCLifetimeType() ||
2823 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2824 !ToQuals.withoutObjCLifetime().empty())
2825 return false;
2826
2827 // Argument must be a pointer to __strong to __weak.
2828 QualType FromPointee;
2829 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2830 FromPointee = FromPointer->getPointeeType();
2831 else
2832 return false;
2833
2834 Qualifiers FromQuals = FromPointee.getQualifiers();
2835 if (!FromPointee->isObjCLifetimeType() ||
2836 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2837 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2838 return false;
2839
2840 // Make sure that we have compatible qualifiers.
2841 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2842 if (!ToQuals.compatiblyIncludes(FromQuals))
2843 return false;
2844
2845 // Remove qualifiers from the pointee type we're converting from; they
2846 // aren't used in the compatibility check belong, and we'll be adding back
2847 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2848 FromPointee = FromPointee.getUnqualifiedType();
2849
2850 // The unqualified form of the pointee types must be compatible.
2851 ToPointee = ToPointee.getUnqualifiedType();
2852 bool IncompatibleObjC;
2853 if (Context.typesAreCompatible(FromPointee, ToPointee))
2854 FromPointee = ToPointee;
2855 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2856 IncompatibleObjC))
2857 return false;
2858
2859 /// Construct the type we're converting to, which is a pointer to
2860 /// __autoreleasing pointee.
2861 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2862 ConvertedType = Context.getPointerType(FromPointee);
2863 return true;
2864}
2865
2866bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2867 QualType& ConvertedType) {
2868 QualType ToPointeeType;
2869 if (const BlockPointerType *ToBlockPtr =
2870 ToType->getAs<BlockPointerType>())
2871 ToPointeeType = ToBlockPtr->getPointeeType();
2872 else
2873 return false;
2874
2875 QualType FromPointeeType;
2876 if (const BlockPointerType *FromBlockPtr =
2877 FromType->getAs<BlockPointerType>())
2878 FromPointeeType = FromBlockPtr->getPointeeType();
2879 else
2880 return false;
2881 // We have pointer to blocks, check whether the only
2882 // differences in the argument and result types are in Objective-C
2883 // pointer conversions. If so, we permit the conversion.
2884
2885 const FunctionProtoType *FromFunctionType
2886 = FromPointeeType->getAs<FunctionProtoType>();
2887 const FunctionProtoType *ToFunctionType
2888 = ToPointeeType->getAs<FunctionProtoType>();
2889
2890 if (!FromFunctionType || !ToFunctionType)
2891 return false;
2892
2893 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2894 return true;
2895
2896 // Perform the quick checks that will tell us whether these
2897 // function types are obviously different.
2898 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2899 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2900 return false;
2901
2902 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2903 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2904 if (FromEInfo != ToEInfo)
2905 return false;
2906
2907 bool IncompatibleObjC = false;
2908 if (Context.hasSameType(FromFunctionType->getReturnType(),
2909 ToFunctionType->getReturnType())) {
2910 // Okay, the types match exactly. Nothing to do.
2911 } else {
2912 QualType RHS = FromFunctionType->getReturnType();
2913 QualType LHS = ToFunctionType->getReturnType();
2914 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2915 !RHS.hasQualifiers() && LHS.hasQualifiers())
2916 LHS = LHS.getUnqualifiedType();
2917
2918 if (Context.hasSameType(RHS,LHS)) {
2919 // OK exact match.
2920 } else if (isObjCPointerConversion(RHS, LHS,
2921 ConvertedType, IncompatibleObjC)) {
2922 if (IncompatibleObjC)
2923 return false;
2924 // Okay, we have an Objective-C pointer conversion.
2925 }
2926 else
2927 return false;
2928 }
2929
2930 // Check argument types.
2931 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2932 ArgIdx != NumArgs; ++ArgIdx) {
2933 IncompatibleObjC = false;
2934 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2935 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2936 if (Context.hasSameType(FromArgType, ToArgType)) {
2937 // Okay, the types match exactly. Nothing to do.
2938 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2939 ConvertedType, IncompatibleObjC)) {
2940 if (IncompatibleObjC)
2941 return false;
2942 // Okay, we have an Objective-C pointer conversion.
2943 } else
2944 // Argument types are too different. Abort.
2945 return false;
2946 }
2947
2948 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2949 bool CanUseToFPT, CanUseFromFPT;
2950 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2951 CanUseToFPT, CanUseFromFPT,
2952 NewParamInfos))
2953 return false;
2954
2955 ConvertedType = ToType;
2956 return true;
2957}
2958
2959enum {
2960 ft_default,
2961 ft_different_class,
2962 ft_parameter_arity,
2963 ft_parameter_mismatch,
2964 ft_return_type,
2965 ft_qualifer_mismatch,
2966 ft_noexcept
2967};
2968
2969/// Attempts to get the FunctionProtoType from a Type. Handles
2970/// MemberFunctionPointers properly.
2971static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2972 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2973 return FPT;
2974
2975 if (auto *MPT = FromType->getAs<MemberPointerType>())
2976 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2977
2978 return nullptr;
2979}
2980
2981/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2982/// function types. Catches different number of parameter, mismatch in
2983/// parameter types, and different return types.
2984void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2985 QualType FromType, QualType ToType) {
2986 // If either type is not valid, include no extra info.
2987 if (FromType.isNull() || ToType.isNull()) {
2988 PDiag << ft_default;
2989 return;
2990 }
2991
2992 // Get the function type from the pointers.
2993 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2994 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2995 *ToMember = ToType->castAs<MemberPointerType>();
2996 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2997 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2998 << QualType(FromMember->getClass(), 0);
2999 return;
3000 }
3001 FromType = FromMember->getPointeeType();
3002 ToType = ToMember->getPointeeType();
3003 }
3004
3005 if (FromType->isPointerType())
3006 FromType = FromType->getPointeeType();
3007 if (ToType->isPointerType())
3008 ToType = ToType->getPointeeType();
3009
3010 // Remove references.
3011 FromType = FromType.getNonReferenceType();
3012 ToType = ToType.getNonReferenceType();
3013
3014 // Don't print extra info for non-specialized template functions.
3015 if (FromType->isInstantiationDependentType() &&
3016 !FromType->getAs<TemplateSpecializationType>()) {
3017 PDiag << ft_default;
3018 return;
3019 }
3020
3021 // No extra info for same types.
3022 if (Context.hasSameType(FromType, ToType)) {
3023 PDiag << ft_default;
3024 return;
3025 }
3026
3027 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3028 *ToFunction = tryGetFunctionProtoType(ToType);
3029
3030 // Both types need to be function types.
3031 if (!FromFunction || !ToFunction) {
3032 PDiag << ft_default;
3033 return;
3034 }
3035
3036 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3037 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3038 << FromFunction->getNumParams();
3039 return;
3040 }
3041
3042 // Handle different parameter types.
3043 unsigned ArgPos;
3044 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3045 PDiag << ft_parameter_mismatch << ArgPos + 1
3046 << ToFunction->getParamType(ArgPos)
3047 << FromFunction->getParamType(ArgPos);
3048 return;
3049 }
3050
3051 // Handle different return type.
3052 if (!Context.hasSameType(FromFunction->getReturnType(),
3053 ToFunction->getReturnType())) {
3054 PDiag << ft_return_type << ToFunction->getReturnType()
3055 << FromFunction->getReturnType();
3056 return;
3057 }
3058
3059 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3060 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3061 << FromFunction->getMethodQuals();
3062 return;
3063 }
3064
3065 // Handle exception specification differences on canonical type (in C++17
3066 // onwards).
3067 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3068 ->isNothrow() !=
3069 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3070 ->isNothrow()) {
3071 PDiag << ft_noexcept;
3072 return;
3073 }
3074
3075 // Unable to find a difference, so add no extra info.
3076 PDiag << ft_default;
3077}
3078
3079/// FunctionParamTypesAreEqual - This routine checks two function proto types
3080/// for equality of their parameter types. Caller has already checked that
3081/// they have same number of parameters. If the parameters are different,
3082/// ArgPos will have the parameter index of the first different parameter.
3083/// If `Reversed` is true, the parameters of `NewType` will be compared in
3084/// reverse order. That's useful if one of the functions is being used as a C++20
3085/// synthesized operator overload with a reversed parameter order.
3086bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3087 const FunctionProtoType *NewType,
3088 unsigned *ArgPos, bool Reversed) {
3089 assert(OldType->getNumParams() == NewType->getNumParams() &&(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 3091, __extension__ __PRETTY_FUNCTION__
))
3090 "Can't compare parameters of functions with different number of "(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 3091, __extension__ __PRETTY_FUNCTION__
))
3091 "parameters!")(static_cast <bool> (OldType->getNumParams() == NewType
->getNumParams() && "Can't compare parameters of functions with different number of "
"parameters!") ? void (0) : __assert_fail ("OldType->getNumParams() == NewType->getNumParams() && \"Can't compare parameters of functions with different number of \" \"parameters!\""
, "clang/lib/Sema/SemaOverload.cpp", 3091, __extension__ __PRETTY_FUNCTION__
))
;
3092 for (size_t I = 0; I < OldType->getNumParams(); I++) {
3093 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3094 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
3095
3096 // Ignore address spaces in pointee type. This is to disallow overloading
3097 // on __ptr32/__ptr64 address spaces.
3098 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
3099 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
3100
3101 if (!Context.hasSameType(Old, New)) {
3102 if (ArgPos)
3103 *ArgPos = I;
3104 return false;
3105 }
3106 }
3107 return true;
3108}
3109
3110/// CheckPointerConversion - Check the pointer conversion from the
3111/// expression From to the type ToType. This routine checks for
3112/// ambiguous or inaccessible derived-to-base pointer
3113/// conversions for which IsPointerConversion has already returned
3114/// true. It returns true and produces a diagnostic if there was an
3115/// error, or returns false otherwise.
3116bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3117 CastKind &Kind,
3118 CXXCastPath& BasePath,
3119 bool IgnoreBaseAccess,
3120 bool Diagnose) {
3121 QualType FromType = From->getType();
3122 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3123
3124 Kind = CK_BitCast;
3125
3126 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3127 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3128 Expr::NPCK_ZeroExpression) {
3129 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3130 DiagRuntimeBehavior(From->getExprLoc(), From,
3131 PDiag(diag::warn_impcast_bool_to_null_pointer)
3132 << ToType << From->getSourceRange());
3133 else if (!isUnevaluatedContext())
3134 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3135 << ToType << From->getSourceRange();
3136 }
3137 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3138 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3139 QualType FromPointeeType = FromPtrType->getPointeeType(),
3140 ToPointeeType = ToPtrType->getPointeeType();
3141
3142 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3143 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3144 // We must have a derived-to-base conversion. Check an
3145 // ambiguous or inaccessible conversion.
3146 unsigned InaccessibleID = 0;
3147 unsigned AmbiguousID = 0;
3148 if (Diagnose) {
3149 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3150 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3151 }
3152 if (CheckDerivedToBaseConversion(
3153 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3154 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3155 &BasePath, IgnoreBaseAccess))
3156 return true;
3157
3158 // The conversion was successful.
3159 Kind = CK_DerivedToBase;
3160 }
3161
3162 if (Diagnose && !IsCStyleOrFunctionalCast &&
3163 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3164 assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3165, __extension__ __PRETTY_FUNCTION__
))
3165 "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "clang/lib/Sema/SemaOverload.cpp", 3165, __extension__ __PRETTY_FUNCTION__
))
;
3166 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3167 << From->getSourceRange();
3168 }
3169 }
3170 } else if (const ObjCObjectPointerType *ToPtrType =
3171 ToType->getAs<ObjCObjectPointerType>()) {
3172 if (const ObjCObjectPointerType *FromPtrType =
3173 FromType->getAs<ObjCObjectPointerType>()) {
3174 // Objective-C++ conversions are always okay.
3175 // FIXME: We should have a different class of conversions for the
3176 // Objective-C++ implicit conversions.
3177 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3178 return false;
3179 } else if (FromType->isBlockPointerType()) {
3180 Kind = CK_BlockPointerToObjCPointerCast;
3181 } else {
3182 Kind = CK_CPointerToObjCPointerCast;
3183 }
3184 } else if (ToType->isBlockPointerType()) {
3185 if (!FromType->isBlockPointerType())
3186 Kind = CK_AnyPointerToBlockPointerCast;
3187 }
3188
3189 // We shouldn't fall into this case unless it's valid for other
3190 // reasons.
3191 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3192 Kind = CK_NullToPointer;
3193
3194 return false;
3195}
3196
3197/// IsMemberPointerConversion - Determines whether the conversion of the
3198/// expression From, which has the (possibly adjusted) type FromType, can be
3199/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3200/// If so, returns true and places the converted type (that might differ from
3201/// ToType in its cv-qualifiers at some level) into ConvertedType.
3202bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3203 QualType ToType,
3204 bool InOverloadResolution,
3205 QualType &ConvertedType) {
3206 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3207 if (!ToTypePtr)
3208 return false;
3209
3210 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3211 if (From->isNullPointerConstant(Context,
3212 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3213 : Expr::NPC_ValueDependentIsNull)) {
3214 ConvertedType = ToType;
3215 return true;
3216 }
3217
3218 // Otherwise, both types have to be member pointers.
3219 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3220 if (!FromTypePtr)
3221 return false;
3222
3223 // A pointer to member of B can be converted to a pointer to member of D,
3224 // where D is derived from B (C++ 4.11p2).
3225 QualType FromClass(FromTypePtr->getClass(), 0);
3226 QualType ToClass(ToTypePtr->getClass(), 0);
3227
3228 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3229 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3230 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3231 ToClass.getTypePtr());
3232 return true;
3233 }
3234
3235 return false;
3236}
3237
3238/// CheckMemberPointerConversion - Check the member pointer conversion from the
3239/// expression From to the type ToType. This routine checks for ambiguous or
3240/// virtual or inaccessible base-to-derived member pointer conversions
3241/// for which IsMemberPointerConversion has already returned true. It returns
3242/// true and produces a diagnostic if there was an error, or returns false
3243/// otherwise.
3244bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3245 CastKind &Kind,
3246 CXXCastPath &BasePath,
3247 bool IgnoreBaseAccess) {
3248 QualType FromType = From->getType();
3249 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3250 if (!FromPtrType) {
3251 // This must be a null pointer to member pointer conversion
3252 assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3254, __extension__ __PRETTY_FUNCTION__
))
3253 Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3254, __extension__ __PRETTY_FUNCTION__
))
3254 "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "clang/lib/Sema/SemaOverload.cpp", 3254, __extension__ __PRETTY_FUNCTION__
))
;
3255 Kind = CK_NullToMemberPointer;
3256 return false;
3257 }
3258
3259 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3260 assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3261, __extension__ __PRETTY_FUNCTION__
))
3261 "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "clang/lib/Sema/SemaOverload.cpp", 3261, __extension__ __PRETTY_FUNCTION__
))
;
3262
3263 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3264 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3265
3266 // FIXME: What about dependent types?
3267 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3267, __extension__ __PRETTY_FUNCTION__
))
;
3268 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "clang/lib/Sema/SemaOverload.cpp", 3268, __extension__ __PRETTY_FUNCTION__
))
;
3269
3270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3271 /*DetectVirtual=*/true);
3272 bool DerivationOkay =
3273 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3274 assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3275, __extension__ __PRETTY_FUNCTION__
))
3275 "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "clang/lib/Sema/SemaOverload.cpp", 3275, __extension__ __PRETTY_FUNCTION__
))
;
3276 (void)DerivationOkay;
3277
3278 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3279 getUnqualifiedType())) {
3280 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3281 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3282 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3283 return true;
3284 }
3285
3286 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3287 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3288 << FromClass << ToClass << QualType(VBase, 0)
3289 << From->getSourceRange();
3290 return true;
3291 }
3292
3293 if (!IgnoreBaseAccess)
3294 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3295 Paths.front(),
3296 diag::err_downcast_from_inaccessible_base);
3297
3298 // Must be a base to derived member conversion.
3299 BuildBasePathArray(Paths, BasePath);
3300 Kind = CK_BaseToDerivedMemberPointer;
3301 return false;
3302}
3303
3304/// Determine whether the lifetime conversion between the two given
3305/// qualifiers sets is nontrivial.
3306static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3307 Qualifiers ToQuals) {
3308 // Converting anything to const __unsafe_unretained is trivial.
3309 if (ToQuals.hasConst() &&
3310 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3311 return false;
3312
3313 return true;
3314}
3315
3316/// Perform a single iteration of the loop for checking if a qualification
3317/// conversion is valid.
3318///
3319/// Specifically, check whether any change between the qualifiers of \p
3320/// FromType and \p ToType is permissible, given knowledge about whether every
3321/// outer layer is const-qualified.
3322static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3323 bool CStyle, bool IsTopLevel,
3324 bool &PreviousToQualsIncludeConst,
3325 bool &ObjCLifetimeConversion) {
3326 Qualifiers FromQuals = FromType.getQualifiers();
3327 Qualifiers ToQuals = ToType.getQualifiers();
3328
3329 // Ignore __unaligned qualifier.
3330 FromQuals.removeUnaligned();
3331
3332 // Objective-C ARC:
3333 // Check Objective-C lifetime conversions.
3334 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3335 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3336 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3337 ObjCLifetimeConversion = true;
3338 FromQuals.removeObjCLifetime();
3339 ToQuals.removeObjCLifetime();
3340 } else {
3341 // Qualification conversions cannot cast between different
3342 // Objective-C lifetime qualifiers.
3343 return false;
3344 }
3345 }
3346
3347 // Allow addition/removal of GC attributes but not changing GC attributes.
3348 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3349 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3350 FromQuals.removeObjCGCAttr();
3351 ToQuals.removeObjCGCAttr();
3352 }
3353
3354 // -- for every j > 0, if const is in cv 1,j then const is in cv
3355 // 2,j, and similarly for volatile.
3356 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3357 return false;
3358
3359 // If address spaces mismatch:
3360 // - in top level it is only valid to convert to addr space that is a
3361 // superset in all cases apart from C-style casts where we allow
3362 // conversions between overlapping address spaces.
3363 // - in non-top levels it is not a valid conversion.
3364 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3365 (!IsTopLevel ||
3366 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3367 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3368 return false;
3369
3370 // -- if the cv 1,j and cv 2,j are different, then const is in
3371 // every cv for 0 < k < j.
3372 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3373 !PreviousToQualsIncludeConst)
3374 return false;
3375
3376 // The following wording is from C++20, where the result of the conversion
3377 // is T3, not T2.
3378 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3379 // "array of unknown bound of"
3380 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3381 return false;
3382
3383 // -- if the resulting P3,i is different from P1,i [...], then const is
3384 // added to every cv 3_k for 0 < k < i.
3385 if (!CStyle && FromType->isConstantArrayType() &&
3386 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3387 return false;
3388
3389 // Keep track of whether all prior cv-qualifiers in the "to" type
3390 // include const.
3391 PreviousToQualsIncludeConst =
3392 PreviousToQualsIncludeConst && ToQuals.hasConst();
3393 return true;
3394}
3395
3396/// IsQualificationConversion - Determines whether the conversion from
3397/// an rvalue of type FromType to ToType is a qualification conversion
3398/// (C++ 4.4).
3399///
3400/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3401/// when the qualification conversion involves a change in the Objective-C
3402/// object lifetime.
3403bool
3404Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3405 bool CStyle, bool &ObjCLifetimeConversion) {
3406 FromType = Context.getCanonicalType(FromType);
3407 ToType = Context.getCanonicalType(ToType);
3408 ObjCLifetimeConversion = false;
3409
3410 // If FromType and ToType are the same type, this is not a
3411 // qualification conversion.
3412 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3413 return false;
3414
3415 // (C++ 4.4p4):
3416 // A conversion can add cv-qualifiers at levels other than the first
3417 // in multi-level pointers, subject to the following rules: [...]
3418 bool PreviousToQualsIncludeConst = true;
3419 bool UnwrappedAnyPointer = false;
3420 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3421 if (!isQualificationConversionStep(
3422 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3423 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3424 return false;
3425 UnwrappedAnyPointer = true;
3426 }
3427
3428 // We are left with FromType and ToType being the pointee types
3429 // after unwrapping the original FromType and ToType the same number
3430 // of times. If we unwrapped any pointers, and if FromType and
3431 // ToType have the same unqualified type (since we checked
3432 // qualifiers above), then this is a qualification conversion.
3433 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3434}
3435
3436/// - Determine whether this is a conversion from a scalar type to an
3437/// atomic type.
3438///
3439/// If successful, updates \c SCS's second and third steps in the conversion
3440/// sequence to finish the conversion.
3441static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3442 bool InOverloadResolution,
3443 StandardConversionSequence &SCS,
3444 bool CStyle) {
3445 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3446 if (!ToAtomic)
3447 return false;
3448
3449 StandardConversionSequence InnerSCS;
3450 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3451 InOverloadResolution, InnerSCS,
3452 CStyle, /*AllowObjCWritebackConversion=*/false))
3453 return false;
3454
3455 SCS.Second = InnerSCS.Second;
3456 SCS.setToType(1, InnerSCS.getToType(1));
3457 SCS.Third = InnerSCS.Third;
3458 SCS.QualificationIncludesObjCLifetime
3459 = InnerSCS.QualificationIncludesObjCLifetime;
3460 SCS.setToType(2, InnerSCS.getToType(2));
3461 return true;
3462}
3463
3464static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3465 CXXConstructorDecl *Constructor,
3466 QualType Type) {
3467 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3468 if (CtorType->getNumParams() > 0) {
3469 QualType FirstArg = CtorType->getParamType(0);
3470 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3471 return true;
3472 }
3473 return false;
3474}
3475
3476static OverloadingResult
3477IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3478 CXXRecordDecl *To,
3479 UserDefinedConversionSequence &User,
3480 OverloadCandidateSet &CandidateSet,
3481 bool AllowExplicit) {
3482 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3483 for (auto *D : S.LookupConstructors(To)) {
3484 auto Info = getConstructorInfo(D);
3485 if (!Info)
3486 continue;
3487
3488 bool Usable = !Info.Constructor->isInvalidDecl() &&
3489 S.isInitListConstructor(Info.Constructor);
3490 if (Usable) {
3491 bool SuppressUserConversions = false;
3492 if (Info.ConstructorTmpl)
3493 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3494 /*ExplicitArgs*/ nullptr, From,
3495 CandidateSet, SuppressUserConversions,
3496 /*PartialOverloading*/ false,
3497 AllowExplicit);
3498 else
3499 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3500 CandidateSet, SuppressUserConversions,
3501 /*PartialOverloading*/ false, AllowExplicit);
3502 }
3503 }
3504
3505 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3506
3507 OverloadCandidateSet::iterator Best;
3508 switch (auto Result =
3509 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3510 case OR_Deleted:
3511 case OR_Success: {
3512 // Record the standard conversion we used and the conversion function.
3513 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3514 QualType ThisType = Constructor->getThisType();
3515 // Initializer lists don't have conversions as such.
3516 User.Before.setAsIdentityConversion();
3517 User.HadMultipleCandidates = HadMultipleCandidates;
3518 User.ConversionFunction = Constructor;
3519 User.FoundConversionFunction = Best->FoundDecl;
3520 User.After.setAsIdentityConversion();
3521 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3522 User.After.setAllToTypes(ToType);
3523 return Result;
3524 }
3525
3526 case OR_No_Viable_Function:
3527 return OR_No_Viable_Function;
3528 case OR_Ambiguous:
3529 return OR_Ambiguous;
3530 }
3531
3532 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3532)
;
3533}
3534
3535/// Determines whether there is a user-defined conversion sequence
3536/// (C++ [over.ics.user]) that converts expression From to the type
3537/// ToType. If such a conversion exists, User will contain the
3538/// user-defined conversion sequence that performs such a conversion
3539/// and this routine will return true. Otherwise, this routine returns
3540/// false and User is unspecified.
3541///
3542/// \param AllowExplicit true if the conversion should consider C++0x
3543/// "explicit" conversion functions as well as non-explicit conversion
3544/// functions (C++0x [class.conv.fct]p2).
3545///
3546/// \param AllowObjCConversionOnExplicit true if the conversion should
3547/// allow an extra Objective-C pointer conversion on uses of explicit
3548/// constructors. Requires \c AllowExplicit to also be set.
3549static OverloadingResult
3550IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3551 UserDefinedConversionSequence &User,
3552 OverloadCandidateSet &CandidateSet,
3553 AllowedExplicit AllowExplicit,
3554 bool AllowObjCConversionOnExplicit) {
3555 assert(AllowExplicit != AllowedExplicit::None ||(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3556, __extension__ __PRETTY_FUNCTION__
))
3556 !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit != AllowedExplicit::
None || !AllowObjCConversionOnExplicit) ? void (0) : __assert_fail
("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "clang/lib/Sema/SemaOverload.cpp", 3556, __extension__ __PRETTY_FUNCTION__
))
;
3557 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3558
3559 // Whether we will only visit constructors.
3560 bool ConstructorsOnly = false;
3561
3562 // If the type we are conversion to is a class type, enumerate its
3563 // constructors.
3564 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3565 // C++ [over.match.ctor]p1:
3566 // When objects of class type are direct-initialized (8.5), or
3567 // copy-initialized from an expression of the same or a
3568 // derived class type (8.5), overload resolution selects the
3569 // constructor. [...] For copy-initialization, the candidate
3570 // functions are all the converting constructors (12.3.1) of
3571 // that class. The argument list is the expression-list within
3572 // the parentheses of the initializer.
3573 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3574 (From->getType()->getAs<RecordType>() &&
3575 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3576 ConstructorsOnly = true;
3577
3578 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3579 // We're not going to find any constructors.
3580 } else if (CXXRecordDecl *ToRecordDecl
3581 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3582
3583 Expr **Args = &From;
3584 unsigned NumArgs = 1;
3585 bool ListInitializing = false;
3586 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3587 // But first, see if there is an init-list-constructor that will work.
3588 OverloadingResult Result = IsInitializerListConstructorConversion(
3589 S, From, ToType, ToRecordDecl, User, CandidateSet,
3590 AllowExplicit == AllowedExplicit::All);
3591 if (Result != OR_No_Viable_Function)
3592 return Result;
3593 // Never mind.
3594 CandidateSet.clear(
3595 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3596
3597 // If we're list-initializing, we pass the individual elements as
3598 // arguments, not the entire list.
3599 Args = InitList->getInits();
3600 NumArgs = InitList->getNumInits();
3601 ListInitializing = true;
3602 }
3603
3604 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3605 auto Info = getConstructorInfo(D);
3606 if (!Info)
3607 continue;
3608
3609 bool Usable = !Info.Constructor->isInvalidDecl();
3610 if (!ListInitializing)
3611 Usable = Usable && Info.Constructor->isConvertingConstructor(
3612 /*AllowExplicit*/ true);
3613 if (Usable) {
3614 bool SuppressUserConversions = !ConstructorsOnly;
3615 // C++20 [over.best.ics.general]/4.5:
3616 // if the target is the first parameter of a constructor [of class
3617 // X] and the constructor [...] is a candidate by [...] the second
3618 // phase of [over.match.list] when the initializer list has exactly
3619 // one element that is itself an initializer list, [...] and the
3620 // conversion is to X or reference to cv X, user-defined conversion
3621 // sequences are not cnosidered.
3622 if (SuppressUserConversions && ListInitializing) {
3623 SuppressUserConversions =
3624 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3625 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3626 ToType);
3627 }
3628 if (Info.ConstructorTmpl)
3629 S.AddTemplateOverloadCandidate(
3630 Info.ConstructorTmpl, Info.FoundDecl,
3631 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3632 CandidateSet, SuppressUserConversions,
3633 /*PartialOverloading*/ false,
3634 AllowExplicit == AllowedExplicit::All);
3635 else
3636 // Allow one user-defined conversion when user specifies a
3637 // From->ToType conversion via an static cast (c-style, etc).
3638 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3639 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3640 SuppressUserConversions,
3641 /*PartialOverloading*/ false,
3642 AllowExplicit == AllowedExplicit::All);
3643 }
3644 }
3645 }
3646 }
3647
3648 // Enumerate conversion functions, if we're allowed to.
3649 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3650 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3651 // No conversion functions from incomplete types.
3652 } else if (const RecordType *FromRecordType =
3653 From->getType()->getAs<RecordType>()) {
3654 if (CXXRecordDecl *FromRecordDecl
3655 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3656 // Add all of the conversion functions as candidates.
3657 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3658 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3659 DeclAccessPair FoundDecl = I.getPair();
3660 NamedDecl *D = FoundDecl.getDecl();
3661 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3662 if (isa<UsingShadowDecl>(D))
3663 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3664
3665 CXXConversionDecl *Conv;
3666 FunctionTemplateDecl *ConvTemplate;
3667 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3668 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3669 else
3670 Conv = cast<CXXConversionDecl>(D);
3671
3672 if (ConvTemplate)
3673 S.AddTemplateConversionCandidate(
3674 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3675 CandidateSet, AllowObjCConversionOnExplicit,
3676 AllowExplicit != AllowedExplicit::None);
3677 else
3678 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3679 CandidateSet, AllowObjCConversionOnExplicit,
3680 AllowExplicit != AllowedExplicit::None);
3681 }
3682 }
3683 }
3684
3685 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3686
3687 OverloadCandidateSet::iterator Best;
3688 switch (auto Result =
3689 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3690 case OR_Success:
3691 case OR_Deleted:
3692 // Record the standard conversion we used and the conversion function.
3693 if (CXXConstructorDecl *Constructor
3694 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3695 // C++ [over.ics.user]p1:
3696 // If the user-defined conversion is specified by a
3697 // constructor (12.3.1), the initial standard conversion
3698 // sequence converts the source type to the type required by
3699 // the argument of the constructor.
3700 //
3701 QualType ThisType = Constructor->getThisType();
3702 if (isa<InitListExpr>(From)) {
3703 // Initializer lists don't have conversions as such.
3704 User.Before.setAsIdentityConversion();
3705 } else {
3706 if (Best->Conversions[0].isEllipsis())
3707 User.EllipsisConversion = true;
3708 else {
3709 User.Before = Best->Conversions[0].Standard;
3710 User.EllipsisConversion = false;
3711 }
3712 }
3713 User.HadMultipleCandidates = HadMultipleCandidates;
3714 User.ConversionFunction = Constructor;
3715 User.FoundConversionFunction = Best->FoundDecl;
3716 User.After.setAsIdentityConversion();
3717 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3718 User.After.setAllToTypes(ToType);
3719 return Result;
3720 }
3721 if (CXXConversionDecl *Conversion
3722 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3723 // C++ [over.ics.user]p1:
3724 //
3725 // [...] If the user-defined conversion is specified by a
3726 // conversion function (12.3.2), the initial standard
3727 // conversion sequence converts the source type to the
3728 // implicit object parameter of the conversion function.
3729 User.Before = Best->Conversions[0].Standard;
3730 User.HadMultipleCandidates = HadMultipleCandidates;
3731 User.ConversionFunction = Conversion;
3732 User.FoundConversionFunction = Best->FoundDecl;
3733 User.EllipsisConversion = false;
3734
3735 // C++ [over.ics.user]p2:
3736 // The second standard conversion sequence converts the
3737 // result of the user-defined conversion to the target type
3738 // for the sequence. Since an implicit conversion sequence
3739 // is an initialization, the special rules for
3740 // initialization by user-defined conversion apply when
3741 // selecting the best user-defined conversion for a
3742 // user-defined conversion sequence (see 13.3.3 and
3743 // 13.3.3.1).
3744 User.After = Best->FinalConversion;
3745 return Result;
3746 }
3747 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "clang/lib/Sema/SemaOverload.cpp", 3747)
;
3748
3749 case OR_No_Viable_Function:
3750 return OR_No_Viable_Function;
3751
3752 case OR_Ambiguous:
3753 return OR_Ambiguous;
3754 }
3755
3756 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 3756)
;
3757}
3758
3759bool
3760Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3761 ImplicitConversionSequence ICS;
3762 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3763 OverloadCandidateSet::CSK_Normal);
3764 OverloadingResult OvResult =
3765 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3766 CandidateSet, AllowedExplicit::None, false);
3767
3768 if (!(OvResult == OR_Ambiguous ||
3769 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3770 return false;
3771
3772 auto Cands = CandidateSet.CompleteCandidates(
3773 *this,
3774 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3775 From);
3776 if (OvResult == OR_Ambiguous)
3777 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3778 << From->getType() << ToType << From->getSourceRange();
3779 else { // OR_No_Viable_Function && !CandidateSet.empty()
3780 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3781 diag::err_typecheck_nonviable_condition_incomplete,
3782 From->getType(), From->getSourceRange()))
3783 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3784 << false << From->getType() << From->getSourceRange() << ToType;
3785 }
3786
3787 CandidateSet.NoteCandidates(
3788 *this, From, Cands);
3789 return true;
3790}
3791
3792// Helper for compareConversionFunctions that gets the FunctionType that the
3793// conversion-operator return value 'points' to, or nullptr.
3794static const FunctionType *
3795getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3796 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3797 const PointerType *RetPtrTy =
3798 ConvFuncTy->getReturnType()->getAs<PointerType>();
3799
3800 if (!RetPtrTy)
3801 return nullptr;
3802
3803 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3804}
3805
3806/// Compare the user-defined conversion functions or constructors
3807/// of two user-defined conversion sequences to determine whether any ordering
3808/// is possible.
3809static ImplicitConversionSequence::CompareKind
3810compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3811 FunctionDecl *Function2) {
3812 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3813 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3814 if (!Conv1 || !Conv2)
3815 return ImplicitConversionSequence::Indistinguishable;
3816
3817 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3818 return ImplicitConversionSequence::Indistinguishable;
3819
3820 // Objective-C++:
3821 // If both conversion functions are implicitly-declared conversions from
3822 // a lambda closure type to a function pointer and a block pointer,
3823 // respectively, always prefer the conversion to a function pointer,
3824 // because the function pointer is more lightweight and is more likely
3825 // to keep code working.
3826 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3827 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3828 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3829 if (Block1 != Block2)
3830 return Block1 ? ImplicitConversionSequence::Worse
3831 : ImplicitConversionSequence::Better;
3832 }
3833
3834 // In order to support multiple calling conventions for the lambda conversion
3835 // operator (such as when the free and member function calling convention is
3836 // different), prefer the 'free' mechanism, followed by the calling-convention
3837 // of operator(). The latter is in place to support the MSVC-like solution of
3838 // defining ALL of the possible conversions in regards to calling-convention.
3839 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3840 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3841
3842 if (Conv1FuncRet && Conv2FuncRet &&
3843 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3844 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3845 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3846
3847 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3848 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3849
3850 CallingConv CallOpCC =
3851 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3852 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3853 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3854 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3855 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3856
3857 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3858 for (CallingConv CC : PrefOrder) {
3859 if (Conv1CC == CC)
3860 return ImplicitConversionSequence::Better;
3861 if (Conv2CC == CC)
3862 return ImplicitConversionSequence::Worse;
3863 }
3864 }
3865
3866 return ImplicitConversionSequence::Indistinguishable;
3867}
3868
3869static bool hasDeprecatedStringLiteralToCharPtrConversion(
3870 const ImplicitConversionSequence &ICS) {
3871 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3872 (ICS.isUserDefined() &&
3873 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3874}
3875
3876/// CompareImplicitConversionSequences - Compare two implicit
3877/// conversion sequences to determine whether one is better than the
3878/// other or if they are indistinguishable (C++ 13.3.3.2).
3879static ImplicitConversionSequence::CompareKind
3880CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3881 const ImplicitConversionSequence& ICS1,
3882 const ImplicitConversionSequence& ICS2)
3883{
3884 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3885 // conversion sequences (as defined in 13.3.3.1)
3886 // -- a standard conversion sequence (13.3.3.1.1) is a better
3887 // conversion sequence than a user-defined conversion sequence or
3888 // an ellipsis conversion sequence, and
3889 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3890 // conversion sequence than an ellipsis conversion sequence
3891 // (13.3.3.1.3).
3892 //
3893 // C++0x [over.best.ics]p10:
3894 // For the purpose of ranking implicit conversion sequences as
3895 // described in 13.3.3.2, the ambiguous conversion sequence is
3896 // treated as a user-defined sequence that is indistinguishable
3897 // from any other user-defined conversion sequence.
3898
3899 // String literal to 'char *' conversion has been deprecated in C++03. It has
3900 // been removed from C++11. We still accept this conversion, if it happens at
3901 // the best viable function. Otherwise, this conversion is considered worse
3902 // than ellipsis conversion. Consider this as an extension; this is not in the
3903 // standard. For example:
3904 //
3905 // int &f(...); // #1
3906 // void f(char*); // #2
3907 // void g() { int &r = f("foo"); }
3908 //
3909 // In C++03, we pick #2 as the best viable function.
3910 // In C++11, we pick #1 as the best viable function, because ellipsis
3911 // conversion is better than string-literal to char* conversion (since there
3912 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3913 // convert arguments, #2 would be the best viable function in C++11.
3914 // If the best viable function has this conversion, a warning will be issued
3915 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3916
3917 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3918 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3919 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3920 // Ill-formedness must not differ
3921 ICS1.isBad() == ICS2.isBad())
3922 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3923 ? ImplicitConversionSequence::Worse
3924 : ImplicitConversionSequence::Better;
3925
3926 if (ICS1.getKindRank() < ICS2.getKindRank())
3927 return ImplicitConversionSequence::Better;
3928 if (ICS2.getKindRank() < ICS1.getKindRank())
3929 return ImplicitConversionSequence::Worse;
3930
3931 // The following checks require both conversion sequences to be of
3932 // the same kind.
3933 if (ICS1.getKind() != ICS2.getKind())
3934 return ImplicitConversionSequence::Indistinguishable;
3935
3936 ImplicitConversionSequence::CompareKind Result =
3937 ImplicitConversionSequence::Indistinguishable;
3938
3939 // Two implicit conversion sequences of the same form are
3940 // indistinguishable conversion sequences unless one of the
3941 // following rules apply: (C++ 13.3.3.2p3):
3942
3943 // List-initialization sequence L1 is a better conversion sequence than
3944 // list-initialization sequence L2 if:
3945 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3946 // if not that,
3947 // — L1 and L2 convert to arrays of the same element type, and either the
3948 // number of elements n_1 initialized by L1 is less than the number of
3949 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3950 // an array of unknown bound and L1 does not,
3951 // even if one of the other rules in this paragraph would otherwise apply.
3952 if (!ICS1.isBad()) {
3953 bool StdInit1 = false, StdInit2 = false;
3954 if (ICS1.hasInitializerListContainerType())
3955 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3956 nullptr);
3957 if (ICS2.hasInitializerListContainerType())
3958 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3959 nullptr);
3960 if (StdInit1 != StdInit2)
3961 return StdInit1 ? ImplicitConversionSequence::Better
3962 : ImplicitConversionSequence::Worse;
3963
3964 if (ICS1.hasInitializerListContainerType() &&
3965 ICS2.hasInitializerListContainerType())
3966 if (auto *CAT1 = S.Context.getAsConstantArrayType(
3967 ICS1.getInitializerListContainerType()))
3968 if (auto *CAT2 = S.Context.getAsConstantArrayType(
3969 ICS2.getInitializerListContainerType())) {
3970 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3971 CAT2->getElementType())) {
3972 // Both to arrays of the same element type
3973 if (CAT1->getSize() != CAT2->getSize())
3974 // Different sized, the smaller wins
3975 return CAT1->getSize().ult(CAT2->getSize())
3976 ? ImplicitConversionSequence::Better
3977 : ImplicitConversionSequence::Worse;
3978 if (ICS1.isInitializerListOfIncompleteArray() !=
3979 ICS2.isInitializerListOfIncompleteArray())
3980 // One is incomplete, it loses
3981 return ICS2.isInitializerListOfIncompleteArray()
3982 ? ImplicitConversionSequence::Better
3983 : ImplicitConversionSequence::Worse;
3984 }
3985 }
3986 }
3987
3988 if (ICS1.isStandard())
3989 // Standard conversion sequence S1 is a better conversion sequence than
3990 // standard conversion sequence S2 if [...]
3991 Result = CompareStandardConversionSequences(S, Loc,
3992 ICS1.Standard, ICS2.Standard);
3993 else if (ICS1.isUserDefined()) {
3994 // User-defined conversion sequence U1 is a better conversion
3995 // sequence than another user-defined conversion sequence U2 if
3996 // they contain the same user-defined conversion function or
3997 // constructor and if the second standard conversion sequence of
3998 // U1 is better than the second standard conversion sequence of
3999 // U2 (C++ 13.3.3.2p3).
4000 if (ICS1.UserDefined.ConversionFunction ==
4001 ICS2.UserDefined.ConversionFunction)
4002 Result = CompareStandardConversionSequences(S, Loc,
4003 ICS1.UserDefined.After,
4004 ICS2.UserDefined.After);
4005 else
4006 Result = compareConversionFunctions(S,
4007 ICS1.UserDefined.ConversionFunction,
4008 ICS2.UserDefined.ConversionFunction);
4009 }
4010
4011 return Result;
4012}
4013
4014// Per 13.3.3.2p3, compare the given standard conversion sequences to
4015// determine if one is a proper subset of the other.
4016static ImplicitConversionSequence::CompareKind
4017compareStandardConversionSubsets(ASTContext &Context,
4018 const StandardConversionSequence& SCS1,
4019 const StandardConversionSequence& SCS2) {
4020 ImplicitConversionSequence::CompareKind Result
4021 = ImplicitConversionSequence::Indistinguishable;
4022
4023 // the identity conversion sequence is considered to be a subsequence of
4024 // any non-identity conversion sequence
4025 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4026 return ImplicitConversionSequence::Better;
4027 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4028 return ImplicitConversionSequence::Worse;
4029
4030 if (SCS1.Second != SCS2.Second) {
4031 if (SCS1.Second == ICK_Identity)
4032 Result = ImplicitConversionSequence::Better;
4033 else if (SCS2.Second == ICK_Identity)
4034 Result = ImplicitConversionSequence::Worse;
4035 else
4036 return ImplicitConversionSequence::Indistinguishable;
4037 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4038 return ImplicitConversionSequence::Indistinguishable;
4039
4040 if (SCS1.Third == SCS2.Third) {
4041 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4042 : ImplicitConversionSequence::Indistinguishable;
4043 }
4044
4045 if (SCS1.Third == ICK_Identity)
4046 return Result == ImplicitConversionSequence::Worse
4047 ? ImplicitConversionSequence::Indistinguishable
4048 : ImplicitConversionSequence::Better;
4049
4050 if (SCS2.Third == ICK_Identity)
4051 return Result == ImplicitConversionSequence::Better
4052 ? ImplicitConversionSequence::Indistinguishable
4053 : ImplicitConversionSequence::Worse;
4054
4055 return ImplicitConversionSequence::Indistinguishable;
4056}
4057
4058/// Determine whether one of the given reference bindings is better
4059/// than the other based on what kind of bindings they are.
4060static bool
4061isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4062 const StandardConversionSequence &SCS2) {
4063 // C++0x [over.ics.rank]p3b4:
4064 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4065 // implicit object parameter of a non-static member function declared
4066 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4067 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4068 // lvalue reference to a function lvalue and S2 binds an rvalue
4069 // reference*.
4070 //
4071 // FIXME: Rvalue references. We're going rogue with the above edits,
4072 // because the semantics in the current C++0x working paper (N3225 at the
4073 // time of this writing) break the standard definition of std::forward
4074 // and std::reference_wrapper when dealing with references to functions.
4075 // Proposed wording changes submitted to CWG for consideration.
4076 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4077 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4078 return false;
4079
4080 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4081 SCS2.IsLvalueReference) ||
4082 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4083 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4084}
4085
4086enum class FixedEnumPromotion {
4087 None,
4088 ToUnderlyingType,
4089 ToPromotedUnderlyingType
4090};
4091
4092/// Returns kind of fixed enum promotion the \a SCS uses.
4093static FixedEnumPromotion
4094getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4095
4096 if (SCS.Second != ICK_Integral_Promotion)
4097 return FixedEnumPromotion::None;
4098
4099 QualType FromType = SCS.getFromType();
4100 if (!FromType->isEnumeralType())
4101 return FixedEnumPromotion::None;
4102
4103 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4104 if (!Enum->isFixed())
4105 return FixedEnumPromotion::None;
4106
4107 QualType UnderlyingType = Enum->getIntegerType();
4108 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4109 return FixedEnumPromotion::ToUnderlyingType;
4110
4111 return FixedEnumPromotion::ToPromotedUnderlyingType;
4112}
4113
4114/// CompareStandardConversionSequences - Compare two standard
4115/// conversion sequences to determine whether one is better than the
4116/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4117static ImplicitConversionSequence::CompareKind
4118CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4119 const StandardConversionSequence& SCS1,
4120 const StandardConversionSequence& SCS2)
4121{
4122 // Standard conversion sequence S1 is a better conversion sequence
4123 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4124
4125 // -- S1 is a proper subsequence of S2 (comparing the conversion
4126 // sequences in the canonical form defined by 13.3.3.1.1,
4127 // excluding any Lvalue Transformation; the identity conversion
4128 // sequence is considered to be a subsequence of any
4129 // non-identity conversion sequence) or, if not that,
4130 if (ImplicitConversionSequence::CompareKind CK
4131 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4132 return CK;
4133
4134 // -- the rank of S1 is better than the rank of S2 (by the rules
4135 // defined below), or, if not that,
4136 ImplicitConversionRank Rank1 = SCS1.getRank();
4137 ImplicitConversionRank Rank2 = SCS2.getRank();
4138 if (Rank1 < Rank2)
4139 return ImplicitConversionSequence::Better;
4140 else if (Rank2 < Rank1)
4141 return ImplicitConversionSequence::Worse;
4142
4143 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4144 // are indistinguishable unless one of the following rules
4145 // applies:
4146
4147 // A conversion that is not a conversion of a pointer, or
4148 // pointer to member, to bool is better than another conversion
4149 // that is such a conversion.
4150 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4151 return SCS2.isPointerConversionToBool()
4152 ? ImplicitConversionSequence::Better
4153 : ImplicitConversionSequence::Worse;
4154
4155 // C++14 [over.ics.rank]p4b2:
4156 // This is retroactively applied to C++11 by CWG 1601.
4157 //
4158 // A conversion that promotes an enumeration whose underlying type is fixed
4159 // to its underlying type is better than one that promotes to the promoted
4160 // underlying type, if the two are different.
4161 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4162 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4163 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4164 FEP1 != FEP2)
4165 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4166 ? ImplicitConversionSequence::Better
4167 : ImplicitConversionSequence::Worse;
4168
4169 // C++ [over.ics.rank]p4b2:
4170 //
4171 // If class B is derived directly or indirectly from class A,
4172 // conversion of B* to A* is better than conversion of B* to
4173 // void*, and conversion of A* to void* is better than conversion
4174 // of B* to void*.
4175 bool SCS1ConvertsToVoid
4176 = SCS1.isPointerConversionToVoidPointer(S.Context);
4177 bool SCS2ConvertsToVoid
4178 = SCS2.isPointerConversionToVoidPointer(S.Context);
4179 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4180 // Exactly one of the conversion sequences is a conversion to
4181 // a void pointer; it's the worse conversion.
4182 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4183 : ImplicitConversionSequence::Worse;
4184 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4185 // Neither conversion sequence converts to a void pointer; compare
4186 // their derived-to-base conversions.
4187 if (ImplicitConversionSequence::CompareKind DerivedCK
4188 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4189 return DerivedCK;
4190 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4191 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4192 // Both conversion sequences are conversions to void
4193 // pointers. Compare the source types to determine if there's an
4194 // inheritance relationship in their sources.
4195 QualType FromType1 = SCS1.getFromType();
4196 QualType FromType2 = SCS2.getFromType();
4197
4198 // Adjust the types we're converting from via the array-to-pointer
4199 // conversion, if we need to.
4200 if (SCS1.First == ICK_Array_To_Pointer)
4201 FromType1 = S.Context.getArrayDecayedType(FromType1);
4202 if (SCS2.First == ICK_Array_To_Pointer)
4203 FromType2 = S.Context.getArrayDecayedType(FromType2);
4204
4205 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4206 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4207
4208 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4209 return ImplicitConversionSequence::Better;
4210 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4211 return ImplicitConversionSequence::Worse;
4212
4213 // Objective-C++: If one interface is more specific than the
4214 // other, it is the better one.
4215 const ObjCObjectPointerType* FromObjCPtr1
4216 = FromType1->getAs<ObjCObjectPointerType>();
4217 const ObjCObjectPointerType* FromObjCPtr2
4218 = FromType2->getAs<ObjCObjectPointerType>();
4219 if (FromObjCPtr1 && FromObjCPtr2) {
4220 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4221 FromObjCPtr2);
4222 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4223 FromObjCPtr1);
4224 if (AssignLeft != AssignRight) {
4225 return AssignLeft? ImplicitConversionSequence::Better
4226 : ImplicitConversionSequence::Worse;
4227 }
4228 }
4229 }
4230
4231 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4232 // Check for a better reference binding based on the kind of bindings.
4233 if (isBetterReferenceBindingKind(SCS1, SCS2))
4234 return ImplicitConversionSequence::Better;
4235 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4236 return ImplicitConversionSequence::Worse;
4237 }
4238
4239 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4240 // bullet 3).
4241 if (ImplicitConversionSequence::CompareKind QualCK
4242 = CompareQualificationConversions(S, SCS1, SCS2))
4243 return QualCK;
4244
4245 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4246 // C++ [over.ics.rank]p3b4:
4247 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4248 // which the references refer are the same type except for
4249 // top-level cv-qualifiers, and the type to which the reference
4250 // initialized by S2 refers is more cv-qualified than the type
4251 // to which the reference initialized by S1 refers.
4252 QualType T1 = SCS1.getToType(2);
4253 QualType T2 = SCS2.getToType(2);
4254 T1 = S.Context.getCanonicalType(T1);
4255 T2 = S.Context.getCanonicalType(T2);
4256 Qualifiers T1Quals, T2Quals;
4257 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4258 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4259 if (UnqualT1 == UnqualT2) {
4260 // Objective-C++ ARC: If the references refer to objects with different
4261 // lifetimes, prefer bindings that don't change lifetime.
4262 if (SCS1.ObjCLifetimeConversionBinding !=
4263 SCS2.ObjCLifetimeConversionBinding) {
4264 return SCS1.ObjCLifetimeConversionBinding
4265 ? ImplicitConversionSequence::Worse
4266 : ImplicitConversionSequence::Better;
4267 }
4268
4269 // If the type is an array type, promote the element qualifiers to the
4270 // type for comparison.
4271 if (isa<ArrayType>(T1) && T1Quals)
4272 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4273 if (isa<ArrayType>(T2) && T2Quals)
4274 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4275 if (T2.isMoreQualifiedThan(T1))
4276 return ImplicitConversionSequence::Better;
4277 if (T1.isMoreQualifiedThan(T2))
4278 return ImplicitConversionSequence::Worse;
4279 }
4280 }
4281
4282 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4283 // floating-to-integral conversion if the integral conversion
4284 // is between types of the same size.
4285 // For example:
4286 // void f(float);
4287 // void f(int);
4288 // int main {
4289 // long a;
4290 // f(a);
4291 // }
4292 // Here, MSVC will call f(int) instead of generating a compile error
4293 // as clang will do in standard mode.
4294 if (S.getLangOpts().MSVCCompat &&
4295 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4296 SCS1.Second == ICK_Integral_Conversion &&
4297 SCS2.Second == ICK_Floating_Integral &&
4298 S.Context.getTypeSize(SCS1.getFromType()) ==
4299 S.Context.getTypeSize(SCS1.getToType(2)))
4300 return ImplicitConversionSequence::Better;
4301
4302 // Prefer a compatible vector conversion over a lax vector conversion
4303 // For example:
4304 //
4305 // typedef float __v4sf __attribute__((__vector_size__(16)));
4306 // void f(vector float);
4307 // void f(vector signed int);
4308 // int main() {
4309 // __v4sf a;
4310 // f(a);
4311 // }
4312 // Here, we'd like to choose f(vector float) and not
4313 // report an ambiguous call error
4314 if (SCS1.Second == ICK_Vector_Conversion &&
4315 SCS2.Second == ICK_Vector_Conversion) {
4316 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4317 SCS1.getFromType(), SCS1.getToType(2));
4318 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4319 SCS2.getFromType(), SCS2.getToType(2));
4320
4321 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4322 return SCS1IsCompatibleVectorConversion
4323 ? ImplicitConversionSequence::Better
4324 : ImplicitConversionSequence::Worse;
4325 }
4326
4327 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4328 SCS2.Second == ICK_SVE_Vector_Conversion) {
4329 bool SCS1IsCompatibleSVEVectorConversion =
4330 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4331 bool SCS2IsCompatibleSVEVectorConversion =
4332 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4333
4334 if (SCS1IsCompatibleSVEVectorConversion !=
4335 SCS2IsCompatibleSVEVectorConversion)
4336 return SCS1IsCompatibleSVEVectorConversion
4337 ? ImplicitConversionSequence::Better
4338 : ImplicitConversionSequence::Worse;
4339 }
4340
4341 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4342 SCS2.Second == ICK_RVV_Vector_Conversion) {
4343 bool SCS1IsCompatibleRVVVectorConversion =
4344 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4345 bool SCS2IsCompatibleRVVVectorConversion =
4346 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4347
4348 if (SCS1IsCompatibleRVVVectorConversion !=
4349 SCS2IsCompatibleRVVVectorConversion)
4350 return SCS1IsCompatibleRVVVectorConversion
4351 ? ImplicitConversionSequence::Better
4352 : ImplicitConversionSequence::Worse;
4353 }
4354
4355 return ImplicitConversionSequence::Indistinguishable;
4356}
4357
4358/// CompareQualificationConversions - Compares two standard conversion
4359/// sequences to determine whether they can be ranked based on their
4360/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4361static ImplicitConversionSequence::CompareKind
4362CompareQualificationConversions(Sema &S,
4363 const StandardConversionSequence& SCS1,
4364 const StandardConversionSequence& SCS2) {
4365 // C++ [over.ics.rank]p3:
4366 // -- S1 and S2 differ only in their qualification conversion and
4367 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4368 // [C++98]
4369 // [...] and the cv-qualification signature of type T1 is a proper subset
4370 // of the cv-qualification signature of type T2, and S1 is not the
4371 // deprecated string literal array-to-pointer conversion (4.2).
4372 // [C++2a]
4373 // [...] where T1 can be converted to T2 by a qualification conversion.
4374 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4375 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4376 return ImplicitConversionSequence::Indistinguishable;
4377
4378 // FIXME: the example in the standard doesn't use a qualification
4379 // conversion (!)
4380 QualType T1 = SCS1.getToType(2);
4381 QualType T2 = SCS2.getToType(2);
4382 T1 = S.Context.getCanonicalType(T1);
4383 T2 = S.Context.getCanonicalType(T2);
4384 assert(!T1->isReferenceType() && !T2->isReferenceType())(static_cast <bool> (!T1->isReferenceType() &&
!T2->isReferenceType()) ? void (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "clang/lib/Sema/SemaOverload.cpp", 4384, __extension__ __PRETTY_FUNCTION__
))
;
4385 Qualifiers T1Quals, T2Quals;
4386 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4387 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4388
4389 // If the types are the same, we won't learn anything by unwrapping
4390 // them.
4391 if (UnqualT1 == UnqualT2)
4392 return ImplicitConversionSequence::Indistinguishable;
4393
4394 // Don't ever prefer a standard conversion sequence that uses the deprecated
4395 // string literal array to pointer conversion.
4396 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4397 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4398
4399 // Objective-C++ ARC:
4400 // Prefer qualification conversions not involving a change in lifetime
4401 // to qualification conversions that do change lifetime.
4402 if (SCS1.QualificationIncludesObjCLifetime &&
4403 !SCS2.QualificationIncludesObjCLifetime)
4404 CanPick1 = false;
4405 if (SCS2.QualificationIncludesObjCLifetime &&
4406 !SCS1.QualificationIncludesObjCLifetime)
4407 CanPick2 = false;
4408
4409 bool ObjCLifetimeConversion;
4410 if (CanPick1 &&
4411 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4412 CanPick1 = false;
4413 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4414 // directions, so we can't short-cut this second check in general.
4415 if (CanPick2 &&
4416 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4417 CanPick2 = false;
4418
4419 if (CanPick1 != CanPick2)
4420 return CanPick1 ? ImplicitConversionSequence::Better
4421 : ImplicitConversionSequence::Worse;
4422 return ImplicitConversionSequence::Indistinguishable;
4423}
4424
4425/// CompareDerivedToBaseConversions - Compares two standard conversion
4426/// sequences to determine whether they can be ranked based on their
4427/// various kinds of derived-to-base conversions (C++
4428/// [over.ics.rank]p4b3). As part of these checks, we also look at
4429/// conversions between Objective-C interface types.
4430static ImplicitConversionSequence::CompareKind
4431CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4432 const StandardConversionSequence& SCS1,
4433 const StandardConversionSequence& SCS2) {
4434 QualType FromType1 = SCS1.getFromType();
4435 QualType ToType1 = SCS1.getToType(1);
4436 QualType FromType2 = SCS2.getFromType();
4437 QualType ToType2 = SCS2.getToType(1);
4438
4439 // Adjust the types we're converting from via the array-to-pointer
4440 // conversion, if we need to.
4441 if (SCS1.First == ICK_Array_To_Pointer)
4442 FromType1 = S.Context.getArrayDecayedType(FromType1);
4443 if (SCS2.First == ICK_Array_To_Pointer)
4444 FromType2 = S.Context.getArrayDecayedType(FromType2);
4445
4446 // Canonicalize all of the types.
4447 FromType1 = S.Context.getCanonicalType(FromType1);
4448 ToType1 = S.Context.getCanonicalType(ToType1);
4449 FromType2 = S.Context.getCanonicalType(FromType2);
4450 ToType2 = S.Context.getCanonicalType(ToType2);
4451
4452 // C++ [over.ics.rank]p4b3:
4453 //
4454 // If class B is derived directly or indirectly from class A and
4455 // class C is derived directly or indirectly from B,
4456 //
4457 // Compare based on pointer conversions.
4458 if (SCS1.Second == ICK_Pointer_Conversion &&
4459 SCS2.Second == ICK_Pointer_Conversion &&
4460 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4461 FromType1->isPointerType() && FromType2->isPointerType() &&
4462 ToType1->isPointerType() && ToType2->isPointerType()) {
4463 QualType FromPointee1 =
4464 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4465 QualType ToPointee1 =
4466 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4467 QualType FromPointee2 =
4468 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4469 QualType ToPointee2 =
4470 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4471
4472 // -- conversion of C* to B* is better than conversion of C* to A*,
4473 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4474 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4475 return ImplicitConversionSequence::Better;
4476 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4477 return ImplicitConversionSequence::Worse;
4478 }
4479
4480 // -- conversion of B* to A* is better than conversion of C* to A*,
4481 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4482 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4483 return ImplicitConversionSequence::Better;
4484 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4485 return ImplicitConversionSequence::Worse;
4486 }
4487 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4488 SCS2.Second == ICK_Pointer_Conversion) {
4489 const ObjCObjectPointerType *FromPtr1
4490 = FromType1->getAs<ObjCObjectPointerType>();
4491 const ObjCObjectPointerType *FromPtr2
4492 = FromType2->getAs<ObjCObjectPointerType>();
4493 const ObjCObjectPointerType *ToPtr1
4494 = ToType1->getAs<ObjCObjectPointerType>();
4495 const ObjCObjectPointerType *ToPtr2
4496 = ToType2->getAs<ObjCObjectPointerType>();
4497
4498 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4499 // Apply the same conversion ranking rules for Objective-C pointer types
4500 // that we do for C++ pointers to class types. However, we employ the
4501 // Objective-C pseudo-subtyping relationship used for assignment of
4502 // Objective-C pointer types.
4503 bool FromAssignLeft
4504 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4505 bool FromAssignRight
4506 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4507 bool ToAssignLeft
4508 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4509 bool ToAssignRight
4510 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4511
4512 // A conversion to an a non-id object pointer type or qualified 'id'
4513 // type is better than a conversion to 'id'.
4514 if (ToPtr1->isObjCIdType() &&
4515 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4516 return ImplicitConversionSequence::Worse;
4517 if (ToPtr2->isObjCIdType() &&
4518 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4519 return ImplicitConversionSequence::Better;
4520
4521 // A conversion to a non-id object pointer type is better than a
4522 // conversion to a qualified 'id' type
4523 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4524 return ImplicitConversionSequence::Worse;
4525 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4526 return ImplicitConversionSequence::Better;
4527
4528 // A conversion to an a non-Class object pointer type or qualified 'Class'
4529 // type is better than a conversion to 'Class'.
4530 if (ToPtr1->isObjCClassType() &&
4531 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4532 return ImplicitConversionSequence::Worse;
4533 if (ToPtr2->isObjCClassType() &&
4534 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4535 return ImplicitConversionSequence::Better;
4536
4537 // A conversion to a non-Class object pointer type is better than a
4538 // conversion to a qualified 'Class' type.
4539 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4540 return ImplicitConversionSequence::Worse;
4541 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4542 return ImplicitConversionSequence::Better;
4543
4544 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4545 if (S.Context.hasSameType(FromType1, FromType2) &&
4546 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4547 (ToAssignLeft != ToAssignRight)) {
4548 if (FromPtr1->isSpecialized()) {
4549 // "conversion of B<A> * to B * is better than conversion of B * to
4550 // C *.
4551 bool IsFirstSame =
4552 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4553 bool IsSecondSame =
4554 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4555 if (IsFirstSame) {
4556 if (!IsSecondSame)
4557 return ImplicitConversionSequence::Better;
4558 } else if (IsSecondSame)
4559 return ImplicitConversionSequence::Worse;
4560 }
4561 return ToAssignLeft? ImplicitConversionSequence::Worse
4562 : ImplicitConversionSequence::Better;
4563 }
4564
4565 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4566 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4567 (FromAssignLeft != FromAssignRight))
4568 return FromAssignLeft? ImplicitConversionSequence::Better
4569 : ImplicitConversionSequence::Worse;
4570 }
4571 }
4572
4573 // Ranking of member-pointer types.
4574 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4575 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4576 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4577 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4578 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4579 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4580 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4581 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4582 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4583 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4584 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4585 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4586 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4587 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4588 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4589 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4590 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4591 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4592 return ImplicitConversionSequence::Worse;
4593 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4594 return ImplicitConversionSequence::Better;
4595 }
4596 // conversion of B::* to C::* is better than conversion of A::* to C::*
4597 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4598 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4599 return ImplicitConversionSequence::Better;
4600 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4601 return ImplicitConversionSequence::Worse;
4602 }
4603 }
4604
4605 if (SCS1.Second == ICK_Derived_To_Base) {
4606 // -- conversion of C to B is better than conversion of C to A,
4607 // -- binding of an expression of type C to a reference of type
4608 // B& is better than binding an expression of type C to a
4609 // reference of type A&,
4610 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4611 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4612 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4613 return ImplicitConversionSequence::Better;
4614 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4615 return ImplicitConversionSequence::Worse;
4616 }
4617
4618 // -- conversion of B to A is better than conversion of C to A.
4619 // -- binding of an expression of type B to a reference of type
4620 // A& is better than binding an expression of type C to a
4621 // reference of type A&,
4622 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4623 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4624 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4625 return ImplicitConversionSequence::Better;
4626 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4627 return ImplicitConversionSequence::Worse;
4628 }
4629 }
4630
4631 return ImplicitConversionSequence::Indistinguishable;
4632}
4633
4634static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4635 if (!T.getQualifiers().hasUnaligned())
4636 return T;
4637
4638 Qualifiers Q;
4639 T = Ctx.getUnqualifiedArrayType(T, Q);
4640 Q.removeUnaligned();
4641 return Ctx.getQualifiedType(T, Q);
4642}
4643
4644/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4645/// determine whether they are reference-compatible,
4646/// reference-related, or incompatible, for use in C++ initialization by
4647/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4648/// type, and the first type (T1) is the pointee type of the reference
4649/// type being initialized.
4650Sema::ReferenceCompareResult
4651Sema::CompareReferenceRelationship(SourceLocation Loc,
4652 QualType OrigT1, QualType OrigT2,
4653 ReferenceConversions *ConvOut) {
4654 assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4655, __extension__ __PRETTY_FUNCTION__
))
4655 "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4655, __extension__ __PRETTY_FUNCTION__
))
;
4656 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() &&
"T2 cannot be a reference type") ? void (0) : __assert_fail (
"!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "clang/lib/Sema/SemaOverload.cpp", 4656, __extension__ __PRETTY_FUNCTION__
))
;
4657
4658 QualType T1 = Context.getCanonicalType(OrigT1);
4659 QualType T2 = Context.getCanonicalType(OrigT2);
4660 Qualifiers T1Quals, T2Quals;
4661 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4662 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4663
4664 ReferenceConversions ConvTmp;
4665 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4666 Conv = ReferenceConversions();
4667
4668 // C++2a [dcl.init.ref]p4:
4669 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4670 // reference-related to "cv2 T2" if T1 is similar to T2, or
4671 // T1 is a base class of T2.
4672 // "cv1 T1" is reference-compatible with "cv2 T2" if
4673 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4674 // "pointer to cv1 T1" via a standard conversion sequence.
4675
4676 // Check for standard conversions we can apply to pointers: derived-to-base
4677 // conversions, ObjC pointer conversions, and function pointer conversions.
4678 // (Qualification conversions are checked last.)
4679 QualType ConvertedT2;
4680 if (UnqualT1 == UnqualT2) {
4681 // Nothing to do.
4682 } else if (isCompleteType(Loc, OrigT2) &&
4683 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4684 Conv |= ReferenceConversions::DerivedToBase;
4685 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4686 UnqualT2->isObjCObjectOrInterfaceType() &&
4687 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4688 Conv |= ReferenceConversions::ObjC;
4689 else if (UnqualT2->isFunctionType() &&
4690 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4691 Conv |= ReferenceConversions::Function;
4692 // No need to check qualifiers; function types don't have them.
4693 return Ref_Compatible;
4694 }
4695 bool ConvertedReferent = Conv != 0;
4696
4697 // We can have a qualification conversion. Compute whether the types are
4698 // similar at the same time.
4699 bool PreviousToQualsIncludeConst = true;
4700 bool TopLevel = true;
4701 do {
4702 if (T1 == T2)
4703 break;
4704
4705 // We will need a qualification conversion.
4706 Conv |= ReferenceConversions::Qualification;
4707
4708 // Track whether we performed a qualification conversion anywhere other
4709 // than the top level. This matters for ranking reference bindings in
4710 // overload resolution.
4711 if (!TopLevel)
4712 Conv |= ReferenceConversions::NestedQualification;
4713
4714 // MS compiler ignores __unaligned qualifier for references; do the same.
4715 T1 = withoutUnaligned(Context, T1);
4716 T2 = withoutUnaligned(Context, T2);
4717
4718 // If we find a qualifier mismatch, the types are not reference-compatible,
4719 // but are still be reference-related if they're similar.
4720 bool ObjCLifetimeConversion = false;
4721 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4722 PreviousToQualsIncludeConst,
4723 ObjCLifetimeConversion))
4724 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4725 ? Ref_Related
4726 : Ref_Incompatible;
4727
4728 // FIXME: Should we track this for any level other than the first?
4729 if (ObjCLifetimeConversion)
4730 Conv |= ReferenceConversions::ObjCLifetime;
4731
4732 TopLevel = false;
4733 } while (Context.UnwrapSimilarTypes(T1, T2));
4734
4735 // At this point, if the types are reference-related, we must either have the
4736 // same inner type (ignoring qualifiers), or must have already worked out how
4737 // to convert the referent.
4738 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4739 ? Ref_Compatible
4740 : Ref_Incompatible;
4741}
4742
4743/// Look for a user-defined conversion to a value reference-compatible
4744/// with DeclType. Return true if something definite is found.
4745static bool
4746FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4747 QualType DeclType, SourceLocation DeclLoc,
4748 Expr *Init, QualType T2, bool AllowRvalues,
4749 bool AllowExplicit) {
4750 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types."
) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "clang/lib/Sema/SemaOverload.cpp", 4750, __extension__ __PRETTY_FUNCTION__
))
;
4751 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4752
4753 OverloadCandidateSet CandidateSet(
4754 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4755 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4756 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4757 NamedDecl *D = *I;
4758 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4759 if (isa<UsingShadowDecl>(D))
4760 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4761
4762 FunctionTemplateDecl *ConvTemplate
4763 = dyn_cast<FunctionTemplateDecl>(D);
4764 CXXConversionDecl *Conv;
4765 if (ConvTemplate)
4766 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4767 else
4768 Conv = cast<CXXConversionDecl>(D);
4769
4770 if (AllowRvalues) {
4771 // If we are initializing an rvalue reference, don't permit conversion
4772 // functions that return lvalues.
4773 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4774 const ReferenceType *RefType
4775 = Conv->getConversionType()->getAs<LValueReferenceType>();
4776 if (RefType && !RefType->getPointeeType()->isFunctionType())
4777 continue;
4778 }
4779
4780 if (!ConvTemplate &&
4781 S.CompareReferenceRelationship(
4782 DeclLoc,
4783 Conv->getConversionType()
4784 .getNonReferenceType()
4785 .getUnqualifiedType(),
4786 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4787 Sema::Ref_Incompatible)
4788 continue;
4789 } else {
4790 // If the conversion function doesn't return a reference type,
4791 // it can't be considered for this conversion. An rvalue reference
4792 // is only acceptable if its referencee is a function type.
4793
4794 const ReferenceType *RefType =
4795 Conv->getConversionType()->getAs<ReferenceType>();
4796 if (!RefType ||
4797 (!RefType->isLValueReferenceType() &&
4798 !RefType->getPointeeType()->isFunctionType()))
4799 continue;
4800 }
4801
4802 if (ConvTemplate)
4803 S.AddTemplateConversionCandidate(
4804 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4805 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4806 else
4807 S.AddConversionCandidate(
4808 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4809 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4810 }
4811
4812 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4813
4814 OverloadCandidateSet::iterator Best;
4815 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4816 case OR_Success:
4817 // C++ [over.ics.ref]p1:
4818 //
4819 // [...] If the parameter binds directly to the result of
4820 // applying a conversion function to the argument
4821 // expression, the implicit conversion sequence is a
4822 // user-defined conversion sequence (13.3.3.1.2), with the
4823 // second standard conversion sequence either an identity
4824 // conversion or, if the conversion function returns an
4825 // entity of a type that is a derived class of the parameter
4826 // type, a derived-to-base Conversion.
4827 if (!Best->FinalConversion.DirectBinding)
4828 return false;
4829
4830 ICS.setUserDefined();
4831 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4832 ICS.UserDefined.After = Best->FinalConversion;
4833 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4834 ICS.UserDefined.ConversionFunction = Best->Function;
4835 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4836 ICS.UserDefined.EllipsisConversion = false;
4837 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4839, __extension__ __PRETTY_FUNCTION__
))
4838 ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4839, __extension__ __PRETTY_FUNCTION__
))
4839 "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "clang/lib/Sema/SemaOverload.cpp", 4839, __extension__ __PRETTY_FUNCTION__
))
;
4840 return true;
4841
4842 case OR_Ambiguous:
4843 ICS.setAmbiguous();
4844 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4845 Cand != CandidateSet.end(); ++Cand)
4846 if (Cand->Best)
4847 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4848 return true;
4849
4850 case OR_No_Viable_Function:
4851 case OR_Deleted:
4852 // There was no suitable conversion, or we found a deleted
4853 // conversion; continue with other checks.
4854 return false;
4855 }
4856
4857 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "clang/lib/Sema/SemaOverload.cpp"
, 4857)
;
4858}
4859
4860/// Compute an implicit conversion sequence for reference
4861/// initialization.
4862static ImplicitConversionSequence
4863TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4864 SourceLocation DeclLoc,
4865 bool SuppressUserConversions,
4866 bool AllowExplicit) {
4867 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() &&
"Reference init needs a reference") ? void (0) : __assert_fail
("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "clang/lib/Sema/SemaOverload.cpp", 4867, __extension__ __PRETTY_FUNCTION__
))
;
4868
4869 // Most paths end in a failed conversion.
4870 ImplicitConversionSequence ICS;
4871 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4872
4873 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4874 QualType T2 = Init->getType();
4875
4876 // If the initializer is the address of an overloaded function, try
4877 // to resolve the overloaded function. If all goes well, T2 is the
4878 // type of the resulting function.
4879 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4880 DeclAccessPair Found;
4881 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4882 false, Found))
4883 T2 = Fn->getType();
4884 }
4885
4886 // Compute some basic properties of the types and the initializer.
4887 bool isRValRef = DeclType->isRValueReferenceType();
4888 Expr::Classification InitCategory = Init->Classify(S.Context);
4889
4890 Sema::ReferenceConversions RefConv;
4891 Sema::ReferenceCompareResult RefRelationship =
4892 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4893
4894 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4895 ICS.setStandard();
4896 ICS.Standard.First = ICK_Identity;
4897 // FIXME: A reference binding can be a function conversion too. We should
4898 // consider that when ordering reference-to-function bindings.
4899 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4900 ? ICK_Derived_To_Base
4901 : (RefConv & Sema::ReferenceConversions::ObjC)
4902 ? ICK_Compatible_Conversion
4903 : ICK_Identity;
4904 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4905 // a reference binding that performs a non-top-level qualification
4906 // conversion as a qualification conversion, not as an identity conversion.
4907 ICS.Standard.Third = (RefConv &
4908 Sema::ReferenceConversions::NestedQualification)
4909 ? ICK_Qualification
4910 : ICK_Identity;
4911 ICS.Standard.setFromType(T2);
4912 ICS.Standard.setToType(0, T2);
4913 ICS.Standard.setToType(1, T1);
4914 ICS.Standard.setToType(2, T1);
4915 ICS.Standard.ReferenceBinding = true;
4916 ICS.Standard.DirectBinding = BindsDirectly;
4917 ICS.Standard.IsLvalueReference = !isRValRef;
4918 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4919 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4920 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4921 ICS.Standard.ObjCLifetimeConversionBinding =
4922 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4923 ICS.Standard.CopyConstructor = nullptr;
4924 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4925 };
4926
4927 // C++0x [dcl.init.ref]p5:
4928 // A reference to type "cv1 T1" is initialized by an expression
4929 // of type "cv2 T2" as follows:
4930
4931 // -- If reference is an lvalue reference and the initializer expression
4932 if (!isRValRef) {
4933 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4934 // reference-compatible with "cv2 T2," or
4935 //
4936 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4937 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4938 // C++ [over.ics.ref]p1:
4939 // When a parameter of reference type binds directly (8.5.3)
4940 // to an argument expression, the implicit conversion sequence
4941 // is the identity conversion, unless the argument expression
4942 // has a type that is a derived class of the parameter type,
4943 // in which case the implicit conversion sequence is a
4944 // derived-to-base Conversion (13.3.3.1).
4945 SetAsReferenceBinding(/*BindsDirectly=*/true);
4946
4947 // Nothing more to do: the inaccessibility/ambiguity check for
4948 // derived-to-base conversions is suppressed when we're
4949 // computing the implicit conversion sequence (C++
4950 // [over.best.ics]p2).
4951 return ICS;
4952 }
4953
4954 // -- has a class type (i.e., T2 is a class type), where T1 is
4955 // not reference-related to T2, and can be implicitly
4956 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4957 // is reference-compatible with "cv3 T3" 92) (this
4958 // conversion is selected by enumerating the applicable
4959 // conversion functions (13.3.1.6) and choosing the best
4960 // one through overload resolution (13.3)),
4961 if (!SuppressUserConversions && T2->isRecordType() &&
4962 S.isCompleteType(DeclLoc, T2) &&
4963 RefRelationship == Sema::Ref_Incompatible) {
4964 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4965 Init, T2, /*AllowRvalues=*/false,
4966 AllowExplicit))
4967 return ICS;
4968 }
4969 }
4970
4971 // -- Otherwise, the reference shall be an lvalue reference to a
4972 // non-volatile const type (i.e., cv1 shall be const), or the reference
4973 // shall be an rvalue reference.
4974 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4975 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4976 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4977 return ICS;
4978 }
4979
4980 // -- If the initializer expression
4981 //
4982 // -- is an xvalue, class prvalue, array prvalue or function
4983 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4984 if (RefRelationship == Sema::Ref_Compatible &&
4985 (InitCategory.isXValue() ||
4986 (InitCategory.isPRValue() &&
4987 (T2->isRecordType() || T2->isArrayType())) ||
4988 (InitCategory.isLValue() && T2->isFunctionType()))) {
4989 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4990 // binding unless we're binding to a class prvalue.
4991 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4992 // allow the use of rvalue references in C++98/03 for the benefit of
4993 // standard library implementors; therefore, we need the xvalue check here.
4994 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4995 !(InitCategory.isPRValue() || T2->isRecordType()));
4996 return ICS;
4997 }
4998
4999 // -- has a class type (i.e., T2 is a class type), where T1 is not
5000 // reference-related to T2, and can be implicitly converted to
5001 // an xvalue, class prvalue, or function lvalue of type
5002 // "cv3 T3", where "cv1 T1" is reference-compatible with
5003 // "cv3 T3",
5004 //
5005 // then the reference is bound to the value of the initializer
5006 // expression in the first case and to the result of the conversion
5007 // in the second case (or, in either case, to an appropriate base
5008 // class subobject).
5009 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5010 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5011 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5012 Init, T2, /*AllowRvalues=*/true,
5013 AllowExplicit)) {
5014 // In the second case, if the reference is an rvalue reference
5015 // and the second standard conversion sequence of the
5016 // user-defined conversion sequence includes an lvalue-to-rvalue
5017 // conversion, the program is ill-formed.
5018 if (ICS.isUserDefined() && isRValRef &&
5019 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5020 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5021
5022 return ICS;
5023 }
5024
5025 // A temporary of function type cannot be created; don't even try.
5026 if (T1->isFunctionType())
5027 return ICS;
5028
5029 // -- Otherwise, a temporary of type "cv1 T1" is created and
5030 // initialized from the initializer expression using the
5031 // rules for a non-reference copy initialization (8.5). The
5032 // reference is then bound to the temporary. If T1 is
5033 // reference-related to T2, cv1 must be the same
5034 // cv-qualification as, or greater cv-qualification than,
5035 // cv2; otherwise, the program is ill-formed.
5036 if (RefRelationship == Sema::Ref_Related) {
5037 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5038 // we would be reference-compatible or reference-compatible with
5039 // added qualification. But that wasn't the case, so the reference
5040 // initialization fails.
5041 //
5042 // Note that we only want to check address spaces and cvr-qualifiers here.
5043 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5044 Qualifiers T1Quals = T1.getQualifiers();
5045 Qualifiers T2Quals = T2.getQualifiers();
5046 T1Quals.removeObjCGCAttr();
5047 T1Quals.removeObjCLifetime();
5048 T2Quals.removeObjCGCAttr();
5049 T2Quals.removeObjCLifetime();
5050 // MS compiler ignores __unaligned qualifier for references; do the same.
5051 T1Quals.removeUnaligned();
5052 T2Quals.removeUnaligned();
5053 if (!T1Quals.compatiblyIncludes(T2Quals))
5054 return ICS;
5055 }
5056
5057 // If at least one of the types is a class type, the types are not
5058 // related, and we aren't allowed any user conversions, the
5059 // reference binding fails. This case is important for breaking
5060 // recursion, since TryImplicitConversion below will attempt to
5061 // create a temporary through the use of a copy constructor.
5062 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5063 (T1->isRecordType() || T2->isRecordType()))
5064 return ICS;
5065
5066 // If T1 is reference-related to T2 and the reference is an rvalue
5067 // reference, the initializer expression shall not be an lvalue.
5068 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5069 Init->Classify(S.Context).isLValue()) {
5070 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5071 return ICS;
5072 }
5073
5074 // C++ [over.ics.ref]p2:
5075 // When a parameter of reference type is not bound directly to
5076 // an argument expression, the conversion sequence is the one
5077 // required to convert the argument expression to the
5078 // underlying type of the reference according to
5079 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5080 // to copy-initializing a temporary of the underlying type with
5081 // the argument expression. Any difference in top-level
5082 // cv-qualification is subsumed by the initialization itself
5083 // and does not constitute a conversion.
5084 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5085 AllowedExplicit::None,
5086 /*InOverloadResolution=*/false,
5087 /*CStyle=*/false,
5088 /*AllowObjCWritebackConversion=*/false,
5089 /*AllowObjCConversionOnExplicit=*/false);
5090
5091 // Of course, that's still a reference binding.
5092 if (ICS.isStandard()) {
5093 ICS.Standard.ReferenceBinding = true;
5094 ICS.Standard.IsLvalueReference = !isRValRef;
5095 ICS.Standard.BindsToFunctionLvalue = false;
5096 ICS.Standard.BindsToRvalue = true;
5097 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5098 ICS.Standard.ObjCLifetimeConversionBinding = false;
5099 } else if (ICS.isUserDefined()) {
5100 const ReferenceType *LValRefType =
5101 ICS.UserDefined.ConversionFunction->getReturnType()
5102 ->getAs<LValueReferenceType>();
5103
5104 // C++ [over.ics.ref]p3:
5105 // Except for an implicit object parameter, for which see 13.3.1, a
5106 // standard conversion sequence cannot be formed if it requires [...]
5107 // binding an rvalue reference to an lvalue other than a function
5108 // lvalue.
5109 // Note that the function case is not possible here.
5110 if (isRValRef && LValRefType) {
5111 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5112 return ICS;
5113 }
5114
5115 ICS.UserDefined.After.ReferenceBinding = true;
5116 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5117 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5118 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5119 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5120 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5121 }
5122
5123 return ICS;
5124}
5125
5126static ImplicitConversionSequence
5127TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5128 bool SuppressUserConversions,
5129 bool InOverloadResolution,
5130 bool AllowObjCWritebackConversion,
5131 bool AllowExplicit = false);
5132
5133/// TryListConversion - Try to copy-initialize a value of type ToType from the
5134/// initializer list From.
5135static ImplicitConversionSequence
5136TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5137 bool SuppressUserConversions,
5138 bool InOverloadResolution,
5139 bool AllowObjCWritebackConversion) {
5140 // C++11 [over.ics.list]p1:
5141 // When an argument is an initializer list, it is not an expression and
5142 // special rules apply for converting it to a parameter type.
5143
5144 ImplicitConversionSequence Result;
5145 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5146
5147 // We need a complete type for what follows. With one C++20 exception,
5148 // incomplete types can never be initialized from init lists.
5149 QualType InitTy = ToType;
5150 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5151 if (AT && S.getLangOpts().CPlusPlus20)
5152 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5153 // C++20 allows list initialization of an incomplete array type.
5154 InitTy = IAT->getElementType();
5155 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5156 return Result;
5157
5158 // C++20 [over.ics.list]/2:
5159 // If the initializer list is a designated-initializer-list, a conversion
5160 // is only possible if the parameter has an aggregate type
5161 //
5162 // FIXME: The exception for reference initialization here is not part of the
5163 // language rules, but follow other compilers in adding it as a tentative DR
5164 // resolution.
5165 bool IsDesignatedInit = From->hasDesignatedInit();
5166 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5167 IsDesignatedInit)
5168 return Result;
5169
5170 // Per DR1467:
5171 // If the parameter type is a class X and the initializer list has a single
5172 // element of type cv U, where U is X or a class derived from X, the
5173 // implicit conversion sequence is the one required to convert the element
5174 // to the parameter type.
5175 //
5176 // Otherwise, if the parameter type is a character array [... ]
5177 // and the initializer list has a single element that is an
5178 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5179 // implicit conversion sequence is the identity conversion.
5180 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5181 if (ToType->isRecordType()) {
5182 QualType InitType = From->getInit(0)->getType();
5183 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5184 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5185 return TryCopyInitialization(S, From->getInit(0), ToType,
5186 SuppressUserConversions,
5187 InOverloadResolution,
5188 AllowObjCWritebackConversion);
5189 }
5190
5191 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5192 InitializedEntity Entity =
5193 InitializedEntity::InitializeParameter(S.Context, ToType,
5194 /*Consumed=*/false);
5195 if (S.CanPerformCopyInitialization(Entity, From)) {
5196 Result.setStandard();
5197 Result.Standard.setAsIdentityConversion();
5198 Result.Standard.setFromType(ToType);
5199 Result.Standard.setAllToTypes(ToType);
5200 return Result;
5201 }
5202 }
5203 }
5204
5205 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5206 // C++11 [over.ics.list]p2:
5207 // If the parameter type is std::initializer_list<X> or "array of X" and
5208 // all the elements can be implicitly converted to X, the implicit
5209 // conversion sequence is the worst conversion necessary to convert an
5210 // element of the list to X.
5211 //
5212 // C++14 [over.ics.list]p3:
5213 // Otherwise, if the parameter type is "array of N X", if the initializer
5214 // list has exactly N elements or if it has fewer than N elements and X is
5215 // default-constructible, and if all the elements of the initializer list
5216 // can be implicitly converted to X, the implicit conversion sequence is
5217 // the worst conversion necessary to convert an element of the list to X.
5218 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5219 unsigned e = From->getNumInits();
5220 ImplicitConversionSequence DfltElt;
5221 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5222 QualType());
5223 QualType ContTy = ToType;
5224 bool IsUnbounded = false;
5225 if (AT) {
5226 InitTy = AT->getElementType();
5227 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5228 if (CT->getSize().ult(e)) {
5229 // Too many inits, fatally bad
5230 Result.setBad(BadConversionSequence::too_many_initializers, From,
5231 ToType);
5232 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5233 return Result;
5234 }
5235 if (CT->getSize().ugt(e)) {
5236 // Need an init from empty {}, is there one?
5237 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5238 From->getEndLoc());
5239 EmptyList.setType(S.Context.VoidTy);
5240 DfltElt = TryListConversion(
5241 S, &EmptyList, InitTy, SuppressUserConversions,
5242 InOverloadResolution, AllowObjCWritebackConversion);
5243 if (DfltElt.isBad()) {
5244 // No {} init, fatally bad
5245 Result.setBad(BadConversionSequence::too_few_initializers, From,
5246 ToType);
5247 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5248 return Result;
5249 }
5250 }
5251 } else {
5252 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array")(static_cast <bool> (isa<IncompleteArrayType>(AT)
&& "Expected incomplete array") ? void (0) : __assert_fail
("isa<IncompleteArrayType>(AT) && \"Expected incomplete array\""
, "clang/lib/Sema/SemaOverload.cpp", 5252, __extension__ __PRETTY_FUNCTION__
))
;
5253 IsUnbounded = true;
5254 if (!e) {
5255 // Cannot convert to zero-sized.
5256 Result.setBad(BadConversionSequence::too_few_initializers, From,
5257 ToType);
5258 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5259 return Result;
5260 }
5261 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5262 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5263 ArrayType::Normal, 0);
5264 }
5265 }
5266
5267 Result.setStandard();
5268 Result.Standard.setAsIdentityConversion();
5269 Result.Standard.setFromType(InitTy);
5270 Result.Standard.setAllToTypes(InitTy);
5271 for (unsigned i = 0; i < e; ++i) {
5272 Expr *Init = From->getInit(i);
5273 ImplicitConversionSequence ICS = TryCopyInitialization(
5274 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5275 AllowObjCWritebackConversion);
5276
5277 // Keep the worse conversion seen so far.
5278 // FIXME: Sequences are not totally ordered, so 'worse' can be
5279 // ambiguous. CWG has been informed.
5280 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5281 Result) ==
5282 ImplicitConversionSequence::Worse) {
5283 Result = ICS;
5284 // Bail as soon as we find something unconvertible.
5285 if (Result.isBad()) {
5286 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5287 return Result;
5288 }
5289 }
5290 }
5291
5292 // If we needed any implicit {} initialization, compare that now.
5293 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5294 // has been informed that this might not be the best thing.
5295 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5296 S, From->getEndLoc(), DfltElt, Result) ==
5297 ImplicitConversionSequence::Worse)
5298 Result = DfltElt;
5299 // Record the type being initialized so that we may compare sequences
5300 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5301 return Result;
5302 }
5303
5304 // C++14 [over.ics.list]p4:
5305 // C++11 [over.ics.list]p3:
5306 // Otherwise, if the parameter is a non-aggregate class X and overload
5307 // resolution chooses a single best constructor [...] the implicit
5308 // conversion sequence is a user-defined conversion sequence. If multiple
5309 // constructors are viable but none is better than the others, the
5310 // implicit conversion sequence is a user-defined conversion sequence.
5311 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5312 // This function can deal with initializer lists.
5313 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5314 AllowedExplicit::None,
5315 InOverloadResolution, /*CStyle=*/false,
5316 AllowObjCWritebackConversion,
5317 /*AllowObjCConversionOnExplicit=*/false);
5318 }
5319
5320 // C++14 [over.ics.list]p5:
5321 // C++11 [over.ics.list]p4:
5322 // Otherwise, if the parameter has an aggregate type which can be
5323 // initialized from the initializer list [...] the implicit conversion
5324 // sequence is a user-defined conversion sequence.
5325 if (ToType->isAggregateType()) {
5326 // Type is an aggregate, argument is an init list. At this point it comes
5327 // down to checking whether the initialization works.
5328 // FIXME: Find out whether this parameter is consumed or not.
5329 InitializedEntity Entity =
5330 InitializedEntity::InitializeParameter(S.Context, ToType,
5331 /*Consumed=*/false);
5332 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5333 From)) {
5334 Result.setUserDefined();
5335 Result.UserDefined.Before.setAsIdentityConversion();
5336 // Initializer lists don't have a type.
5337 Result.UserDefined.Before.setFromType(QualType());
5338 Result.UserDefined.Before.setAllToTypes(QualType());
5339
5340 Result.UserDefined.After.setAsIdentityConversion();
5341 Result.UserDefined.After.setFromType(ToType);
5342 Result.UserDefined.After.setAllToTypes(ToType);
5343 Result.UserDefined.ConversionFunction = nullptr;
5344 }
5345 return Result;
5346 }
5347
5348 // C++14 [over.ics.list]p6:
5349 // C++11 [over.ics.list]p5:
5350 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5351 if (ToType->isReferenceType()) {
5352 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5353 // mention initializer lists in any way. So we go by what list-
5354 // initialization would do and try to extrapolate from that.
5355
5356 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5357
5358 // If the initializer list has a single element that is reference-related
5359 // to the parameter type, we initialize the reference from that.
5360 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5361 Expr *Init = From->getInit(0);
5362
5363 QualType T2 = Init->getType();
5364
5365 // If the initializer is the address of an overloaded function, try
5366 // to resolve the overloaded function. If all goes well, T2 is the
5367 // type of the resulting function.
5368 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5369 DeclAccessPair Found;
5370 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5371 Init, ToType, false, Found))
5372 T2 = Fn->getType();
5373 }
5374
5375 // Compute some basic properties of the types and the initializer.
5376 Sema::ReferenceCompareResult RefRelationship =
5377 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5378
5379 if (RefRelationship >= Sema::Ref_Related) {
5380 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5381 SuppressUserConversions,
5382 /*AllowExplicit=*/false);
5383 }
5384 }
5385
5386 // Otherwise, we bind the reference to a temporary created from the
5387 // initializer list.
5388 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5389 InOverloadResolution,
5390 AllowObjCWritebackConversion);
5391 if (Result.isFailure())
5392 return Result;
5393 assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5394, __extension__ __PRETTY_FUNCTION__
))
5394 "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "clang/lib/Sema/SemaOverload.cpp", 5394, __extension__ __PRETTY_FUNCTION__
))
;
5395
5396 // Can we even bind to a temporary?
5397 if (ToType->isRValueReferenceType() ||
5398 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5399 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5400 Result.UserDefined.After;
5401 SCS.ReferenceBinding = true;
5402 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5403 SCS.BindsToRvalue = true;
5404 SCS.BindsToFunctionLvalue = false;
5405 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5406 SCS.ObjCLifetimeConversionBinding = false;
5407 } else
5408 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5409 From, ToType);
5410 return Result;
5411 }
5412
5413 // C++14 [over.ics.list]p7:
5414 // C++11 [over.ics.list]p6:
5415 // Otherwise, if the parameter type is not a class:
5416 if (!ToType->isRecordType()) {
5417 // - if the initializer list has one element that is not itself an
5418 // initializer list, the implicit conversion sequence is the one
5419 // required to convert the element to the parameter type.
5420 unsigned NumInits = From->getNumInits();
5421 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5422 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5423 SuppressUserConversions,
5424 InOverloadResolution,
5425 AllowObjCWritebackConversion);
5426 // - if the initializer list has no elements, the implicit conversion
5427 // sequence is the identity conversion.
5428 else if (NumInits == 0) {
5429 Result.setStandard();
5430 Result.Standard.setAsIdentityConversion();
5431 Result.Standard.setFromType(ToType);
5432 Result.Standard.setAllToTypes(ToType);
5433 }
5434 return Result;
5435 }
5436
5437 // C++14 [over.ics.list]p8:
5438 // C++11 [over.ics.list]p7:
5439 // In all cases other than those enumerated above, no conversion is possible
5440 return Result;
5441}
5442
5443/// TryCopyInitialization - Try to copy-initialize a value of type
5444/// ToType from the expression From. Return the implicit conversion
5445/// sequence required to pass this argument, which may be a bad
5446/// conversion sequence (meaning that the argument cannot be passed to
5447/// a parameter of this type). If @p SuppressUserConversions, then we
5448/// do not permit any user-defined conversion sequences.
5449static ImplicitConversionSequence
5450TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5451 bool SuppressUserConversions,
5452 bool InOverloadResolution,
5453 bool AllowObjCWritebackConversion,
5454 bool AllowExplicit) {
5455 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5456 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5457 InOverloadResolution,AllowObjCWritebackConversion);
5458
5459 if (ToType->isReferenceType())
5460 return TryReferenceInit(S, From, ToType,
5461 /*FIXME:*/ From->getBeginLoc(),
5462 SuppressUserConversions, AllowExplicit);
5463
5464 return TryImplicitConversion(S, From, ToType,
5465 SuppressUserConversions,
5466 AllowedExplicit::None,
5467 InOverloadResolution,
5468 /*CStyle=*/false,
5469 AllowObjCWritebackConversion,
5470 /*AllowObjCConversionOnExplicit=*/false);
5471}
5472
5473static bool TryCopyInitialization(const CanQualType FromQTy,
5474 const CanQualType ToQTy,
5475 Sema &S,
5476 SourceLocation Loc,
5477 ExprValueKind FromVK) {
5478 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5479 ImplicitConversionSequence ICS =
5480 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5481
5482 return !ICS.isBad();
5483}
5484
5485/// TryObjectArgumentInitialization - Try to initialize the object
5486/// parameter of the given member function (@c Method) from the
5487/// expression @p From.
5488static ImplicitConversionSequence
5489TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5490 Expr::Classification FromClassification,
5491 CXXMethodDecl *Method,
5492 CXXRecordDecl *ActingContext) {
5493 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5494 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5495 // const volatile object.
5496 Qualifiers Quals = Method->getMethodQualifiers();
5497 if (isa<CXXDestructorDecl>(Method)) {
5498 Quals.addConst();
5499 Quals.addVolatile();
5500 }
5501
5502 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5503
5504 // Set up the conversion sequence as a "bad" conversion, to allow us
5505 // to exit early.
5506 ImplicitConversionSequence ICS;
5507
5508 // We need to have an object of class type.
5509 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5510 FromType = PT->getPointeeType();
5511
5512 // When we had a pointer, it's implicitly dereferenced, so we
5513 // better have an lvalue.
5514 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "clang/lib/Sema/SemaOverload.cpp"
, 5514, __extension__ __PRETTY_FUNCTION__))
;
5515 }
5516
5517 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "clang/lib/Sema/SemaOverload.cpp"
, 5517, __extension__ __PRETTY_FUNCTION__))
;
5518
5519 // C++0x [over.match.funcs]p4:
5520 // For non-static member functions, the type of the implicit object
5521 // parameter is
5522 //
5523 // - "lvalue reference to cv X" for functions declared without a
5524 // ref-qualifier or with the & ref-qualifier
5525 // - "rvalue reference to cv X" for functions declared with the &&
5526 // ref-qualifier
5527 //
5528 // where X is the class of which the function is a member and cv is the
5529 // cv-qualification on the member function declaration.
5530 //
5531 // However, when finding an implicit conversion sequence for the argument, we
5532 // are not allowed to perform user-defined conversions
5533 // (C++ [over.match.funcs]p5). We perform a simplified version of
5534 // reference binding here, that allows class rvalues to bind to
5535 // non-constant references.
5536
5537 // First check the qualifiers.
5538 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5539 if (ImplicitParamType.getCVRQualifiers()
5540 != FromTypeCanon.getLocalCVRQualifiers() &&
5541 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5542 ICS.setBad(BadConversionSequence::bad_qualifiers,
5543 FromType, ImplicitParamType);
5544 return ICS;
5545 }
5546
5547 if (FromTypeCanon.hasAddressSpace()) {
5548 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5549 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5550 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5551 ICS.setBad(BadConversionSequence::bad_qualifiers,
5552 FromType, ImplicitParamType);
5553 return ICS;
5554 }
5555 }
5556
5557 // Check that we have either the same type or a derived type. It
5558 // affects the conversion rank.
5559 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5560 ImplicitConversionKind SecondKind;
5561 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5562 SecondKind = ICK_Identity;
5563 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5564 SecondKind = ICK_Derived_To_Base;
5565 else {
5566 ICS.setBad(BadConversionSequence::unrelated_class,
5567 FromType, ImplicitParamType);
5568 return ICS;
5569 }
5570
5571 // Check the ref-qualifier.
5572 switch (Method->getRefQualifier()) {
5573 case RQ_None:
5574 // Do nothing; we don't care about lvalueness or rvalueness.
5575 break;
5576
5577 case RQ_LValue:
5578 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5579 // non-const lvalue reference cannot bind to an rvalue
5580 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5581 ImplicitParamType);
5582 return ICS;
5583 }
5584 break;
5585
5586 case RQ_RValue:
5587 if (!FromClassification.isRValue()) {
5588 // rvalue reference cannot bind to an lvalue
5589 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5590 ImplicitParamType);
5591 return ICS;
5592 }
5593 break;
5594 }
5595
5596 // Success. Mark this as a reference binding.
5597 ICS.setStandard();
5598 ICS.Standard.setAsIdentityConversion();
5599 ICS.Standard.Second = SecondKind;
5600 ICS.Standard.setFromType(FromType);
5601 ICS.Standard.setAllToTypes(ImplicitParamType);
5602 ICS.Standard.ReferenceBinding = true;
5603 ICS.Standard.DirectBinding = true;
5604 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5605 ICS.Standard.BindsToFunctionLvalue = false;
5606 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5607 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5608 = (Method->getRefQualifier() == RQ_None);
5609 return ICS;
5610}
5611
5612/// PerformObjectArgumentInitialization - Perform initialization of
5613/// the implicit object parameter for the given Method with the given
5614/// expression.
5615ExprResult
5616Sema::PerformObjectArgumentInitialization(Expr *From,
5617 NestedNameSpecifier *Qualifier,
5618 NamedDecl *FoundDecl,
5619 CXXMethodDecl *Method) {
5620 QualType FromRecordType, DestType;
5621 QualType ImplicitParamRecordType =
5622 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5623
5624 Expr::Classification FromClassification;
5625 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5626 FromRecordType = PT->getPointeeType();
5627 DestType = Method->getThisType();
5628 FromClassification = Expr::Classification::makeSimpleLValue();
5629 } else {
5630 FromRecordType = From->getType();
5631 DestType = ImplicitParamRecordType;
5632 FromClassification = From->Classify(Context);
5633
5634 // When performing member access on a prvalue, materialize a temporary.
5635 if (From->isPRValue()) {
5636 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5637 Method->getRefQualifier() !=
5638 RefQualifierKind::RQ_RValue);
5639 }
5640 }
5641
5642 // Note that we always use the true parent context when performing
5643 // the actual argument initialization.
5644 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5645 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5646 Method->getParent());
5647 if (ICS.isBad()) {
5648 switch (ICS.Bad.Kind) {
5649 case BadConversionSequence::bad_qualifiers: {
5650 Qualifiers FromQs = FromRecordType.getQualifiers();
5651 Qualifiers ToQs = DestType.getQualifiers();
5652 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5653 if (CVR) {
5654 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5655 << Method->getDeclName() << FromRecordType << (CVR - 1)
5656 << From->getSourceRange();
5657 Diag(Method->getLocation(), diag::note_previous_decl)
5658 << Method->getDeclName();
5659 return ExprError();
5660 }
5661 break;
5662 }
5663
5664 case BadConversionSequence::lvalue_ref_to_rvalue:
5665 case BadConversionSequence::rvalue_ref_to_lvalue: {
5666 bool IsRValueQualified =
5667 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5668 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5669 << Method->getDeclName() << FromClassification.isRValue()
5670 << IsRValueQualified;
5671 Diag(Method->getLocation(), diag::note_previous_decl)
5672 << Method->getDeclName();
5673 return ExprError();
5674 }
5675
5676 case BadConversionSequence::no_conversion:
5677 case BadConversionSequence::unrelated_class:
5678 break;
5679
5680 case BadConversionSequence::too_few_initializers:
5681 case BadConversionSequence::too_many_initializers:
5682 llvm_unreachable("Lists are not objects")::llvm::llvm_unreachable_internal("Lists are not objects", "clang/lib/Sema/SemaOverload.cpp"
, 5682)
;
5683 }
5684
5685 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5686 << ImplicitParamRecordType << FromRecordType
5687 << From->getSourceRange();
5688 }
5689
5690 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5691 ExprResult FromRes =
5692 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5693 if (FromRes.isInvalid())
5694 return ExprError();
5695 From = FromRes.get();
5696 }
5697
5698 if (!Context.hasSameType(From->getType(), DestType)) {
5699 CastKind CK;
5700 QualType PteeTy = DestType->getPointeeType();
5701 LangAS DestAS =
5702 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5703 if (FromRecordType.getAddressSpace() != DestAS)
5704 CK = CK_AddressSpaceConversion;
5705 else
5706 CK = CK_NoOp;
5707 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5708 }
5709 return From;
5710}
5711
5712/// TryContextuallyConvertToBool - Attempt to contextually convert the
5713/// expression From to bool (C++0x [conv]p3).
5714static ImplicitConversionSequence
5715TryContextuallyConvertToBool(Sema &S, Expr *From) {
5716 // C++ [dcl.init]/17.8:
5717 // - Otherwise, if the initialization is direct-initialization, the source
5718 // type is std::nullptr_t, and the destination type is bool, the initial
5719 // value of the object being initialized is false.
5720 if (From->getType()->isNullPtrType())
5721 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5722 S.Context.BoolTy,
5723 From->isGLValue());
5724
5725 // All other direct-initialization of bool is equivalent to an implicit
5726 // conversion to bool in which explicit conversions are permitted.
5727 return TryImplicitConversion(S, From, S.Context.BoolTy,
5728 /*SuppressUserConversions=*/false,
5729 AllowedExplicit::Conversions,
5730 /*InOverloadResolution=*/false,
5731 /*CStyle=*/false,
5732 /*AllowObjCWritebackConversion=*/false,
5733 /*AllowObjCConversionOnExplicit=*/false);
5734}
5735
5736/// PerformContextuallyConvertToBool - Perform a contextual conversion
5737/// of the expression From to bool (C++0x [conv]p3).
5738ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5739 if (checkPlaceholderForOverload(*this, From))
5740 return ExprError();
5741
5742 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5743 if (!ICS.isBad())
5744 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5745
5746 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5747 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5748 << From->getType() << From->getSourceRange();
5749 return ExprError();
5750}
5751
5752/// Check that the specified conversion is permitted in a converted constant
5753/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5754/// is acceptable.
5755static bool CheckConvertedConstantConversions(Sema &S,
5756 StandardConversionSequence &SCS) {
5757 // Since we know that the target type is an integral or unscoped enumeration
5758 // type, most conversion kinds are impossible. All possible First and Third
5759 // conversions are fine.
5760 switch (SCS.Second) {
5761 case ICK_Identity:
5762 case ICK_Integral_Promotion:
5763 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5764 case ICK_Zero_Queue_Conversion:
5765 return true;
5766
5767 case ICK_Boolean_Conversion:
5768 // Conversion from an integral or unscoped enumeration type to bool is
5769 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5770 // conversion, so we allow it in a converted constant expression.
5771 //
5772 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5773 // a lot of popular code. We should at least add a warning for this
5774 // (non-conforming) extension.
5775 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5776 SCS.getToType(2)->isBooleanType();
5777
5778 case ICK_Pointer_Conversion:
5779 case ICK_Pointer_Member:
5780 // C++1z: null pointer conversions and null member pointer conversions are
5781 // only permitted if the source type is std::nullptr_t.
5782 return SCS.getFromType()->isNullPtrType();
5783
5784 case ICK_Floating_Promotion:
5785 case ICK_Complex_Promotion:
5786 case ICK_Floating_Conversion:
5787 case ICK_Complex_Conversion:
5788 case ICK_Floating_Integral:
5789 case ICK_Compatible_Conversion:
5790 case ICK_Derived_To_Base:
5791 case ICK_Vector_Conversion:
5792 case ICK_SVE_Vector_Conversion:
5793 case ICK_RVV_Vector_Conversion:
5794 case ICK_Vector_Splat:
5795 case ICK_Complex_Real:
5796 case ICK_Block_Pointer_Conversion:
5797 case ICK_TransparentUnionConversion:
5798 case ICK_Writeback_Conversion:
5799 case ICK_Zero_Event_Conversion:
5800 case ICK_C_Only_Conversion:
5801 case ICK_Incompatible_Pointer_Conversion:
5802 return false;
5803
5804 case ICK_Lvalue_To_Rvalue:
5805 case ICK_Array_To_Pointer:
5806 case ICK_Function_To_Pointer:
5807 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5807)
;
5808
5809 case ICK_Function_Conversion:
5810 case ICK_Qualification:
5811 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "clang/lib/Sema/SemaOverload.cpp", 5811)
;
5812
5813 case ICK_Num_Conversion_Kinds:
5814 break;
5815 }
5816
5817 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "clang/lib/Sema/SemaOverload.cpp"
, 5817)
;
5818}
5819
5820/// CheckConvertedConstantExpression - Check that the expression From is a
5821/// converted constant expression of type T, perform the conversion and produce
5822/// the converted expression, per C++11 [expr.const]p3.
5823static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5824 QualType T, APValue &Value,
5825 Sema::CCEKind CCE,
5826 bool RequireInt,
5827 NamedDecl *Dest) {
5828 assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5829, __extension__ __PRETTY_FUNCTION__
))
5829 "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "clang/lib/Sema/SemaOverload.cpp", 5829, __extension__ __PRETTY_FUNCTION__
))
;
5830
5831 if (checkPlaceholderForOverload(S, From))
5832 return ExprError();
5833
5834 // C++1z [expr.const]p3:
5835 // A converted constant expression of type T is an expression,
5836 // implicitly converted to type T, where the converted
5837 // expression is a constant expression and the implicit conversion
5838 // sequence contains only [... list of conversions ...].
5839 ImplicitConversionSequence ICS =
5840 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5841 ? TryContextuallyConvertToBool(S, From)
5842 : TryCopyInitialization(S, From, T,
5843 /*SuppressUserConversions=*/false,
5844 /*InOverloadResolution=*/false,
5845 /*AllowObjCWritebackConversion=*/false,
5846 /*AllowExplicit=*/false);
5847 StandardConversionSequence *SCS = nullptr;
5848 switch (ICS.getKind()) {
5849 case ImplicitConversionSequence::StandardConversion:
5850 SCS = &ICS.Standard;
5851 break;
5852 case ImplicitConversionSequence::UserDefinedConversion:
5853 if (T->isRecordType())
5854 SCS = &ICS.UserDefined.Before;
5855 else
5856 SCS = &ICS.UserDefined.After;
5857 break;
5858 case ImplicitConversionSequence::AmbiguousConversion:
5859 case ImplicitConversionSequence::BadConversion:
5860 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5861 return S.Diag(From->getBeginLoc(),
5862 diag::err_typecheck_converted_constant_expression)
5863 << From->getType() << From->getSourceRange() << T;
5864 return ExprError();
5865
5866 case ImplicitConversionSequence::EllipsisConversion:
5867 case ImplicitConversionSequence::StaticObjectArgumentConversion:
5868 llvm_unreachable("bad conversion in converted constant expression")::llvm::llvm_unreachable_internal("bad conversion in converted constant expression"
, "clang/lib/Sema/SemaOverload.cpp", 5868)
;
5869 }
5870
5871 // Check that we would only use permitted conversions.
5872 if (!CheckConvertedConstantConversions(S, *SCS)) {
5873 return S.Diag(From->getBeginLoc(),
5874 diag::err_typecheck_converted_constant_expression_disallowed)
5875 << From->getType() << From->getSourceRange() << T;
5876 }
5877 // [...] and where the reference binding (if any) binds directly.
5878 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5879 return S.Diag(From->getBeginLoc(),
5880 diag::err_typecheck_converted_constant_expression_indirect)
5881 << From->getType() << From->getSourceRange() << T;
5882 }
5883
5884 // Usually we can simply apply the ImplicitConversionSequence we formed
5885 // earlier, but that's not guaranteed to work when initializing an object of
5886 // class type.
5887 ExprResult Result;
5888