Bug Summary

File:build/source/clang/lib/Sema/SemaOverload.cpp
Warning:line 10090, column 44
Called C++ object pointer is null

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