Bug Summary

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