Bug Summary

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

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 -fhalf-no-semantic-interposition -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-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.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 /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../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-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/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++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 314, __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")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 352, __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())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 398, __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())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 424, __PRETTY_FUNCTION__))
;
425 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 425, __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 (isStdInitializerListElement())
545 OS << "Worst std::initializer_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-13~++20210413100635+64c24f493e5f/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))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 935, __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)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1086, __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) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1286, __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())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1610, __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()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1739, __PRETTY_FUNCTION__))
1739 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1739, __PRETTY_FUNCTION__))
;
1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
1741 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
1742 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1742, __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() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
1748 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
1749 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1749, __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(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
1757 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 1758, __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 and __float128 if
1873 // 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 if (&S.Context.getFloatTypeSemantics(FromType) !=
1880 &S.Context.getFloatTypeSemantics(ToType)) {
1881 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1882 ToType == S.Context.LongDoubleTy) ||
1883 (FromType == S.Context.LongDoubleTy &&
1884 ToType == S.Context.Float128Ty));
1885 if (Float128AndLongDouble &&
1886 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1887 &llvm::APFloat::PPCDoubleDouble()))
1888 return false;
1889 }
1890 // Floating point conversions (C++ 4.8).
1891 SCS.Second = ICK_Floating_Conversion;
1892 FromType = ToType.getUnqualifiedType();
1893 } else if ((FromType->isRealFloatingType() &&
1894 ToType->isIntegralType(S.Context)) ||
1895 (FromType->isIntegralOrUnscopedEnumerationType() &&
1896 ToType->isRealFloatingType())) {
1897 // Conversions between bfloat and int are not permitted.
1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1899 return false;
1900
1901 // Floating-integral conversions (C++ 4.9).
1902 SCS.Second = ICK_Floating_Integral;
1903 FromType = ToType.getUnqualifiedType();
1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1905 SCS.Second = ICK_Block_Pointer_Conversion;
1906 } else if (AllowObjCWritebackConversion &&
1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1908 SCS.Second = ICK_Writeback_Conversion;
1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1910 FromType, IncompatibleObjC)) {
1911 // Pointer conversions (C++ 4.10).
1912 SCS.Second = ICK_Pointer_Conversion;
1913 SCS.IncompatibleObjC = IncompatibleObjC;
1914 FromType = FromType.getUnqualifiedType();
1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1916 InOverloadResolution, FromType)) {
1917 // Pointer to member conversions (4.11).
1918 SCS.Second = ICK_Pointer_Member;
1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1920 SCS.Second = SecondICK;
1921 FromType = ToType.getUnqualifiedType();
1922 } else if (!S.getLangOpts().CPlusPlus &&
1923 S.Context.typesAreCompatible(ToType, FromType)) {
1924 // Compatible conversions (Clang extension for C function overloading)
1925 SCS.Second = ICK_Compatible_Conversion;
1926 FromType = ToType.getUnqualifiedType();
1927 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1928 InOverloadResolution,
1929 SCS, CStyle)) {
1930 SCS.Second = ICK_TransparentUnionConversion;
1931 FromType = ToType;
1932 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1933 CStyle)) {
1934 // tryAtomicConversion has updated the standard conversion sequence
1935 // appropriately.
1936 return true;
1937 } else if (ToType->isEventT() &&
1938 From->isIntegerConstantExpr(S.getASTContext()) &&
1939 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1940 SCS.Second = ICK_Zero_Event_Conversion;
1941 FromType = ToType;
1942 } else if (ToType->isQueueT() &&
1943 From->isIntegerConstantExpr(S.getASTContext()) &&
1944 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1945 SCS.Second = ICK_Zero_Queue_Conversion;
1946 FromType = ToType;
1947 } else if (ToType->isSamplerT() &&
1948 From->isIntegerConstantExpr(S.getASTContext())) {
1949 SCS.Second = ICK_Compatible_Conversion;
1950 FromType = ToType;
1951 } else {
1952 // No second conversion required.
1953 SCS.Second = ICK_Identity;
1954 }
1955 SCS.setToType(1, FromType);
1956
1957 // The third conversion can be a function pointer conversion or a
1958 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1959 bool ObjCLifetimeConversion;
1960 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1961 // Function pointer conversions (removing 'noexcept') including removal of
1962 // 'noreturn' (Clang extension).
1963 SCS.Third = ICK_Function_Conversion;
1964 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1965 ObjCLifetimeConversion)) {
1966 SCS.Third = ICK_Qualification;
1967 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1968 FromType = ToType;
1969 } else {
1970 // No conversion required
1971 SCS.Third = ICK_Identity;
1972 }
1973
1974 // C++ [over.best.ics]p6:
1975 // [...] Any difference in top-level cv-qualification is
1976 // subsumed by the initialization itself and does not constitute
1977 // a conversion. [...]
1978 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1979 QualType CanonTo = S.Context.getCanonicalType(ToType);
1980 if (CanonFrom.getLocalUnqualifiedType()
1981 == CanonTo.getLocalUnqualifiedType() &&
1982 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1983 FromType = ToType;
1984 CanonFrom = CanonTo;
1985 }
1986
1987 SCS.setToType(2, FromType);
1988
1989 if (CanonFrom == CanonTo)
1990 return true;
1991
1992 // If we have not converted the argument type to the parameter type,
1993 // this is a bad conversion sequence, unless we're resolving an overload in C.
1994 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1995 return false;
1996
1997 ExprResult ER = ExprResult{From};
1998 Sema::AssignConvertType Conv =
1999 S.CheckSingleAssignmentConstraints(ToType, ER,
2000 /*Diagnose=*/false,
2001 /*DiagnoseCFAudited=*/false,
2002 /*ConvertRHS=*/false);
2003 ImplicitConversionKind SecondConv;
2004 switch (Conv) {
2005 case Sema::Compatible:
2006 SecondConv = ICK_C_Only_Conversion;
2007 break;
2008 // For our purposes, discarding qualifiers is just as bad as using an
2009 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2010 // qualifiers, as well.
2011 case Sema::CompatiblePointerDiscardsQualifiers:
2012 case Sema::IncompatiblePointer:
2013 case Sema::IncompatiblePointerSign:
2014 SecondConv = ICK_Incompatible_Pointer_Conversion;
2015 break;
2016 default:
2017 return false;
2018 }
2019
2020 // First can only be an lvalue conversion, so we pretend that this was the
2021 // second conversion. First should already be valid from earlier in the
2022 // function.
2023 SCS.Second = SecondConv;
2024 SCS.setToType(1, ToType);
2025
2026 // Third is Identity, because Second should rank us worse than any other
2027 // conversion. This could also be ICK_Qualification, but it's simpler to just
2028 // lump everything in with the second conversion, and we don't gain anything
2029 // from making this ICK_Qualification.
2030 SCS.Third = ICK_Identity;
2031 SCS.setToType(2, ToType);
2032 return true;
2033}
2034
2035static bool
2036IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2037 QualType &ToType,
2038 bool InOverloadResolution,
2039 StandardConversionSequence &SCS,
2040 bool CStyle) {
2041
2042 const RecordType *UT = ToType->getAsUnionType();
2043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2044 return false;
2045 // The field to initialize within the transparent union.
2046 RecordDecl *UD = UT->getDecl();
2047 // It's compatible if the expression matches any of the fields.
2048 for (const auto *it : UD->fields()) {
2049 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2050 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2051 ToType = it->getType();
2052 return true;
2053 }
2054 }
2055 return false;
2056}
2057
2058/// IsIntegralPromotion - Determines whether the conversion from the
2059/// expression From (whose potentially-adjusted type is FromType) to
2060/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2061/// sets PromotedType to the promoted type.
2062bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2063 const BuiltinType *To = ToType->getAs<BuiltinType>();
2064 // All integers are built-in.
2065 if (!To) {
2066 return false;
2067 }
2068
2069 // An rvalue of type char, signed char, unsigned char, short int, or
2070 // unsigned short int can be converted to an rvalue of type int if
2071 // int can represent all the values of the source type; otherwise,
2072 // the source rvalue can be converted to an rvalue of type unsigned
2073 // int (C++ 4.5p1).
2074 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2075 !FromType->isEnumeralType()) {
2076 if (// We can promote any signed, promotable integer type to an int
2077 (FromType->isSignedIntegerType() ||
2078 // We can promote any unsigned integer type whose size is
2079 // less than int to an int.
2080 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2081 return To->getKind() == BuiltinType::Int;
2082 }
2083
2084 return To->getKind() == BuiltinType::UInt;
2085 }
2086
2087 // C++11 [conv.prom]p3:
2088 // A prvalue of an unscoped enumeration type whose underlying type is not
2089 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2090 // following types that can represent all the values of the enumeration
2091 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2092 // unsigned int, long int, unsigned long int, long long int, or unsigned
2093 // long long int. If none of the types in that list can represent all the
2094 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2095 // type can be converted to an rvalue a prvalue of the extended integer type
2096 // with lowest integer conversion rank (4.13) greater than the rank of long
2097 // long in which all the values of the enumeration can be represented. If
2098 // there are two such extended types, the signed one is chosen.
2099 // C++11 [conv.prom]p4:
2100 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2101 // can be converted to a prvalue of its underlying type. Moreover, if
2102 // integral promotion can be applied to its underlying type, a prvalue of an
2103 // unscoped enumeration type whose underlying type is fixed can also be
2104 // converted to a prvalue of the promoted underlying type.
2105 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2106 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2107 // provided for a scoped enumeration.
2108 if (FromEnumType->getDecl()->isScoped())
2109 return false;
2110
2111 // We can perform an integral promotion to the underlying type of the enum,
2112 // even if that's not the promoted type. Note that the check for promoting
2113 // the underlying type is based on the type alone, and does not consider
2114 // the bitfield-ness of the actual source expression.
2115 if (FromEnumType->getDecl()->isFixed()) {
2116 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2117 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2118 IsIntegralPromotion(nullptr, Underlying, ToType);
2119 }
2120
2121 // We have already pre-calculated the promotion type, so this is trivial.
2122 if (ToType->isIntegerType() &&
2123 isCompleteType(From->getBeginLoc(), FromType))
2124 return Context.hasSameUnqualifiedType(
2125 ToType, FromEnumType->getDecl()->getPromotionType());
2126
2127 // C++ [conv.prom]p5:
2128 // If the bit-field has an enumerated type, it is treated as any other
2129 // value of that type for promotion purposes.
2130 //
2131 // ... so do not fall through into the bit-field checks below in C++.
2132 if (getLangOpts().CPlusPlus)
2133 return false;
2134 }
2135
2136 // C++0x [conv.prom]p2:
2137 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2138 // to an rvalue a prvalue of the first of the following types that can
2139 // represent all the values of its underlying type: int, unsigned int,
2140 // long int, unsigned long int, long long int, or unsigned long long int.
2141 // If none of the types in that list can represent all the values of its
2142 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2143 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2144 // type.
2145 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2146 ToType->isIntegerType()) {
2147 // Determine whether the type we're converting from is signed or
2148 // unsigned.
2149 bool FromIsSigned = FromType->isSignedIntegerType();
2150 uint64_t FromSize = Context.getTypeSize(FromType);
2151
2152 // The types we'll try to promote to, in the appropriate
2153 // order. Try each of these types.
2154 QualType PromoteTypes[6] = {
2155 Context.IntTy, Context.UnsignedIntTy,
2156 Context.LongTy, Context.UnsignedLongTy ,
2157 Context.LongLongTy, Context.UnsignedLongLongTy
2158 };
2159 for (int Idx = 0; Idx < 6; ++Idx) {
2160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2161 if (FromSize < ToSize ||
2162 (FromSize == ToSize &&
2163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2164 // We found the type that we can promote to. If this is the
2165 // type we wanted, we have a promotion. Otherwise, no
2166 // promotion.
2167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2168 }
2169 }
2170 }
2171
2172 // An rvalue for an integral bit-field (9.6) can be converted to an
2173 // rvalue of type int if int can represent all the values of the
2174 // bit-field; otherwise, it can be converted to unsigned int if
2175 // unsigned int can represent all the values of the bit-field. If
2176 // the bit-field is larger yet, no integral promotion applies to
2177 // it. If the bit-field has an enumerated type, it is treated as any
2178 // other value of that type for promotion purposes (C++ 4.5p3).
2179 // FIXME: We should delay checking of bit-fields until we actually perform the
2180 // conversion.
2181 //
2182 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2183 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2184 // bit-fields and those whose underlying type is larger than int) for GCC
2185 // compatibility.
2186 if (From) {
2187 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2188 Optional<llvm::APSInt> BitWidth;
2189 if (FromType->isIntegralType(Context) &&
2190 (BitWidth =
2191 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2192 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2193 ToSize = Context.getTypeSize(ToType);
2194
2195 // Are we promoting to an int from a bitfield that fits in an int?
2196 if (*BitWidth < ToSize ||
2197 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2198 return To->getKind() == BuiltinType::Int;
2199 }
2200
2201 // Are we promoting to an unsigned int from an unsigned bitfield
2202 // that fits into an unsigned int?
2203 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2204 return To->getKind() == BuiltinType::UInt;
2205 }
2206
2207 return false;
2208 }
2209 }
2210 }
2211
2212 // An rvalue of type bool can be converted to an rvalue of type int,
2213 // with false becoming zero and true becoming one (C++ 4.5p4).
2214 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2215 return true;
2216 }
2217
2218 return false;
2219}
2220
2221/// IsFloatingPointPromotion - Determines whether the conversion from
2222/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2223/// returns true and sets PromotedType to the promoted type.
2224bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2227 /// An rvalue of type float can be converted to an rvalue of type
2228 /// double. (C++ 4.6p1).
2229 if (FromBuiltin->getKind() == BuiltinType::Float &&
2230 ToBuiltin->getKind() == BuiltinType::Double)
2231 return true;
2232
2233 // C99 6.3.1.5p1:
2234 // When a float is promoted to double or long double, or a
2235 // double is promoted to long double [...].
2236 if (!getLangOpts().CPlusPlus &&
2237 (FromBuiltin->getKind() == BuiltinType::Float ||
2238 FromBuiltin->getKind() == BuiltinType::Double) &&
2239 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2240 ToBuiltin->getKind() == BuiltinType::Float128))
2241 return true;
2242
2243 // Half can be promoted to float.
2244 if (!getLangOpts().NativeHalfType &&
2245 FromBuiltin->getKind() == BuiltinType::Half &&
2246 ToBuiltin->getKind() == BuiltinType::Float)
2247 return true;
2248 }
2249
2250 return false;
2251}
2252
2253/// Determine if a conversion is a complex promotion.
2254///
2255/// A complex promotion is defined as a complex -> complex conversion
2256/// where the conversion between the underlying real types is a
2257/// floating-point or integral promotion.
2258bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2260 if (!FromComplex)
2261 return false;
2262
2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2264 if (!ToComplex)
2265 return false;
2266
2267 return IsFloatingPointPromotion(FromComplex->getElementType(),
2268 ToComplex->getElementType()) ||
2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2270 ToComplex->getElementType());
2271}
2272
2273/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2274/// the pointer type FromPtr to a pointer to type ToPointee, with the
2275/// same type qualifiers as FromPtr has on its pointee type. ToType,
2276/// if non-empty, will be a pointer to ToType that may or may not have
2277/// the right set of qualifiers on its pointee.
2278///
2279static QualType
2280BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2281 QualType ToPointee, QualType ToType,
2282 ASTContext &Context,
2283 bool StripObjCLifetime = false) {
2284 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
2286 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
;
2287
2288 /// Conversions to 'id' subsume cv-qualifier conversions.
2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2290 return ToType.getUnqualifiedType();
2291
2292 QualType CanonFromPointee
2293 = Context.getCanonicalType(FromPtr->getPointeeType());
2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2295 Qualifiers Quals = CanonFromPointee.getQualifiers();
2296
2297 if (StripObjCLifetime)
2298 Quals.removeObjCLifetime();
2299
2300 // Exact qualifier match -> return the pointer type we're converting to.
2301 if (CanonToPointee.getLocalQualifiers() == Quals) {
2302 // ToType is exactly what we need. Return it.
2303 if (!ToType.isNull())
2304 return ToType.getUnqualifiedType();
2305
2306 // Build a pointer to ToPointee. It has the right qualifiers
2307 // already.
2308 if (isa<ObjCObjectPointerType>(ToType))
2309 return Context.getObjCObjectPointerType(ToPointee);
2310 return Context.getPointerType(ToPointee);
2311 }
2312
2313 // Just build a canonical type that has the right qualifiers.
2314 QualType QualifiedCanonToPointee
2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2316
2317 if (isa<ObjCObjectPointerType>(ToType))
2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2319 return Context.getPointerType(QualifiedCanonToPointee);
2320}
2321
2322static bool isNullPointerConstantForConversion(Expr *Expr,
2323 bool InOverloadResolution,
2324 ASTContext &Context) {
2325 // Handle value-dependent integral null pointer constants correctly.
2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2329 return !InOverloadResolution;
2330
2331 return Expr->isNullPointerConstant(Context,
2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2333 : Expr::NPC_ValueDependentIsNull);
2334}
2335
2336/// IsPointerConversion - Determines whether the conversion of the
2337/// expression From, which has the (possibly adjusted) type FromType,
2338/// can be converted to the type ToType via a pointer conversion (C++
2339/// 4.10). If so, returns true and places the converted type (that
2340/// might differ from ToType in its cv-qualifiers at some level) into
2341/// ConvertedType.
2342///
2343/// This routine also supports conversions to and from block pointers
2344/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2345/// pointers to interfaces. FIXME: Once we've determined the
2346/// appropriate overloading rules for Objective-C, we may want to
2347/// split the Objective-C checks into a different routine; however,
2348/// GCC seems to consider all of these conversions to be pointer
2349/// conversions, so for now they live here. IncompatibleObjC will be
2350/// set if the conversion is an allowed Objective-C conversion that
2351/// should result in a warning.
2352bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2353 bool InOverloadResolution,
2354 QualType& ConvertedType,
2355 bool &IncompatibleObjC) {
2356 IncompatibleObjC = false;
2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2358 IncompatibleObjC))
2359 return true;
2360
2361 // Conversion from a null pointer constant to any Objective-C pointer type.
2362 if (ToType->isObjCObjectPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // Blocks: Block pointers can be converted to void*.
2369 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2371 ConvertedType = ToType;
2372 return true;
2373 }
2374 // Blocks: A null pointer constant can be converted to a block
2375 // pointer type.
2376 if (ToType->isBlockPointerType() &&
2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2378 ConvertedType = ToType;
2379 return true;
2380 }
2381
2382 // If the left-hand-side is nullptr_t, the right side can be a null
2383 // pointer constant.
2384 if (ToType->isNullPtrType() &&
2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386 ConvertedType = ToType;
2387 return true;
2388 }
2389
2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2391 if (!ToTypePtr)
2392 return false;
2393
2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2396 ConvertedType = ToType;
2397 return true;
2398 }
2399
2400 // Beyond this point, both types need to be pointers
2401 // , including objective-c pointers.
2402 QualType ToPointeeType = ToTypePtr->getPointeeType();
2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2404 !getLangOpts().ObjCAutoRefCount) {
2405 ConvertedType = BuildSimilarlyQualifiedPointerType(
2406 FromType->getAs<ObjCObjectPointerType>(),
2407 ToPointeeType,
2408 ToType, Context);
2409 return true;
2410 }
2411 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2412 if (!FromTypePtr)
2413 return false;
2414
2415 QualType FromPointeeType = FromTypePtr->getPointeeType();
2416
2417 // If the unqualified pointee types are the same, this can't be a
2418 // pointer conversion, so don't do all of the work below.
2419 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2420 return false;
2421
2422 // An rvalue of type "pointer to cv T," where T is an object type,
2423 // can be converted to an rvalue of type "pointer to cv void" (C++
2424 // 4.10p2).
2425 if (FromPointeeType->isIncompleteOrObjectType() &&
2426 ToPointeeType->isVoidType()) {
2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428 ToPointeeType,
2429 ToType, Context,
2430 /*StripObjCLifetime=*/true);
2431 return true;
2432 }
2433
2434 // MSVC allows implicit function to void* type conversion.
2435 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2436 ToPointeeType->isVoidType()) {
2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438 ToPointeeType,
2439 ToType, Context);
2440 return true;
2441 }
2442
2443 // When we're overloading in C, we allow a special kind of pointer
2444 // conversion for compatible-but-not-identical pointee types.
2445 if (!getLangOpts().CPlusPlus &&
2446 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2447 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2448 ToPointeeType,
2449 ToType, Context);
2450 return true;
2451 }
2452
2453 // C++ [conv.ptr]p3:
2454 //
2455 // An rvalue of type "pointer to cv D," where D is a class type,
2456 // can be converted to an rvalue of type "pointer to cv B," where
2457 // B is a base class (clause 10) of D. If B is an inaccessible
2458 // (clause 11) or ambiguous (10.2) base class of D, a program that
2459 // necessitates this conversion is ill-formed. The result of the
2460 // conversion is a pointer to the base class sub-object of the
2461 // derived class object. The null pointer value is converted to
2462 // the null pointer value of the destination type.
2463 //
2464 // Note that we do not check for ambiguity or inaccessibility
2465 // here. That is handled by CheckPointerConversion.
2466 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2467 ToPointeeType->isRecordType() &&
2468 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2469 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2470 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2471 ToPointeeType,
2472 ToType, Context);
2473 return true;
2474 }
2475
2476 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2477 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2478 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2479 ToPointeeType,
2480 ToType, Context);
2481 return true;
2482 }
2483
2484 return false;
2485}
2486
2487/// Adopt the given qualifiers for the given type.
2488static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2489 Qualifiers TQs = T.getQualifiers();
2490
2491 // Check whether qualifiers already match.
2492 if (TQs == Qs)
2493 return T;
2494
2495 if (Qs.compatiblyIncludes(TQs))
2496 return Context.getQualifiedType(T, Qs);
2497
2498 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2499}
2500
2501/// isObjCPointerConversion - Determines whether this is an
2502/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2503/// with the same arguments and return values.
2504bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2505 QualType& ConvertedType,
2506 bool &IncompatibleObjC) {
2507 if (!getLangOpts().ObjC)
2508 return false;
2509
2510 // The set of qualifiers on the type we're converting from.
2511 Qualifiers FromQualifiers = FromType.getQualifiers();
2512
2513 // First, we handle all conversions on ObjC object pointer types.
2514 const ObjCObjectPointerType* ToObjCPtr =
2515 ToType->getAs<ObjCObjectPointerType>();
2516 const ObjCObjectPointerType *FromObjCPtr =
2517 FromType->getAs<ObjCObjectPointerType>();
2518
2519 if (ToObjCPtr && FromObjCPtr) {
2520 // If the pointee types are the same (ignoring qualifications),
2521 // then this is not a pointer conversion.
2522 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2523 FromObjCPtr->getPointeeType()))
2524 return false;
2525
2526 // Conversion between Objective-C pointers.
2527 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2528 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2529 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2530 if (getLangOpts().CPlusPlus && LHS && RHS &&
2531 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2532 FromObjCPtr->getPointeeType()))
2533 return false;
2534 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2535 ToObjCPtr->getPointeeType(),
2536 ToType, Context);
2537 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2538 return true;
2539 }
2540
2541 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2542 // Okay: this is some kind of implicit downcast of Objective-C
2543 // interfaces, which is permitted. However, we're going to
2544 // complain about it.
2545 IncompatibleObjC = true;
2546 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2547 ToObjCPtr->getPointeeType(),
2548 ToType, Context);
2549 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2550 return true;
2551 }
2552 }
2553 // Beyond this point, both types need to be C pointers or block pointers.
2554 QualType ToPointeeType;
2555 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2556 ToPointeeType = ToCPtr->getPointeeType();
2557 else if (const BlockPointerType *ToBlockPtr =
2558 ToType->getAs<BlockPointerType>()) {
2559 // Objective C++: We're able to convert from a pointer to any object
2560 // to a block pointer type.
2561 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2562 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2563 return true;
2564 }
2565 ToPointeeType = ToBlockPtr->getPointeeType();
2566 }
2567 else if (FromType->getAs<BlockPointerType>() &&
2568 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2569 // Objective C++: We're able to convert from a block pointer type to a
2570 // pointer to any object.
2571 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2572 return true;
2573 }
2574 else
2575 return false;
2576
2577 QualType FromPointeeType;
2578 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2579 FromPointeeType = FromCPtr->getPointeeType();
2580 else if (const BlockPointerType *FromBlockPtr =
2581 FromType->getAs<BlockPointerType>())
2582 FromPointeeType = FromBlockPtr->getPointeeType();
2583 else
2584 return false;
2585
2586 // If we have pointers to pointers, recursively check whether this
2587 // is an Objective-C conversion.
2588 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2589 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2590 IncompatibleObjC)) {
2591 // We always complain about this conversion.
2592 IncompatibleObjC = true;
2593 ConvertedType = Context.getPointerType(ConvertedType);
2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595 return true;
2596 }
2597 // Allow conversion of pointee being objective-c pointer to another one;
2598 // as in I* to id.
2599 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2600 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2601 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2602 IncompatibleObjC)) {
2603
2604 ConvertedType = Context.getPointerType(ConvertedType);
2605 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2606 return true;
2607 }
2608
2609 // If we have pointers to functions or blocks, check whether the only
2610 // differences in the argument and result types are in Objective-C
2611 // pointer conversions. If so, we permit the conversion (but
2612 // complain about it).
2613 const FunctionProtoType *FromFunctionType
2614 = FromPointeeType->getAs<FunctionProtoType>();
2615 const FunctionProtoType *ToFunctionType
2616 = ToPointeeType->getAs<FunctionProtoType>();
2617 if (FromFunctionType && ToFunctionType) {
2618 // If the function types are exactly the same, this isn't an
2619 // Objective-C pointer conversion.
2620 if (Context.getCanonicalType(FromPointeeType)
2621 == Context.getCanonicalType(ToPointeeType))
2622 return false;
2623
2624 // Perform the quick checks that will tell us whether these
2625 // function types are obviously different.
2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2628 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2629 return false;
2630
2631 bool HasObjCConversion = false;
2632 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2633 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2634 // Okay, the types match exactly. Nothing to do.
2635 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2636 ToFunctionType->getReturnType(),
2637 ConvertedType, IncompatibleObjC)) {
2638 // Okay, we have an Objective-C pointer conversion.
2639 HasObjCConversion = true;
2640 } else {
2641 // Function types are too different. Abort.
2642 return false;
2643 }
2644
2645 // Check argument types.
2646 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2647 ArgIdx != NumArgs; ++ArgIdx) {
2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2650 if (Context.getCanonicalType(FromArgType)
2651 == Context.getCanonicalType(ToArgType)) {
2652 // Okay, the types match exactly. Nothing to do.
2653 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2654 ConvertedType, IncompatibleObjC)) {
2655 // Okay, we have an Objective-C pointer conversion.
2656 HasObjCConversion = true;
2657 } else {
2658 // Argument types are too different. Abort.
2659 return false;
2660 }
2661 }
2662
2663 if (HasObjCConversion) {
2664 // We had an Objective-C conversion. Allow this pointer
2665 // conversion, but complain about it.
2666 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2667 IncompatibleObjC = true;
2668 return true;
2669 }
2670 }
2671
2672 return false;
2673}
2674
2675/// Determine whether this is an Objective-C writeback conversion,
2676/// used for parameter passing when performing automatic reference counting.
2677///
2678/// \param FromType The type we're converting form.
2679///
2680/// \param ToType The type we're converting to.
2681///
2682/// \param ConvertedType The type that will be produced after applying
2683/// this conversion.
2684bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2685 QualType &ConvertedType) {
2686 if (!getLangOpts().ObjCAutoRefCount ||
2687 Context.hasSameUnqualifiedType(FromType, ToType))
2688 return false;
2689
2690 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2691 QualType ToPointee;
2692 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2693 ToPointee = ToPointer->getPointeeType();
2694 else
2695 return false;
2696
2697 Qualifiers ToQuals = ToPointee.getQualifiers();
2698 if (!ToPointee->isObjCLifetimeType() ||
2699 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2700 !ToQuals.withoutObjCLifetime().empty())
2701 return false;
2702
2703 // Argument must be a pointer to __strong to __weak.
2704 QualType FromPointee;
2705 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2706 FromPointee = FromPointer->getPointeeType();
2707 else
2708 return false;
2709
2710 Qualifiers FromQuals = FromPointee.getQualifiers();
2711 if (!FromPointee->isObjCLifetimeType() ||
2712 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2713 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2714 return false;
2715
2716 // Make sure that we have compatible qualifiers.
2717 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2718 if (!ToQuals.compatiblyIncludes(FromQuals))
2719 return false;
2720
2721 // Remove qualifiers from the pointee type we're converting from; they
2722 // aren't used in the compatibility check belong, and we'll be adding back
2723 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2724 FromPointee = FromPointee.getUnqualifiedType();
2725
2726 // The unqualified form of the pointee types must be compatible.
2727 ToPointee = ToPointee.getUnqualifiedType();
2728 bool IncompatibleObjC;
2729 if (Context.typesAreCompatible(FromPointee, ToPointee))
2730 FromPointee = ToPointee;
2731 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2732 IncompatibleObjC))
2733 return false;
2734
2735 /// Construct the type we're converting to, which is a pointer to
2736 /// __autoreleasing pointee.
2737 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2738 ConvertedType = Context.getPointerType(FromPointee);
2739 return true;
2740}
2741
2742bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2743 QualType& ConvertedType) {
2744 QualType ToPointeeType;
2745 if (const BlockPointerType *ToBlockPtr =
2746 ToType->getAs<BlockPointerType>())
2747 ToPointeeType = ToBlockPtr->getPointeeType();
2748 else
2749 return false;
2750
2751 QualType FromPointeeType;
2752 if (const BlockPointerType *FromBlockPtr =
2753 FromType->getAs<BlockPointerType>())
2754 FromPointeeType = FromBlockPtr->getPointeeType();
2755 else
2756 return false;
2757 // We have pointer to blocks, check whether the only
2758 // differences in the argument and result types are in Objective-C
2759 // pointer conversions. If so, we permit the conversion.
2760
2761 const FunctionProtoType *FromFunctionType
2762 = FromPointeeType->getAs<FunctionProtoType>();
2763 const FunctionProtoType *ToFunctionType
2764 = ToPointeeType->getAs<FunctionProtoType>();
2765
2766 if (!FromFunctionType || !ToFunctionType)
2767 return false;
2768
2769 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2770 return true;
2771
2772 // Perform the quick checks that will tell us whether these
2773 // function types are obviously different.
2774 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2775 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2776 return false;
2777
2778 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2779 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2780 if (FromEInfo != ToEInfo)
2781 return false;
2782
2783 bool IncompatibleObjC = false;
2784 if (Context.hasSameType(FromFunctionType->getReturnType(),
2785 ToFunctionType->getReturnType())) {
2786 // Okay, the types match exactly. Nothing to do.
2787 } else {
2788 QualType RHS = FromFunctionType->getReturnType();
2789 QualType LHS = ToFunctionType->getReturnType();
2790 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2791 !RHS.hasQualifiers() && LHS.hasQualifiers())
2792 LHS = LHS.getUnqualifiedType();
2793
2794 if (Context.hasSameType(RHS,LHS)) {
2795 // OK exact match.
2796 } else if (isObjCPointerConversion(RHS, LHS,
2797 ConvertedType, IncompatibleObjC)) {
2798 if (IncompatibleObjC)
2799 return false;
2800 // Okay, we have an Objective-C pointer conversion.
2801 }
2802 else
2803 return false;
2804 }
2805
2806 // Check argument types.
2807 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2808 ArgIdx != NumArgs; ++ArgIdx) {
2809 IncompatibleObjC = false;
2810 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2811 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2812 if (Context.hasSameType(FromArgType, ToArgType)) {
2813 // Okay, the types match exactly. Nothing to do.
2814 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2815 ConvertedType, IncompatibleObjC)) {
2816 if (IncompatibleObjC)
2817 return false;
2818 // Okay, we have an Objective-C pointer conversion.
2819 } else
2820 // Argument types are too different. Abort.
2821 return false;
2822 }
2823
2824 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2825 bool CanUseToFPT, CanUseFromFPT;
2826 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2827 CanUseToFPT, CanUseFromFPT,
2828 NewParamInfos))
2829 return false;
2830
2831 ConvertedType = ToType;
2832 return true;
2833}
2834
2835enum {
2836 ft_default,
2837 ft_different_class,
2838 ft_parameter_arity,
2839 ft_parameter_mismatch,
2840 ft_return_type,
2841 ft_qualifer_mismatch,
2842 ft_noexcept
2843};
2844
2845/// Attempts to get the FunctionProtoType from a Type. Handles
2846/// MemberFunctionPointers properly.
2847static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2848 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2849 return FPT;
2850
2851 if (auto *MPT = FromType->getAs<MemberPointerType>())
2852 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2853
2854 return nullptr;
2855}
2856
2857/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2858/// function types. Catches different number of parameter, mismatch in
2859/// parameter types, and different return types.
2860void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2861 QualType FromType, QualType ToType) {
2862 // If either type is not valid, include no extra info.
2863 if (FromType.isNull() || ToType.isNull()) {
2864 PDiag << ft_default;
2865 return;
2866 }
2867
2868 // Get the function type from the pointers.
2869 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2870 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2871 *ToMember = ToType->castAs<MemberPointerType>();
2872 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2873 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2874 << QualType(FromMember->getClass(), 0);
2875 return;
2876 }
2877 FromType = FromMember->getPointeeType();
2878 ToType = ToMember->getPointeeType();
2879 }
2880
2881 if (FromType->isPointerType())
2882 FromType = FromType->getPointeeType();
2883 if (ToType->isPointerType())
2884 ToType = ToType->getPointeeType();
2885
2886 // Remove references.
2887 FromType = FromType.getNonReferenceType();
2888 ToType = ToType.getNonReferenceType();
2889
2890 // Don't print extra info for non-specialized template functions.
2891 if (FromType->isInstantiationDependentType() &&
2892 !FromType->getAs<TemplateSpecializationType>()) {
2893 PDiag << ft_default;
2894 return;
2895 }
2896
2897 // No extra info for same types.
2898 if (Context.hasSameType(FromType, ToType)) {
2899 PDiag << ft_default;
2900 return;
2901 }
2902
2903 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2904 *ToFunction = tryGetFunctionProtoType(ToType);
2905
2906 // Both types need to be function types.
2907 if (!FromFunction || !ToFunction) {
2908 PDiag << ft_default;
2909 return;
2910 }
2911
2912 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2913 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2914 << FromFunction->getNumParams();
2915 return;
2916 }
2917
2918 // Handle different parameter types.
2919 unsigned ArgPos;
2920 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2921 PDiag << ft_parameter_mismatch << ArgPos + 1
2922 << ToFunction->getParamType(ArgPos)
2923 << FromFunction->getParamType(ArgPos);
2924 return;
2925 }
2926
2927 // Handle different return type.
2928 if (!Context.hasSameType(FromFunction->getReturnType(),
2929 ToFunction->getReturnType())) {
2930 PDiag << ft_return_type << ToFunction->getReturnType()
2931 << FromFunction->getReturnType();
2932 return;
2933 }
2934
2935 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2936 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2937 << FromFunction->getMethodQuals();
2938 return;
2939 }
2940
2941 // Handle exception specification differences on canonical type (in C++17
2942 // onwards).
2943 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2944 ->isNothrow() !=
2945 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2946 ->isNothrow()) {
2947 PDiag << ft_noexcept;
2948 return;
2949 }
2950
2951 // Unable to find a difference, so add no extra info.
2952 PDiag << ft_default;
2953}
2954
2955/// FunctionParamTypesAreEqual - This routine checks two function proto types
2956/// for equality of their argument types. Caller has already checked that
2957/// they have same number of arguments. If the parameters are different,
2958/// ArgPos will have the parameter index of the first different parameter.
2959bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2960 const FunctionProtoType *NewType,
2961 unsigned *ArgPos) {
2962 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2963 N = NewType->param_type_begin(),
2964 E = OldType->param_type_end();
2965 O && (O != E); ++O, ++N) {
2966 // Ignore address spaces in pointee type. This is to disallow overloading
2967 // on __ptr32/__ptr64 address spaces.
2968 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2969 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2970
2971 if (!Context.hasSameType(Old, New)) {
2972 if (ArgPos)
2973 *ArgPos = O - OldType->param_type_begin();
2974 return false;
2975 }
2976 }
2977 return true;
2978}
2979
2980/// CheckPointerConversion - Check the pointer conversion from the
2981/// expression From to the type ToType. This routine checks for
2982/// ambiguous or inaccessible derived-to-base pointer
2983/// conversions for which IsPointerConversion has already returned
2984/// true. It returns true and produces a diagnostic if there was an
2985/// error, or returns false otherwise.
2986bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2987 CastKind &Kind,
2988 CXXCastPath& BasePath,
2989 bool IgnoreBaseAccess,
2990 bool Diagnose) {
2991 QualType FromType = From->getType();
2992 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2993
2994 Kind = CK_BitCast;
2995
2996 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2997 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2998 Expr::NPCK_ZeroExpression) {
2999 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3000 DiagRuntimeBehavior(From->getExprLoc(), From,
3001 PDiag(diag::warn_impcast_bool_to_null_pointer)
3002 << ToType << From->getSourceRange());
3003 else if (!isUnevaluatedContext())
3004 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3005 << ToType << From->getSourceRange();
3006 }
3007 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3008 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3009 QualType FromPointeeType = FromPtrType->getPointeeType(),
3010 ToPointeeType = ToPtrType->getPointeeType();
3011
3012 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3013 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3014 // We must have a derived-to-base conversion. Check an
3015 // ambiguous or inaccessible conversion.
3016 unsigned InaccessibleID = 0;
3017 unsigned AmbiguousID = 0;
3018 if (Diagnose) {
3019 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3020 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3021 }
3022 if (CheckDerivedToBaseConversion(
3023 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3024 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3025 &BasePath, IgnoreBaseAccess))
3026 return true;
3027
3028 // The conversion was successful.
3029 Kind = CK_DerivedToBase;
3030 }
3031
3032 if (Diagnose && !IsCStyleOrFunctionalCast &&
3033 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3034 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3035, __PRETTY_FUNCTION__))
3035 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3035, __PRETTY_FUNCTION__))
;
3036 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3037 << From->getSourceRange();
3038 }
3039 }
3040 } else if (const ObjCObjectPointerType *ToPtrType =
3041 ToType->getAs<ObjCObjectPointerType>()) {
3042 if (const ObjCObjectPointerType *FromPtrType =
3043 FromType->getAs<ObjCObjectPointerType>()) {
3044 // Objective-C++ conversions are always okay.
3045 // FIXME: We should have a different class of conversions for the
3046 // Objective-C++ implicit conversions.
3047 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3048 return false;
3049 } else if (FromType->isBlockPointerType()) {
3050 Kind = CK_BlockPointerToObjCPointerCast;
3051 } else {
3052 Kind = CK_CPointerToObjCPointerCast;
3053 }
3054 } else if (ToType->isBlockPointerType()) {
3055 if (!FromType->isBlockPointerType())
3056 Kind = CK_AnyPointerToBlockPointerCast;
3057 }
3058
3059 // We shouldn't fall into this case unless it's valid for other
3060 // reasons.
3061 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3062 Kind = CK_NullToPointer;
3063
3064 return false;
3065}
3066
3067/// IsMemberPointerConversion - Determines whether the conversion of the
3068/// expression From, which has the (possibly adjusted) type FromType, can be
3069/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3070/// If so, returns true and places the converted type (that might differ from
3071/// ToType in its cv-qualifiers at some level) into ConvertedType.
3072bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3073 QualType ToType,
3074 bool InOverloadResolution,
3075 QualType &ConvertedType) {
3076 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3077 if (!ToTypePtr)
3078 return false;
3079
3080 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3081 if (From->isNullPointerConstant(Context,
3082 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3083 : Expr::NPC_ValueDependentIsNull)) {
3084 ConvertedType = ToType;
3085 return true;
3086 }
3087
3088 // Otherwise, both types have to be member pointers.
3089 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3090 if (!FromTypePtr)
3091 return false;
3092
3093 // A pointer to member of B can be converted to a pointer to member of D,
3094 // where D is derived from B (C++ 4.11p2).
3095 QualType FromClass(FromTypePtr->getClass(), 0);
3096 QualType ToClass(ToTypePtr->getClass(), 0);
3097
3098 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3099 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3100 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3101 ToClass.getTypePtr());
3102 return true;
3103 }
3104
3105 return false;
3106}
3107
3108/// CheckMemberPointerConversion - Check the member pointer conversion from the
3109/// expression From to the type ToType. This routine checks for ambiguous or
3110/// virtual or inaccessible base-to-derived member pointer conversions
3111/// for which IsMemberPointerConversion has already returned true. It returns
3112/// true and produces a diagnostic if there was an error, or returns false
3113/// otherwise.
3114bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3115 CastKind &Kind,
3116 CXXCastPath &BasePath,
3117 bool IgnoreBaseAccess) {
3118 QualType FromType = From->getType();
3119 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3120 if (!FromPtrType) {
3121 // This must be a null pointer to member pointer conversion
3122 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
3123 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
3124 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
;
3125 Kind = CK_NullToMemberPointer;
3126 return false;
3127 }
3128
3129 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3130 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
3131 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132
3133 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3134 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3135
3136 // FIXME: What about dependent types?
3137 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3137, __PRETTY_FUNCTION__))
;
3138 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3138, __PRETTY_FUNCTION__))
;
3139
3140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3141 /*DetectVirtual=*/true);
3142 bool DerivationOkay =
3143 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3144 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3145, __PRETTY_FUNCTION__))
3145 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146 (void)DerivationOkay;
3147
3148 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3149 getUnqualifiedType())) {
3150 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3151 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3152 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3153 return true;
3154 }
3155
3156 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3157 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3158 << FromClass << ToClass << QualType(VBase, 0)
3159 << From->getSourceRange();
3160 return true;
3161 }
3162
3163 if (!IgnoreBaseAccess)
3164 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3165 Paths.front(),
3166 diag::err_downcast_from_inaccessible_base);
3167
3168 // Must be a base to derived member conversion.
3169 BuildBasePathArray(Paths, BasePath);
3170 Kind = CK_BaseToDerivedMemberPointer;
3171 return false;
3172}
3173
3174/// Determine whether the lifetime conversion between the two given
3175/// qualifiers sets is nontrivial.
3176static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3177 Qualifiers ToQuals) {
3178 // Converting anything to const __unsafe_unretained is trivial.
3179 if (ToQuals.hasConst() &&
3180 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3181 return false;
3182
3183 return true;
3184}
3185
3186/// Perform a single iteration of the loop for checking if a qualification
3187/// conversion is valid.
3188///
3189/// Specifically, check whether any change between the qualifiers of \p
3190/// FromType and \p ToType is permissible, given knowledge about whether every
3191/// outer layer is const-qualified.
3192static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3193 bool CStyle, bool IsTopLevel,
3194 bool &PreviousToQualsIncludeConst,
3195 bool &ObjCLifetimeConversion) {
3196 Qualifiers FromQuals = FromType.getQualifiers();
3197 Qualifiers ToQuals = ToType.getQualifiers();
3198
3199 // Ignore __unaligned qualifier if this type is void.
3200 if (ToType.getUnqualifiedType()->isVoidType())
3201 FromQuals.removeUnaligned();
3202
3203 // Objective-C ARC:
3204 // Check Objective-C lifetime conversions.
3205 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3206 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3207 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3208 ObjCLifetimeConversion = true;
3209 FromQuals.removeObjCLifetime();
3210 ToQuals.removeObjCLifetime();
3211 } else {
3212 // Qualification conversions cannot cast between different
3213 // Objective-C lifetime qualifiers.
3214 return false;
3215 }
3216 }
3217
3218 // Allow addition/removal of GC attributes but not changing GC attributes.
3219 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3220 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3221 FromQuals.removeObjCGCAttr();
3222 ToQuals.removeObjCGCAttr();
3223 }
3224
3225 // -- for every j > 0, if const is in cv 1,j then const is in cv
3226 // 2,j, and similarly for volatile.
3227 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3228 return false;
3229
3230 // If address spaces mismatch:
3231 // - in top level it is only valid to convert to addr space that is a
3232 // superset in all cases apart from C-style casts where we allow
3233 // conversions between overlapping address spaces.
3234 // - in non-top levels it is not a valid conversion.
3235 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3236 (!IsTopLevel ||
3237 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3238 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3239 return false;
3240
3241 // -- if the cv 1,j and cv 2,j are different, then const is in
3242 // every cv for 0 < k < j.
3243 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3244 !PreviousToQualsIncludeConst)
3245 return false;
3246
3247 // Keep track of whether all prior cv-qualifiers in the "to" type
3248 // include const.
3249 PreviousToQualsIncludeConst =
3250 PreviousToQualsIncludeConst && ToQuals.hasConst();
3251 return true;
3252}
3253
3254/// IsQualificationConversion - Determines whether the conversion from
3255/// an rvalue of type FromType to ToType is a qualification conversion
3256/// (C++ 4.4).
3257///
3258/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3259/// when the qualification conversion involves a change in the Objective-C
3260/// object lifetime.
3261bool
3262Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3263 bool CStyle, bool &ObjCLifetimeConversion) {
3264 FromType = Context.getCanonicalType(FromType);
3265 ToType = Context.getCanonicalType(ToType);
3266 ObjCLifetimeConversion = false;
3267
3268 // If FromType and ToType are the same type, this is not a
3269 // qualification conversion.
3270 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3271 return false;
3272
3273 // (C++ 4.4p4):
3274 // A conversion can add cv-qualifiers at levels other than the first
3275 // in multi-level pointers, subject to the following rules: [...]
3276 bool PreviousToQualsIncludeConst = true;
3277 bool UnwrappedAnyPointer = false;
3278 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3279 if (!isQualificationConversionStep(
3280 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3281 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3282 return false;
3283 UnwrappedAnyPointer = true;
3284 }
3285
3286 // We are left with FromType and ToType being the pointee types
3287 // after unwrapping the original FromType and ToType the same number
3288 // of times. If we unwrapped any pointers, and if FromType and
3289 // ToType have the same unqualified type (since we checked
3290 // qualifiers above), then this is a qualification conversion.
3291 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3292}
3293
3294/// - Determine whether this is a conversion from a scalar type to an
3295/// atomic type.
3296///
3297/// If successful, updates \c SCS's second and third steps in the conversion
3298/// sequence to finish the conversion.
3299static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3300 bool InOverloadResolution,
3301 StandardConversionSequence &SCS,
3302 bool CStyle) {
3303 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3304 if (!ToAtomic)
3305 return false;
3306
3307 StandardConversionSequence InnerSCS;
3308 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3309 InOverloadResolution, InnerSCS,
3310 CStyle, /*AllowObjCWritebackConversion=*/false))
3311 return false;
3312
3313 SCS.Second = InnerSCS.Second;
3314 SCS.setToType(1, InnerSCS.getToType(1));
3315 SCS.Third = InnerSCS.Third;
3316 SCS.QualificationIncludesObjCLifetime
3317 = InnerSCS.QualificationIncludesObjCLifetime;
3318 SCS.setToType(2, InnerSCS.getToType(2));
3319 return true;
3320}
3321
3322static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3323 CXXConstructorDecl *Constructor,
3324 QualType Type) {
3325 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3326 if (CtorType->getNumParams() > 0) {
3327 QualType FirstArg = CtorType->getParamType(0);
3328 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3329 return true;
3330 }
3331 return false;
3332}
3333
3334static OverloadingResult
3335IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3336 CXXRecordDecl *To,
3337 UserDefinedConversionSequence &User,
3338 OverloadCandidateSet &CandidateSet,
3339 bool AllowExplicit) {
3340 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3341 for (auto *D : S.LookupConstructors(To)) {
3342 auto Info = getConstructorInfo(D);
3343 if (!Info)
3344 continue;
3345
3346 bool Usable = !Info.Constructor->isInvalidDecl() &&
3347 S.isInitListConstructor(Info.Constructor);
3348 if (Usable) {
3349 // If the first argument is (a reference to) the target type,
3350 // suppress conversions.
3351 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3352 S.Context, Info.Constructor, ToType);
3353 if (Info.ConstructorTmpl)
3354 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3355 /*ExplicitArgs*/ nullptr, From,
3356 CandidateSet, SuppressUserConversions,
3357 /*PartialOverloading*/ false,
3358 AllowExplicit);
3359 else
3360 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3361 CandidateSet, SuppressUserConversions,
3362 /*PartialOverloading*/ false, AllowExplicit);
3363 }
3364 }
3365
3366 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3367
3368 OverloadCandidateSet::iterator Best;
3369 switch (auto Result =
3370 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3371 case OR_Deleted:
3372 case OR_Success: {
3373 // Record the standard conversion we used and the conversion function.
3374 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3375 QualType ThisType = Constructor->getThisType();
3376 // Initializer lists don't have conversions as such.
3377 User.Before.setAsIdentityConversion();
3378 User.HadMultipleCandidates = HadMultipleCandidates;
3379 User.ConversionFunction = Constructor;
3380 User.FoundConversionFunction = Best->FoundDecl;
3381 User.After.setAsIdentityConversion();
3382 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3383 User.After.setAllToTypes(ToType);
3384 return Result;
3385 }
3386
3387 case OR_No_Viable_Function:
3388 return OR_No_Viable_Function;
3389 case OR_Ambiguous:
3390 return OR_Ambiguous;
3391 }
3392
3393 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3393)
;
3394}
3395
3396/// Determines whether there is a user-defined conversion sequence
3397/// (C++ [over.ics.user]) that converts expression From to the type
3398/// ToType. If such a conversion exists, User will contain the
3399/// user-defined conversion sequence that performs such a conversion
3400/// and this routine will return true. Otherwise, this routine returns
3401/// false and User is unspecified.
3402///
3403/// \param AllowExplicit true if the conversion should consider C++0x
3404/// "explicit" conversion functions as well as non-explicit conversion
3405/// functions (C++0x [class.conv.fct]p2).
3406///
3407/// \param AllowObjCConversionOnExplicit true if the conversion should
3408/// allow an extra Objective-C pointer conversion on uses of explicit
3409/// constructors. Requires \c AllowExplicit to also be set.
3410static OverloadingResult
3411IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3412 UserDefinedConversionSequence &User,
3413 OverloadCandidateSet &CandidateSet,
3414 AllowedExplicit AllowExplicit,
3415 bool AllowObjCConversionOnExplicit) {
3416 assert(AllowExplicit != AllowedExplicit::None ||((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3417, __PRETTY_FUNCTION__))
3417 !AllowObjCConversionOnExplicit)((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3417, __PRETTY_FUNCTION__))
;
3418 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3419
3420 // Whether we will only visit constructors.
3421 bool ConstructorsOnly = false;
3422
3423 // If the type we are conversion to is a class type, enumerate its
3424 // constructors.
3425 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3426 // C++ [over.match.ctor]p1:
3427 // When objects of class type are direct-initialized (8.5), or
3428 // copy-initialized from an expression of the same or a
3429 // derived class type (8.5), overload resolution selects the
3430 // constructor. [...] For copy-initialization, the candidate
3431 // functions are all the converting constructors (12.3.1) of
3432 // that class. The argument list is the expression-list within
3433 // the parentheses of the initializer.
3434 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3435 (From->getType()->getAs<RecordType>() &&
3436 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3437 ConstructorsOnly = true;
3438
3439 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3440 // We're not going to find any constructors.
3441 } else if (CXXRecordDecl *ToRecordDecl
3442 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3443
3444 Expr **Args = &From;
3445 unsigned NumArgs = 1;
3446 bool ListInitializing = false;
3447 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3448 // But first, see if there is an init-list-constructor that will work.
3449 OverloadingResult Result = IsInitializerListConstructorConversion(
3450 S, From, ToType, ToRecordDecl, User, CandidateSet,
3451 AllowExplicit == AllowedExplicit::All);
3452 if (Result != OR_No_Viable_Function)
3453 return Result;
3454 // Never mind.
3455 CandidateSet.clear(
3456 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3457
3458 // If we're list-initializing, we pass the individual elements as
3459 // arguments, not the entire list.
3460 Args = InitList->getInits();
3461 NumArgs = InitList->getNumInits();
3462 ListInitializing = true;
3463 }
3464
3465 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3466 auto Info = getConstructorInfo(D);
3467 if (!Info)
3468 continue;
3469
3470 bool Usable = !Info.Constructor->isInvalidDecl();
3471 if (!ListInitializing)
3472 Usable = Usable && Info.Constructor->isConvertingConstructor(
3473 /*AllowExplicit*/ true);
3474 if (Usable) {
3475 bool SuppressUserConversions = !ConstructorsOnly;
3476 if (SuppressUserConversions && ListInitializing) {
3477 SuppressUserConversions = false;
3478 if (NumArgs == 1) {
3479 // If the first argument is (a reference to) the target type,
3480 // suppress conversions.
3481 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3482 S.Context, Info.Constructor, ToType);
3483 }
3484 }
3485 if (Info.ConstructorTmpl)
3486 S.AddTemplateOverloadCandidate(
3487 Info.ConstructorTmpl, Info.FoundDecl,
3488 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3489 CandidateSet, SuppressUserConversions,
3490 /*PartialOverloading*/ false,
3491 AllowExplicit == AllowedExplicit::All);
3492 else
3493 // Allow one user-defined conversion when user specifies a
3494 // From->ToType conversion via an static cast (c-style, etc).
3495 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3496 llvm::makeArrayRef(Args, NumArgs),
3497 CandidateSet, SuppressUserConversions,
3498 /*PartialOverloading*/ false,
3499 AllowExplicit == AllowedExplicit::All);
3500 }
3501 }
3502 }
3503 }
3504
3505 // Enumerate conversion functions, if we're allowed to.
3506 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3507 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3508 // No conversion functions from incomplete types.
3509 } else if (const RecordType *FromRecordType =
3510 From->getType()->getAs<RecordType>()) {
3511 if (CXXRecordDecl *FromRecordDecl
3512 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3513 // Add all of the conversion functions as candidates.
3514 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3515 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3516 DeclAccessPair FoundDecl = I.getPair();
3517 NamedDecl *D = FoundDecl.getDecl();
3518 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3519 if (isa<UsingShadowDecl>(D))
3520 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3521
3522 CXXConversionDecl *Conv;
3523 FunctionTemplateDecl *ConvTemplate;
3524 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3525 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3526 else
3527 Conv = cast<CXXConversionDecl>(D);
3528
3529 if (ConvTemplate)
3530 S.AddTemplateConversionCandidate(
3531 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3532 CandidateSet, AllowObjCConversionOnExplicit,
3533 AllowExplicit != AllowedExplicit::None);
3534 else
3535 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3536 CandidateSet, AllowObjCConversionOnExplicit,
3537 AllowExplicit != AllowedExplicit::None);
3538 }
3539 }
3540 }
3541
3542 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3543
3544 OverloadCandidateSet::iterator Best;
3545 switch (auto Result =
3546 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3547 case OR_Success:
3548 case OR_Deleted:
3549 // Record the standard conversion we used and the conversion function.
3550 if (CXXConstructorDecl *Constructor
3551 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3552 // C++ [over.ics.user]p1:
3553 // If the user-defined conversion is specified by a
3554 // constructor (12.3.1), the initial standard conversion
3555 // sequence converts the source type to the type required by
3556 // the argument of the constructor.
3557 //
3558 QualType ThisType = Constructor->getThisType();
3559 if (isa<InitListExpr>(From)) {
3560 // Initializer lists don't have conversions as such.
3561 User.Before.setAsIdentityConversion();
3562 } else {
3563 if (Best->Conversions[0].isEllipsis())
3564 User.EllipsisConversion = true;
3565 else {
3566 User.Before = Best->Conversions[0].Standard;
3567 User.EllipsisConversion = false;
3568 }
3569 }
3570 User.HadMultipleCandidates = HadMultipleCandidates;
3571 User.ConversionFunction = Constructor;
3572 User.FoundConversionFunction = Best->FoundDecl;
3573 User.After.setAsIdentityConversion();
3574 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3575 User.After.setAllToTypes(ToType);
3576 return Result;
3577 }
3578 if (CXXConversionDecl *Conversion
3579 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3580 // C++ [over.ics.user]p1:
3581 //
3582 // [...] If the user-defined conversion is specified by a
3583 // conversion function (12.3.2), the initial standard
3584 // conversion sequence converts the source type to the
3585 // implicit object parameter of the conversion function.
3586 User.Before = Best->Conversions[0].Standard;
3587 User.HadMultipleCandidates = HadMultipleCandidates;
3588 User.ConversionFunction = Conversion;
3589 User.FoundConversionFunction = Best->FoundDecl;
3590 User.EllipsisConversion = false;
3591
3592 // C++ [over.ics.user]p2:
3593 // The second standard conversion sequence converts the
3594 // result of the user-defined conversion to the target type
3595 // for the sequence. Since an implicit conversion sequence
3596 // is an initialization, the special rules for
3597 // initialization by user-defined conversion apply when
3598 // selecting the best user-defined conversion for a
3599 // user-defined conversion sequence (see 13.3.3 and
3600 // 13.3.3.1).
3601 User.After = Best->FinalConversion;
3602 return Result;
3603 }
3604 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3604)
;
3605
3606 case OR_No_Viable_Function:
3607 return OR_No_Viable_Function;
3608
3609 case OR_Ambiguous:
3610 return OR_Ambiguous;
3611 }
3612
3613 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 3613)
;
3614}
3615
3616bool
3617Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3618 ImplicitConversionSequence ICS;
3619 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3620 OverloadCandidateSet::CSK_Normal);
3621 OverloadingResult OvResult =
3622 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3623 CandidateSet, AllowedExplicit::None, false);
3624
3625 if (!(OvResult == OR_Ambiguous ||
3626 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3627 return false;
3628
3629 auto Cands = CandidateSet.CompleteCandidates(
3630 *this,
3631 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3632 From);
3633 if (OvResult == OR_Ambiguous)
3634 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3635 << From->getType() << ToType << From->getSourceRange();
3636 else { // OR_No_Viable_Function && !CandidateSet.empty()
3637 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3638 diag::err_typecheck_nonviable_condition_incomplete,
3639 From->getType(), From->getSourceRange()))
3640 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3641 << false << From->getType() << From->getSourceRange() << ToType;
3642 }
3643
3644 CandidateSet.NoteCandidates(
3645 *this, From, Cands);
3646 return true;
3647}
3648
3649// Helper for compareConversionFunctions that gets the FunctionType that the
3650// conversion-operator return value 'points' to, or nullptr.
3651static const FunctionType *
3652getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3653 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3654 const PointerType *RetPtrTy =
3655 ConvFuncTy->getReturnType()->getAs<PointerType>();
3656
3657 if (!RetPtrTy)
3658 return nullptr;
3659
3660 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3661}
3662
3663/// Compare the user-defined conversion functions or constructors
3664/// of two user-defined conversion sequences to determine whether any ordering
3665/// is possible.
3666static ImplicitConversionSequence::CompareKind
3667compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3668 FunctionDecl *Function2) {
3669 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3670 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3671 if (!Conv1 || !Conv2)
3672 return ImplicitConversionSequence::Indistinguishable;
3673
3674 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3675 return ImplicitConversionSequence::Indistinguishable;
3676
3677 // Objective-C++:
3678 // If both conversion functions are implicitly-declared conversions from
3679 // a lambda closure type to a function pointer and a block pointer,
3680 // respectively, always prefer the conversion to a function pointer,
3681 // because the function pointer is more lightweight and is more likely
3682 // to keep code working.
3683 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3684 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3685 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3686 if (Block1 != Block2)
3687 return Block1 ? ImplicitConversionSequence::Worse
3688 : ImplicitConversionSequence::Better;
3689 }
3690
3691 // In order to support multiple calling conventions for the lambda conversion
3692 // operator (such as when the free and member function calling convention is
3693 // different), prefer the 'free' mechanism, followed by the calling-convention
3694 // of operator(). The latter is in place to support the MSVC-like solution of
3695 // defining ALL of the possible conversions in regards to calling-convention.
3696 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3697 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3698
3699 if (Conv1FuncRet && Conv2FuncRet &&
3700 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3701 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3702 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3703
3704 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3705 const FunctionProtoType *CallOpProto =
3706 CallOp->getType()->getAs<FunctionProtoType>();
3707
3708 CallingConv CallOpCC =
3709 CallOp->getType()->castAs<FunctionType>()->getCallConv();
3710 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3711 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3712 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3713 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3714
3715 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3716 for (CallingConv CC : PrefOrder) {
3717 if (Conv1CC == CC)
3718 return ImplicitConversionSequence::Better;
3719 if (Conv2CC == CC)
3720 return ImplicitConversionSequence::Worse;
3721 }
3722 }
3723
3724 return ImplicitConversionSequence::Indistinguishable;
3725}
3726
3727static bool hasDeprecatedStringLiteralToCharPtrConversion(
3728 const ImplicitConversionSequence &ICS) {
3729 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3730 (ICS.isUserDefined() &&
3731 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3732}
3733
3734/// CompareImplicitConversionSequences - Compare two implicit
3735/// conversion sequences to determine whether one is better than the
3736/// other or if they are indistinguishable (C++ 13.3.3.2).
3737static ImplicitConversionSequence::CompareKind
3738CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3739 const ImplicitConversionSequence& ICS1,
3740 const ImplicitConversionSequence& ICS2)
3741{
3742 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3743 // conversion sequences (as defined in 13.3.3.1)
3744 // -- a standard conversion sequence (13.3.3.1.1) is a better
3745 // conversion sequence than a user-defined conversion sequence or
3746 // an ellipsis conversion sequence, and
3747 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3748 // conversion sequence than an ellipsis conversion sequence
3749 // (13.3.3.1.3).
3750 //
3751 // C++0x [over.best.ics]p10:
3752 // For the purpose of ranking implicit conversion sequences as
3753 // described in 13.3.3.2, the ambiguous conversion sequence is
3754 // treated as a user-defined sequence that is indistinguishable
3755 // from any other user-defined conversion sequence.
3756
3757 // String literal to 'char *' conversion has been deprecated in C++03. It has
3758 // been removed from C++11. We still accept this conversion, if it happens at
3759 // the best viable function. Otherwise, this conversion is considered worse
3760 // than ellipsis conversion. Consider this as an extension; this is not in the
3761 // standard. For example:
3762 //
3763 // int &f(...); // #1
3764 // void f(char*); // #2
3765 // void g() { int &r = f("foo"); }
3766 //
3767 // In C++03, we pick #2 as the best viable function.
3768 // In C++11, we pick #1 as the best viable function, because ellipsis
3769 // conversion is better than string-literal to char* conversion (since there
3770 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3771 // convert arguments, #2 would be the best viable function in C++11.
3772 // If the best viable function has this conversion, a warning will be issued
3773 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3774
3775 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3776 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3777 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3778 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3779 ? ImplicitConversionSequence::Worse
3780 : ImplicitConversionSequence::Better;
3781
3782 if (ICS1.getKindRank() < ICS2.getKindRank())
3783 return ImplicitConversionSequence::Better;
3784 if (ICS2.getKindRank() < ICS1.getKindRank())
3785 return ImplicitConversionSequence::Worse;
3786
3787 // The following checks require both conversion sequences to be of
3788 // the same kind.
3789 if (ICS1.getKind() != ICS2.getKind())
3790 return ImplicitConversionSequence::Indistinguishable;
3791
3792 ImplicitConversionSequence::CompareKind Result =
3793 ImplicitConversionSequence::Indistinguishable;
3794
3795 // Two implicit conversion sequences of the same form are
3796 // indistinguishable conversion sequences unless one of the
3797 // following rules apply: (C++ 13.3.3.2p3):
3798
3799 // List-initialization sequence L1 is a better conversion sequence than
3800 // list-initialization sequence L2 if:
3801 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3802 // if not that,
3803 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3804 // and N1 is smaller than N2.,
3805 // even if one of the other rules in this paragraph would otherwise apply.
3806 if (!ICS1.isBad()) {
3807 if (ICS1.isStdInitializerListElement() &&
3808 !ICS2.isStdInitializerListElement())
3809 return ImplicitConversionSequence::Better;
3810 if (!ICS1.isStdInitializerListElement() &&
3811 ICS2.isStdInitializerListElement())
3812 return ImplicitConversionSequence::Worse;
3813 }
3814
3815 if (ICS1.isStandard())
3816 // Standard conversion sequence S1 is a better conversion sequence than
3817 // standard conversion sequence S2 if [...]
3818 Result = CompareStandardConversionSequences(S, Loc,
3819 ICS1.Standard, ICS2.Standard);
3820 else if (ICS1.isUserDefined()) {
3821 // User-defined conversion sequence U1 is a better conversion
3822 // sequence than another user-defined conversion sequence U2 if
3823 // they contain the same user-defined conversion function or
3824 // constructor and if the second standard conversion sequence of
3825 // U1 is better than the second standard conversion sequence of
3826 // U2 (C++ 13.3.3.2p3).
3827 if (ICS1.UserDefined.ConversionFunction ==
3828 ICS2.UserDefined.ConversionFunction)
3829 Result = CompareStandardConversionSequences(S, Loc,
3830 ICS1.UserDefined.After,
3831 ICS2.UserDefined.After);
3832 else
3833 Result = compareConversionFunctions(S,
3834 ICS1.UserDefined.ConversionFunction,
3835 ICS2.UserDefined.ConversionFunction);
3836 }
3837
3838 return Result;
3839}
3840
3841// Per 13.3.3.2p3, compare the given standard conversion sequences to
3842// determine if one is a proper subset of the other.
3843static ImplicitConversionSequence::CompareKind
3844compareStandardConversionSubsets(ASTContext &Context,
3845 const StandardConversionSequence& SCS1,
3846 const StandardConversionSequence& SCS2) {
3847 ImplicitConversionSequence::CompareKind Result
3848 = ImplicitConversionSequence::Indistinguishable;
3849
3850 // the identity conversion sequence is considered to be a subsequence of
3851 // any non-identity conversion sequence
3852 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3853 return ImplicitConversionSequence::Better;
3854 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3855 return ImplicitConversionSequence::Worse;
3856
3857 if (SCS1.Second != SCS2.Second) {
3858 if (SCS1.Second == ICK_Identity)
3859 Result = ImplicitConversionSequence::Better;
3860 else if (SCS2.Second == ICK_Identity)
3861 Result = ImplicitConversionSequence::Worse;
3862 else
3863 return ImplicitConversionSequence::Indistinguishable;
3864 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3865 return ImplicitConversionSequence::Indistinguishable;
3866
3867 if (SCS1.Third == SCS2.Third) {
3868 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3869 : ImplicitConversionSequence::Indistinguishable;
3870 }
3871
3872 if (SCS1.Third == ICK_Identity)
3873 return Result == ImplicitConversionSequence::Worse
3874 ? ImplicitConversionSequence::Indistinguishable
3875 : ImplicitConversionSequence::Better;
3876
3877 if (SCS2.Third == ICK_Identity)
3878 return Result == ImplicitConversionSequence::Better
3879 ? ImplicitConversionSequence::Indistinguishable
3880 : ImplicitConversionSequence::Worse;
3881
3882 return ImplicitConversionSequence::Indistinguishable;
3883}
3884
3885/// Determine whether one of the given reference bindings is better
3886/// than the other based on what kind of bindings they are.
3887static bool
3888isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3889 const StandardConversionSequence &SCS2) {
3890 // C++0x [over.ics.rank]p3b4:
3891 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3892 // implicit object parameter of a non-static member function declared
3893 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3894 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3895 // lvalue reference to a function lvalue and S2 binds an rvalue
3896 // reference*.
3897 //
3898 // FIXME: Rvalue references. We're going rogue with the above edits,
3899 // because the semantics in the current C++0x working paper (N3225 at the
3900 // time of this writing) break the standard definition of std::forward
3901 // and std::reference_wrapper when dealing with references to functions.
3902 // Proposed wording changes submitted to CWG for consideration.
3903 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3904 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3905 return false;
3906
3907 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3908 SCS2.IsLvalueReference) ||
3909 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3910 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3911}
3912
3913enum class FixedEnumPromotion {
3914 None,
3915 ToUnderlyingType,
3916 ToPromotedUnderlyingType
3917};
3918
3919/// Returns kind of fixed enum promotion the \a SCS uses.
3920static FixedEnumPromotion
3921getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3922
3923 if (SCS.Second != ICK_Integral_Promotion)
3924 return FixedEnumPromotion::None;
3925
3926 QualType FromType = SCS.getFromType();
3927 if (!FromType->isEnumeralType())
3928 return FixedEnumPromotion::None;
3929
3930 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3931 if (!Enum->isFixed())
3932 return FixedEnumPromotion::None;
3933
3934 QualType UnderlyingType = Enum->getIntegerType();
3935 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3936 return FixedEnumPromotion::ToUnderlyingType;
3937
3938 return FixedEnumPromotion::ToPromotedUnderlyingType;
3939}
3940
3941/// CompareStandardConversionSequences - Compare two standard
3942/// conversion sequences to determine whether one is better than the
3943/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3944static ImplicitConversionSequence::CompareKind
3945CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3946 const StandardConversionSequence& SCS1,
3947 const StandardConversionSequence& SCS2)
3948{
3949 // Standard conversion sequence S1 is a better conversion sequence
3950 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3951
3952 // -- S1 is a proper subsequence of S2 (comparing the conversion
3953 // sequences in the canonical form defined by 13.3.3.1.1,
3954 // excluding any Lvalue Transformation; the identity conversion
3955 // sequence is considered to be a subsequence of any
3956 // non-identity conversion sequence) or, if not that,
3957 if (ImplicitConversionSequence::CompareKind CK
3958 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3959 return CK;
3960
3961 // -- the rank of S1 is better than the rank of S2 (by the rules
3962 // defined below), or, if not that,
3963 ImplicitConversionRank Rank1 = SCS1.getRank();
3964 ImplicitConversionRank Rank2 = SCS2.getRank();
3965 if (Rank1 < Rank2)
3966 return ImplicitConversionSequence::Better;
3967 else if (Rank2 < Rank1)
3968 return ImplicitConversionSequence::Worse;
3969
3970 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3971 // are indistinguishable unless one of the following rules
3972 // applies:
3973
3974 // A conversion that is not a conversion of a pointer, or
3975 // pointer to member, to bool is better than another conversion
3976 // that is such a conversion.
3977 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3978 return SCS2.isPointerConversionToBool()
3979 ? ImplicitConversionSequence::Better
3980 : ImplicitConversionSequence::Worse;
3981
3982 // C++14 [over.ics.rank]p4b2:
3983 // This is retroactively applied to C++11 by CWG 1601.
3984 //
3985 // A conversion that promotes an enumeration whose underlying type is fixed
3986 // to its underlying type is better than one that promotes to the promoted
3987 // underlying type, if the two are different.
3988 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3989 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3990 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3991 FEP1 != FEP2)
3992 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3993 ? ImplicitConversionSequence::Better
3994 : ImplicitConversionSequence::Worse;
3995
3996 // C++ [over.ics.rank]p4b2:
3997 //
3998 // If class B is derived directly or indirectly from class A,
3999 // conversion of B* to A* is better than conversion of B* to
4000 // void*, and conversion of A* to void* is better than conversion
4001 // of B* to void*.
4002 bool SCS1ConvertsToVoid
4003 = SCS1.isPointerConversionToVoidPointer(S.Context);
4004 bool SCS2ConvertsToVoid
4005 = SCS2.isPointerConversionToVoidPointer(S.Context);
4006 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4007 // Exactly one of the conversion sequences is a conversion to
4008 // a void pointer; it's the worse conversion.
4009 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4010 : ImplicitConversionSequence::Worse;
4011 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4012 // Neither conversion sequence converts to a void pointer; compare
4013 // their derived-to-base conversions.
4014 if (ImplicitConversionSequence::CompareKind DerivedCK
4015 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4016 return DerivedCK;
4017 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4018 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4019 // Both conversion sequences are conversions to void
4020 // pointers. Compare the source types to determine if there's an
4021 // inheritance relationship in their sources.
4022 QualType FromType1 = SCS1.getFromType();
4023 QualType FromType2 = SCS2.getFromType();
4024
4025 // Adjust the types we're converting from via the array-to-pointer
4026 // conversion, if we need to.
4027 if (SCS1.First == ICK_Array_To_Pointer)
4028 FromType1 = S.Context.getArrayDecayedType(FromType1);
4029 if (SCS2.First == ICK_Array_To_Pointer)
4030 FromType2 = S.Context.getArrayDecayedType(FromType2);
4031
4032 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4033 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4034
4035 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4036 return ImplicitConversionSequence::Better;
4037 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4038 return ImplicitConversionSequence::Worse;
4039
4040 // Objective-C++: If one interface is more specific than the
4041 // other, it is the better one.
4042 const ObjCObjectPointerType* FromObjCPtr1
4043 = FromType1->getAs<ObjCObjectPointerType>();
4044 const ObjCObjectPointerType* FromObjCPtr2
4045 = FromType2->getAs<ObjCObjectPointerType>();
4046 if (FromObjCPtr1 && FromObjCPtr2) {
4047 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4048 FromObjCPtr2);
4049 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4050 FromObjCPtr1);
4051 if (AssignLeft != AssignRight) {
4052 return AssignLeft? ImplicitConversionSequence::Better
4053 : ImplicitConversionSequence::Worse;
4054 }
4055 }
4056 }
4057
4058 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4059 // Check for a better reference binding based on the kind of bindings.
4060 if (isBetterReferenceBindingKind(SCS1, SCS2))
4061 return ImplicitConversionSequence::Better;
4062 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4063 return ImplicitConversionSequence::Worse;
4064 }
4065
4066 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4067 // bullet 3).
4068 if (ImplicitConversionSequence::CompareKind QualCK
4069 = CompareQualificationConversions(S, SCS1, SCS2))
4070 return QualCK;
4071
4072 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4073 // C++ [over.ics.rank]p3b4:
4074 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4075 // which the references refer are the same type except for
4076 // top-level cv-qualifiers, and the type to which the reference
4077 // initialized by S2 refers is more cv-qualified than the type
4078 // to which the reference initialized by S1 refers.
4079 QualType T1 = SCS1.getToType(2);
4080 QualType T2 = SCS2.getToType(2);
4081 T1 = S.Context.getCanonicalType(T1);
4082 T2 = S.Context.getCanonicalType(T2);
4083 Qualifiers T1Quals, T2Quals;
4084 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4085 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4086 if (UnqualT1 == UnqualT2) {
4087 // Objective-C++ ARC: If the references refer to objects with different
4088 // lifetimes, prefer bindings that don't change lifetime.
4089 if (SCS1.ObjCLifetimeConversionBinding !=
4090 SCS2.ObjCLifetimeConversionBinding) {
4091 return SCS1.ObjCLifetimeConversionBinding
4092 ? ImplicitConversionSequence::Worse
4093 : ImplicitConversionSequence::Better;
4094 }
4095
4096 // If the type is an array type, promote the element qualifiers to the
4097 // type for comparison.
4098 if (isa<ArrayType>(T1) && T1Quals)
4099 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4100 if (isa<ArrayType>(T2) && T2Quals)
4101 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4102 if (T2.isMoreQualifiedThan(T1))
4103 return ImplicitConversionSequence::Better;
4104 if (T1.isMoreQualifiedThan(T2))
4105 return ImplicitConversionSequence::Worse;
4106 }
4107 }
4108
4109 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4110 // floating-to-integral conversion if the integral conversion
4111 // is between types of the same size.
4112 // For example:
4113 // void f(float);
4114 // void f(int);
4115 // int main {
4116 // long a;
4117 // f(a);
4118 // }
4119 // Here, MSVC will call f(int) instead of generating a compile error
4120 // as clang will do in standard mode.
4121 if (S.getLangOpts().MSVCCompat &&
4122 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4123 SCS1.Second == ICK_Integral_Conversion &&
4124 SCS2.Second == ICK_Floating_Integral &&
4125 S.Context.getTypeSize(SCS1.getFromType()) ==
4126 S.Context.getTypeSize(SCS1.getToType(2)))
4127 return ImplicitConversionSequence::Better;
4128
4129 // Prefer a compatible vector conversion over a lax vector conversion
4130 // For example:
4131 //
4132 // typedef float __v4sf __attribute__((__vector_size__(16)));
4133 // void f(vector float);
4134 // void f(vector signed int);
4135 // int main() {
4136 // __v4sf a;
4137 // f(a);
4138 // }
4139 // Here, we'd like to choose f(vector float) and not
4140 // report an ambiguous call error
4141 if (SCS1.Second == ICK_Vector_Conversion &&
4142 SCS2.Second == ICK_Vector_Conversion) {
4143 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4144 SCS1.getFromType(), SCS1.getToType(2));
4145 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4146 SCS2.getFromType(), SCS2.getToType(2));
4147
4148 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4149 return SCS1IsCompatibleVectorConversion
4150 ? ImplicitConversionSequence::Better
4151 : ImplicitConversionSequence::Worse;
4152 }
4153
4154 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4155 SCS2.Second == ICK_SVE_Vector_Conversion) {
4156 bool SCS1IsCompatibleSVEVectorConversion =
4157 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4158 bool SCS2IsCompatibleSVEVectorConversion =
4159 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4160
4161 if (SCS1IsCompatibleSVEVectorConversion !=
4162 SCS2IsCompatibleSVEVectorConversion)
4163 return SCS1IsCompatibleSVEVectorConversion
4164 ? ImplicitConversionSequence::Better
4165 : ImplicitConversionSequence::Worse;
4166 }
4167
4168 return ImplicitConversionSequence::Indistinguishable;
4169}
4170
4171/// CompareQualificationConversions - Compares two standard conversion
4172/// sequences to determine whether they can be ranked based on their
4173/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4174static ImplicitConversionSequence::CompareKind
4175CompareQualificationConversions(Sema &S,
4176 const StandardConversionSequence& SCS1,
4177 const StandardConversionSequence& SCS2) {
4178 // C++ 13.3.3.2p3:
4179 // -- S1 and S2 differ only in their qualification conversion and
4180 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4181 // cv-qualification signature of type T1 is a proper subset of
4182 // the cv-qualification signature of type T2, and S1 is not the
4183 // deprecated string literal array-to-pointer conversion (4.2).
4184 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4185 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4186 return ImplicitConversionSequence::Indistinguishable;
4187
4188 // FIXME: the example in the standard doesn't use a qualification
4189 // conversion (!)
4190 QualType T1 = SCS1.getToType(2);
4191 QualType T2 = SCS2.getToType(2);
4192 T1 = S.Context.getCanonicalType(T1);
4193 T2 = S.Context.getCanonicalType(T2);
4194 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4194, __PRETTY_FUNCTION__))
;
4195 Qualifiers T1Quals, T2Quals;
4196 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4197 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4198
4199 // If the types are the same, we won't learn anything by unwrapping
4200 // them.
4201 if (UnqualT1 == UnqualT2)
4202 return ImplicitConversionSequence::Indistinguishable;
4203
4204 ImplicitConversionSequence::CompareKind Result
4205 = ImplicitConversionSequence::Indistinguishable;
4206
4207 // Objective-C++ ARC:
4208 // Prefer qualification conversions not involving a change in lifetime
4209 // to qualification conversions that do not change lifetime.
4210 if (SCS1.QualificationIncludesObjCLifetime !=
4211 SCS2.QualificationIncludesObjCLifetime) {
4212 Result = SCS1.QualificationIncludesObjCLifetime
4213 ? ImplicitConversionSequence::Worse
4214 : ImplicitConversionSequence::Better;
4215 }
4216
4217 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4218 // Within each iteration of the loop, we check the qualifiers to
4219 // determine if this still looks like a qualification
4220 // conversion. Then, if all is well, we unwrap one more level of
4221 // pointers or pointers-to-members and do it all again
4222 // until there are no more pointers or pointers-to-members left
4223 // to unwrap. This essentially mimics what
4224 // IsQualificationConversion does, but here we're checking for a
4225 // strict subset of qualifiers.
4226 if (T1.getQualifiers().withoutObjCLifetime() ==
4227 T2.getQualifiers().withoutObjCLifetime())
4228 // The qualifiers are the same, so this doesn't tell us anything
4229 // about how the sequences rank.
4230 // ObjC ownership quals are omitted above as they interfere with
4231 // the ARC overload rule.
4232 ;
4233 else if (T2.isMoreQualifiedThan(T1)) {
4234 // T1 has fewer qualifiers, so it could be the better sequence.
4235 if (Result == ImplicitConversionSequence::Worse)
4236 // Neither has qualifiers that are a subset of the other's
4237 // qualifiers.
4238 return ImplicitConversionSequence::Indistinguishable;
4239
4240 Result = ImplicitConversionSequence::Better;
4241 } else if (T1.isMoreQualifiedThan(T2)) {
4242 // T2 has fewer qualifiers, so it could be the better sequence.
4243 if (Result == ImplicitConversionSequence::Better)
4244 // Neither has qualifiers that are a subset of the other's
4245 // qualifiers.
4246 return ImplicitConversionSequence::Indistinguishable;
4247
4248 Result = ImplicitConversionSequence::Worse;
4249 } else {
4250 // Qualifiers are disjoint.
4251 return ImplicitConversionSequence::Indistinguishable;
4252 }
4253
4254 // If the types after this point are equivalent, we're done.
4255 if (S.Context.hasSameUnqualifiedType(T1, T2))
4256 break;
4257 }
4258
4259 // Check that the winning standard conversion sequence isn't using
4260 // the deprecated string literal array to pointer conversion.
4261 switch (Result) {
4262 case ImplicitConversionSequence::Better:
4263 if (SCS1.DeprecatedStringLiteralToCharPtr)
4264 Result = ImplicitConversionSequence::Indistinguishable;
4265 break;
4266
4267 case ImplicitConversionSequence::Indistinguishable:
4268 break;
4269
4270 case ImplicitConversionSequence::Worse:
4271 if (SCS2.DeprecatedStringLiteralToCharPtr)
4272 Result = ImplicitConversionSequence::Indistinguishable;
4273 break;
4274 }
4275
4276 return Result;
4277}
4278
4279/// CompareDerivedToBaseConversions - Compares two standard conversion
4280/// sequences to determine whether they can be ranked based on their
4281/// various kinds of derived-to-base conversions (C++
4282/// [over.ics.rank]p4b3). As part of these checks, we also look at
4283/// conversions between Objective-C interface types.
4284static ImplicitConversionSequence::CompareKind
4285CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4286 const StandardConversionSequence& SCS1,
4287 const StandardConversionSequence& SCS2) {
4288 QualType FromType1 = SCS1.getFromType();
4289 QualType ToType1 = SCS1.getToType(1);
4290 QualType FromType2 = SCS2.getFromType();
4291 QualType ToType2 = SCS2.getToType(1);
4292
4293 // Adjust the types we're converting from via the array-to-pointer
4294 // conversion, if we need to.
4295 if (SCS1.First == ICK_Array_To_Pointer)
4296 FromType1 = S.Context.getArrayDecayedType(FromType1);
4297 if (SCS2.First == ICK_Array_To_Pointer)
4298 FromType2 = S.Context.getArrayDecayedType(FromType2);
4299
4300 // Canonicalize all of the types.
4301 FromType1 = S.Context.getCanonicalType(FromType1);
4302 ToType1 = S.Context.getCanonicalType(ToType1);
4303 FromType2 = S.Context.getCanonicalType(FromType2);
4304 ToType2 = S.Context.getCanonicalType(ToType2);
4305
4306 // C++ [over.ics.rank]p4b3:
4307 //
4308 // If class B is derived directly or indirectly from class A and
4309 // class C is derived directly or indirectly from B,
4310 //
4311 // Compare based on pointer conversions.
4312 if (SCS1.Second == ICK_Pointer_Conversion &&
4313 SCS2.Second == ICK_Pointer_Conversion &&
4314 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4315 FromType1->isPointerType() && FromType2->isPointerType() &&
4316 ToType1->isPointerType() && ToType2->isPointerType()) {
4317 QualType FromPointee1 =
4318 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4319 QualType ToPointee1 =
4320 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4321 QualType FromPointee2 =
4322 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4323 QualType ToPointee2 =
4324 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4325
4326 // -- conversion of C* to B* is better than conversion of C* to A*,
4327 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4328 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4329 return ImplicitConversionSequence::Better;
4330 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4331 return ImplicitConversionSequence::Worse;
4332 }
4333
4334 // -- conversion of B* to A* is better than conversion of C* to A*,
4335 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4336 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4337 return ImplicitConversionSequence::Better;
4338 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4339 return ImplicitConversionSequence::Worse;
4340 }
4341 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4342 SCS2.Second == ICK_Pointer_Conversion) {
4343 const ObjCObjectPointerType *FromPtr1
4344 = FromType1->getAs<ObjCObjectPointerType>();
4345 const ObjCObjectPointerType *FromPtr2
4346 = FromType2->getAs<ObjCObjectPointerType>();
4347 const ObjCObjectPointerType *ToPtr1
4348 = ToType1->getAs<ObjCObjectPointerType>();
4349 const ObjCObjectPointerType *ToPtr2
4350 = ToType2->getAs<ObjCObjectPointerType>();
4351
4352 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4353 // Apply the same conversion ranking rules for Objective-C pointer types
4354 // that we do for C++ pointers to class types. However, we employ the
4355 // Objective-C pseudo-subtyping relationship used for assignment of
4356 // Objective-C pointer types.
4357 bool FromAssignLeft
4358 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4359 bool FromAssignRight
4360 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4361 bool ToAssignLeft
4362 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4363 bool ToAssignRight
4364 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4365
4366 // A conversion to an a non-id object pointer type or qualified 'id'
4367 // type is better than a conversion to 'id'.
4368 if (ToPtr1->isObjCIdType() &&
4369 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4370 return ImplicitConversionSequence::Worse;
4371 if (ToPtr2->isObjCIdType() &&
4372 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4373 return ImplicitConversionSequence::Better;
4374
4375 // A conversion to a non-id object pointer type is better than a
4376 // conversion to a qualified 'id' type
4377 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4378 return ImplicitConversionSequence::Worse;
4379 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4380 return ImplicitConversionSequence::Better;
4381
4382 // A conversion to an a non-Class object pointer type or qualified 'Class'
4383 // type is better than a conversion to 'Class'.
4384 if (ToPtr1->isObjCClassType() &&
4385 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4386 return ImplicitConversionSequence::Worse;
4387 if (ToPtr2->isObjCClassType() &&
4388 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4389 return ImplicitConversionSequence::Better;
4390
4391 // A conversion to a non-Class object pointer type is better than a
4392 // conversion to a qualified 'Class' type.
4393 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4394 return ImplicitConversionSequence::Worse;
4395 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4396 return ImplicitConversionSequence::Better;
4397
4398 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4399 if (S.Context.hasSameType(FromType1, FromType2) &&
4400 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4401 (ToAssignLeft != ToAssignRight)) {
4402 if (FromPtr1->isSpecialized()) {
4403 // "conversion of B<A> * to B * is better than conversion of B * to
4404 // C *.
4405 bool IsFirstSame =
4406 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4407 bool IsSecondSame =
4408 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4409 if (IsFirstSame) {
4410 if (!IsSecondSame)
4411 return ImplicitConversionSequence::Better;
4412 } else if (IsSecondSame)
4413 return ImplicitConversionSequence::Worse;
4414 }
4415 return ToAssignLeft? ImplicitConversionSequence::Worse
4416 : ImplicitConversionSequence::Better;
4417 }
4418
4419 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4420 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4421 (FromAssignLeft != FromAssignRight))
4422 return FromAssignLeft? ImplicitConversionSequence::Better
4423 : ImplicitConversionSequence::Worse;
4424 }
4425 }
4426
4427 // Ranking of member-pointer types.
4428 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4429 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4430 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4431 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4432 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4433 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4434 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4435 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4436 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4437 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4438 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4439 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4440 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4441 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4442 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4443 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4444 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4445 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4446 return ImplicitConversionSequence::Worse;
4447 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4448 return ImplicitConversionSequence::Better;
4449 }
4450 // conversion of B::* to C::* is better than conversion of A::* to C::*
4451 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4452 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4453 return ImplicitConversionSequence::Better;
4454 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4455 return ImplicitConversionSequence::Worse;
4456 }
4457 }
4458
4459 if (SCS1.Second == ICK_Derived_To_Base) {
4460 // -- conversion of C to B is better than conversion of C to A,
4461 // -- binding of an expression of type C to a reference of type
4462 // B& is better than binding an expression of type C to a
4463 // reference of type A&,
4464 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4465 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4466 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4467 return ImplicitConversionSequence::Better;
4468 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4469 return ImplicitConversionSequence::Worse;
4470 }
4471
4472 // -- conversion of B to A is better than conversion of C to A.
4473 // -- binding of an expression of type B to a reference of type
4474 // A& is better than binding an expression of type C to a
4475 // reference of type A&,
4476 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4477 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4478 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4479 return ImplicitConversionSequence::Better;
4480 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4481 return ImplicitConversionSequence::Worse;
4482 }
4483 }
4484
4485 return ImplicitConversionSequence::Indistinguishable;
4486}
4487
4488/// Determine whether the given type is valid, e.g., it is not an invalid
4489/// C++ class.
4490static bool isTypeValid(QualType T) {
4491 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4492 return !Record->isInvalidDecl();
4493
4494 return true;
4495}
4496
4497static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4498 if (!T.getQualifiers().hasUnaligned())
4499 return T;
4500
4501 Qualifiers Q;
4502 T = Ctx.getUnqualifiedArrayType(T, Q);
4503 Q.removeUnaligned();
4504 return Ctx.getQualifiedType(T, Q);
4505}
4506
4507/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4508/// determine whether they are reference-compatible,
4509/// reference-related, or incompatible, for use in C++ initialization by
4510/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4511/// type, and the first type (T1) is the pointee type of the reference
4512/// type being initialized.
4513Sema::ReferenceCompareResult
4514Sema::CompareReferenceRelationship(SourceLocation Loc,
4515 QualType OrigT1, QualType OrigT2,
4516 ReferenceConversions *ConvOut) {
4517 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4518, __PRETTY_FUNCTION__))
4518 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4518, __PRETTY_FUNCTION__))
;
4519 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4519, __PRETTY_FUNCTION__))
;
4520
4521 QualType T1 = Context.getCanonicalType(OrigT1);
4522 QualType T2 = Context.getCanonicalType(OrigT2);
4523 Qualifiers T1Quals, T2Quals;
4524 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4525 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4526
4527 ReferenceConversions ConvTmp;
4528 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4529 Conv = ReferenceConversions();
4530
4531 // C++2a [dcl.init.ref]p4:
4532 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4533 // reference-related to "cv2 T2" if T1 is similar to T2, or
4534 // T1 is a base class of T2.
4535 // "cv1 T1" is reference-compatible with "cv2 T2" if
4536 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4537 // "pointer to cv1 T1" via a standard conversion sequence.
4538
4539 // Check for standard conversions we can apply to pointers: derived-to-base
4540 // conversions, ObjC pointer conversions, and function pointer conversions.
4541 // (Qualification conversions are checked last.)
4542 QualType ConvertedT2;
4543 if (UnqualT1 == UnqualT2) {
4544 // Nothing to do.
4545 } else if (isCompleteType(Loc, OrigT2) &&
4546 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4547 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4548 Conv |= ReferenceConversions::DerivedToBase;
4549 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4550 UnqualT2->isObjCObjectOrInterfaceType() &&
4551 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4552 Conv |= ReferenceConversions::ObjC;
4553 else if (UnqualT2->isFunctionType() &&
4554 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4555 Conv |= ReferenceConversions::Function;
4556 // No need to check qualifiers; function types don't have them.
4557 return Ref_Compatible;
4558 }
4559 bool ConvertedReferent = Conv != 0;
4560
4561 // We can have a qualification conversion. Compute whether the types are
4562 // similar at the same time.
4563 bool PreviousToQualsIncludeConst = true;
4564 bool TopLevel = true;
4565 do {
4566 if (T1 == T2)
4567 break;
4568
4569 // We will need a qualification conversion.
4570 Conv |= ReferenceConversions::Qualification;
4571
4572 // Track whether we performed a qualification conversion anywhere other
4573 // than the top level. This matters for ranking reference bindings in
4574 // overload resolution.
4575 if (!TopLevel)
4576 Conv |= ReferenceConversions::NestedQualification;
4577
4578 // MS compiler ignores __unaligned qualifier for references; do the same.
4579 T1 = withoutUnaligned(Context, T1);
4580 T2 = withoutUnaligned(Context, T2);
4581
4582 // If we find a qualifier mismatch, the types are not reference-compatible,
4583 // but are still be reference-related if they're similar.
4584 bool ObjCLifetimeConversion = false;
4585 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4586 PreviousToQualsIncludeConst,
4587 ObjCLifetimeConversion))
4588 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4589 ? Ref_Related
4590 : Ref_Incompatible;
4591
4592 // FIXME: Should we track this for any level other than the first?
4593 if (ObjCLifetimeConversion)
4594 Conv |= ReferenceConversions::ObjCLifetime;
4595
4596 TopLevel = false;
4597 } while (Context.UnwrapSimilarTypes(T1, T2));
4598
4599 // At this point, if the types are reference-related, we must either have the
4600 // same inner type (ignoring qualifiers), or must have already worked out how
4601 // to convert the referent.
4602 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4603 ? Ref_Compatible
4604 : Ref_Incompatible;
4605}
4606
4607/// Look for a user-defined conversion to a value reference-compatible
4608/// with DeclType. Return true if something definite is found.
4609static bool
4610FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4611 QualType DeclType, SourceLocation DeclLoc,
4612 Expr *Init, QualType T2, bool AllowRvalues,
4613 bool AllowExplicit) {
4614 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4614, __PRETTY_FUNCTION__))
;
4615 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4616
4617 OverloadCandidateSet CandidateSet(
4618 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4619 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4620 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4621 NamedDecl *D = *I;
4622 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4623 if (isa<UsingShadowDecl>(D))
4624 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4625
4626 FunctionTemplateDecl *ConvTemplate
4627 = dyn_cast<FunctionTemplateDecl>(D);
4628 CXXConversionDecl *Conv;
4629 if (ConvTemplate)
4630 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4631 else
4632 Conv = cast<CXXConversionDecl>(D);
4633
4634 if (AllowRvalues) {
4635 // If we are initializing an rvalue reference, don't permit conversion
4636 // functions that return lvalues.
4637 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4638 const ReferenceType *RefType
4639 = Conv->getConversionType()->getAs<LValueReferenceType>();
4640 if (RefType && !RefType->getPointeeType()->isFunctionType())
4641 continue;
4642 }
4643
4644 if (!ConvTemplate &&
4645 S.CompareReferenceRelationship(
4646 DeclLoc,
4647 Conv->getConversionType()
4648 .getNonReferenceType()
4649 .getUnqualifiedType(),
4650 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4651 Sema::Ref_Incompatible)
4652 continue;
4653 } else {
4654 // If the conversion function doesn't return a reference type,
4655 // it can't be considered for this conversion. An rvalue reference
4656 // is only acceptable if its referencee is a function type.
4657
4658 const ReferenceType *RefType =
4659 Conv->getConversionType()->getAs<ReferenceType>();
4660 if (!RefType ||
4661 (!RefType->isLValueReferenceType() &&
4662 !RefType->getPointeeType()->isFunctionType()))
4663 continue;
4664 }
4665
4666 if (ConvTemplate)
4667 S.AddTemplateConversionCandidate(
4668 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4669 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4670 else
4671 S.AddConversionCandidate(
4672 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4673 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4674 }
4675
4676 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4677
4678 OverloadCandidateSet::iterator Best;
4679 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4680 case OR_Success:
4681 // C++ [over.ics.ref]p1:
4682 //
4683 // [...] If the parameter binds directly to the result of
4684 // applying a conversion function to the argument
4685 // expression, the implicit conversion sequence is a
4686 // user-defined conversion sequence (13.3.3.1.2), with the
4687 // second standard conversion sequence either an identity
4688 // conversion or, if the conversion function returns an
4689 // entity of a type that is a derived class of the parameter
4690 // type, a derived-to-base Conversion.
4691 if (!Best->FinalConversion.DirectBinding)
4692 return false;
4693
4694 ICS.setUserDefined();
4695 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4696 ICS.UserDefined.After = Best->FinalConversion;
4697 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4698 ICS.UserDefined.ConversionFunction = Best->Function;
4699 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4700 ICS.UserDefined.EllipsisConversion = false;
4701 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4703, __PRETTY_FUNCTION__))
4702 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4703, __PRETTY_FUNCTION__))
4703 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4703, __PRETTY_FUNCTION__))
;
4704 return true;
4705
4706 case OR_Ambiguous:
4707 ICS.setAmbiguous();
4708 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4709 Cand != CandidateSet.end(); ++Cand)
4710 if (Cand->Best)
4711 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4712 return true;
4713
4714 case OR_No_Viable_Function:
4715 case OR_Deleted:
4716 // There was no suitable conversion, or we found a deleted
4717 // conversion; continue with other checks.
4718 return false;
4719 }
4720
4721 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4721)
;
4722}
4723
4724/// Compute an implicit conversion sequence for reference
4725/// initialization.
4726static ImplicitConversionSequence
4727TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4728 SourceLocation DeclLoc,
4729 bool SuppressUserConversions,
4730 bool AllowExplicit) {
4731 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 4731, __PRETTY_FUNCTION__))
;
4732
4733 // Most paths end in a failed conversion.
4734 ImplicitConversionSequence ICS;
4735 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4736
4737 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4738 QualType T2 = Init->getType();
4739
4740 // If the initializer is the address of an overloaded function, try
4741 // to resolve the overloaded function. If all goes well, T2 is the
4742 // type of the resulting function.
4743 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4744 DeclAccessPair Found;
4745 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4746 false, Found))
4747 T2 = Fn->getType();
4748 }
4749
4750 // Compute some basic properties of the types and the initializer.
4751 bool isRValRef = DeclType->isRValueReferenceType();
4752 Expr::Classification InitCategory = Init->Classify(S.Context);
4753
4754 Sema::ReferenceConversions RefConv;
4755 Sema::ReferenceCompareResult RefRelationship =
4756 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4757
4758 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4759 ICS.setStandard();
4760 ICS.Standard.First = ICK_Identity;
4761 // FIXME: A reference binding can be a function conversion too. We should
4762 // consider that when ordering reference-to-function bindings.
4763 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4764 ? ICK_Derived_To_Base
4765 : (RefConv & Sema::ReferenceConversions::ObjC)
4766 ? ICK_Compatible_Conversion
4767 : ICK_Identity;
4768 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4769 // a reference binding that performs a non-top-level qualification
4770 // conversion as a qualification conversion, not as an identity conversion.
4771 ICS.Standard.Third = (RefConv &
4772 Sema::ReferenceConversions::NestedQualification)
4773 ? ICK_Qualification
4774 : ICK_Identity;
4775 ICS.Standard.setFromType(T2);
4776 ICS.Standard.setToType(0, T2);
4777 ICS.Standard.setToType(1, T1);
4778 ICS.Standard.setToType(2, T1);
4779 ICS.Standard.ReferenceBinding = true;
4780 ICS.Standard.DirectBinding = BindsDirectly;
4781 ICS.Standard.IsLvalueReference = !isRValRef;
4782 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4783 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4784 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4785 ICS.Standard.ObjCLifetimeConversionBinding =
4786 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4787 ICS.Standard.CopyConstructor = nullptr;
4788 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4789 };
4790
4791 // C++0x [dcl.init.ref]p5:
4792 // A reference to type "cv1 T1" is initialized by an expression
4793 // of type "cv2 T2" as follows:
4794
4795 // -- If reference is an lvalue reference and the initializer expression
4796 if (!isRValRef) {
4797 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4798 // reference-compatible with "cv2 T2," or
4799 //
4800 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4801 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4802 // C++ [over.ics.ref]p1:
4803 // When a parameter of reference type binds directly (8.5.3)
4804 // to an argument expression, the implicit conversion sequence
4805 // is the identity conversion, unless the argument expression
4806 // has a type that is a derived class of the parameter type,
4807 // in which case the implicit conversion sequence is a
4808 // derived-to-base Conversion (13.3.3.1).
4809 SetAsReferenceBinding(/*BindsDirectly=*/true);
4810
4811 // Nothing more to do: the inaccessibility/ambiguity check for
4812 // derived-to-base conversions is suppressed when we're
4813 // computing the implicit conversion sequence (C++
4814 // [over.best.ics]p2).
4815 return ICS;
4816 }
4817
4818 // -- has a class type (i.e., T2 is a class type), where T1 is
4819 // not reference-related to T2, and can be implicitly
4820 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4821 // is reference-compatible with "cv3 T3" 92) (this
4822 // conversion is selected by enumerating the applicable
4823 // conversion functions (13.3.1.6) and choosing the best
4824 // one through overload resolution (13.3)),
4825 if (!SuppressUserConversions && T2->isRecordType() &&
4826 S.isCompleteType(DeclLoc, T2) &&
4827 RefRelationship == Sema::Ref_Incompatible) {
4828 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4829 Init, T2, /*AllowRvalues=*/false,
4830 AllowExplicit))
4831 return ICS;
4832 }
4833 }
4834
4835 // -- Otherwise, the reference shall be an lvalue reference to a
4836 // non-volatile const type (i.e., cv1 shall be const), or the reference
4837 // shall be an rvalue reference.
4838 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4839 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4840 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4841 return ICS;
4842 }
4843
4844 // -- If the initializer expression
4845 //
4846 // -- is an xvalue, class prvalue, array prvalue or function
4847 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4848 if (RefRelationship == Sema::Ref_Compatible &&
4849 (InitCategory.isXValue() ||
4850 (InitCategory.isPRValue() &&
4851 (T2->isRecordType() || T2->isArrayType())) ||
4852 (InitCategory.isLValue() && T2->isFunctionType()))) {
4853 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4854 // binding unless we're binding to a class prvalue.
4855 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4856 // allow the use of rvalue references in C++98/03 for the benefit of
4857 // standard library implementors; therefore, we need the xvalue check here.
4858 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4859 !(InitCategory.isPRValue() || T2->isRecordType()));
4860 return ICS;
4861 }
4862
4863 // -- has a class type (i.e., T2 is a class type), where T1 is not
4864 // reference-related to T2, and can be implicitly converted to
4865 // an xvalue, class prvalue, or function lvalue of type
4866 // "cv3 T3", where "cv1 T1" is reference-compatible with
4867 // "cv3 T3",
4868 //
4869 // then the reference is bound to the value of the initializer
4870 // expression in the first case and to the result of the conversion
4871 // in the second case (or, in either case, to an appropriate base
4872 // class subobject).
4873 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4874 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4875 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4876 Init, T2, /*AllowRvalues=*/true,
4877 AllowExplicit)) {
4878 // In the second case, if the reference is an rvalue reference
4879 // and the second standard conversion sequence of the
4880 // user-defined conversion sequence includes an lvalue-to-rvalue
4881 // conversion, the program is ill-formed.
4882 if (ICS.isUserDefined() && isRValRef &&
4883 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4884 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4885
4886 return ICS;
4887 }
4888
4889 // A temporary of function type cannot be created; don't even try.
4890 if (T1->isFunctionType())
4891 return ICS;
4892
4893 // -- Otherwise, a temporary of type "cv1 T1" is created and
4894 // initialized from the initializer expression using the
4895 // rules for a non-reference copy initialization (8.5). The
4896 // reference is then bound to the temporary. If T1 is
4897 // reference-related to T2, cv1 must be the same
4898 // cv-qualification as, or greater cv-qualification than,
4899 // cv2; otherwise, the program is ill-formed.
4900 if (RefRelationship == Sema::Ref_Related) {
4901 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4902 // we would be reference-compatible or reference-compatible with
4903 // added qualification. But that wasn't the case, so the reference
4904 // initialization fails.
4905 //
4906 // Note that we only want to check address spaces and cvr-qualifiers here.
4907 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4908 Qualifiers T1Quals = T1.getQualifiers();
4909 Qualifiers T2Quals = T2.getQualifiers();
4910 T1Quals.removeObjCGCAttr();
4911 T1Quals.removeObjCLifetime();
4912 T2Quals.removeObjCGCAttr();
4913 T2Quals.removeObjCLifetime();
4914 // MS compiler ignores __unaligned qualifier for references; do the same.
4915 T1Quals.removeUnaligned();
4916 T2Quals.removeUnaligned();
4917 if (!T1Quals.compatiblyIncludes(T2Quals))
4918 return ICS;
4919 }
4920
4921 // If at least one of the types is a class type, the types are not
4922 // related, and we aren't allowed any user conversions, the
4923 // reference binding fails. This case is important for breaking
4924 // recursion, since TryImplicitConversion below will attempt to
4925 // create a temporary through the use of a copy constructor.
4926 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4927 (T1->isRecordType() || T2->isRecordType()))
4928 return ICS;
4929
4930 // If T1 is reference-related to T2 and the reference is an rvalue
4931 // reference, the initializer expression shall not be an lvalue.
4932 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4933 Init->Classify(S.Context).isLValue()) {
4934 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4935 return ICS;
4936 }
4937
4938 // C++ [over.ics.ref]p2:
4939 // When a parameter of reference type is not bound directly to
4940 // an argument expression, the conversion sequence is the one
4941 // required to convert the argument expression to the
4942 // underlying type of the reference according to
4943 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4944 // to copy-initializing a temporary of the underlying type with
4945 // the argument expression. Any difference in top-level
4946 // cv-qualification is subsumed by the initialization itself
4947 // and does not constitute a conversion.
4948 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4949 AllowedExplicit::None,
4950 /*InOverloadResolution=*/false,
4951 /*CStyle=*/false,
4952 /*AllowObjCWritebackConversion=*/false,
4953 /*AllowObjCConversionOnExplicit=*/false);
4954
4955 // Of course, that's still a reference binding.
4956 if (ICS.isStandard()) {
4957 ICS.Standard.ReferenceBinding = true;
4958 ICS.Standard.IsLvalueReference = !isRValRef;
4959 ICS.Standard.BindsToFunctionLvalue = false;
4960 ICS.Standard.BindsToRvalue = true;
4961 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4962 ICS.Standard.ObjCLifetimeConversionBinding = false;
4963 } else if (ICS.isUserDefined()) {
4964 const ReferenceType *LValRefType =
4965 ICS.UserDefined.ConversionFunction->getReturnType()
4966 ->getAs<LValueReferenceType>();
4967
4968 // C++ [over.ics.ref]p3:
4969 // Except for an implicit object parameter, for which see 13.3.1, a
4970 // standard conversion sequence cannot be formed if it requires [...]
4971 // binding an rvalue reference to an lvalue other than a function
4972 // lvalue.
4973 // Note that the function case is not possible here.
4974 if (isRValRef && LValRefType) {
4975 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4976 return ICS;
4977 }
4978
4979 ICS.UserDefined.After.ReferenceBinding = true;
4980 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4981 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4982 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4983 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4984 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4985 }
4986
4987 return ICS;
4988}
4989
4990static ImplicitConversionSequence
4991TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4992 bool SuppressUserConversions,
4993 bool InOverloadResolution,
4994 bool AllowObjCWritebackConversion,
4995 bool AllowExplicit = false);
4996
4997/// TryListConversion - Try to copy-initialize a value of type ToType from the
4998/// initializer list From.
4999static ImplicitConversionSequence
5000TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5001 bool SuppressUserConversions,
5002 bool InOverloadResolution,
5003 bool AllowObjCWritebackConversion) {
5004 // C++11 [over.ics.list]p1:
5005 // When an argument is an initializer list, it is not an expression and
5006 // special rules apply for converting it to a parameter type.
5007
5008 ImplicitConversionSequence Result;
5009 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5010
5011 // We need a complete type for what follows. Incomplete types can never be
5012 // initialized from init lists.
5013 if (!S.isCompleteType(From->getBeginLoc(), ToType))
5014 return Result;
5015
5016 // Per DR1467:
5017 // If the parameter type is a class X and the initializer list has a single
5018 // element of type cv U, where U is X or a class derived from X, the
5019 // implicit conversion sequence is the one required to convert the element
5020 // to the parameter type.
5021 //
5022 // Otherwise, if the parameter type is a character array [... ]
5023 // and the initializer list has a single element that is an
5024 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5025 // implicit conversion sequence is the identity conversion.
5026 if (From->getNumInits() == 1) {
5027 if (ToType->isRecordType()) {
5028 QualType InitType = From->getInit(0)->getType();
5029 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5030 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5031 return TryCopyInitialization(S, From->getInit(0), ToType,
5032 SuppressUserConversions,
5033 InOverloadResolution,
5034 AllowObjCWritebackConversion);
5035 }
5036
5037 if (const auto *AT = S.Context.getAsArrayType(ToType)) {
5038 if (S.IsStringInit(From->getInit(0), AT)) {
5039 InitializedEntity Entity =
5040 InitializedEntity::InitializeParameter(S.Context, ToType,
5041 /*Consumed=*/false);
5042 if (S.CanPerformCopyInitialization(Entity, From)) {
5043 Result.setStandard();
5044 Result.Standard.setAsIdentityConversion();
5045 Result.Standard.setFromType(ToType);
5046 Result.Standard.setAllToTypes(ToType);
5047 return Result;
5048 }
5049 }
5050 }
5051 }
5052
5053 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5054 // C++11 [over.ics.list]p2:
5055 // If the parameter type is std::initializer_list<X> or "array of X" and
5056 // all the elements can be implicitly converted to X, the implicit
5057 // conversion sequence is the worst conversion necessary to convert an
5058 // element of the list to X.
5059 //
5060 // C++14 [over.ics.list]p3:
5061 // Otherwise, if the parameter type is "array of N X", if the initializer
5062 // list has exactly N elements or if it has fewer than N elements and X is
5063 // default-constructible, and if all the elements of the initializer list
5064 // can be implicitly converted to X, the implicit conversion sequence is
5065 // the worst conversion necessary to convert an element of the list to X.
5066 //
5067 // FIXME: We're missing a lot of these checks.
5068 bool toStdInitializerList = false;
5069 QualType X;
5070 if (ToType->isArrayType())
5071 X = S.Context.getAsArrayType(ToType)->getElementType();
5072 else
5073 toStdInitializerList = S.isStdInitializerList(ToType, &X);
5074 if (!X.isNull()) {
5075 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5076 Expr *Init = From->getInit(i);
5077 ImplicitConversionSequence ICS =
5078 TryCopyInitialization(S, Init, X, SuppressUserConversions,
5079 InOverloadResolution,
5080 AllowObjCWritebackConversion);
5081 // If a single element isn't convertible, fail.
5082 if (ICS.isBad()) {
5083 Result = ICS;
5084 break;
5085 }
5086 // Otherwise, look for the worst conversion.
5087 if (Result.isBad() || CompareImplicitConversionSequences(
5088 S, From->getBeginLoc(), ICS, Result) ==
5089 ImplicitConversionSequence::Worse)
5090 Result = ICS;
5091 }
5092
5093 // For an empty list, we won't have computed any conversion sequence.
5094 // Introduce the identity conversion sequence.
5095 if (From->getNumInits() == 0) {
5096 Result.setStandard();
5097 Result.Standard.setAsIdentityConversion();
5098 Result.Standard.setFromType(ToType);
5099 Result.Standard.setAllToTypes(ToType);
5100 }
5101
5102 Result.setStdInitializerListElement(toStdInitializerList);
5103 return Result;
5104 }
5105
5106 // C++14 [over.ics.list]p4:
5107 // C++11 [over.ics.list]p3:
5108 // Otherwise, if the parameter is a non-aggregate class X and overload
5109 // resolution chooses a single best constructor [...] the implicit
5110 // conversion sequence is a user-defined conversion sequence. If multiple
5111 // constructors are viable but none is better than the others, the
5112 // implicit conversion sequence is a user-defined conversion sequence.
5113 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5114 // This function can deal with initializer lists.
5115 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5116 AllowedExplicit::None,
5117 InOverloadResolution, /*CStyle=*/false,
5118 AllowObjCWritebackConversion,
5119 /*AllowObjCConversionOnExplicit=*/false);
5120 }
5121
5122 // C++14 [over.ics.list]p5:
5123 // C++11 [over.ics.list]p4:
5124 // Otherwise, if the parameter has an aggregate type which can be
5125 // initialized from the initializer list [...] the implicit conversion
5126 // sequence is a user-defined conversion sequence.
5127 if (ToType->isAggregateType()) {
5128 // Type is an aggregate, argument is an init list. At this point it comes
5129 // down to checking whether the initialization works.
5130 // FIXME: Find out whether this parameter is consumed or not.
5131 InitializedEntity Entity =
5132 InitializedEntity::InitializeParameter(S.Context, ToType,
5133 /*Consumed=*/false);
5134 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5135 From)) {
5136 Result.setUserDefined();
5137 Result.UserDefined.Before.setAsIdentityConversion();
5138 // Initializer lists don't have a type.
5139 Result.UserDefined.Before.setFromType(QualType());
5140 Result.UserDefined.Before.setAllToTypes(QualType());
5141
5142 Result.UserDefined.After.setAsIdentityConversion();
5143 Result.UserDefined.After.setFromType(ToType);
5144 Result.UserDefined.After.setAllToTypes(ToType);
5145 Result.UserDefined.ConversionFunction = nullptr;
5146 }
5147 return Result;
5148 }
5149
5150 // C++14 [over.ics.list]p6:
5151 // C++11 [over.ics.list]p5:
5152 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5153 if (ToType->isReferenceType()) {
5154 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5155 // mention initializer lists in any way. So we go by what list-
5156 // initialization would do and try to extrapolate from that.
5157
5158 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5159
5160 // If the initializer list has a single element that is reference-related
5161 // to the parameter type, we initialize the reference from that.
5162 if (From->getNumInits() == 1) {
5163 Expr *Init = From->getInit(0);
5164
5165 QualType T2 = Init->getType();
5166
5167 // If the initializer is the address of an overloaded function, try
5168 // to resolve the overloaded function. If all goes well, T2 is the
5169 // type of the resulting function.
5170 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5171 DeclAccessPair Found;
5172 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5173 Init, ToType, false, Found))
5174 T2 = Fn->getType();
5175 }
5176
5177 // Compute some basic properties of the types and the initializer.
5178 Sema::ReferenceCompareResult RefRelationship =
5179 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5180
5181 if (RefRelationship >= Sema::Ref_Related) {
5182 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5183 SuppressUserConversions,
5184 /*AllowExplicit=*/false);
5185 }
5186 }
5187
5188 // Otherwise, we bind the reference to a temporary created from the
5189 // initializer list.
5190 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5191 InOverloadResolution,
5192 AllowObjCWritebackConversion);
5193 if (Result.isFailure())
5194 return Result;
5195 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5196, __PRETTY_FUNCTION__))
5196 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5196, __PRETTY_FUNCTION__))
;
5197
5198 // Can we even bind to a temporary?
5199 if (ToType->isRValueReferenceType() ||
5200 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5201 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5202 Result.UserDefined.After;
5203 SCS.ReferenceBinding = true;
5204 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5205 SCS.BindsToRvalue = true;
5206 SCS.BindsToFunctionLvalue = false;
5207 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5208 SCS.ObjCLifetimeConversionBinding = false;
5209 } else
5210 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5211 From, ToType);
5212 return Result;
5213 }
5214
5215 // C++14 [over.ics.list]p7:
5216 // C++11 [over.ics.list]p6:
5217 // Otherwise, if the parameter type is not a class:
5218 if (!ToType->isRecordType()) {
5219 // - if the initializer list has one element that is not itself an
5220 // initializer list, the implicit conversion sequence is the one
5221 // required to convert the element to the parameter type.
5222 unsigned NumInits = From->getNumInits();
5223 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5224 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5225 SuppressUserConversions,
5226 InOverloadResolution,
5227 AllowObjCWritebackConversion);
5228 // - if the initializer list has no elements, the implicit conversion
5229 // sequence is the identity conversion.
5230 else if (NumInits == 0) {
5231 Result.setStandard();
5232 Result.Standard.setAsIdentityConversion();
5233 Result.Standard.setFromType(ToType);
5234 Result.Standard.setAllToTypes(ToType);
5235 }
5236 return Result;
5237 }
5238
5239 // C++14 [over.ics.list]p8:
5240 // C++11 [over.ics.list]p7:
5241 // In all cases other than those enumerated above, no conversion is possible
5242 return Result;
5243}
5244
5245/// TryCopyInitialization - Try to copy-initialize a value of type
5246/// ToType from the expression From. Return the implicit conversion
5247/// sequence required to pass this argument, which may be a bad
5248/// conversion sequence (meaning that the argument cannot be passed to
5249/// a parameter of this type). If @p SuppressUserConversions, then we
5250/// do not permit any user-defined conversion sequences.
5251static ImplicitConversionSequence
5252TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5253 bool SuppressUserConversions,
5254 bool InOverloadResolution,
5255 bool AllowObjCWritebackConversion,
5256 bool AllowExplicit) {
5257 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5258 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5259 InOverloadResolution,AllowObjCWritebackConversion);
5260
5261 if (ToType->isReferenceType())
5262 return TryReferenceInit(S, From, ToType,
5263 /*FIXME:*/ From->getBeginLoc(),
5264 SuppressUserConversions, AllowExplicit);
5265
5266 return TryImplicitConversion(S, From, ToType,
5267 SuppressUserConversions,
5268 AllowedExplicit::None,
5269 InOverloadResolution,
5270 /*CStyle=*/false,
5271 AllowObjCWritebackConversion,
5272 /*AllowObjCConversionOnExplicit=*/false);
5273}
5274
5275static bool TryCopyInitialization(const CanQualType FromQTy,
5276 const CanQualType ToQTy,
5277 Sema &S,
5278 SourceLocation Loc,
5279 ExprValueKind FromVK) {
5280 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5281 ImplicitConversionSequence ICS =
5282 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5283
5284 return !ICS.isBad();
5285}
5286
5287/// TryObjectArgumentInitialization - Try to initialize the object
5288/// parameter of the given member function (@c Method) from the
5289/// expression @p From.
5290static ImplicitConversionSequence
5291TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5292 Expr::Classification FromClassification,
5293 CXXMethodDecl *Method,
5294 CXXRecordDecl *ActingContext) {
5295 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5296 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5297 // const volatile object.
5298 Qualifiers Quals = Method->getMethodQualifiers();
5299 if (isa<CXXDestructorDecl>(Method)) {
5300 Quals.addConst();
5301 Quals.addVolatile();
5302 }
5303
5304 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5305
5306 // Set up the conversion sequence as a "bad" conversion, to allow us
5307 // to exit early.
5308 ImplicitConversionSequence ICS;
5309
5310 // We need to have an object of class type.
5311 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5312 FromType = PT->getPointeeType();
5313
5314 // When we had a pointer, it's implicitly dereferenced, so we
5315 // better have an lvalue.
5316 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5316, __PRETTY_FUNCTION__))
;
5317 }
5318
5319 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5319, __PRETTY_FUNCTION__))
;
5320
5321 // C++0x [over.match.funcs]p4:
5322 // For non-static member functions, the type of the implicit object
5323 // parameter is
5324 //
5325 // - "lvalue reference to cv X" for functions declared without a
5326 // ref-qualifier or with the & ref-qualifier
5327 // - "rvalue reference to cv X" for functions declared with the &&
5328 // ref-qualifier
5329 //
5330 // where X is the class of which the function is a member and cv is the
5331 // cv-qualification on the member function declaration.
5332 //
5333 // However, when finding an implicit conversion sequence for the argument, we
5334 // are not allowed to perform user-defined conversions
5335 // (C++ [over.match.funcs]p5). We perform a simplified version of
5336 // reference binding here, that allows class rvalues to bind to
5337 // non-constant references.
5338
5339 // First check the qualifiers.
5340 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5341 if (ImplicitParamType.getCVRQualifiers()
5342 != FromTypeCanon.getLocalCVRQualifiers() &&
5343 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5344 ICS.setBad(BadConversionSequence::bad_qualifiers,
5345 FromType, ImplicitParamType);
5346 return ICS;
5347 }
5348
5349 if (FromTypeCanon.hasAddressSpace()) {
5350 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5351 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5352 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5353 ICS.setBad(BadConversionSequence::bad_qualifiers,
5354 FromType, ImplicitParamType);
5355 return ICS;
5356 }
5357 }
5358
5359 // Check that we have either the same type or a derived type. It
5360 // affects the conversion rank.
5361 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5362 ImplicitConversionKind SecondKind;
5363 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5364 SecondKind = ICK_Identity;
5365 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5366 SecondKind = ICK_Derived_To_Base;
5367 else {
5368 ICS.setBad(BadConversionSequence::unrelated_class,
5369 FromType, ImplicitParamType);
5370 return ICS;
5371 }
5372
5373 // Check the ref-qualifier.
5374 switch (Method->getRefQualifier()) {
5375 case RQ_None:
5376 // Do nothing; we don't care about lvalueness or rvalueness.
5377 break;
5378
5379 case RQ_LValue:
5380 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5381 // non-const lvalue reference cannot bind to an rvalue
5382 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5383 ImplicitParamType);
5384 return ICS;
5385 }
5386 break;
5387
5388 case RQ_RValue:
5389 if (!FromClassification.isRValue()) {
5390 // rvalue reference cannot bind to an lvalue
5391 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5392 ImplicitParamType);
5393 return ICS;
5394 }
5395 break;
5396 }
5397
5398 // Success. Mark this as a reference binding.
5399 ICS.setStandard();
5400 ICS.Standard.setAsIdentityConversion();
5401 ICS.Standard.Second = SecondKind;
5402 ICS.Standard.setFromType(FromType);
5403 ICS.Standard.setAllToTypes(ImplicitParamType);
5404 ICS.Standard.ReferenceBinding = true;
5405 ICS.Standard.DirectBinding = true;
5406 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5407 ICS.Standard.BindsToFunctionLvalue = false;
5408 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5409 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5410 = (Method->getRefQualifier() == RQ_None);
5411 return ICS;
5412}
5413
5414/// PerformObjectArgumentInitialization - Perform initialization of
5415/// the implicit object parameter for the given Method with the given
5416/// expression.
5417ExprResult
5418Sema::PerformObjectArgumentInitialization(Expr *From,
5419 NestedNameSpecifier *Qualifier,
5420 NamedDecl *FoundDecl,
5421 CXXMethodDecl *Method) {
5422 QualType FromRecordType, DestType;
5423 QualType ImplicitParamRecordType =
5424 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5425
5426 Expr::Classification FromClassification;
5427 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5428 FromRecordType = PT->getPointeeType();
5429 DestType = Method->getThisType();
5430 FromClassification = Expr::Classification::makeSimpleLValue();
5431 } else {
5432 FromRecordType = From->getType();
5433 DestType = ImplicitParamRecordType;
5434 FromClassification = From->Classify(Context);
5435
5436 // When performing member access on an rvalue, materialize a temporary.
5437 if (From->isRValue()) {
5438 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5439 Method->getRefQualifier() !=
5440 RefQualifierKind::RQ_RValue);
5441 }
5442 }
5443
5444 // Note that we always use the true parent context when performing
5445 // the actual argument initialization.
5446 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5447 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5448 Method->getParent());
5449 if (ICS.isBad()) {
5450 switch (ICS.Bad.Kind) {
5451 case BadConversionSequence::bad_qualifiers: {
5452 Qualifiers FromQs = FromRecordType.getQualifiers();
5453 Qualifiers ToQs = DestType.getQualifiers();
5454 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5455 if (CVR) {
5456 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5457 << Method->getDeclName() << FromRecordType << (CVR - 1)
5458 << From->getSourceRange();
5459 Diag(Method->getLocation(), diag::note_previous_decl)
5460 << Method->getDeclName();
5461 return ExprError();
5462 }
5463 break;
5464 }
5465
5466 case BadConversionSequence::lvalue_ref_to_rvalue:
5467 case BadConversionSequence::rvalue_ref_to_lvalue: {
5468 bool IsRValueQualified =
5469 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5470 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5471 << Method->getDeclName() << FromClassification.isRValue()
5472 << IsRValueQualified;
5473 Diag(Method->getLocation(), diag::note_previous_decl)
5474 << Method->getDeclName();
5475 return ExprError();
5476 }
5477
5478 case BadConversionSequence::no_conversion:
5479 case BadConversionSequence::unrelated_class:
5480 break;
5481 }
5482
5483 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5484 << ImplicitParamRecordType << FromRecordType
5485 << From->getSourceRange();
5486 }
5487
5488 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5489 ExprResult FromRes =
5490 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5491 if (FromRes.isInvalid())
5492 return ExprError();
5493 From = FromRes.get();
5494 }
5495
5496 if (!Context.hasSameType(From->getType(), DestType)) {
5497 CastKind CK;
5498 QualType PteeTy = DestType->getPointeeType();
5499 LangAS DestAS =
5500 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5501 if (FromRecordType.getAddressSpace() != DestAS)
5502 CK = CK_AddressSpaceConversion;
5503 else
5504 CK = CK_NoOp;
5505 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5506 }
5507 return From;
5508}
5509
5510/// TryContextuallyConvertToBool - Attempt to contextually convert the
5511/// expression From to bool (C++0x [conv]p3).
5512static ImplicitConversionSequence
5513TryContextuallyConvertToBool(Sema &S, Expr *From) {
5514 // C++ [dcl.init]/17.8:
5515 // - Otherwise, if the initialization is direct-initialization, the source
5516 // type is std::nullptr_t, and the destination type is bool, the initial
5517 // value of the object being initialized is false.
5518 if (From->getType()->isNullPtrType())
5519 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5520 S.Context.BoolTy,
5521 From->isGLValue());
5522
5523 // All other direct-initialization of bool is equivalent to an implicit
5524 // conversion to bool in which explicit conversions are permitted.
5525 return TryImplicitConversion(S, From, S.Context.BoolTy,
5526 /*SuppressUserConversions=*/false,
5527 AllowedExplicit::Conversions,
5528 /*InOverloadResolution=*/false,
5529 /*CStyle=*/false,
5530 /*AllowObjCWritebackConversion=*/false,
5531 /*AllowObjCConversionOnExplicit=*/false);
5532}
5533
5534/// PerformContextuallyConvertToBool - Perform a contextual conversion
5535/// of the expression From to bool (C++0x [conv]p3).
5536ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5537 if (checkPlaceholderForOverload(*this, From))
5538 return ExprError();
5539
5540 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5541 if (!ICS.isBad())
5542 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5543
5544 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5545 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5546 << From->getType() << From->getSourceRange();
5547 return ExprError();
5548}
5549
5550/// Check that the specified conversion is permitted in a converted constant
5551/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5552/// is acceptable.
5553static bool CheckConvertedConstantConversions(Sema &S,
5554 StandardConversionSequence &SCS) {
5555 // Since we know that the target type is an integral or unscoped enumeration
5556 // type, most conversion kinds are impossible. All possible First and Third
5557 // conversions are fine.
5558 switch (SCS.Second) {
5559 case ICK_Identity:
5560 case ICK_Integral_Promotion:
5561 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5562 case ICK_Zero_Queue_Conversion:
5563 return true;
5564
5565 case ICK_Boolean_Conversion:
5566 // Conversion from an integral or unscoped enumeration type to bool is
5567 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5568 // conversion, so we allow it in a converted constant expression.
5569 //
5570 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5571 // a lot of popular code. We should at least add a warning for this
5572 // (non-conforming) extension.
5573 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5574 SCS.getToType(2)->isBooleanType();
5575
5576 case ICK_Pointer_Conversion:
5577 case ICK_Pointer_Member:
5578 // C++1z: null pointer conversions and null member pointer conversions are
5579 // only permitted if the source type is std::nullptr_t.
5580 return SCS.getFromType()->isNullPtrType();
5581
5582 case ICK_Floating_Promotion:
5583 case ICK_Complex_Promotion:
5584 case ICK_Floating_Conversion:
5585 case ICK_Complex_Conversion:
5586 case ICK_Floating_Integral:
5587 case ICK_Compatible_Conversion:
5588 case ICK_Derived_To_Base:
5589 case ICK_Vector_Conversion:
5590 case ICK_SVE_Vector_Conversion:
5591 case ICK_Vector_Splat:
5592 case ICK_Complex_Real:
5593 case ICK_Block_Pointer_Conversion:
5594 case ICK_TransparentUnionConversion:
5595 case ICK_Writeback_Conversion:
5596 case ICK_Zero_Event_Conversion:
5597 case ICK_C_Only_Conversion:
5598 case ICK_Incompatible_Pointer_Conversion:
5599 return false;
5600
5601 case ICK_Lvalue_To_Rvalue:
5602 case ICK_Array_To_Pointer:
5603 case ICK_Function_To_Pointer:
5604 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5604)
;
5605
5606 case ICK_Function_Conversion:
5607 case ICK_Qualification:
5608 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5608)
;
5609
5610 case ICK_Num_Conversion_Kinds:
5611 break;
5612 }
5613
5614 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5614)
;
5615}
5616
5617/// CheckConvertedConstantExpression - Check that the expression From is a
5618/// converted constant expression of type T, perform the conversion and produce
5619/// the converted expression, per C++11 [expr.const]p3.
5620static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5621 QualType T, APValue &Value,
5622 Sema::CCEKind CCE,
5623 bool RequireInt,
5624 NamedDecl *Dest) {
5625 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5626, __PRETTY_FUNCTION__))
5626 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5626, __PRETTY_FUNCTION__))
;
5627
5628 if (checkPlaceholderForOverload(S, From))
5629 return ExprError();
5630
5631 // C++1z [expr.const]p3:
5632 // A converted constant expression of type T is an expression,
5633 // implicitly converted to type T, where the converted
5634 // expression is a constant expression and the implicit conversion
5635 // sequence contains only [... list of conversions ...].
5636 // C++1z [stmt.if]p2:
5637 // If the if statement is of the form if constexpr, the value of the
5638 // condition shall be a contextually converted constant expression of type
5639 // bool.
5640 ImplicitConversionSequence ICS =
5641 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5642 ? TryContextuallyConvertToBool(S, From)
5643 : TryCopyInitialization(S, From, T,
5644 /*SuppressUserConversions=*/false,
5645 /*InOverloadResolution=*/false,
5646 /*AllowObjCWritebackConversion=*/false,
5647 /*AllowExplicit=*/false);
5648 StandardConversionSequence *SCS = nullptr;
5649 switch (ICS.getKind()) {
5650 case ImplicitConversionSequence::StandardConversion:
5651 SCS = &ICS.Standard;
5652 break;
5653 case ImplicitConversionSequence::UserDefinedConversion:
5654 if (T->isRecordType())
5655 SCS = &ICS.UserDefined.Before;
5656 else
5657 SCS = &ICS.UserDefined.After;
5658 break;
5659 case ImplicitConversionSequence::AmbiguousConversion:
5660 case ImplicitConversionSequence::BadConversion:
5661 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5662 return S.Diag(From->getBeginLoc(),
5663 diag::err_typecheck_converted_constant_expression)
5664 << From->getType() << From->getSourceRange() << T;
5665 return ExprError();
5666
5667 case ImplicitConversionSequence::EllipsisConversion:
5668 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5668)
;
5669 }
5670
5671 // Check that we would only use permitted conversions.
5672 if (!CheckConvertedConstantConversions(S, *SCS)) {
5673 return S.Diag(From->getBeginLoc(),
5674 diag::err_typecheck_converted_constant_expression_disallowed)
5675 << From->getType() << From->getSourceRange() << T;
5676 }
5677 // [...] and where the reference binding (if any) binds directly.
5678 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5679 return S.Diag(From->getBeginLoc(),
5680 diag::err_typecheck_converted_constant_expression_indirect)
5681 << From->getType() << From->getSourceRange() << T;
5682 }
5683
5684 // Usually we can simply apply the ImplicitConversionSequence we formed
5685 // earlier, but that's not guaranteed to work when initializing an object of
5686 // class type.
5687 ExprResult Result;
5688 if (T->isRecordType()) {
5689 assert(CCE == Sema::CCEK_TemplateArg &&((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5690, __PRETTY_FUNCTION__))
5690 "unexpected class type converted constant expr")((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5690, __PRETTY_FUNCTION__))
;
5691 Result = S.PerformCopyInitialization(
5692 InitializedEntity::InitializeTemplateParameter(
5693 T, cast<NonTypeTemplateParmDecl>(Dest)),
5694 SourceLocation(), From);
5695 } else {
5696 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5697 }
5698 if (Result.isInvalid())
5699 return Result;
5700
5701 // C++2a [intro.execution]p5:
5702 // A full-expression is [...] a constant-expression [...]
5703 Result =
5704 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5705 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5706 if (Result.isInvalid())
5707 return Result;
5708
5709 // Check for a narrowing implicit conversion.
5710 bool ReturnPreNarrowingValue = false;
5711 APValue PreNarrowingValue;
5712 QualType PreNarrowingType;
5713 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5714 PreNarrowingType)) {
5715 case NK_Dependent_Narrowing:
5716 // Implicit conversion to a narrower type, but the expression is
5717 // value-dependent so we can't tell whether it's actually narrowing.
5718 case NK_Variable_Narrowing:
5719 // Implicit conversion to a narrower type, and the value is not a constant
5720 // expression. We'll diagnose this in a moment.
5721 case NK_Not_Narrowing:
5722 break;
5723
5724 case NK_Constant_Narrowing:
5725 if (CCE == Sema::CCEK_ArrayBound &&
5726 PreNarrowingType->isIntegralOrEnumerationType() &&
5727 PreNarrowingValue.isInt()) {
5728 // Don't diagnose array bound narrowing here; we produce more precise
5729 // errors by allowing the un-narrowed value through.
5730 ReturnPreNarrowingValue = true;
5731 break;
5732 }
5733 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5734 << CCE << /*Constant*/ 1
5735 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5736 break;
5737
5738 case NK_Type_Narrowing:
5739 // FIXME: It would be better to diagnose that the expression is not a
5740 // constant expression.
5741 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5742 << CCE << /*Constant*/ 0 << From->getType() << T;
5743 break;
5744 }
5745
5746 if (Result.get()->isValueDependent()) {
5747 Value = APValue();
5748 return Result;
5749 }
5750
5751 // Check the expression is a constant expression.
5752 SmallVector<PartialDiagnosticAt, 8> Notes;
5753 Expr::EvalResult Eval;
5754 Eval.Diag = &Notes;
5755
5756 ConstantExprKind Kind;
5757 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5758 Kind = ConstantExprKind::ClassTemplateArgument;
5759 else if (CCE == Sema::CCEK_TemplateArg)
5760 Kind = ConstantExprKind::NonClassTemplateArgument;
5761 else
5762 Kind = ConstantExprKind::Normal;
5763
5764 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5765 (RequireInt && !Eval.Val.isInt())) {
5766 // The expression can't be folded, so we can't keep it at this position in
5767 // the AST.
5768 Result = ExprError();
5769 } else {
5770 Value = Eval.Val;
5771
5772 if (Notes.empty()) {
5773 // It's a constant expression.
5774 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5775 if (ReturnPreNarrowingValue)
5776 Value = std::move(PreNarrowingValue);
5777 return E;
5778 }
5779 }
5780
5781 // It's not a constant expression. Produce an appropriate diagnostic.
5782 if (Notes.size() == 1 &&
5783 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5784 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5785 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5786 diag::note_constexpr_invalid_template_arg) {
5787 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5788 for (unsigned I = 0; I < Notes.size(); ++I)
5789 S.Diag(Notes[I].first, Notes[I].second);
5790 } else {
5791 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5792 << CCE << From->getSourceRange();
5793 for (unsigned I = 0; I < Notes.size(); ++I)
5794 S.Diag(Notes[I].first, Notes[I].second);
5795 }
5796 return ExprError();
5797}
5798
5799ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5800 APValue &Value, CCEKind CCE,
5801 NamedDecl *Dest) {
5802 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5803 Dest);
5804}
5805
5806ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5807 llvm::APSInt &Value,
5808 CCEKind CCE) {
5809 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOverload.cpp"
, 5809, __PRETTY_FUNCTION__))
;
5810
5811 APValue V;
5812 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5813 /*Dest=*/nullptr);
5814 if (!R.isInvalid() && !R.get()->isValueDependent())
5815 Value = V.getInt();
5816 return R;
5817}
5818
5819
5820/// dropPointerConversions - If the given standard conversion sequence
5821/// involves any pointer conversions, remove them. This may change
5822/// the result type of the conversion sequence.
5823static void dropPointerConversion(StandardConversionSequence &SCS) {
5824 if (SCS.Second == ICK_Pointer_Conversion) {
5825 SCS.Second = ICK_Identity;
5826 SCS.Third = ICK_Identity;
5827 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5828 }
5829}
5830
5831/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5832/// convert the expression From to an Objective-C pointer type.
5833static ImplicitConversionSequence
5834TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5835 // Do an implicit conversion to 'id'.
5836 QualType Ty = S.Context.getObjCIdType();
5837 ImplicitConversionSequence ICS
5838 = TryImplicitConversion(S, From, Ty,
5839 // FIXME: Are these flags correct?
5840 /*SuppressUserConversions=*/false,
5841 AllowedExplicit::Conversions,
5842 /*InOverloadResolution=*/false,
5843 /*CStyle=*/false,
5844 /*AllowObjCWritebackConversion=*/false,
5845 /*AllowObjCConversionOnExplicit=*/true);
5846
5847 // Strip off any final conversions to 'id'.
5848 switch (ICS.getKind()) {
5849 case ImplicitConversionSequence::BadConversion:
5850 case ImplicitConversionSequence::AmbiguousConversion:
5851 case ImplicitConversionSequence::EllipsisConversion:
5852 break;
5853
5854 case ImplicitConversionSequence::UserDefinedConversion:
5855 dropPointerConversion(ICS.UserDefined.After);
5856 break;
5857
5858 case ImplicitConversionSequence::StandardConversion:
5859 dropPointerConversion(ICS.Standard);
5860 break;
5861 }
5862
5863 return ICS;
5864}
5865
5866/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5867/// conversion of the expression From to an Objective-C pointer type.
5868/// Returns a valid but null ExprResult if no conversion sequence exists.
5869ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5870 if (checkPlaceholderForOverload(*this, From))
5871 return ExprError();
5872
5873 QualType Ty = Context.getObjCIdType();
5874 ImplicitConversionSequence ICS =
5875 TryContextuallyConvertToObjCPointer(*this, From);
5876 if (!ICS.isBad())
5877 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5878 return ExprResult();
5879}
5880
5881/// Determine whether the provided type is an integral type, or an enumeration
5882/// type of a permitted flavor.
5883bool Sema::ICEConvertDiagnoser::match(QualType T) {
5884 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5885 : T->isIntegralOrUnscopedEnumerationType();
5886}
5887
5888static ExprResult
5889diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5890 Sema::ContextualImplicitConverter &Converter,
5891 QualType T, UnresolvedSetImpl &ViableConversions) {
5892
5893 if (Converter.Suppress)
5894 return ExprError();
5895
5896 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5897 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5898 CXXConversionDecl *Conv =
5899 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5900 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5901 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5902 }
5903 return From;
5904}
5905
5906static bool
5907diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5908 Sema::ContextualImplicitConverter &Converter,
5909 QualType T, bool HadMultipleCandidates,
5910 UnresolvedSetImpl &ExplicitConversions) {
5911 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5912 DeclAccessPair Found = ExplicitConversions[0];
5913 CXXConversionDecl *Conversion =
5914 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5915
5916 // The user probably meant to invoke the given explicit
5917 // conversion; use it.
5918 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5919 std::string TypeStr;
5920 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5921
5922 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5923 << FixItHint::CreateInsertion(From->getBeginLoc(),
5924 "static_cast<" + TypeStr + ">(")
5925 << FixItHint::CreateInsertion(
5926 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5927 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5928
5929 // If we aren't in a SFINAE context, build a call to the
5930 // explicit conversion function.
5931 if (SemaRef.isSFINAEContext())
5932 return true;
5933
5934 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5935 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5936 HadMultipleCandidates);
5937 if (Result.isInvalid())
5938 return true;
5939 // Record usage of conversion in an implicit cast.
5940 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5941 CK_UserDefinedConversion, Result.get(),
5942 nullptr, Result.get()->getValueKind(),
5943 SemaRef.CurFPFeatureOverrides());
5944 }
5945 return false;
5946}
5947
5948static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5949 Sema::ContextualImplicitConverter &Converter,
5950 QualType T, bool HadMultipleCandidates,
5951 DeclAccessPair &Found) {
5952 CXXConversionDecl *Conversion =
5953