Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Warning:line 1539, column 50
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOverload.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/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~svn329677/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-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaOverload.cpp

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