Bug Summary

File:tools/clang/include/clang/Sema/Sema.h
Warning:line 1553, 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-eagerly-assume -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 -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337204/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.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-7~svn337204/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -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-2018-07-17-043059-5239-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp

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