Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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