Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaOverload.cpp
Warning:line 13755, column 21
Although the value stored to 'LHS' is used in the enclosing expression, the value is never actually read from 'LHS'

Annotated Source Code

Press '?' to see keyboard shortcuts

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