Bug Summary

File:clang/lib/Sema/SemaOverload.cpp
Warning:line 10234, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/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/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/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/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-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191=. -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 -o /tmp/scan-build-2020-11-21-121427-42170-1 -x c++ /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaOverload.cpp

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