Bug Summary

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