Bug Summary

File:tools/clang/include/clang/Sema/Sema.h
Warning:line 1663, column 50
Called C++ object pointer is null

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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.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-9~svn358860/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn358860/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn358860/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/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn358860/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn358860=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-04-22-050718-5320-1 -x c++ /build/llvm-toolchain-snapshot-9~svn358860/tools/clang/lib/Sema/SemaOverload.cpp -faddrsig

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