Bug Summary

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