Bug Summary

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

Annotated Source Code

[?] Use j/k keys for keyboard navigation

/build/llvm-toolchain-snapshot-6.0~svn321639/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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 296, __extension__ __PRETTY_FUNCTION__))
;
297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
309 switch (Second) {
310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 FloatingIntegralConversion:
328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333 assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 333, __extension__ __PRETTY_FUNCTION__))
;
334
335 // If it's value-dependent, we can't tell whether it's narrowing.
336 if (Initializer->isValueDependent())
337 return NK_Dependent_Narrowing;
338
339 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
344 // And back.
345 llvm::APSInt ConvertedValue = IntConstantValue;
346 bool ignored;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
352 ConstantType = Initializer->getType();
353 return NK_Constant_Narrowing;
354 }
355 } else {
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
358 }
359 }
360 return NK_Not_Narrowing;
361
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
375
376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 // Constant!
378 assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
;
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
381 bool ignored;
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
389 return NK_Constant_Narrowing;
390 }
391 } else {
392 return NK_Variable_Narrowing;
393 }
394 }
395 return NK_Not_Narrowing;
396
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
402 case ICK_Integral_Conversion:
403 IntegralConversion: {
404 assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 404, __extension__ __PRETTY_FUNCTION__))
;
405 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 405, __extension__ __PRETTY_FUNCTION__))
;
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411 if (FromWidth > ToWidth ||
412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
425 }
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 // narrowing.
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
431 Narrowing = true;
432 } else {
433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
444 if (ConvertedValue != InitializerValue)
445 Narrowing = true;
446 }
447 if (Narrowing) {
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
451 }
452 }
453 return NK_Not_Narrowing;
454 }
455
456 default:
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
459 }
460}
461
462/// dump - Print this standard conversion sequence to standard
463/// error. Useful for debugging overloading issues.
464LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
465 raw_ostream &OS = llvm::errs();
466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
468 OS << GetImplicitConversionName(First);
469 PrintedSomething = true;
470 }
471
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
474 OS << " -> ";
475 }
476 OS << GetImplicitConversionName(Second);
477
478 if (CopyConstructor) {
479 OS << " (by copy constructor)";
480 } else if (DirectBinding) {
481 OS << " (direct reference binding)";
482 } else if (ReferenceBinding) {
483 OS << " (reference binding)";
484 }
485 PrintedSomething = true;
486 }
487
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
490 OS << " -> ";
491 }
492 OS << GetImplicitConversionName(Third);
493 PrintedSomething = true;
494 }
495
496 if (!PrintedSomething) {
497 OS << "No conversions required";
498 }
499}
500
501/// dump - Print this user-defined conversion sequence to standard
502/// error. Useful for debugging overloading issues.
503void UserDefinedConversionSequence::dump() const {
504 raw_ostream &OS = llvm::errs();
505 if (Before.First || Before.Second || Before.Third) {
506 Before.dump();
507 OS << " -> ";
508 }
509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
511 else
512 OS << "aggregate initialization";
513 if (After.First || After.Second || After.Third) {
514 OS << " -> ";
515 After.dump();
516 }
517}
518
519/// dump - Print this implicit conversion sequence to standard
520/// error. Useful for debugging overloading issues.
521void ImplicitConversionSequence::dump() const {
522 raw_ostream &OS = llvm::errs();
523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
525 switch (ConversionKind) {
526 case StandardConversion:
527 OS << "Standard conversion: ";
528 Standard.dump();
529 break;
530 case UserDefinedConversion:
531 OS << "User-defined conversion: ";
532 UserDefined.dump();
533 break;
534 case EllipsisConversion:
535 OS << "Ellipsis conversion";
536 break;
537 case AmbiguousConversion:
538 OS << "Ambiguous conversion";
539 break;
540 case BadConversion:
541 OS << "Bad conversion";
542 break;
543 }
544
545 OS << "\n";
546}
547
548void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
550}
551
552void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
554}
555
556void
557AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
561}
562
563namespace {
564 // Structure used by DeductionFailureInfo to store
565 // template argument information.
566 struct DFIArguments {
567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
569 };
570 // Structure used by DeductionFailureInfo to store
571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
574 };
575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
580 };
581}
582
583/// \brief Convert from Sema's representation of template deduction information
584/// to the form used in overload-candidate information.
585DeductionFailureInfo
586clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
589 DeductionFailureInfo Result;
590 Result.Result = static_cast<unsigned>(TDK);
591 Result.HasDiagnostic = false;
592 switch (TDK) {
593 case Sema::TDK_Invalid:
594 case Sema::TDK_InstantiationDepth:
595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
597 case Sema::TDK_MiscellaneousDeductionFailure:
598 case Sema::TDK_CUDATargetMismatch:
599 Result.Data = nullptr;
600 break;
601
602 case Sema::TDK_Incomplete:
603 case Sema::TDK_InvalidExplicitArguments:
604 Result.Data = Info.Param.getOpaqueValue();
605 break;
606
607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
628 case Sema::TDK_Inconsistent:
629 case Sema::TDK_Underqualified: {
630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
638
639 case Sema::TDK_SubstitutionFailure:
640 Result.Data = Info.take();
641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
647 break;
648
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 651)
;
652 }
653
654 return Result;
655}
656
657void DeductionFailureInfo::Destroy() {
658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
660 case Sema::TDK_Invalid:
661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
665 case Sema::TDK_InvalidExplicitArguments:
666 case Sema::TDK_CUDATargetMismatch:
667 case Sema::TDK_NonDependentConversionFailure:
668 break;
669
670 case Sema::TDK_Inconsistent:
671 case Sema::TDK_Underqualified:
672 case Sema::TDK_DeducedMismatch:
673 case Sema::TDK_DeducedMismatchNested:
674 case Sema::TDK_NonDeducedMismatch:
675 // FIXME: Destroy the data?
676 Data = nullptr;
677 break;
678
679 case Sema::TDK_SubstitutionFailure:
680 // FIXME: Destroy the template argument list?
681 Data = nullptr;
682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
685 }
686 break;
687
688 // Unhandled
689 case Sema::TDK_MiscellaneousDeductionFailure:
690 break;
691 }
692}
693
694PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
695 if (HasDiagnostic)
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
697 return nullptr;
698}
699
700TemplateParameter DeductionFailureInfo::getTemplateParameter() {
701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_SubstitutionFailure:
708 case Sema::TDK_DeducedMismatch:
709 case Sema::TDK_DeducedMismatchNested:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_CUDATargetMismatch:
712 case Sema::TDK_NonDependentConversionFailure:
713 return TemplateParameter();
714
715 case Sema::TDK_Incomplete:
716 case Sema::TDK_InvalidExplicitArguments:
717 return TemplateParameter::getFromOpaqueValue(Data);
718
719 case Sema::TDK_Inconsistent:
720 case Sema::TDK_Underqualified:
721 return static_cast<DFIParamWithArguments*>(Data)->Param;
722
723 // Unhandled
724 case Sema::TDK_MiscellaneousDeductionFailure:
725 break;
726 }
727
728 return TemplateParameter();
729}
730
731TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
743 case Sema::TDK_CUDATargetMismatch:
744 case Sema::TDK_NonDependentConversionFailure:
745 return nullptr;
746
747 case Sema::TDK_DeducedMismatch:
748 case Sema::TDK_DeducedMismatchNested:
749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
753
754 // Unhandled
755 case Sema::TDK_MiscellaneousDeductionFailure:
756 break;
757 }
758
759 return nullptr;
760}
761
762const TemplateArgument *DeductionFailureInfo::getFirstArg() {
763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
765 case Sema::TDK_Invalid:
766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
770 case Sema::TDK_InvalidExplicitArguments:
771 case Sema::TDK_SubstitutionFailure:
772 case Sema::TDK_CUDATargetMismatch:
773 case Sema::TDK_NonDependentConversionFailure:
774 return nullptr;
775
776 case Sema::TDK_Inconsistent:
777 case Sema::TDK_Underqualified:
778 case Sema::TDK_DeducedMismatch:
779 case Sema::TDK_DeducedMismatchNested:
780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
782
783 // Unhandled
784 case Sema::TDK_MiscellaneousDeductionFailure:
785 break;
786 }
787
788 return nullptr;
789}
790
791const TemplateArgument *DeductionFailureInfo::getSecondArg() {
792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
794 case Sema::TDK_Invalid:
795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
799 case Sema::TDK_InvalidExplicitArguments:
800 case Sema::TDK_SubstitutionFailure:
801 case Sema::TDK_CUDATargetMismatch:
802 case Sema::TDK_NonDependentConversionFailure:
803 return nullptr;
804
805 case Sema::TDK_Inconsistent:
806 case Sema::TDK_Underqualified:
807 case Sema::TDK_DeducedMismatch:
808 case Sema::TDK_DeducedMismatchNested:
809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
811
812 // Unhandled
813 case Sema::TDK_MiscellaneousDeductionFailure:
814 break;
815 }
816
817 return nullptr;
818}
819
820llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
826 default:
827 return llvm::None;
828 }
829}
830
831void OverloadCandidateSet::destroyCandidates() {
832 for (iterator i = begin(), e = end(); i != e; ++i) {
833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
837 }
838}
839
840void OverloadCandidateSet::clear(CandidateSetKind CSK) {
841 destroyCandidates();
842 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
844 Candidates.clear();
845 Functions.clear();
846 Kind = CSK;
847}
848
849namespace {
850 class UnbridgedCastsSet {
851 struct Entry {
852 Expr **Addr;
853 Expr *Saved;
854 };
855 SmallVector<Entry, 2> Entries;
856
857 public:
858 void save(Sema &S, Expr *&E) {
859 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 859, __extension__ __PRETTY_FUNCTION__))
;
860 Entry entry = { &E, E };
861 Entries.push_back(entry);
862 E = S.stripARCUnbridgedCast(E);
863 }
864
865 void restore() {
866 for (SmallVectorImpl<Entry>::iterator
867 i = Entries.begin(), e = Entries.end(); i != e; ++i)
868 *i->Addr = i->Saved;
869 }
870 };
871}
872
873/// checkPlaceholderForOverload - Do any interesting placeholder-like
874/// preprocessing on the given expression.
875///
876/// \param unbridgedCasts a collection to which to add unbridged casts;
877/// without this, they will be immediately diagnosed as errors
878///
879/// Return true on unrecoverable error.
880static bool
881checkPlaceholderForOverload(Sema &S, Expr *&E,
882 UnbridgedCastsSet *unbridgedCasts = nullptr) {
883 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
884 // We can't handle overloaded expressions here because overload
885 // resolution might reasonably tweak them.
886 if (placeholder->getKind() == BuiltinType::Overload) return false;
887
888 // If the context potentially accepts unbridged ARC casts, strip
889 // the unbridged cast and add it to the collection for later restoration.
890 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
891 unbridgedCasts) {
892 unbridgedCasts->save(S, E);
893 return false;
894 }
895
896 // Go ahead and check everything else.
897 ExprResult result = S.CheckPlaceholderExpr(E);
898 if (result.isInvalid())
899 return true;
900
901 E = result.get();
902 return false;
903 }
904
905 // Nothing to do.
906 return false;
907}
908
909/// checkArgPlaceholdersForOverload - Check a set of call operands for
910/// placeholders.
911static bool checkArgPlaceholdersForOverload(Sema &S,
912 MultiExprArg Args,
913 UnbridgedCastsSet &unbridged) {
914 for (unsigned i = 0, e = Args.size(); i != e; ++i)
915 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
916 return true;
917
918 return false;
919}
920
921/// Determine whether the given New declaration is an overload of the
922/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
923/// New and Old cannot be overloaded, e.g., if New has the same signature as
924/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
925/// functions (or function templates) at all. When it does return Ovl_Match or
926/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
927/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
928/// declaration.
929///
930/// Example: Given the following input:
931///
932/// void f(int, float); // #1
933/// void f(int, int); // #2
934/// int f(int, int); // #3
935///
936/// When we process #1, there is no previous declaration of "f", so IsOverload
937/// will not be used.
938///
939/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
940/// the parameter types, we see that #1 and #2 are overloaded (since they have
941/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
942/// unchanged.
943///
944/// When we process #3, Old is an overload set containing #1 and #2. We compare
945/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
946/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
947/// functions are not part of the signature), IsOverload returns Ovl_Match and
948/// MatchedDecl will be set to point to the FunctionDecl for #2.
949///
950/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
951/// by a using declaration. The rules for whether to hide shadow declarations
952/// ignore some properties which otherwise figure into a function template's
953/// signature.
954Sema::OverloadKind
955Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
956 NamedDecl *&Match, bool NewIsUsingDecl) {
957 for (LookupResult::iterator I = Old.begin(), E = Old.end();
958 I != E; ++I) {
959 NamedDecl *OldD = *I;
960
961 bool OldIsUsingDecl = false;
962 if (isa<UsingShadowDecl>(OldD)) {
963 OldIsUsingDecl = true;
964
965 // We can always introduce two using declarations into the same
966 // context, even if they have identical signatures.
967 if (NewIsUsingDecl) continue;
968
969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
970 }
971
972 // A using-declaration does not conflict with another declaration
973 // if one of them is hidden.
974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
975 continue;
976
977 // If either declaration was introduced by a using declaration,
978 // we'll need to use slightly different rules for matching.
979 // Essentially, these rules are the normal rules, except that
980 // function templates hide function templates with different
981 // return types or template parameter lists.
982 bool UseMemberUsingDeclRules =
983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
984 !New->getFriendObjectKind();
985
986 if (FunctionDecl *OldF = OldD->getAsFunction()) {
987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
988 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
990 continue;
991 }
992
993 if (!isa<FunctionTemplateDecl>(OldD) &&
994 !shouldLinkPossiblyHiddenDecl(*I, New))
995 continue;
996
997 Match = *I;
998 return Ovl_Match;
999 }
1000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1001 // We can overload with these, which can show up when doing
1002 // redeclaration checks for UsingDecls.
1003 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1003, __extension__ __PRETTY_FUNCTION__))
;
1004 } else if (isa<TagDecl>(OldD)) {
1005 // We can always overload with tags by hiding them.
1006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1007 // Optimistically assume that an unresolved using decl will
1008 // overload; if it doesn't, we'll have to diagnose during
1009 // template instantiation.
1010 //
1011 // Exception: if the scope is dependent and this is not a class
1012 // member, the using declaration can only introduce an enumerator.
1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014 Match = *I;
1015 return Ovl_NonFunction;
1016 }
1017 } else {
1018 // (C++ 13p1):
1019 // Only function declarations can be overloaded; object and type
1020 // declarations cannot be overloaded.
1021 Match = *I;
1022 return Ovl_NonFunction;
1023 }
1024 }
1025
1026 return Ovl_Overload;
1027}
1028
1029bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1031 // C++ [basic.start.main]p2: This function shall not be overloaded.
1032 if (New->isMain())
1033 return false;
1034
1035 // MSVCRT user defined entry points cannot be overloaded.
1036 if (New->isMSVCRTEntryPoint())
1037 return false;
1038
1039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041
1042 // C++ [temp.fct]p2:
1043 // A function template can be overloaded with other function templates
1044 // and with normal (non-template) functions.
1045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1046 return true;
1047
1048 // Is the function New an overload of the function Old?
1049 QualType OldQType = Context.getCanonicalType(Old->getType());
1050 QualType NewQType = Context.getCanonicalType(New->getType());
1051
1052 // Compare the signatures (C++ 1.3.10) of the two functions to
1053 // determine whether they are overloads. If we find any mismatch
1054 // in the signature, they are overloads.
1055
1056 // If either of these functions is a K&R-style function (no
1057 // prototype), then we consider them to have matching signatures.
1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1059 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1060 return false;
1061
1062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1064
1065 // The signature of a function includes the types of its
1066 // parameters (C++ 1.3.10), which includes the presence or absence
1067 // of the ellipsis; see C++ DR 357).
1068 if (OldQType != NewQType &&
1069 (OldType->getNumParams() != NewType->getNumParams() ||
1070 OldType->isVariadic() != NewType->isVariadic() ||
1071 !FunctionParamTypesAreEqual(OldType, NewType)))
1072 return true;
1073
1074 // C++ [temp.over.link]p4:
1075 // The signature of a function template consists of its function
1076 // signature, its return type and its template parameter list. The names
1077 // of the template parameters are significant only for establishing the
1078 // relationship between the template parameters and the rest of the
1079 // signature.
1080 //
1081 // We check the return type and template parameter lists for function
1082 // templates first; the remaining checks follow.
1083 //
1084 // However, we don't consider either of these when deciding whether
1085 // a member introduced by a shadow declaration is hidden.
1086 if (!UseMemberUsingDeclRules && NewTemplate &&
1087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1088 OldTemplate->getTemplateParameters(),
1089 false, TPL_TemplateMatch) ||
1090 OldType->getReturnType() != NewType->getReturnType()))
1091 return true;
1092
1093 // If the function is a class member, its signature includes the
1094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1095 //
1096 // As part of this, also check whether one of the member functions
1097 // is static, in which case they are not overloads (C++
1098 // 13.1p2). While not part of the definition of the signature,
1099 // this check is important to determine whether these functions
1100 // can be overloaded.
1101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1103 if (OldMethod && NewMethod &&
1104 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1106 if (!UseMemberUsingDeclRules &&
1107 (OldMethod->getRefQualifier() == RQ_None ||
1108 NewMethod->getRefQualifier() == RQ_None)) {
1109 // C++0x [over.load]p2:
1110 // - Member function declarations with the same name and the same
1111 // parameter-type-list as well as member function template
1112 // declarations with the same name, the same parameter-type-list, and
1113 // the same template parameter lists cannot be overloaded if any of
1114 // them, but not all, have a ref-qualifier (8.3.5).
1115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1117 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1118 }
1119 return true;
1120 }
1121
1122 // We may not have applied the implicit const for a constexpr member
1123 // function yet (because we haven't yet resolved whether this is a static
1124 // or non-static member function). Add it now, on the assumption that this
1125 // is a redeclaration of OldMethod.
1126 unsigned OldQuals = OldMethod->getTypeQualifiers();
1127 unsigned NewQuals = NewMethod->getTypeQualifiers();
1128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1129 !isa<CXXConstructorDecl>(NewMethod))
1130 NewQuals |= Qualifiers::Const;
1131
1132 // We do not allow overloading based off of '__restrict'.
1133 OldQuals &= ~Qualifiers::Restrict;
1134 NewQuals &= ~Qualifiers::Restrict;
1135 if (OldQuals != NewQuals)
1136 return true;
1137 }
1138
1139 // Though pass_object_size is placed on parameters and takes an argument, we
1140 // consider it to be a function-level modifier for the sake of function
1141 // identity. Either the function has one or more parameters with
1142 // pass_object_size or it doesn't.
1143 if (functionHasPassObjectSizeParams(New) !=
1144 functionHasPassObjectSizeParams(Old))
1145 return true;
1146
1147 // enable_if attributes are an order-sensitive part of the signature.
1148 for (specific_attr_iterator<EnableIfAttr>
1149 NewI = New->specific_attr_begin<EnableIfAttr>(),
1150 NewE = New->specific_attr_end<EnableIfAttr>(),
1151 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1152 OldE = Old->specific_attr_end<EnableIfAttr>();
1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1154 if (NewI == NewE || OldI == OldE)
1155 return true;
1156 llvm::FoldingSetNodeID NewID, OldID;
1157 NewI->getCond()->Profile(NewID, Context, true);
1158 OldI->getCond()->Profile(OldID, Context, true);
1159 if (NewID != OldID)
1160 return true;
1161 }
1162
1163 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1164 // Don't allow overloading of destructors. (In theory we could, but it
1165 // would be a giant change to clang.)
1166 if (isa<CXXDestructorDecl>(New))
1167 return false;
1168
1169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1170 OldTarget = IdentifyCUDATarget(Old);
1171 if (NewTarget == CFT_InvalidTarget)
1172 return false;
1173
1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1174, __extension__ __PRETTY_FUNCTION__))
;
1175
1176 // Allow overloading of functions with same signature and different CUDA
1177 // target attributes.
1178 return NewTarget != OldTarget;
1179 }
1180
1181 // The signatures match; this is not an overload.
1182 return false;
1183}
1184
1185/// \brief Checks availability of the function depending on the current
1186/// function context. Inside an unavailable function, unavailability is ignored.
1187///
1188/// \returns true if \arg FD is unavailable and current context is inside
1189/// an available function, false otherwise.
1190bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1191 if (!FD->isUnavailable())
1192 return false;
1193
1194 // Walk up the context of the caller.
1195 Decl *C = cast<Decl>(CurContext);
1196 do {
1197 if (C->isUnavailable())
1198 return false;
1199 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1200 return true;
1201}
1202
1203/// \brief Tries a user-defined conversion from From to ToType.
1204///
1205/// Produces an implicit conversion sequence for when a standard conversion
1206/// is not an option. See TryImplicitConversion for more information.
1207static ImplicitConversionSequence
1208TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1210 bool AllowExplicit,
1211 bool InOverloadResolution,
1212 bool CStyle,
1213 bool AllowObjCWritebackConversion,
1214 bool AllowObjCConversionOnExplicit) {
1215 ImplicitConversionSequence ICS;
1216
1217 if (SuppressUserConversions) {
1218 // We're not in the case above, so there is no conversion that
1219 // we can perform.
1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1221 return ICS;
1222 }
1223
1224 // Attempt user-defined conversion.
1225 OverloadCandidateSet Conversions(From->getExprLoc(),
1226 OverloadCandidateSet::CSK_Normal);
1227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1228 Conversions, AllowExplicit,
1229 AllowObjCConversionOnExplicit)) {
1230 case OR_Success:
1231 case OR_Deleted:
1232 ICS.setUserDefined();
1233 // C++ [over.ics.user]p4:
1234 // A conversion of an expression of class type to the same class
1235 // type is given Exact Match rank, and a conversion of an
1236 // expression of class type to a base class of that type is
1237 // given Conversion rank, in spite of the fact that a copy
1238 // constructor (i.e., a user-defined conversion function) is
1239 // called for those cases.
1240 if (CXXConstructorDecl *Constructor
1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242 QualType FromCanon
1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244 QualType ToCanon
1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1246 if (Constructor->isCopyConstructor() &&
1247 (FromCanon == ToCanon ||
1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1249 // Turn this into a "standard" conversion sequence, so that it
1250 // gets ranked with standard conversion sequences.
1251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1252 ICS.setStandard();
1253 ICS.Standard.setAsIdentityConversion();
1254 ICS.Standard.setFromType(From->getType());
1255 ICS.Standard.setAllToTypes(ToType);
1256 ICS.Standard.CopyConstructor = Constructor;
1257 ICS.Standard.FoundCopyConstructor = Found;
1258 if (ToCanon != FromCanon)
1259 ICS.Standard.Second = ICK_Derived_To_Base;
1260 }
1261 }
1262 break;
1263
1264 case OR_Ambiguous:
1265 ICS.setAmbiguous();
1266 ICS.Ambiguous.setFromType(From->getType());
1267 ICS.Ambiguous.setToType(ToType);
1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1269 Cand != Conversions.end(); ++Cand)
1270 if (Cand->Viable)
1271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1272 break;
1273
1274 // Fall through.
1275 case OR_No_Viable_Function:
1276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1277 break;
1278 }
1279
1280 return ICS;
1281}
1282
1283/// TryImplicitConversion - Attempt to perform an implicit conversion
1284/// from the given expression (Expr) to the given type (ToType). This
1285/// function returns an implicit conversion sequence that can be used
1286/// to perform the initialization. Given
1287///
1288/// void f(float f);
1289/// void g(int i) { f(i); }
1290///
1291/// this routine would produce an implicit conversion sequence to
1292/// describe the initialization of f from i, which will be a standard
1293/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1294/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295//
1296/// Note that this routine only determines how the conversion can be
1297/// performed; it does not actually perform the conversion. As such,
1298/// it will not produce any diagnostics if no conversion is available,
1299/// but will instead return an implicit conversion sequence of kind
1300/// "BadConversion".
1301///
1302/// If @p SuppressUserConversions, then user-defined conversions are
1303/// not permitted.
1304/// If @p AllowExplicit, then explicit user-defined conversions are
1305/// permitted.
1306///
1307/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1308/// writeback conversion, which allows __autoreleasing id* parameters to
1309/// be initialized with __strong id* or __weak id* arguments.
1310static ImplicitConversionSequence
1311TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1312 bool SuppressUserConversions,
1313 bool AllowExplicit,
1314 bool InOverloadResolution,
1315 bool CStyle,
1316 bool AllowObjCWritebackConversion,
1317 bool AllowObjCConversionOnExplicit) {
1318 ImplicitConversionSequence ICS;
1319 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1321 ICS.setStandard();
1322 return ICS;
1323 }
1324
1325 if (!S.getLangOpts().CPlusPlus) {
1326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1327 return ICS;
1328 }
1329
1330 // C++ [over.ics.user]p4:
1331 // A conversion of an expression of class type to the same class
1332 // type is given Exact Match rank, and a conversion of an
1333 // expression of class type to a base class of that type is
1334 // given Conversion rank, in spite of the fact that a copy/move
1335 // constructor (i.e., a user-defined conversion function) is
1336 // called for those cases.
1337 QualType FromType = From->getType();
1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1339 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1341 ICS.setStandard();
1342 ICS.Standard.setAsIdentityConversion();
1343 ICS.Standard.setFromType(FromType);
1344 ICS.Standard.setAllToTypes(ToType);
1345
1346 // We don't actually check at this point whether there is a valid
1347 // copy/move constructor, since overloading just assumes that it
1348 // exists. When we actually perform initialization, we'll find the
1349 // appropriate constructor to copy the returned object, if needed.
1350 ICS.Standard.CopyConstructor = nullptr;
1351
1352 // Determine whether this is considered a derived-to-base conversion.
1353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1354 ICS.Standard.Second = ICK_Derived_To_Base;
1355
1356 return ICS;
1357 }
1358
1359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1360 AllowExplicit, InOverloadResolution, CStyle,
1361 AllowObjCWritebackConversion,
1362 AllowObjCConversionOnExplicit);
1363}
1364
1365ImplicitConversionSequence
1366Sema::TryImplicitConversion(Expr *From, QualType ToType,
1367 bool SuppressUserConversions,
1368 bool AllowExplicit,
1369 bool InOverloadResolution,
1370 bool CStyle,
1371 bool AllowObjCWritebackConversion) {
1372 return ::TryImplicitConversion(*this, From, ToType,
1373 SuppressUserConversions, AllowExplicit,
1374 InOverloadResolution, CStyle,
1375 AllowObjCWritebackConversion,
1376 /*AllowObjCConversionOnExplicit=*/false);
1377}
1378
1379/// PerformImplicitConversion - Perform an implicit conversion of the
1380/// expression From to the type ToType. Returns the
1381/// converted expression. Flavor is the kind of conversion we're
1382/// performing, used in the error message. If @p AllowExplicit,
1383/// explicit user-defined conversions are permitted.
1384ExprResult
1385Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1386 AssignmentAction Action, bool AllowExplicit) {
1387 ImplicitConversionSequence ICS;
1388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1389}
1390
1391ExprResult
1392Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1393 AssignmentAction Action, bool AllowExplicit,
1394 ImplicitConversionSequence& ICS) {
1395 if (checkPlaceholderForOverload(*this, From))
1396 return ExprError();
1397
1398 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1399 bool AllowObjCWritebackConversion
1400 = getLangOpts().ObjCAutoRefCount &&
1401 (Action == AA_Passing || Action == AA_Sending);
1402 if (getLangOpts().ObjC1)
1403 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1404 ToType, From->getType(), From);
1405 ICS = ::TryImplicitConversion(*this, From, ToType,
1406 /*SuppressUserConversions=*/false,
1407 AllowExplicit,
1408 /*InOverloadResolution=*/false,
1409 /*CStyle=*/false,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
1412 return PerformImplicitConversion(From, ToType, ICS, Action);
1413}
1414
1415/// \brief Determine whether the conversion from FromType to ToType is a valid
1416/// conversion that strips "noexcept" or "noreturn" off the nested function
1417/// type.
1418bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1419 QualType &ResultTy) {
1420 if (Context.hasSameUnqualifiedType(FromType, ToType))
1421 return false;
1422
1423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1424 // or F(t noexcept) -> F(t)
1425 // where F adds one of the following at most once:
1426 // - a pointer
1427 // - a member pointer
1428 // - a block pointer
1429 // Changes here need matching changes in FindCompositePointerType.
1430 CanQualType CanTo = Context.getCanonicalType(ToType);
1431 CanQualType CanFrom = Context.getCanonicalType(FromType);
1432 Type::TypeClass TyClass = CanTo->getTypeClass();
1433 if (TyClass != CanFrom->getTypeClass()) return false;
1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1435 if (TyClass == Type::Pointer) {
1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1438 } else if (TyClass == Type::BlockPointer) {
1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1441 } else if (TyClass == Type::MemberPointer) {
1442 auto ToMPT = CanTo.getAs<MemberPointerType>();
1443 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1444 // A function pointer conversion cannot change the class of the function.
1445 if (ToMPT->getClass() != FromMPT->getClass())
1446 return false;
1447 CanTo = ToMPT->getPointeeType();
1448 CanFrom = FromMPT->getPointeeType();
1449 } else {
1450 return false;
1451 }
1452
1453 TyClass = CanTo->getTypeClass();
1454 if (TyClass != CanFrom->getTypeClass()) return false;
1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1456 return false;
1457 }
1458
1459 const auto *FromFn = cast<FunctionType>(CanFrom);
1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1461
1462 const auto *ToFn = cast<FunctionType>(CanTo);
1463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464
1465 bool Changed = false;
1466
1467 // Drop 'noreturn' if not present in target type.
1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1470 Changed = true;
1471 }
1472
1473 // Drop 'noexcept' if not present in target type.
1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1475 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1477 FromFn = cast<FunctionType>(
1478 Context.getFunctionType(FromFPT->getReturnType(),
1479 FromFPT->getParamTypes(),
1480 FromFPT->getExtProtoInfo().withExceptionSpec(
1481 FunctionProtoType::ExceptionSpecInfo()))
1482 .getTypePtr());
1483 Changed = true;
1484 }
1485
1486 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1487 // only if the ExtParameterInfo lists of the two function prototypes can be
1488 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1489 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1490 bool CanUseToFPT, CanUseFromFPT;
1491 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1492 CanUseFromFPT, NewParamInfos) &&
1493 CanUseToFPT && !CanUseFromFPT) {
1494 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1495 ExtInfo.ExtParameterInfos =
1496 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1497 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1498 FromFPT->getParamTypes(), ExtInfo);
1499 FromFn = QT->getAs<FunctionType>();
1500 Changed = true;
1501 }
1502 }
1503
1504 if (!Changed)
1505 return false;
1506
1507 assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1507, __extension__ __PRETTY_FUNCTION__))
;
1508 if (QualType(FromFn, 0) != CanTo) return false;
1509
1510 ResultTy = ToType;
1511 return true;
1512}
1513
1514/// \brief Determine whether the conversion from FromType to ToType is a valid
1515/// vector conversion.
1516///
1517/// \param ICK Will be set to the vector conversion kind, if this is a vector
1518/// conversion.
1519static bool IsVectorConversion(Sema &S, QualType FromType,
1520 QualType ToType, ImplicitConversionKind &ICK) {
1521 // We need at least one of these types to be a vector type to have a vector
1522 // conversion.
1523 if (!ToType->isVectorType() && !FromType->isVectorType())
1524 return false;
1525
1526 // Identical types require no conversions.
1527 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1528 return false;
1529
1530 // There are no conversions between extended vector types, only identity.
1531 if (ToType->isExtVectorType()) {
1532 // There are no conversions between extended vector types other than the
1533 // identity conversion.
1534 if (FromType->isExtVectorType())
1535 return false;
1536
1537 // Vector splat from any arithmetic type to a vector.
1538 if (FromType->isArithmeticType()) {
1539 ICK = ICK_Vector_Splat;
1540 return true;
1541 }
1542 }
1543
1544 // We can perform the conversion between vector types in the following cases:
1545 // 1)vector types are equivalent AltiVec and GCC vector types
1546 // 2)lax vector conversions are permitted and the vector types are of the
1547 // same size
1548 if (ToType->isVectorType() && FromType->isVectorType()) {
1549 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1550 S.isLaxVectorConversion(FromType, ToType)) {
1551 ICK = ICK_Vector_Conversion;
1552 return true;
1553 }
1554 }
1555
1556 return false;
1557}
1558
1559static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1560 bool InOverloadResolution,
1561 StandardConversionSequence &SCS,
1562 bool CStyle);
1563
1564/// IsStandardConversion - Determines whether there is a standard
1565/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1566/// expression From to the type ToType. Standard conversion sequences
1567/// only consider non-class types; for conversions that involve class
1568/// types, use TryImplicitConversion. If a conversion exists, SCS will
1569/// contain the standard conversion sequence required to perform this
1570/// conversion and this routine will return true. Otherwise, this
1571/// routine will return false and the value of SCS is unspecified.
1572static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1573 bool InOverloadResolution,
1574 StandardConversionSequence &SCS,
1575 bool CStyle,
1576 bool AllowObjCWritebackConversion) {
1577 QualType FromType = From->getType();
1578
1579 // Standard conversions (C++ [conv])
1580 SCS.setAsIdentityConversion();
1581 SCS.IncompatibleObjC = false;
1582 SCS.setFromType(FromType);
1583 SCS.CopyConstructor = nullptr;
1584
1585 // There are no standard conversions for class types in C++, so
1586 // abort early. When overloading in C, however, we do permit them.
1587 if (S.getLangOpts().CPlusPlus &&
1588 (FromType->isRecordType() || ToType->isRecordType()))
1589 return false;
1590
1591 // The first conversion can be an lvalue-to-rvalue conversion,
1592 // array-to-pointer conversion, or function-to-pointer conversion
1593 // (C++ 4p1).
1594
1595 if (FromType == S.Context.OverloadTy) {
1596 DeclAccessPair AccessPair;
1597 if (FunctionDecl *Fn
1598 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1599 AccessPair)) {
1600 // We were able to resolve the address of the overloaded function,
1601 // so we can convert to the type of that function.
1602 FromType = Fn->getType();
1603 SCS.setFromType(FromType);
1604
1605 // we can sometimes resolve &foo<int> regardless of ToType, so check
1606 // if the type matches (identity) or we are converting to bool
1607 if (!S.Context.hasSameUnqualifiedType(
1608 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1609 QualType resultTy;
1610 // if the function type matches except for [[noreturn]], it's ok
1611 if (!S.IsFunctionConversion(FromType,
1612 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1613 // otherwise, only a boolean conversion is standard
1614 if (!ToType->isBooleanType())
1615 return false;
1616 }
1617
1618 // Check if the "from" expression is taking the address of an overloaded
1619 // function and recompute the FromType accordingly. Take advantage of the
1620 // fact that non-static member functions *must* have such an address-of
1621 // expression.
1622 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1623 if (Method && !Method->isStatic()) {
1624 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1625, __extension__ __PRETTY_FUNCTION__))
1625 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1625, __extension__ __PRETTY_FUNCTION__))
;
1626 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1628, __extension__ __PRETTY_FUNCTION__))
1627 == 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1628, __extension__ __PRETTY_FUNCTION__))
1628 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1628, __extension__ __PRETTY_FUNCTION__))
;
1629 const Type *ClassType
1630 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1631 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1632 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1633 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1635, __extension__ __PRETTY_FUNCTION__))
1634 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1635, __extension__ __PRETTY_FUNCTION__))
1635 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1635, __extension__ __PRETTY_FUNCTION__))
;
1636 FromType = S.Context.getPointerType(FromType);
1637 }
1638
1639 // Check that we've computed the proper type after overload resolution.
1640 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1641 // be calling it from within an NDEBUG block.
1642 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1643 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1644 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
;
1645 } else {
1646 return false;
1647 }
1648 }
1649 // Lvalue-to-rvalue conversion (C++11 4.1):
1650 // A glvalue (3.10) of a non-function, non-array type T can
1651 // be converted to a prvalue.
1652 bool argIsLValue = From->isGLValue();
1653 if (argIsLValue &&
1654 !FromType->isFunctionType() && !FromType->isArrayType() &&
1655 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1656 SCS.First = ICK_Lvalue_To_Rvalue;
1657
1658 // C11 6.3.2.1p2:
1659 // ... if the lvalue has atomic type, the value has the non-atomic version
1660 // of the type of the lvalue ...
1661 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1662 FromType = Atomic->getValueType();
1663
1664 // If T is a non-class type, the type of the rvalue is the
1665 // cv-unqualified version of T. Otherwise, the type of the rvalue
1666 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1667 // just strip the qualifiers because they don't matter.
1668 FromType = FromType.getUnqualifiedType();
1669 } else if (FromType->isArrayType()) {
1670 // Array-to-pointer conversion (C++ 4.2)
1671 SCS.First = ICK_Array_To_Pointer;
1672
1673 // An lvalue or rvalue of type "array of N T" or "array of unknown
1674 // bound of T" can be converted to an rvalue of type "pointer to
1675 // T" (C++ 4.2p1).
1676 FromType = S.Context.getArrayDecayedType(FromType);
1677
1678 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1679 // This conversion is deprecated in C++03 (D.4)
1680 SCS.DeprecatedStringLiteralToCharPtr = true;
1681
1682 // For the purpose of ranking in overload resolution
1683 // (13.3.3.1.1), this conversion is considered an
1684 // array-to-pointer conversion followed by a qualification
1685 // conversion (4.4). (C++ 4.2p2)
1686 SCS.Second = ICK_Identity;
1687 SCS.Third = ICK_Qualification;
1688 SCS.QualificationIncludesObjCLifetime = false;
1689 SCS.setAllToTypes(FromType);
1690 return true;
1691 }
1692 } else if (FromType->isFunctionType() && argIsLValue) {
1693 // Function-to-pointer conversion (C++ 4.3).
1694 SCS.First = ICK_Function_To_Pointer;
1695
1696 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1697 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1698 if (!S.checkAddressOfFunctionIsAvailable(FD))
1699 return false;
1700
1701 // An lvalue of function type T can be converted to an rvalue of
1702 // type "pointer to T." The result is a pointer to the
1703 // function. (C++ 4.3p1).
1704 FromType = S.Context.getPointerType(FromType);
1705 } else {
1706 // We don't require any conversions for the first step.
1707 SCS.First = ICK_Identity;
1708 }
1709 SCS.setToType(0, FromType);
1710
1711 // The second conversion can be an integral promotion, floating
1712 // point promotion, integral conversion, floating point conversion,
1713 // floating-integral conversion, pointer conversion,
1714 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1715 // For overloading in C, this can also be a "compatible-type"
1716 // conversion.
1717 bool IncompatibleObjC = false;
1718 ImplicitConversionKind SecondICK = ICK_Identity;
1719 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1720 // The unqualified versions of the types are the same: there's no
1721 // conversion to do.
1722 SCS.Second = ICK_Identity;
1723 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1724 // Integral promotion (C++ 4.5).
1725 SCS.Second = ICK_Integral_Promotion;
1726 FromType = ToType.getUnqualifiedType();
1727 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1728 // Floating point promotion (C++ 4.6).
1729 SCS.Second = ICK_Floating_Promotion;
1730 FromType = ToType.getUnqualifiedType();
1731 } else if (S.IsComplexPromotion(FromType, ToType)) {
1732 // Complex promotion (Clang extension)
1733 SCS.Second = ICK_Complex_Promotion;
1734 FromType = ToType.getUnqualifiedType();
1735 } else if (ToType->isBooleanType() &&
1736 (FromType->isArithmeticType() ||
1737 FromType->isAnyPointerType() ||
1738 FromType->isBlockPointerType() ||
1739 FromType->isMemberPointerType() ||
1740 FromType->isNullPtrType())) {
1741 // Boolean conversions (C++ 4.12).
1742 SCS.Second = ICK_Boolean_Conversion;
1743 FromType = S.Context.BoolTy;
1744 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1745 ToType->isIntegralType(S.Context)) {
1746 // Integral conversions (C++ 4.7).
1747 SCS.Second = ICK_Integral_Conversion;
1748 FromType = ToType.getUnqualifiedType();
1749 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1750 // Complex conversions (C99 6.3.1.6)
1751 SCS.Second = ICK_Complex_Conversion;
1752 FromType = ToType.getUnqualifiedType();
1753 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1754 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1755 // Complex-real conversions (C99 6.3.1.7)
1756 SCS.Second = ICK_Complex_Real;
1757 FromType = ToType.getUnqualifiedType();
1758 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1759 // FIXME: disable conversions between long double and __float128 if
1760 // their representation is different until there is back end support
1761 // We of course allow this conversion if long double is really double.
1762 if (&S.Context.getFloatTypeSemantics(FromType) !=
1763 &S.Context.getFloatTypeSemantics(ToType)) {
1764 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1765 ToType == S.Context.LongDoubleTy) ||
1766 (FromType == S.Context.LongDoubleTy &&
1767 ToType == S.Context.Float128Ty));
1768 if (Float128AndLongDouble &&
1769 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1770 &llvm::APFloat::IEEEdouble()))
1771 return false;
1772 }
1773 // Floating point conversions (C++ 4.8).
1774 SCS.Second = ICK_Floating_Conversion;
1775 FromType = ToType.getUnqualifiedType();
1776 } else if ((FromType->isRealFloatingType() &&
1777 ToType->isIntegralType(S.Context)) ||
1778 (FromType->isIntegralOrUnscopedEnumerationType() &&
1779 ToType->isRealFloatingType())) {
1780 // Floating-integral conversions (C++ 4.9).
1781 SCS.Second = ICK_Floating_Integral;
1782 FromType = ToType.getUnqualifiedType();
1783 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1784 SCS.Second = ICK_Block_Pointer_Conversion;
1785 } else if (AllowObjCWritebackConversion &&
1786 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1787 SCS.Second = ICK_Writeback_Conversion;
1788 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1789 FromType, IncompatibleObjC)) {
1790 // Pointer conversions (C++ 4.10).
1791 SCS.Second = ICK_Pointer_Conversion;
1792 SCS.IncompatibleObjC = IncompatibleObjC;
1793 FromType = FromType.getUnqualifiedType();
1794 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1795 InOverloadResolution, FromType)) {
1796 // Pointer to member conversions (4.11).
1797 SCS.Second = ICK_Pointer_Member;
1798 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1799 SCS.Second = SecondICK;
1800 FromType = ToType.getUnqualifiedType();
1801 } else if (!S.getLangOpts().CPlusPlus &&
1802 S.Context.typesAreCompatible(ToType, FromType)) {
1803 // Compatible conversions (Clang extension for C function overloading)
1804 SCS.Second = ICK_Compatible_Conversion;
1805 FromType = ToType.getUnqualifiedType();
1806 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1807 InOverloadResolution,
1808 SCS, CStyle)) {
1809 SCS.Second = ICK_TransparentUnionConversion;
1810 FromType = ToType;
1811 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1812 CStyle)) {
1813 // tryAtomicConversion has updated the standard conversion sequence
1814 // appropriately.
1815 return true;
1816 } else if (ToType->isEventT() &&
1817 From->isIntegerConstantExpr(S.getASTContext()) &&
1818 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1819 SCS.Second = ICK_Zero_Event_Conversion;
1820 FromType = ToType;
1821 } else if (ToType->isQueueT() &&
1822 From->isIntegerConstantExpr(S.getASTContext()) &&
1823 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1824 SCS.Second = ICK_Zero_Queue_Conversion;
1825 FromType = ToType;
1826 } else {
1827 // No second conversion required.
1828 SCS.Second = ICK_Identity;
1829 }
1830 SCS.setToType(1, FromType);
1831
1832 // The third conversion can be a function pointer conversion or a
1833 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1834 bool ObjCLifetimeConversion;
1835 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1836 // Function pointer conversions (removing 'noexcept') including removal of
1837 // 'noreturn' (Clang extension).
1838 SCS.Third = ICK_Function_Conversion;
1839 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1840 ObjCLifetimeConversion)) {
1841 SCS.Third = ICK_Qualification;
1842 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1843 FromType = ToType;
1844 } else {
1845 // No conversion required
1846 SCS.Third = ICK_Identity;
1847 }
1848
1849 // C++ [over.best.ics]p6:
1850 // [...] Any difference in top-level cv-qualification is
1851 // subsumed by the initialization itself and does not constitute
1852 // a conversion. [...]
1853 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1854 QualType CanonTo = S.Context.getCanonicalType(ToType);
1855 if (CanonFrom.getLocalUnqualifiedType()
1856 == CanonTo.getLocalUnqualifiedType() &&
1857 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1858 FromType = ToType;
1859 CanonFrom = CanonTo;
1860 }
1861
1862 SCS.setToType(2, FromType);
1863
1864 if (CanonFrom == CanonTo)
1865 return true;
1866
1867 // If we have not converted the argument type to the parameter type,
1868 // this is a bad conversion sequence, unless we're resolving an overload in C.
1869 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1870 return false;
1871
1872 ExprResult ER = ExprResult{From};
1873 Sema::AssignConvertType Conv =
1874 S.CheckSingleAssignmentConstraints(ToType, ER,
1875 /*Diagnose=*/false,
1876 /*DiagnoseCFAudited=*/false,
1877 /*ConvertRHS=*/false);
1878 ImplicitConversionKind SecondConv;
1879 switch (Conv) {
1880 case Sema::Compatible:
1881 SecondConv = ICK_C_Only_Conversion;
1882 break;
1883 // For our purposes, discarding qualifiers is just as bad as using an
1884 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1885 // qualifiers, as well.
1886 case Sema::CompatiblePointerDiscardsQualifiers:
1887 case Sema::IncompatiblePointer:
1888 case Sema::IncompatiblePointerSign:
1889 SecondConv = ICK_Incompatible_Pointer_Conversion;
1890 break;
1891 default:
1892 return false;
1893 }
1894
1895 // First can only be an lvalue conversion, so we pretend that this was the
1896 // second conversion. First should already be valid from earlier in the
1897 // function.
1898 SCS.Second = SecondConv;
1899 SCS.setToType(1, ToType);
1900
1901 // Third is Identity, because Second should rank us worse than any other
1902 // conversion. This could also be ICK_Qualification, but it's simpler to just
1903 // lump everything in with the second conversion, and we don't gain anything
1904 // from making this ICK_Qualification.
1905 SCS.Third = ICK_Identity;
1906 SCS.setToType(2, ToType);
1907 return true;
1908}
1909
1910static bool
1911IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1912 QualType &ToType,
1913 bool InOverloadResolution,
1914 StandardConversionSequence &SCS,
1915 bool CStyle) {
1916
1917 const RecordType *UT = ToType->getAsUnionType();
1918 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1919 return false;
1920 // The field to initialize within the transparent union.
1921 RecordDecl *UD = UT->getDecl();
1922 // It's compatible if the expression matches any of the fields.
1923 for (const auto *it : UD->fields()) {
1924 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1925 CStyle, /*ObjCWritebackConversion=*/false)) {
1926 ToType = it->getType();
1927 return true;
1928 }
1929 }
1930 return false;
1931}
1932
1933/// IsIntegralPromotion - Determines whether the conversion from the
1934/// expression From (whose potentially-adjusted type is FromType) to
1935/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1936/// sets PromotedType to the promoted type.
1937bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1938 const BuiltinType *To = ToType->getAs<BuiltinType>();
1939 // All integers are built-in.
1940 if (!To) {
1941 return false;
1942 }
1943
1944 // An rvalue of type char, signed char, unsigned char, short int, or
1945 // unsigned short int can be converted to an rvalue of type int if
1946 // int can represent all the values of the source type; otherwise,
1947 // the source rvalue can be converted to an rvalue of type unsigned
1948 // int (C++ 4.5p1).
1949 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1950 !FromType->isEnumeralType()) {
1951 if (// We can promote any signed, promotable integer type to an int
1952 (FromType->isSignedIntegerType() ||
1953 // We can promote any unsigned integer type whose size is
1954 // less than int to an int.
1955 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1956 return To->getKind() == BuiltinType::Int;
1957 }
1958
1959 return To->getKind() == BuiltinType::UInt;
1960 }
1961
1962 // C++11 [conv.prom]p3:
1963 // A prvalue of an unscoped enumeration type whose underlying type is not
1964 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1965 // following types that can represent all the values of the enumeration
1966 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1967 // unsigned int, long int, unsigned long int, long long int, or unsigned
1968 // long long int. If none of the types in that list can represent all the
1969 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1970 // type can be converted to an rvalue a prvalue of the extended integer type
1971 // with lowest integer conversion rank (4.13) greater than the rank of long
1972 // long in which all the values of the enumeration can be represented. If
1973 // there are two such extended types, the signed one is chosen.
1974 // C++11 [conv.prom]p4:
1975 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1976 // can be converted to a prvalue of its underlying type. Moreover, if
1977 // integral promotion can be applied to its underlying type, a prvalue of an
1978 // unscoped enumeration type whose underlying type is fixed can also be
1979 // converted to a prvalue of the promoted underlying type.
1980 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1981 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1982 // provided for a scoped enumeration.
1983 if (FromEnumType->getDecl()->isScoped())
1984 return false;
1985
1986 // We can perform an integral promotion to the underlying type of the enum,
1987 // even if that's not the promoted type. Note that the check for promoting
1988 // the underlying type is based on the type alone, and does not consider
1989 // the bitfield-ness of the actual source expression.
1990 if (FromEnumType->getDecl()->isFixed()) {
1991 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1992 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1993 IsIntegralPromotion(nullptr, Underlying, ToType);
1994 }
1995
1996 // We have already pre-calculated the promotion type, so this is trivial.
1997 if (ToType->isIntegerType() &&
1998 isCompleteType(From->getLocStart(), FromType))
1999 return Context.hasSameUnqualifiedType(
2000 ToType, FromEnumType->getDecl()->getPromotionType());
2001 }
2002
2003 // C++0x [conv.prom]p2:
2004 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2005 // to an rvalue a prvalue of the first of the following types that can
2006 // represent all the values of its underlying type: int, unsigned int,
2007 // long int, unsigned long int, long long int, or unsigned long long int.
2008 // If none of the types in that list can represent all the values of its
2009 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2010 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2011 // type.
2012 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2013 ToType->isIntegerType()) {
2014 // Determine whether the type we're converting from is signed or
2015 // unsigned.
2016 bool FromIsSigned = FromType->isSignedIntegerType();
2017 uint64_t FromSize = Context.getTypeSize(FromType);
2018
2019 // The types we'll try to promote to, in the appropriate
2020 // order. Try each of these types.
2021 QualType PromoteTypes[6] = {
2022 Context.IntTy, Context.UnsignedIntTy,
2023 Context.LongTy, Context.UnsignedLongTy ,
2024 Context.LongLongTy, Context.UnsignedLongLongTy
2025 };
2026 for (int Idx = 0; Idx < 6; ++Idx) {
2027 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2028 if (FromSize < ToSize ||
2029 (FromSize == ToSize &&
2030 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2031 // We found the type that we can promote to. If this is the
2032 // type we wanted, we have a promotion. Otherwise, no
2033 // promotion.
2034 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2035 }
2036 }
2037 }
2038
2039 // An rvalue for an integral bit-field (9.6) can be converted to an
2040 // rvalue of type int if int can represent all the values of the
2041 // bit-field; otherwise, it can be converted to unsigned int if
2042 // unsigned int can represent all the values of the bit-field. If
2043 // the bit-field is larger yet, no integral promotion applies to
2044 // it. If the bit-field has an enumerated type, it is treated as any
2045 // other value of that type for promotion purposes (C++ 4.5p3).
2046 // FIXME: We should delay checking of bit-fields until we actually perform the
2047 // conversion.
2048 if (From) {
2049 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2050 llvm::APSInt BitWidth;
2051 if (FromType->isIntegralType(Context) &&
2052 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2053 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2054 ToSize = Context.getTypeSize(ToType);
2055
2056 // Are we promoting to an int from a bitfield that fits in an int?
2057 if (BitWidth < ToSize ||
2058 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2059 return To->getKind() == BuiltinType::Int;
2060 }
2061
2062 // Are we promoting to an unsigned int from an unsigned bitfield
2063 // that fits into an unsigned int?
2064 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2065 return To->getKind() == BuiltinType::UInt;
2066 }
2067
2068 return false;
2069 }
2070 }
2071 }
2072
2073 // An rvalue of type bool can be converted to an rvalue of type int,
2074 // with false becoming zero and true becoming one (C++ 4.5p4).
2075 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2076 return true;
2077 }
2078
2079 return false;
2080}
2081
2082/// IsFloatingPointPromotion - Determines whether the conversion from
2083/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2084/// returns true and sets PromotedType to the promoted type.
2085bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2086 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2087 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2088 /// An rvalue of type float can be converted to an rvalue of type
2089 /// double. (C++ 4.6p1).
2090 if (FromBuiltin->getKind() == BuiltinType::Float &&
2091 ToBuiltin->getKind() == BuiltinType::Double)
2092 return true;
2093
2094 // C99 6.3.1.5p1:
2095 // When a float is promoted to double or long double, or a
2096 // double is promoted to long double [...].
2097 if (!getLangOpts().CPlusPlus &&
2098 (FromBuiltin->getKind() == BuiltinType::Float ||
2099 FromBuiltin->getKind() == BuiltinType::Double) &&
2100 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2101 ToBuiltin->getKind() == BuiltinType::Float128))
2102 return true;
2103
2104 // Half can be promoted to float.
2105 if (!getLangOpts().NativeHalfType &&
2106 FromBuiltin->getKind() == BuiltinType::Half &&
2107 ToBuiltin->getKind() == BuiltinType::Float)
2108 return true;
2109 }
2110
2111 return false;
2112}
2113
2114/// \brief Determine if a conversion is a complex promotion.
2115///
2116/// A complex promotion is defined as a complex -> complex conversion
2117/// where the conversion between the underlying real types is a
2118/// floating-point or integral promotion.
2119bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2120 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2121 if (!FromComplex)
2122 return false;
2123
2124 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2125 if (!ToComplex)
2126 return false;
2127
2128 return IsFloatingPointPromotion(FromComplex->getElementType(),
2129 ToComplex->getElementType()) ||
2130 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2131 ToComplex->getElementType());
2132}
2133
2134/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2135/// the pointer type FromPtr to a pointer to type ToPointee, with the
2136/// same type qualifiers as FromPtr has on its pointee type. ToType,
2137/// if non-empty, will be a pointer to ToType that may or may not have
2138/// the right set of qualifiers on its pointee.
2139///
2140static QualType
2141BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2142 QualType ToPointee, QualType ToType,
2143 ASTContext &Context,
2144 bool StripObjCLifetime = false) {
2145 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2147, __extension__ __PRETTY_FUNCTION__))
2146 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2147, __extension__ __PRETTY_FUNCTION__))
2147 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2147, __extension__ __PRETTY_FUNCTION__))
;
2148
2149 /// Conversions to 'id' subsume cv-qualifier conversions.
2150 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2151 return ToType.getUnqualifiedType();
2152
2153 QualType CanonFromPointee
2154 = Context.getCanonicalType(FromPtr->getPointeeType());
2155 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2156 Qualifiers Quals = CanonFromPointee.getQualifiers();
2157
2158 if (StripObjCLifetime)
2159 Quals.removeObjCLifetime();
2160
2161 // Exact qualifier match -> return the pointer type we're converting to.
2162 if (CanonToPointee.getLocalQualifiers() == Quals) {
2163 // ToType is exactly what we need. Return it.
2164 if (!ToType.isNull())
2165 return ToType.getUnqualifiedType();
2166
2167 // Build a pointer to ToPointee. It has the right qualifiers
2168 // already.
2169 if (isa<ObjCObjectPointerType>(ToType))
2170 return Context.getObjCObjectPointerType(ToPointee);
2171 return Context.getPointerType(ToPointee);
2172 }
2173
2174 // Just build a canonical type that has the right qualifiers.
2175 QualType QualifiedCanonToPointee
2176 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2177
2178 if (isa<ObjCObjectPointerType>(ToType))
2179 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2180 return Context.getPointerType(QualifiedCanonToPointee);
2181}
2182
2183static bool isNullPointerConstantForConversion(Expr *Expr,
2184 bool InOverloadResolution,
2185 ASTContext &Context) {
2186 // Handle value-dependent integral null pointer constants correctly.
2187 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2188 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2189 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2190 return !InOverloadResolution;
2191
2192 return Expr->isNullPointerConstant(Context,
2193 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2194 : Expr::NPC_ValueDependentIsNull);
2195}
2196
2197/// IsPointerConversion - Determines whether the conversion of the
2198/// expression From, which has the (possibly adjusted) type FromType,
2199/// can be converted to the type ToType via a pointer conversion (C++
2200/// 4.10). If so, returns true and places the converted type (that
2201/// might differ from ToType in its cv-qualifiers at some level) into
2202/// ConvertedType.
2203///
2204/// This routine also supports conversions to and from block pointers
2205/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2206/// pointers to interfaces. FIXME: Once we've determined the
2207/// appropriate overloading rules for Objective-C, we may want to
2208/// split the Objective-C checks into a different routine; however,
2209/// GCC seems to consider all of these conversions to be pointer
2210/// conversions, so for now they live here. IncompatibleObjC will be
2211/// set if the conversion is an allowed Objective-C conversion that
2212/// should result in a warning.
2213bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2214 bool InOverloadResolution,
2215 QualType& ConvertedType,
2216 bool &IncompatibleObjC) {
2217 IncompatibleObjC = false;
2218 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2219 IncompatibleObjC))
2220 return true;
2221
2222 // Conversion from a null pointer constant to any Objective-C pointer type.
2223 if (ToType->isObjCObjectPointerType() &&
2224 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2225 ConvertedType = ToType;
2226 return true;
2227 }
2228
2229 // Blocks: Block pointers can be converted to void*.
2230 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2231 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2232 ConvertedType = ToType;
2233 return true;
2234 }
2235 // Blocks: A null pointer constant can be converted to a block
2236 // pointer type.
2237 if (ToType->isBlockPointerType() &&
2238 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2239 ConvertedType = ToType;
2240 return true;
2241 }
2242
2243 // If the left-hand-side is nullptr_t, the right side can be a null
2244 // pointer constant.
2245 if (ToType->isNullPtrType() &&
2246 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247 ConvertedType = ToType;
2248 return true;
2249 }
2250
2251 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2252 if (!ToTypePtr)
2253 return false;
2254
2255 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2256 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2257 ConvertedType = ToType;
2258 return true;
2259 }
2260
2261 // Beyond this point, both types need to be pointers
2262 // , including objective-c pointers.
2263 QualType ToPointeeType = ToTypePtr->getPointeeType();
2264 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2265 !getLangOpts().ObjCAutoRefCount) {
2266 ConvertedType = BuildSimilarlyQualifiedPointerType(
2267 FromType->getAs<ObjCObjectPointerType>(),
2268 ToPointeeType,
2269 ToType, Context);
2270 return true;
2271 }
2272 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2273 if (!FromTypePtr)
2274 return false;
2275
2276 QualType FromPointeeType = FromTypePtr->getPointeeType();
2277
2278 // If the unqualified pointee types are the same, this can't be a
2279 // pointer conversion, so don't do all of the work below.
2280 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2281 return false;
2282
2283 // An rvalue of type "pointer to cv T," where T is an object type,
2284 // can be converted to an rvalue of type "pointer to cv void" (C++
2285 // 4.10p2).
2286 if (FromPointeeType->isIncompleteOrObjectType() &&
2287 ToPointeeType->isVoidType()) {
2288 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2289 ToPointeeType,
2290 ToType, Context,
2291 /*StripObjCLifetime=*/true);
2292 return true;
2293 }
2294
2295 // MSVC allows implicit function to void* type conversion.
2296 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2297 ToPointeeType->isVoidType()) {
2298 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2299 ToPointeeType,
2300 ToType, Context);
2301 return true;
2302 }
2303
2304 // When we're overloading in C, we allow a special kind of pointer
2305 // conversion for compatible-but-not-identical pointee types.
2306 if (!getLangOpts().CPlusPlus &&
2307 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2308 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2309 ToPointeeType,
2310 ToType, Context);
2311 return true;
2312 }
2313
2314 // C++ [conv.ptr]p3:
2315 //
2316 // An rvalue of type "pointer to cv D," where D is a class type,
2317 // can be converted to an rvalue of type "pointer to cv B," where
2318 // B is a base class (clause 10) of D. If B is an inaccessible
2319 // (clause 11) or ambiguous (10.2) base class of D, a program that
2320 // necessitates this conversion is ill-formed. The result of the
2321 // conversion is a pointer to the base class sub-object of the
2322 // derived class object. The null pointer value is converted to
2323 // the null pointer value of the destination type.
2324 //
2325 // Note that we do not check for ambiguity or inaccessibility
2326 // here. That is handled by CheckPointerConversion.
2327 if (getLangOpts().CPlusPlus &&
2328 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2329 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2330 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2331 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2332 ToPointeeType,
2333 ToType, Context);
2334 return true;
2335 }
2336
2337 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2338 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2339 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2340 ToPointeeType,
2341 ToType, Context);
2342 return true;
2343 }
2344
2345 return false;
2346}
2347
2348/// \brief Adopt the given qualifiers for the given type.
2349static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2350 Qualifiers TQs = T.getQualifiers();
2351
2352 // Check whether qualifiers already match.
2353 if (TQs == Qs)
2354 return T;
2355
2356 if (Qs.compatiblyIncludes(TQs))
2357 return Context.getQualifiedType(T, Qs);
2358
2359 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2360}
2361
2362/// isObjCPointerConversion - Determines whether this is an
2363/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2364/// with the same arguments and return values.
2365bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2366 QualType& ConvertedType,
2367 bool &IncompatibleObjC) {
2368 if (!getLangOpts().ObjC1)
2369 return false;
2370
2371 // The set of qualifiers on the type we're converting from.
2372 Qualifiers FromQualifiers = FromType.getQualifiers();
2373
2374 // First, we handle all conversions on ObjC object pointer types.
2375 const ObjCObjectPointerType* ToObjCPtr =
2376 ToType->getAs<ObjCObjectPointerType>();
2377 const ObjCObjectPointerType *FromObjCPtr =
2378 FromType->getAs<ObjCObjectPointerType>();
2379
2380 if (ToObjCPtr && FromObjCPtr) {
2381 // If the pointee types are the same (ignoring qualifications),
2382 // then this is not a pointer conversion.
2383 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2384 FromObjCPtr->getPointeeType()))
2385 return false;
2386
2387 // Conversion between Objective-C pointers.
2388 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2389 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2390 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2391 if (getLangOpts().CPlusPlus && LHS && RHS &&
2392 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2393 FromObjCPtr->getPointeeType()))
2394 return false;
2395 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2396 ToObjCPtr->getPointeeType(),
2397 ToType, Context);
2398 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2399 return true;
2400 }
2401
2402 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2403 // Okay: this is some kind of implicit downcast of Objective-C
2404 // interfaces, which is permitted. However, we're going to
2405 // complain about it.
2406 IncompatibleObjC = true;
2407 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2408 ToObjCPtr->getPointeeType(),
2409 ToType, Context);
2410 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2411 return true;
2412 }
2413 }
2414 // Beyond this point, both types need to be C pointers or block pointers.
2415 QualType ToPointeeType;
2416 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2417 ToPointeeType = ToCPtr->getPointeeType();
2418 else if (const BlockPointerType *ToBlockPtr =
2419 ToType->getAs<BlockPointerType>()) {
2420 // Objective C++: We're able to convert from a pointer to any object
2421 // to a block pointer type.
2422 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2423 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2424 return true;
2425 }
2426 ToPointeeType = ToBlockPtr->getPointeeType();
2427 }
2428 else if (FromType->getAs<BlockPointerType>() &&
2429 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2430 // Objective C++: We're able to convert from a block pointer type to a
2431 // pointer to any object.
2432 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2433 return true;
2434 }
2435 else
2436 return false;
2437
2438 QualType FromPointeeType;
2439 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2440 FromPointeeType = FromCPtr->getPointeeType();
2441 else if (const BlockPointerType *FromBlockPtr =
2442 FromType->getAs<BlockPointerType>())
2443 FromPointeeType = FromBlockPtr->getPointeeType();
2444 else
2445 return false;
2446
2447 // If we have pointers to pointers, recursively check whether this
2448 // is an Objective-C conversion.
2449 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2450 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2451 IncompatibleObjC)) {
2452 // We always complain about this conversion.
2453 IncompatibleObjC = true;
2454 ConvertedType = Context.getPointerType(ConvertedType);
2455 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2456 return true;
2457 }
2458 // Allow conversion of pointee being objective-c pointer to another one;
2459 // as in I* to id.
2460 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2461 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2462 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2463 IncompatibleObjC)) {
2464
2465 ConvertedType = Context.getPointerType(ConvertedType);
2466 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2467 return true;
2468 }
2469
2470 // If we have pointers to functions or blocks, check whether the only
2471 // differences in the argument and result types are in Objective-C
2472 // pointer conversions. If so, we permit the conversion (but
2473 // complain about it).
2474 const FunctionProtoType *FromFunctionType
2475 = FromPointeeType->getAs<FunctionProtoType>();
2476 const FunctionProtoType *ToFunctionType
2477 = ToPointeeType->getAs<FunctionProtoType>();
2478 if (FromFunctionType && ToFunctionType) {
2479 // If the function types are exactly the same, this isn't an
2480 // Objective-C pointer conversion.
2481 if (Context.getCanonicalType(FromPointeeType)
2482 == Context.getCanonicalType(ToPointeeType))
2483 return false;
2484
2485 // Perform the quick checks that will tell us whether these
2486 // function types are obviously different.
2487 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2488 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2489 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2490 return false;
2491
2492 bool HasObjCConversion = false;
2493 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2494 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2497 ToFunctionType->getReturnType(),
2498 ConvertedType, IncompatibleObjC)) {
2499 // Okay, we have an Objective-C pointer conversion.
2500 HasObjCConversion = true;
2501 } else {
2502 // Function types are too different. Abort.
2503 return false;
2504 }
2505
2506 // Check argument types.
2507 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2508 ArgIdx != NumArgs; ++ArgIdx) {
2509 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2510 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2511 if (Context.getCanonicalType(FromArgType)
2512 == Context.getCanonicalType(ToArgType)) {
2513 // Okay, the types match exactly. Nothing to do.
2514 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2515 ConvertedType, IncompatibleObjC)) {
2516 // Okay, we have an Objective-C pointer conversion.
2517 HasObjCConversion = true;
2518 } else {
2519 // Argument types are too different. Abort.
2520 return false;
2521 }
2522 }
2523
2524 if (HasObjCConversion) {
2525 // We had an Objective-C conversion. Allow this pointer
2526 // conversion, but complain about it.
2527 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2528 IncompatibleObjC = true;
2529 return true;
2530 }
2531 }
2532
2533 return false;
2534}
2535
2536/// \brief Determine whether this is an Objective-C writeback conversion,
2537/// used for parameter passing when performing automatic reference counting.
2538///
2539/// \param FromType The type we're converting form.
2540///
2541/// \param ToType The type we're converting to.
2542///
2543/// \param ConvertedType The type that will be produced after applying
2544/// this conversion.
2545bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2546 QualType &ConvertedType) {
2547 if (!getLangOpts().ObjCAutoRefCount ||
2548 Context.hasSameUnqualifiedType(FromType, ToType))
2549 return false;
2550
2551 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2552 QualType ToPointee;
2553 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2554 ToPointee = ToPointer->getPointeeType();
2555 else
2556 return false;
2557
2558 Qualifiers ToQuals = ToPointee.getQualifiers();
2559 if (!ToPointee->isObjCLifetimeType() ||
2560 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2561 !ToQuals.withoutObjCLifetime().empty())
2562 return false;
2563
2564 // Argument must be a pointer to __strong to __weak.
2565 QualType FromPointee;
2566 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2567 FromPointee = FromPointer->getPointeeType();
2568 else
2569 return false;
2570
2571 Qualifiers FromQuals = FromPointee.getQualifiers();
2572 if (!FromPointee->isObjCLifetimeType() ||
2573 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2574 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2575 return false;
2576
2577 // Make sure that we have compatible qualifiers.
2578 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2579 if (!ToQuals.compatiblyIncludes(FromQuals))
2580 return false;
2581
2582 // Remove qualifiers from the pointee type we're converting from; they
2583 // aren't used in the compatibility check belong, and we'll be adding back
2584 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2585 FromPointee = FromPointee.getUnqualifiedType();
2586
2587 // The unqualified form of the pointee types must be compatible.
2588 ToPointee = ToPointee.getUnqualifiedType();
2589 bool IncompatibleObjC;
2590 if (Context.typesAreCompatible(FromPointee, ToPointee))
2591 FromPointee = ToPointee;
2592 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2593 IncompatibleObjC))
2594 return false;
2595
2596 /// \brief Construct the type we're converting to, which is a pointer to
2597 /// __autoreleasing pointee.
2598 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2599 ConvertedType = Context.getPointerType(FromPointee);
2600 return true;
2601}
2602
2603bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2604 QualType& ConvertedType) {
2605 QualType ToPointeeType;
2606 if (const BlockPointerType *ToBlockPtr =
2607 ToType->getAs<BlockPointerType>())
2608 ToPointeeType = ToBlockPtr->getPointeeType();
2609 else
2610 return false;
2611
2612 QualType FromPointeeType;
2613 if (const BlockPointerType *FromBlockPtr =
2614 FromType->getAs<BlockPointerType>())
2615 FromPointeeType = FromBlockPtr->getPointeeType();
2616 else
2617 return false;
2618 // We have pointer to blocks, check whether the only
2619 // differences in the argument and result types are in Objective-C
2620 // pointer conversions. If so, we permit the conversion.
2621
2622 const FunctionProtoType *FromFunctionType
2623 = FromPointeeType->getAs<FunctionProtoType>();
2624 const FunctionProtoType *ToFunctionType
2625 = ToPointeeType->getAs<FunctionProtoType>();
2626
2627 if (!FromFunctionType || !ToFunctionType)
2628 return false;
2629
2630 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2631 return true;
2632
2633 // Perform the quick checks that will tell us whether these
2634 // function types are obviously different.
2635 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2636 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2637 return false;
2638
2639 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2640 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2641 if (FromEInfo != ToEInfo)
2642 return false;
2643
2644 bool IncompatibleObjC = false;
2645 if (Context.hasSameType(FromFunctionType->getReturnType(),
2646 ToFunctionType->getReturnType())) {
2647 // Okay, the types match exactly. Nothing to do.
2648 } else {
2649 QualType RHS = FromFunctionType->getReturnType();
2650 QualType LHS = ToFunctionType->getReturnType();
2651 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2652 !RHS.hasQualifiers() && LHS.hasQualifiers())
2653 LHS = LHS.getUnqualifiedType();
2654
2655 if (Context.hasSameType(RHS,LHS)) {
2656 // OK exact match.
2657 } else if (isObjCPointerConversion(RHS, LHS,
2658 ConvertedType, IncompatibleObjC)) {
2659 if (IncompatibleObjC)
2660 return false;
2661 // Okay, we have an Objective-C pointer conversion.
2662 }
2663 else
2664 return false;
2665 }
2666
2667 // Check argument types.
2668 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2669 ArgIdx != NumArgs; ++ArgIdx) {
2670 IncompatibleObjC = false;
2671 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2672 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2673 if (Context.hasSameType(FromArgType, ToArgType)) {
2674 // Okay, the types match exactly. Nothing to do.
2675 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2676 ConvertedType, IncompatibleObjC)) {
2677 if (IncompatibleObjC)
2678 return false;
2679 // Okay, we have an Objective-C pointer conversion.
2680 } else
2681 // Argument types are too different. Abort.
2682 return false;
2683 }
2684
2685 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2686 bool CanUseToFPT, CanUseFromFPT;
2687 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2688 CanUseToFPT, CanUseFromFPT,
2689 NewParamInfos))
2690 return false;
2691
2692 ConvertedType = ToType;
2693 return true;
2694}
2695
2696enum {
2697 ft_default,
2698 ft_different_class,
2699 ft_parameter_arity,
2700 ft_parameter_mismatch,
2701 ft_return_type,
2702 ft_qualifer_mismatch,
2703 ft_noexcept
2704};
2705
2706/// Attempts to get the FunctionProtoType from a Type. Handles
2707/// MemberFunctionPointers properly.
2708static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2709 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2710 return FPT;
2711
2712 if (auto *MPT = FromType->getAs<MemberPointerType>())
2713 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2714
2715 return nullptr;
2716}
2717
2718/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2719/// function types. Catches different number of parameter, mismatch in
2720/// parameter types, and different return types.
2721void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2722 QualType FromType, QualType ToType) {
2723 // If either type is not valid, include no extra info.
2724 if (FromType.isNull() || ToType.isNull()) {
2725 PDiag << ft_default;
2726 return;
2727 }
2728
2729 // Get the function type from the pointers.
2730 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2731 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2732 *ToMember = ToType->getAs<MemberPointerType>();
2733 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2734 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2735 << QualType(FromMember->getClass(), 0);
2736 return;
2737 }
2738 FromType = FromMember->getPointeeType();
2739 ToType = ToMember->getPointeeType();
2740 }
2741
2742 if (FromType->isPointerType())
2743 FromType = FromType->getPointeeType();
2744 if (ToType->isPointerType())
2745 ToType = ToType->getPointeeType();
2746
2747 // Remove references.
2748 FromType = FromType.getNonReferenceType();
2749 ToType = ToType.getNonReferenceType();
2750
2751 // Don't print extra info for non-specialized template functions.
2752 if (FromType->isInstantiationDependentType() &&
2753 !FromType->getAs<TemplateSpecializationType>()) {
2754 PDiag << ft_default;
2755 return;
2756 }
2757
2758 // No extra info for same types.
2759 if (Context.hasSameType(FromType, ToType)) {
2760 PDiag << ft_default;
2761 return;
2762 }
2763
2764 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2765 *ToFunction = tryGetFunctionProtoType(ToType);
2766
2767 // Both types need to be function types.
2768 if (!FromFunction || !ToFunction) {
2769 PDiag << ft_default;
2770 return;
2771 }
2772
2773 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2774 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2775 << FromFunction->getNumParams();
2776 return;
2777 }
2778
2779 // Handle different parameter types.
2780 unsigned ArgPos;
2781 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2782 PDiag << ft_parameter_mismatch << ArgPos + 1
2783 << ToFunction->getParamType(ArgPos)
2784 << FromFunction->getParamType(ArgPos);
2785 return;
2786 }
2787
2788 // Handle different return type.
2789 if (!Context.hasSameType(FromFunction->getReturnType(),
2790 ToFunction->getReturnType())) {
2791 PDiag << ft_return_type << ToFunction->getReturnType()
2792 << FromFunction->getReturnType();
2793 return;
2794 }
2795
2796 unsigned FromQuals = FromFunction->getTypeQuals(),
2797 ToQuals = ToFunction->getTypeQuals();
2798 if (FromQuals != ToQuals) {
2799 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2800 return;
2801 }
2802
2803 // Handle exception specification differences on canonical type (in C++17
2804 // onwards).
2805 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2806 ->isNothrow(Context) !=
2807 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2808 ->isNothrow(Context)) {
2809 PDiag << ft_noexcept;
2810 return;
2811 }
2812
2813 // Unable to find a difference, so add no extra info.
2814 PDiag << ft_default;
2815}
2816
2817/// FunctionParamTypesAreEqual - This routine checks two function proto types
2818/// for equality of their argument types. Caller has already checked that
2819/// they have same number of arguments. If the parameters are different,
2820/// ArgPos will have the parameter index of the first different parameter.
2821bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2822 const FunctionProtoType *NewType,
2823 unsigned *ArgPos) {
2824 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2825 N = NewType->param_type_begin(),
2826 E = OldType->param_type_end();
2827 O && (O != E); ++O, ++N) {
2828 if (!Context.hasSameType(O->getUnqualifiedType(),
2829 N->getUnqualifiedType())) {
2830 if (ArgPos)
2831 *ArgPos = O - OldType->param_type_begin();
2832 return false;
2833 }
2834 }
2835 return true;
2836}
2837
2838/// CheckPointerConversion - Check the pointer conversion from the
2839/// expression From to the type ToType. This routine checks for
2840/// ambiguous or inaccessible derived-to-base pointer
2841/// conversions for which IsPointerConversion has already returned
2842/// true. It returns true and produces a diagnostic if there was an
2843/// error, or returns false otherwise.
2844bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2845 CastKind &Kind,
2846 CXXCastPath& BasePath,
2847 bool IgnoreBaseAccess,
2848 bool Diagnose) {
2849 QualType FromType = From->getType();
2850 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2851
2852 Kind = CK_BitCast;
2853
2854 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2855 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2856 Expr::NPCK_ZeroExpression) {
2857 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2858 DiagRuntimeBehavior(From->getExprLoc(), From,
2859 PDiag(diag::warn_impcast_bool_to_null_pointer)
2860 << ToType << From->getSourceRange());
2861 else if (!isUnevaluatedContext())
2862 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2863 << ToType << From->getSourceRange();
2864 }
2865 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2866 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2867 QualType FromPointeeType = FromPtrType->getPointeeType(),
2868 ToPointeeType = ToPtrType->getPointeeType();
2869
2870 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2871 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2872 // We must have a derived-to-base conversion. Check an
2873 // ambiguous or inaccessible conversion.
2874 unsigned InaccessibleID = 0;
2875 unsigned AmbigiousID = 0;
2876 if (Diagnose) {
2877 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2878 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2879 }
2880 if (CheckDerivedToBaseConversion(
2881 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2882 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2883 &BasePath, IgnoreBaseAccess))
2884 return true;
2885
2886 // The conversion was successful.
2887 Kind = CK_DerivedToBase;
2888 }
2889
2890 if (Diagnose && !IsCStyleOrFunctionalCast &&
2891 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2892 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2893, __extension__ __PRETTY_FUNCTION__))
2893 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2893, __extension__ __PRETTY_FUNCTION__))
;
2894 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2895 << From->getSourceRange();
2896 }
2897 }
2898 } else if (const ObjCObjectPointerType *ToPtrType =
2899 ToType->getAs<ObjCObjectPointerType>()) {
2900 if (const ObjCObjectPointerType *FromPtrType =
2901 FromType->getAs<ObjCObjectPointerType>()) {
2902 // Objective-C++ conversions are always okay.
2903 // FIXME: We should have a different class of conversions for the
2904 // Objective-C++ implicit conversions.
2905 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2906 return false;
2907 } else if (FromType->isBlockPointerType()) {
2908 Kind = CK_BlockPointerToObjCPointerCast;
2909 } else {
2910 Kind = CK_CPointerToObjCPointerCast;
2911 }
2912 } else if (ToType->isBlockPointerType()) {
2913 if (!FromType->isBlockPointerType())
2914 Kind = CK_AnyPointerToBlockPointerCast;
2915 }
2916
2917 // We shouldn't fall into this case unless it's valid for other
2918 // reasons.
2919 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2920 Kind = CK_NullToPointer;
2921
2922 return false;
2923}
2924
2925/// IsMemberPointerConversion - Determines whether the conversion of the
2926/// expression From, which has the (possibly adjusted) type FromType, can be
2927/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2928/// If so, returns true and places the converted type (that might differ from
2929/// ToType in its cv-qualifiers at some level) into ConvertedType.
2930bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2931 QualType ToType,
2932 bool InOverloadResolution,
2933 QualType &ConvertedType) {
2934 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2935 if (!ToTypePtr)
2936 return false;
2937
2938 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2939 if (From->isNullPointerConstant(Context,
2940 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2941 : Expr::NPC_ValueDependentIsNull)) {
2942 ConvertedType = ToType;
2943 return true;
2944 }
2945
2946 // Otherwise, both types have to be member pointers.
2947 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2948 if (!FromTypePtr)
2949 return false;
2950
2951 // A pointer to member of B can be converted to a pointer to member of D,
2952 // where D is derived from B (C++ 4.11p2).
2953 QualType FromClass(FromTypePtr->getClass(), 0);
2954 QualType ToClass(ToTypePtr->getClass(), 0);
2955
2956 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2957 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2958 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2959 ToClass.getTypePtr());
2960 return true;
2961 }
2962
2963 return false;
2964}
2965
2966/// CheckMemberPointerConversion - Check the member pointer conversion from the
2967/// expression From to the type ToType. This routine checks for ambiguous or
2968/// virtual or inaccessible base-to-derived member pointer conversions
2969/// for which IsMemberPointerConversion has already returned true. It returns
2970/// true and produces a diagnostic if there was an error, or returns false
2971/// otherwise.
2972bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2973 CastKind &Kind,
2974 CXXCastPath &BasePath,
2975 bool IgnoreBaseAccess) {
2976 QualType FromType = From->getType();
2977 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2978 if (!FromPtrType) {
2979 // This must be a null pointer to member pointer conversion
2980 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2982, __extension__ __PRETTY_FUNCTION__))
2981 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2982, __extension__ __PRETTY_FUNCTION__))
2982 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2982, __extension__ __PRETTY_FUNCTION__))
;
2983 Kind = CK_NullToMemberPointer;
2984 return false;
2985 }
2986
2987 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2988 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2989, __extension__ __PRETTY_FUNCTION__))
2989 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2989, __extension__ __PRETTY_FUNCTION__))
;
2990
2991 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2992 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2993
2994 // FIXME: What about dependent types?
2995 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2995, __extension__ __PRETTY_FUNCTION__))
;
2996 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 2996, __extension__ __PRETTY_FUNCTION__))
;
2997
2998 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2999 /*DetectVirtual=*/true);
3000 bool DerivationOkay =
3001 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3002 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 3003, __extension__ __PRETTY_FUNCTION__))
3003 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 3003, __extension__ __PRETTY_FUNCTION__))
;
3004 (void)DerivationOkay;
3005
3006 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3007 getUnqualifiedType())) {
3008 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3009 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3010 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3011 return true;
3012 }
3013
3014 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3015 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3016 << FromClass << ToClass << QualType(VBase, 0)
3017 << From->getSourceRange();
3018 return true;
3019 }
3020
3021 if (!IgnoreBaseAccess)
3022 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3023 Paths.front(),
3024 diag::err_downcast_from_inaccessible_base);
3025
3026 // Must be a base to derived member conversion.
3027 BuildBasePathArray(Paths, BasePath);
3028 Kind = CK_BaseToDerivedMemberPointer;
3029 return false;
3030}
3031
3032/// Determine whether the lifetime conversion between the two given
3033/// qualifiers sets is nontrivial.
3034static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3035 Qualifiers ToQuals) {
3036 // Converting anything to const __unsafe_unretained is trivial.
3037 if (ToQuals.hasConst() &&
3038 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3039 return false;
3040
3041 return true;
3042}
3043
3044/// IsQualificationConversion - Determines whether the conversion from
3045/// an rvalue of type FromType to ToType is a qualification conversion
3046/// (C++ 4.4).
3047///
3048/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3049/// when the qualification conversion involves a change in the Objective-C
3050/// object lifetime.
3051bool
3052Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3053 bool CStyle, bool &ObjCLifetimeConversion) {
3054 FromType = Context.getCanonicalType(FromType);
3055 ToType = Context.getCanonicalType(ToType);
3056 ObjCLifetimeConversion = false;
3057
3058 // If FromType and ToType are the same type, this is not a
3059 // qualification conversion.
3060 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3061 return false;
3062
3063 // (C++ 4.4p4):
3064 // A conversion can add cv-qualifiers at levels other than the first
3065 // in multi-level pointers, subject to the following rules: [...]
3066 bool PreviousToQualsIncludeConst = true;
3067 bool UnwrappedAnyPointer = false;
3068 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3069 // Within each iteration of the loop, we check the qualifiers to
3070 // determine if this still looks like a qualification
3071 // conversion. Then, if all is well, we unwrap one more level of
3072 // pointers or pointers-to-members and do it all again
3073 // until there are no more pointers or pointers-to-members left to
3074 // unwrap.
3075 UnwrappedAnyPointer = true;
3076
3077 Qualifiers FromQuals = FromType.getQualifiers();
3078 Qualifiers ToQuals = ToType.getQualifiers();
3079
3080 // Ignore __unaligned qualifier if this type is void.
3081 if (ToType.getUnqualifiedType()->isVoidType())
3082 FromQuals.removeUnaligned();
3083
3084 // Objective-C ARC:
3085 // Check Objective-C lifetime conversions.
3086 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3087 UnwrappedAnyPointer) {
3088 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3089 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3090 ObjCLifetimeConversion = true;
3091 FromQuals.removeObjCLifetime();
3092 ToQuals.removeObjCLifetime();
3093 } else {
3094 // Qualification conversions cannot cast between different
3095 // Objective-C lifetime qualifiers.
3096 return false;
3097 }
3098 }
3099
3100 // Allow addition/removal of GC attributes but not changing GC attributes.
3101 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3102 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3103 FromQuals.removeObjCGCAttr();
3104 ToQuals.removeObjCGCAttr();
3105 }
3106
3107 // -- for every j > 0, if const is in cv 1,j then const is in cv
3108 // 2,j, and similarly for volatile.
3109 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3110 return false;
3111
3112 // -- if the cv 1,j and cv 2,j are different, then const is in
3113 // every cv for 0 < k < j.
3114 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3115 && !PreviousToQualsIncludeConst)
3116 return false;
3117
3118 // Keep track of whether all prior cv-qualifiers in the "to" type
3119 // include const.
3120 PreviousToQualsIncludeConst
3121 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3122 }
3123
3124 // We are left with FromType and ToType being the pointee types
3125 // after unwrapping the original FromType and ToType the same number
3126 // of types. If we unwrapped any pointers, and if FromType and
3127 // ToType have the same unqualified type (since we checked
3128 // qualifiers above), then this is a qualification conversion.
3129 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3130}
3131
3132/// \brief - Determine whether this is a conversion from a scalar type to an
3133/// atomic type.
3134///
3135/// If successful, updates \c SCS's second and third steps in the conversion
3136/// sequence to finish the conversion.
3137static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3138 bool InOverloadResolution,
3139 StandardConversionSequence &SCS,
3140 bool CStyle) {
3141 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3142 if (!ToAtomic)
3143 return false;
3144
3145 StandardConversionSequence InnerSCS;
3146 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3147 InOverloadResolution, InnerSCS,
3148 CStyle, /*AllowObjCWritebackConversion=*/false))
3149 return false;
3150
3151 SCS.Second = InnerSCS.Second;
3152 SCS.setToType(1, InnerSCS.getToType(1));
3153 SCS.Third = InnerSCS.Third;
3154 SCS.QualificationIncludesObjCLifetime
3155 = InnerSCS.QualificationIncludesObjCLifetime;
3156 SCS.setToType(2, InnerSCS.getToType(2));
3157 return true;
3158}
3159
3160static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3161 CXXConstructorDecl *Constructor,
3162 QualType Type) {
3163 const FunctionProtoType *CtorType =
3164 Constructor->getType()->getAs<FunctionProtoType>();
3165 if (CtorType->getNumParams() > 0) {
3166 QualType FirstArg = CtorType->getParamType(0);
3167 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3168 return true;
3169 }
3170 return false;
3171}
3172
3173static OverloadingResult
3174IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3175 CXXRecordDecl *To,
3176 UserDefinedConversionSequence &User,
3177 OverloadCandidateSet &CandidateSet,
3178 bool AllowExplicit) {
3179 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3180 for (auto *D : S.LookupConstructors(To)) {
3181 auto Info = getConstructorInfo(D);
3182 if (!Info)
3183 continue;
3184
3185 bool Usable = !Info.Constructor->isInvalidDecl() &&
3186 S.isInitListConstructor(Info.Constructor) &&
3187 (AllowExplicit || !Info.Constructor->isExplicit());
3188 if (Usable) {
3189 // If the first argument is (a reference to) the target type,
3190 // suppress conversions.
3191 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3192 S.Context, Info.Constructor, ToType);
3193 if (Info.ConstructorTmpl)
3194 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3195 /*ExplicitArgs*/ nullptr, From,
3196 CandidateSet, SuppressUserConversions);
3197 else
3198 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3199 CandidateSet, SuppressUserConversions);
3200 }
3201 }
3202
3203 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3204
3205 OverloadCandidateSet::iterator Best;
3206 switch (auto Result =
3207 CandidateSet.BestViableFunction(S, From->getLocStart(),
3208 Best)) {
3209 case OR_Deleted:
3210 case OR_Success: {
3211 // Record the standard conversion we used and the conversion function.
3212 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3213 QualType ThisType = Constructor->getThisType(S.Context);
3214 // Initializer lists don't have conversions as such.
3215 User.Before.setAsIdentityConversion();
3216 User.HadMultipleCandidates = HadMultipleCandidates;
3217 User.ConversionFunction = Constructor;
3218 User.FoundConversionFunction = Best->FoundDecl;
3219 User.After.setAsIdentityConversion();
3220 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3221 User.After.setAllToTypes(ToType);
3222 return Result;
3223 }
3224
3225 case OR_No_Viable_Function:
3226 return OR_No_Viable_Function;
3227 case OR_Ambiguous:
3228 return OR_Ambiguous;
3229 }
3230
3231 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 3231)
;
3232}
3233
3234/// Determines whether there is a user-defined conversion sequence
3235/// (C++ [over.ics.user]) that converts expression From to the type
3236/// ToType. If such a conversion exists, User will contain the
3237/// user-defined conversion sequence that performs such a conversion
3238/// and this routine will return true. Otherwise, this routine returns
3239/// false and User is unspecified.
3240///
3241/// \param AllowExplicit true if the conversion should consider C++0x
3242/// "explicit" conversion functions as well as non-explicit conversion
3243/// functions (C++0x [class.conv.fct]p2).
3244///
3245/// \param AllowObjCConversionOnExplicit true if the conversion should
3246/// allow an extra Objective-C pointer conversion on uses of explicit
3247/// constructors. Requires \c AllowExplicit to also be set.
3248static OverloadingResult
3249IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3250 UserDefinedConversionSequence &User,
3251 OverloadCandidateSet &CandidateSet,
3252 bool AllowExplicit,
3253 bool AllowObjCConversionOnExplicit) {
3254 assert(AllowExplicit || !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit || !AllowObjCConversionOnExplicit
) ? void (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 3254, __extension__ __PRETTY_FUNCTION__))
;
3255 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3256
3257 // Whether we will only visit constructors.
3258 bool ConstructorsOnly = false;
3259
3260 // If the type we are conversion to is a class type, enumerate its
3261 // constructors.
3262 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3263 // C++ [over.match.ctor]p1:
3264 // When objects of class type are direct-initialized (8.5), or
3265 // copy-initialized from an expression of the same or a
3266 // derived class type (8.5), overload resolution selects the
3267 // constructor. [...] For copy-initialization, the candidate
3268 // functions are all the converting constructors (12.3.1) of
3269 // that class. The argument list is the expression-list within
3270 // the parentheses of the initializer.
3271 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3272 (From->getType()->getAs<RecordType>() &&
3273 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3274 ConstructorsOnly = true;
3275
3276 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3277 // We're not going to find any constructors.
3278 } else if (CXXRecordDecl *ToRecordDecl
3279 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3280
3281 Expr **Args = &From;
3282 unsigned NumArgs = 1;
3283 bool ListInitializing = false;
3284 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3285 // But first, see if there is an init-list-constructor that will work.
3286 OverloadingResult Result = IsInitializerListConstructorConversion(
3287 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3288 if (Result != OR_No_Viable_Function)
3289 return Result;
3290 // Never mind.
3291 CandidateSet.clear(
3292 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3293
3294 // If we're list-initializing, we pass the individual elements as
3295 // arguments, not the entire list.
3296 Args = InitList->getInits();
3297 NumArgs = InitList->getNumInits();
3298 ListInitializing = true;
3299 }
3300
3301 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3302 auto Info = getConstructorInfo(D);
3303 if (!Info)
3304 continue;
3305
3306 bool Usable = !Info.Constructor->isInvalidDecl();
3307 if (ListInitializing)
3308 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3309 else
3310 Usable = Usable &&
3311 Info.Constructor->isConvertingConstructor(AllowExplicit);
3312 if (Usable) {
3313 bool SuppressUserConversions = !ConstructorsOnly;
3314 if (SuppressUserConversions && ListInitializing) {
3315 SuppressUserConversions = false;
3316 if (NumArgs == 1) {
3317 // If the first argument is (a reference to) the target type,
3318 // suppress conversions.
3319 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3320 S.Context, Info.Constructor, ToType);
3321 }
3322 }
3323 if (Info.ConstructorTmpl)
3324 S.AddTemplateOverloadCandidate(
3325 Info.ConstructorTmpl, Info.FoundDecl,
3326 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3327 CandidateSet, SuppressUserConversions);
3328 else
3329 // Allow one user-defined conversion when user specifies a
3330 // From->ToType conversion via an static cast (c-style, etc).
3331 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3332 llvm::makeArrayRef(Args, NumArgs),
3333 CandidateSet, SuppressUserConversions);
3334 }
3335 }
3336 }
3337 }
3338
3339 // Enumerate conversion functions, if we're allowed to.
3340 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3341 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3342 // No conversion functions from incomplete types.
3343 } else if (const RecordType *FromRecordType
3344 = From->getType()->getAs<RecordType>()) {
3345 if (CXXRecordDecl *FromRecordDecl
3346 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3347 // Add all of the conversion functions as candidates.
3348 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3349 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3350 DeclAccessPair FoundDecl = I.getPair();
3351 NamedDecl *D = FoundDecl.getDecl();
3352 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3353 if (isa<UsingShadowDecl>(D))
3354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3355
3356 CXXConversionDecl *Conv;
3357 FunctionTemplateDecl *ConvTemplate;
3358 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3359 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3360 else
3361 Conv = cast<CXXConversionDecl>(D);
3362
3363 if (AllowExplicit || !Conv->isExplicit()) {
3364 if (ConvTemplate)
3365 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3366 ActingContext, From, ToType,
3367 CandidateSet,
3368 AllowObjCConversionOnExplicit);
3369 else
3370 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3371 From, ToType, CandidateSet,
3372 AllowObjCConversionOnExplicit);
3373 }
3374 }
3375 }
3376 }
3377
3378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3379
3380 OverloadCandidateSet::iterator Best;
3381 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3382 Best)) {
3383 case OR_Success:
3384 case OR_Deleted:
3385 // Record the standard conversion we used and the conversion function.
3386 if (CXXConstructorDecl *Constructor
3387 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3388 // C++ [over.ics.user]p1:
3389 // If the user-defined conversion is specified by a
3390 // constructor (12.3.1), the initial standard conversion
3391 // sequence converts the source type to the type required by
3392 // the argument of the constructor.
3393 //
3394 QualType ThisType = Constructor->getThisType(S.Context);
3395 if (isa<InitListExpr>(From)) {
3396 // Initializer lists don't have conversions as such.
3397 User.Before.setAsIdentityConversion();
3398 } else {
3399 if (Best->Conversions[0].isEllipsis())
3400 User.EllipsisConversion = true;
3401 else {
3402 User.Before = Best->Conversions[0].Standard;
3403 User.EllipsisConversion = false;
3404 }
3405 }
3406 User.HadMultipleCandidates = HadMultipleCandidates;
3407 User.ConversionFunction = Constructor;
3408 User.FoundConversionFunction = Best->FoundDecl;
3409 User.After.setAsIdentityConversion();
3410 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3411 User.After.setAllToTypes(ToType);
3412 return Result;
3413 }
3414 if (CXXConversionDecl *Conversion
3415 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3416 // C++ [over.ics.user]p1:
3417 //
3418 // [...] If the user-defined conversion is specified by a
3419 // conversion function (12.3.2), the initial standard
3420 // conversion sequence converts the source type to the
3421 // implicit object parameter of the conversion function.
3422 User.Before = Best->Conversions[0].Standard;
3423 User.HadMultipleCandidates = HadMultipleCandidates;
3424 User.ConversionFunction = Conversion;
3425 User.FoundConversionFunction = Best->FoundDecl;
3426 User.EllipsisConversion = false;
3427
3428 // C++ [over.ics.user]p2:
3429 // The second standard conversion sequence converts the
3430 // result of the user-defined conversion to the target type
3431 // for the sequence. Since an implicit conversion sequence
3432 // is an initialization, the special rules for
3433 // initialization by user-defined conversion apply when
3434 // selecting the best user-defined conversion for a
3435 // user-defined conversion sequence (see 13.3.3 and
3436 // 13.3.3.1).
3437 User.After = Best->FinalConversion;
3438 return Result;
3439 }
3440 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 3440)
;
3441
3442 case OR_No_Viable_Function:
3443 return OR_No_Viable_Function;
3444
3445 case OR_Ambiguous:
3446 return OR_Ambiguous;
3447 }
3448
3449 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 3449)
;
3450}
3451
3452bool
3453Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3454 ImplicitConversionSequence ICS;
3455 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3456 OverloadCandidateSet::CSK_Normal);
3457 OverloadingResult OvResult =
3458 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3459 CandidateSet, false, false);
3460 if (OvResult == OR_Ambiguous)
3461 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3462 << From->getType() << ToType << From->getSourceRange();
3463 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3464 if (!RequireCompleteType(From->getLocStart(), ToType,
3465 diag::err_typecheck_nonviable_condition_incomplete,
3466 From->getType(), From->getSourceRange()))
3467 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3468 << false << From->getType() << From->getSourceRange() << ToType;
3469 } else
3470 return false;
3471 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3472 return true;
3473}
3474
3475/// \brief Compare the user-defined conversion functions or constructors
3476/// of two user-defined conversion sequences to determine whether any ordering
3477/// is possible.
3478static ImplicitConversionSequence::CompareKind
3479compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3480 FunctionDecl *Function2) {
3481 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3482 return ImplicitConversionSequence::Indistinguishable;
3483
3484 // Objective-C++:
3485 // If both conversion functions are implicitly-declared conversions from
3486 // a lambda closure type to a function pointer and a block pointer,
3487 // respectively, always prefer the conversion to a function pointer,
3488 // because the function pointer is more lightweight and is more likely
3489 // to keep code working.
3490 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3491 if (!Conv1)
3492 return ImplicitConversionSequence::Indistinguishable;
3493
3494 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3495 if (!Conv2)
3496 return ImplicitConversionSequence::Indistinguishable;
3497
3498 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3499 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3500 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3501 if (Block1 != Block2)
3502 return Block1 ? ImplicitConversionSequence::Worse
3503 : ImplicitConversionSequence::Better;
3504 }
3505
3506 return ImplicitConversionSequence::Indistinguishable;
3507}
3508
3509static bool hasDeprecatedStringLiteralToCharPtrConversion(
3510 const ImplicitConversionSequence &ICS) {
3511 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3512 (ICS.isUserDefined() &&
3513 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3514}
3515
3516/// CompareImplicitConversionSequences - Compare two implicit
3517/// conversion sequences to determine whether one is better than the
3518/// other or if they are indistinguishable (C++ 13.3.3.2).
3519static ImplicitConversionSequence::CompareKind
3520CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3521 const ImplicitConversionSequence& ICS1,
3522 const ImplicitConversionSequence& ICS2)
3523{
3524 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3525 // conversion sequences (as defined in 13.3.3.1)
3526 // -- a standard conversion sequence (13.3.3.1.1) is a better
3527 // conversion sequence than a user-defined conversion sequence or
3528 // an ellipsis conversion sequence, and
3529 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3530 // conversion sequence than an ellipsis conversion sequence
3531 // (13.3.3.1.3).
3532 //
3533 // C++0x [over.best.ics]p10:
3534 // For the purpose of ranking implicit conversion sequences as
3535 // described in 13.3.3.2, the ambiguous conversion sequence is
3536 // treated as a user-defined sequence that is indistinguishable
3537 // from any other user-defined conversion sequence.
3538
3539 // String literal to 'char *' conversion has been deprecated in C++03. It has
3540 // been removed from C++11. We still accept this conversion, if it happens at
3541 // the best viable function. Otherwise, this conversion is considered worse
3542 // than ellipsis conversion. Consider this as an extension; this is not in the
3543 // standard. For example:
3544 //
3545 // int &f(...); // #1
3546 // void f(char*); // #2
3547 // void g() { int &r = f("foo"); }
3548 //
3549 // In C++03, we pick #2 as the best viable function.
3550 // In C++11, we pick #1 as the best viable function, because ellipsis
3551 // conversion is better than string-literal to char* conversion (since there
3552 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3553 // convert arguments, #2 would be the best viable function in C++11.
3554 // If the best viable function has this conversion, a warning will be issued
3555 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3556
3557 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3558 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3559 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3560 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3561 ? ImplicitConversionSequence::Worse
3562 : ImplicitConversionSequence::Better;
3563
3564 if (ICS1.getKindRank() < ICS2.getKindRank())
3565 return ImplicitConversionSequence::Better;
3566 if (ICS2.getKindRank() < ICS1.getKindRank())
3567 return ImplicitConversionSequence::Worse;
3568
3569 // The following checks require both conversion sequences to be of
3570 // the same kind.
3571 if (ICS1.getKind() != ICS2.getKind())
3572 return ImplicitConversionSequence::Indistinguishable;
3573
3574 ImplicitConversionSequence::CompareKind Result =
3575 ImplicitConversionSequence::Indistinguishable;
3576
3577 // Two implicit conversion sequences of the same form are
3578 // indistinguishable conversion sequences unless one of the
3579 // following rules apply: (C++ 13.3.3.2p3):
3580
3581 // List-initialization sequence L1 is a better conversion sequence than
3582 // list-initialization sequence L2 if:
3583 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3584 // if not that,
3585 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3586 // and N1 is smaller than N2.,
3587 // even if one of the other rules in this paragraph would otherwise apply.
3588 if (!ICS1.isBad()) {
3589 if (ICS1.isStdInitializerListElement() &&
3590 !ICS2.isStdInitializerListElement())
3591 return ImplicitConversionSequence::Better;
3592 if (!ICS1.isStdInitializerListElement() &&
3593 ICS2.isStdInitializerListElement())
3594 return ImplicitConversionSequence::Worse;
3595 }
3596
3597 if (ICS1.isStandard())
3598 // Standard conversion sequence S1 is a better conversion sequence than
3599 // standard conversion sequence S2 if [...]
3600 Result = CompareStandardConversionSequences(S, Loc,
3601 ICS1.Standard, ICS2.Standard);
3602 else if (ICS1.isUserDefined()) {
3603 // User-defined conversion sequence U1 is a better conversion
3604 // sequence than another user-defined conversion sequence U2 if
3605 // they contain the same user-defined conversion function or
3606 // constructor and if the second standard conversion sequence of
3607 // U1 is better than the second standard conversion sequence of
3608 // U2 (C++ 13.3.3.2p3).
3609 if (ICS1.UserDefined.ConversionFunction ==
3610 ICS2.UserDefined.ConversionFunction)
3611 Result = CompareStandardConversionSequences(S, Loc,
3612 ICS1.UserDefined.After,
3613 ICS2.UserDefined.After);
3614 else
3615 Result = compareConversionFunctions(S,
3616 ICS1.UserDefined.ConversionFunction,
3617 ICS2.UserDefined.ConversionFunction);
3618 }
3619
3620 return Result;
3621}
3622
3623static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3624 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3625 Qualifiers Quals;
3626 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3627 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3628 }
3629
3630 return Context.hasSameUnqualifiedType(T1, T2);
3631}
3632
3633// Per 13.3.3.2p3, compare the given standard conversion sequences to
3634// determine if one is a proper subset of the other.
3635static ImplicitConversionSequence::CompareKind
3636compareStandardConversionSubsets(ASTContext &Context,
3637 const StandardConversionSequence& SCS1,
3638 const StandardConversionSequence& SCS2) {
3639 ImplicitConversionSequence::CompareKind Result
3640 = ImplicitConversionSequence::Indistinguishable;
3641
3642 // the identity conversion sequence is considered to be a subsequence of
3643 // any non-identity conversion sequence
3644 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3645 return ImplicitConversionSequence::Better;
3646 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3647 return ImplicitConversionSequence::Worse;
3648
3649 if (SCS1.Second != SCS2.Second) {
3650 if (SCS1.Second == ICK_Identity)
3651 Result = ImplicitConversionSequence::Better;
3652 else if (SCS2.Second == ICK_Identity)
3653 Result = ImplicitConversionSequence::Worse;
3654 else
3655 return ImplicitConversionSequence::Indistinguishable;
3656 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3657 return ImplicitConversionSequence::Indistinguishable;
3658
3659 if (SCS1.Third == SCS2.Third) {
3660 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3661 : ImplicitConversionSequence::Indistinguishable;
3662 }
3663
3664 if (SCS1.Third == ICK_Identity)
3665 return Result == ImplicitConversionSequence::Worse
3666 ? ImplicitConversionSequence::Indistinguishable
3667 : ImplicitConversionSequence::Better;
3668
3669 if (SCS2.Third == ICK_Identity)
3670 return Result == ImplicitConversionSequence::Better
3671 ? ImplicitConversionSequence::Indistinguishable
3672 : ImplicitConversionSequence::Worse;
3673
3674 return ImplicitConversionSequence::Indistinguishable;
3675}
3676
3677/// \brief Determine whether one of the given reference bindings is better
3678/// than the other based on what kind of bindings they are.
3679static bool
3680isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3681 const StandardConversionSequence &SCS2) {
3682 // C++0x [over.ics.rank]p3b4:
3683 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3684 // implicit object parameter of a non-static member function declared
3685 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3686 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3687 // lvalue reference to a function lvalue and S2 binds an rvalue
3688 // reference*.
3689 //
3690 // FIXME: Rvalue references. We're going rogue with the above edits,
3691 // because the semantics in the current C++0x working paper (N3225 at the
3692 // time of this writing) break the standard definition of std::forward
3693 // and std::reference_wrapper when dealing with references to functions.
3694 // Proposed wording changes submitted to CWG for consideration.
3695 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3696 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3697 return false;
3698
3699 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3700 SCS2.IsLvalueReference) ||
3701 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3702 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3703}
3704
3705/// CompareStandardConversionSequences - Compare two standard
3706/// conversion sequences to determine whether one is better than the
3707/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3708static ImplicitConversionSequence::CompareKind
3709CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3710 const StandardConversionSequence& SCS1,
3711 const StandardConversionSequence& SCS2)
3712{
3713 // Standard conversion sequence S1 is a better conversion sequence
3714 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3715
3716 // -- S1 is a proper subsequence of S2 (comparing the conversion
3717 // sequences in the canonical form defined by 13.3.3.1.1,
3718 // excluding any Lvalue Transformation; the identity conversion
3719 // sequence is considered to be a subsequence of any
3720 // non-identity conversion sequence) or, if not that,
3721 if (ImplicitConversionSequence::CompareKind CK
3722 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3723 return CK;
3724
3725 // -- the rank of S1 is better than the rank of S2 (by the rules
3726 // defined below), or, if not that,
3727 ImplicitConversionRank Rank1 = SCS1.getRank();
3728 ImplicitConversionRank Rank2 = SCS2.getRank();
3729 if (Rank1 < Rank2)
3730 return ImplicitConversionSequence::Better;
3731 else if (Rank2 < Rank1)
3732 return ImplicitConversionSequence::Worse;
3733
3734 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3735 // are indistinguishable unless one of the following rules
3736 // applies:
3737
3738 // A conversion that is not a conversion of a pointer, or
3739 // pointer to member, to bool is better than another conversion
3740 // that is such a conversion.
3741 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3742 return SCS2.isPointerConversionToBool()
3743 ? ImplicitConversionSequence::Better
3744 : ImplicitConversionSequence::Worse;
3745
3746 // C++ [over.ics.rank]p4b2:
3747 //
3748 // If class B is derived directly or indirectly from class A,
3749 // conversion of B* to A* is better than conversion of B* to
3750 // void*, and conversion of A* to void* is better than conversion
3751 // of B* to void*.
3752 bool SCS1ConvertsToVoid
3753 = SCS1.isPointerConversionToVoidPointer(S.Context);
3754 bool SCS2ConvertsToVoid
3755 = SCS2.isPointerConversionToVoidPointer(S.Context);
3756 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3757 // Exactly one of the conversion sequences is a conversion to
3758 // a void pointer; it's the worse conversion.
3759 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3760 : ImplicitConversionSequence::Worse;
3761 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3762 // Neither conversion sequence converts to a void pointer; compare
3763 // their derived-to-base conversions.
3764 if (ImplicitConversionSequence::CompareKind DerivedCK
3765 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3766 return DerivedCK;
3767 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3768 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3769 // Both conversion sequences are conversions to void
3770 // pointers. Compare the source types to determine if there's an
3771 // inheritance relationship in their sources.
3772 QualType FromType1 = SCS1.getFromType();
3773 QualType FromType2 = SCS2.getFromType();
3774
3775 // Adjust the types we're converting from via the array-to-pointer
3776 // conversion, if we need to.
3777 if (SCS1.First == ICK_Array_To_Pointer)
3778 FromType1 = S.Context.getArrayDecayedType(FromType1);
3779 if (SCS2.First == ICK_Array_To_Pointer)
3780 FromType2 = S.Context.getArrayDecayedType(FromType2);
3781
3782 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3783 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3784
3785 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3786 return ImplicitConversionSequence::Better;
3787 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3788 return ImplicitConversionSequence::Worse;
3789
3790 // Objective-C++: If one interface is more specific than the
3791 // other, it is the better one.
3792 const ObjCObjectPointerType* FromObjCPtr1
3793 = FromType1->getAs<ObjCObjectPointerType>();
3794 const ObjCObjectPointerType* FromObjCPtr2
3795 = FromType2->getAs<ObjCObjectPointerType>();
3796 if (FromObjCPtr1 && FromObjCPtr2) {
3797 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3798 FromObjCPtr2);
3799 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3800 FromObjCPtr1);
3801 if (AssignLeft != AssignRight) {
3802 return AssignLeft? ImplicitConversionSequence::Better
3803 : ImplicitConversionSequence::Worse;
3804 }
3805 }
3806 }
3807
3808 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3809 // bullet 3).
3810 if (ImplicitConversionSequence::CompareKind QualCK
3811 = CompareQualificationConversions(S, SCS1, SCS2))
3812 return QualCK;
3813
3814 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3815 // Check for a better reference binding based on the kind of bindings.
3816 if (isBetterReferenceBindingKind(SCS1, SCS2))
3817 return ImplicitConversionSequence::Better;
3818 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3819 return ImplicitConversionSequence::Worse;
3820
3821 // C++ [over.ics.rank]p3b4:
3822 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3823 // which the references refer are the same type except for
3824 // top-level cv-qualifiers, and the type to which the reference
3825 // initialized by S2 refers is more cv-qualified than the type
3826 // to which the reference initialized by S1 refers.
3827 QualType T1 = SCS1.getToType(2);
3828 QualType T2 = SCS2.getToType(2);
3829 T1 = S.Context.getCanonicalType(T1);
3830 T2 = S.Context.getCanonicalType(T2);
3831 Qualifiers T1Quals, T2Quals;
3832 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3833 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3834 if (UnqualT1 == UnqualT2) {
3835 // Objective-C++ ARC: If the references refer to objects with different
3836 // lifetimes, prefer bindings that don't change lifetime.
3837 if (SCS1.ObjCLifetimeConversionBinding !=
3838 SCS2.ObjCLifetimeConversionBinding) {
3839 return SCS1.ObjCLifetimeConversionBinding
3840 ? ImplicitConversionSequence::Worse
3841 : ImplicitConversionSequence::Better;
3842 }
3843
3844 // If the type is an array type, promote the element qualifiers to the
3845 // type for comparison.
3846 if (isa<ArrayType>(T1) && T1Quals)
3847 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3848 if (isa<ArrayType>(T2) && T2Quals)
3849 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3850 if (T2.isMoreQualifiedThan(T1))
3851 return ImplicitConversionSequence::Better;
3852 else if (T1.isMoreQualifiedThan(T2))
3853 return ImplicitConversionSequence::Worse;
3854 }
3855 }
3856
3857 // In Microsoft mode, prefer an integral conversion to a
3858 // floating-to-integral conversion if the integral conversion
3859 // is between types of the same size.
3860 // For example:
3861 // void f(float);
3862 // void f(int);
3863 // int main {
3864 // long a;
3865 // f(a);
3866 // }
3867 // Here, MSVC will call f(int) instead of generating a compile error
3868 // as clang will do in standard mode.
3869 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3870 SCS2.Second == ICK_Floating_Integral &&
3871 S.Context.getTypeSize(SCS1.getFromType()) ==
3872 S.Context.getTypeSize(SCS1.getToType(2)))
3873 return ImplicitConversionSequence::Better;
3874
3875 return ImplicitConversionSequence::Indistinguishable;
3876}
3877
3878/// CompareQualificationConversions - Compares two standard conversion
3879/// sequences to determine whether they can be ranked based on their
3880/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3881static ImplicitConversionSequence::CompareKind
3882CompareQualificationConversions(Sema &S,
3883 const StandardConversionSequence& SCS1,
3884 const StandardConversionSequence& SCS2) {
3885 // C++ 13.3.3.2p3:
3886 // -- S1 and S2 differ only in their qualification conversion and
3887 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3888 // cv-qualification signature of type T1 is a proper subset of
3889 // the cv-qualification signature of type T2, and S1 is not the
3890 // deprecated string literal array-to-pointer conversion (4.2).
3891 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3892 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3893 return ImplicitConversionSequence::Indistinguishable;
3894
3895 // FIXME: the example in the standard doesn't use a qualification
3896 // conversion (!)
3897 QualType T1 = SCS1.getToType(2);
3898 QualType T2 = SCS2.getToType(2);
3899 T1 = S.Context.getCanonicalType(T1);
3900 T2 = S.Context.getCanonicalType(T2);
3901 Qualifiers T1Quals, T2Quals;
3902 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3903 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3904
3905 // If the types are the same, we won't learn anything by unwrapped
3906 // them.
3907 if (UnqualT1 == UnqualT2)
3908 return ImplicitConversionSequence::Indistinguishable;
3909
3910 // If the type is an array type, promote the element qualifiers to the type
3911 // for comparison.
3912 if (isa<ArrayType>(T1) && T1Quals)
3913 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3914 if (isa<ArrayType>(T2) && T2Quals)
3915 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3916
3917 ImplicitConversionSequence::CompareKind Result
3918 = ImplicitConversionSequence::Indistinguishable;
3919
3920 // Objective-C++ ARC:
3921 // Prefer qualification conversions not involving a change in lifetime
3922 // to qualification conversions that do not change lifetime.
3923 if (SCS1.QualificationIncludesObjCLifetime !=
3924 SCS2.QualificationIncludesObjCLifetime) {
3925 Result = SCS1.QualificationIncludesObjCLifetime
3926 ? ImplicitConversionSequence::Worse
3927 : ImplicitConversionSequence::Better;
3928 }
3929
3930 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3931 // Within each iteration of the loop, we check the qualifiers to
3932 // determine if this still looks like a qualification
3933 // conversion. Then, if all is well, we unwrap one more level of
3934 // pointers or pointers-to-members and do it all again
3935 // until there are no more pointers or pointers-to-members left
3936 // to unwrap. This essentially mimics what
3937 // IsQualificationConversion does, but here we're checking for a
3938 // strict subset of qualifiers.
3939 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3940 // The qualifiers are the same, so this doesn't tell us anything
3941 // about how the sequences rank.
3942 ;
3943 else if (T2.isMoreQualifiedThan(T1)) {
3944 // T1 has fewer qualifiers, so it could be the better sequence.
3945 if (Result == ImplicitConversionSequence::Worse)
3946 // Neither has qualifiers that are a subset of the other's
3947 // qualifiers.
3948 return ImplicitConversionSequence::Indistinguishable;
3949
3950 Result = ImplicitConversionSequence::Better;
3951 } else if (T1.isMoreQualifiedThan(T2)) {
3952 // T2 has fewer qualifiers, so it could be the better sequence.
3953 if (Result == ImplicitConversionSequence::Better)
3954 // Neither has qualifiers that are a subset of the other's
3955 // qualifiers.
3956 return ImplicitConversionSequence::Indistinguishable;
3957
3958 Result = ImplicitConversionSequence::Worse;
3959 } else {
3960 // Qualifiers are disjoint.
3961 return ImplicitConversionSequence::Indistinguishable;
3962 }
3963
3964 // If the types after this point are equivalent, we're done.
3965 if (S.Context.hasSameUnqualifiedType(T1, T2))
3966 break;
3967 }
3968
3969 // Check that the winning standard conversion sequence isn't using
3970 // the deprecated string literal array to pointer conversion.
3971 switch (Result) {
3972 case ImplicitConversionSequence::Better:
3973 if (SCS1.DeprecatedStringLiteralToCharPtr)
3974 Result = ImplicitConversionSequence::Indistinguishable;
3975 break;
3976
3977 case ImplicitConversionSequence::Indistinguishable:
3978 break;
3979
3980 case ImplicitConversionSequence::Worse:
3981 if (SCS2.DeprecatedStringLiteralToCharPtr)
3982 Result = ImplicitConversionSequence::Indistinguishable;
3983 break;
3984 }
3985
3986 return Result;
3987}
3988
3989/// CompareDerivedToBaseConversions - Compares two standard conversion
3990/// sequences to determine whether they can be ranked based on their
3991/// various kinds of derived-to-base conversions (C++
3992/// [over.ics.rank]p4b3). As part of these checks, we also look at
3993/// conversions between Objective-C interface types.
3994static ImplicitConversionSequence::CompareKind
3995CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3996 const StandardConversionSequence& SCS1,
3997 const StandardConversionSequence& SCS2) {
3998 QualType FromType1 = SCS1.getFromType();
3999 QualType ToType1 = SCS1.getToType(1);
4000 QualType FromType2 = SCS2.getFromType();
4001 QualType ToType2 = SCS2.getToType(1);
4002
4003 // Adjust the types we're converting from via the array-to-pointer
4004 // conversion, if we need to.
4005 if (SCS1.First == ICK_Array_To_Pointer)
4006 FromType1 = S.Context.getArrayDecayedType(FromType1);
4007 if (SCS2.First == ICK_Array_To_Pointer)
4008 FromType2 = S.Context.getArrayDecayedType(FromType2);
4009
4010 // Canonicalize all of the types.
4011 FromType1 = S.Context.getCanonicalType(FromType1);
4012 ToType1 = S.Context.getCanonicalType(ToType1);
4013 FromType2 = S.Context.getCanonicalType(FromType2);
4014 ToType2 = S.Context.getCanonicalType(ToType2);
4015
4016 // C++ [over.ics.rank]p4b3:
4017 //
4018 // If class B is derived directly or indirectly from class A and
4019 // class C is derived directly or indirectly from B,
4020 //
4021 // Compare based on pointer conversions.
4022 if (SCS1.Second == ICK_Pointer_Conversion &&
4023 SCS2.Second == ICK_Pointer_Conversion &&
4024 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4025 FromType1->isPointerType() && FromType2->isPointerType() &&
4026 ToType1->isPointerType() && ToType2->isPointerType()) {
4027 QualType FromPointee1
4028 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4029 QualType ToPointee1
4030 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4031 QualType FromPointee2
4032 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4033 QualType ToPointee2
4034 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4035
4036 // -- conversion of C* to B* is better than conversion of C* to A*,
4037 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4038 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4039 return ImplicitConversionSequence::Better;
4040 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4041 return ImplicitConversionSequence::Worse;
4042 }
4043
4044 // -- conversion of B* to A* is better than conversion of C* to A*,
4045 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4046 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4047 return ImplicitConversionSequence::Better;
4048 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4049 return ImplicitConversionSequence::Worse;
4050 }
4051 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4052 SCS2.Second == ICK_Pointer_Conversion) {
4053 const ObjCObjectPointerType *FromPtr1
4054 = FromType1->getAs<ObjCObjectPointerType>();
4055 const ObjCObjectPointerType *FromPtr2
4056 = FromType2->getAs<ObjCObjectPointerType>();
4057 const ObjCObjectPointerType *ToPtr1
4058 = ToType1->getAs<ObjCObjectPointerType>();
4059 const ObjCObjectPointerType *ToPtr2
4060 = ToType2->getAs<ObjCObjectPointerType>();
4061
4062 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4063 // Apply the same conversion ranking rules for Objective-C pointer types
4064 // that we do for C++ pointers to class types. However, we employ the
4065 // Objective-C pseudo-subtyping relationship used for assignment of
4066 // Objective-C pointer types.
4067 bool FromAssignLeft
4068 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4069 bool FromAssignRight
4070 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4071 bool ToAssignLeft
4072 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4073 bool ToAssignRight
4074 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4075
4076 // A conversion to an a non-id object pointer type or qualified 'id'
4077 // type is better than a conversion to 'id'.
4078 if (ToPtr1->isObjCIdType() &&
4079 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCIdType() &&
4082 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4083 return ImplicitConversionSequence::Better;
4084
4085 // A conversion to a non-id object pointer type is better than a
4086 // conversion to a qualified 'id' type
4087 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4088 return ImplicitConversionSequence::Worse;
4089 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4090 return ImplicitConversionSequence::Better;
4091
4092 // A conversion to an a non-Class object pointer type or qualified 'Class'
4093 // type is better than a conversion to 'Class'.
4094 if (ToPtr1->isObjCClassType() &&
4095 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4096 return ImplicitConversionSequence::Worse;
4097 if (ToPtr2->isObjCClassType() &&
4098 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4099 return ImplicitConversionSequence::Better;
4100
4101 // A conversion to a non-Class object pointer type is better than a
4102 // conversion to a qualified 'Class' type.
4103 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4104 return ImplicitConversionSequence::Worse;
4105 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4106 return ImplicitConversionSequence::Better;
4107
4108 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4109 if (S.Context.hasSameType(FromType1, FromType2) &&
4110 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4111 (ToAssignLeft != ToAssignRight)) {
4112 if (FromPtr1->isSpecialized()) {
4113 // "conversion of B<A> * to B * is better than conversion of B * to
4114 // C *.
4115 bool IsFirstSame =
4116 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4117 bool IsSecondSame =
4118 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4119 if (IsFirstSame) {
4120 if (!IsSecondSame)
4121 return ImplicitConversionSequence::Better;
4122 } else if (IsSecondSame)
4123 return ImplicitConversionSequence::Worse;
4124 }
4125 return ToAssignLeft? ImplicitConversionSequence::Worse
4126 : ImplicitConversionSequence::Better;
4127 }
4128
4129 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4130 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4131 (FromAssignLeft != FromAssignRight))
4132 return FromAssignLeft? ImplicitConversionSequence::Better
4133 : ImplicitConversionSequence::Worse;
4134 }
4135 }
4136
4137 // Ranking of member-pointer types.
4138 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4139 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4140 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4141 const MemberPointerType * FromMemPointer1 =
4142 FromType1->getAs<MemberPointerType>();
4143 const MemberPointerType * ToMemPointer1 =
4144 ToType1->getAs<MemberPointerType>();
4145 const MemberPointerType * FromMemPointer2 =
4146 FromType2->getAs<MemberPointerType>();
4147 const MemberPointerType * ToMemPointer2 =
4148 ToType2->getAs<MemberPointerType>();
4149 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4150 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4151 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4152 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4153 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4154 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4155 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4156 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4157 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4158 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4159 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4160 return ImplicitConversionSequence::Worse;
4161 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4162 return ImplicitConversionSequence::Better;
4163 }
4164 // conversion of B::* to C::* is better than conversion of A::* to C::*
4165 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4166 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4167 return ImplicitConversionSequence::Better;
4168 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4169 return ImplicitConversionSequence::Worse;
4170 }
4171 }
4172
4173 if (SCS1.Second == ICK_Derived_To_Base) {
4174 // -- conversion of C to B is better than conversion of C to A,
4175 // -- binding of an expression of type C to a reference of type
4176 // B& is better than binding an expression of type C to a
4177 // reference of type A&,
4178 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4179 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4180 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4181 return ImplicitConversionSequence::Better;
4182 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4183 return ImplicitConversionSequence::Worse;
4184 }
4185
4186 // -- conversion of B to A is better than conversion of C to A.
4187 // -- binding of an expression of type B to a reference of type
4188 // A& is better than binding an expression of type C to a
4189 // reference of type A&,
4190 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4191 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4192 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4193 return ImplicitConversionSequence::Better;
4194 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4195 return ImplicitConversionSequence::Worse;
4196 }
4197 }
4198
4199 return ImplicitConversionSequence::Indistinguishable;
4200}
4201
4202/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4203/// C++ class.
4204static bool isTypeValid(QualType T) {
4205 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4206 return !Record->isInvalidDecl();
4207
4208 return true;
4209}
4210
4211/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4212/// determine whether they are reference-related,
4213/// reference-compatible, reference-compatible with added
4214/// qualification, or incompatible, for use in C++ initialization by
4215/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4216/// type, and the first type (T1) is the pointee type of the reference
4217/// type being initialized.
4218Sema::ReferenceCompareResult
4219Sema::CompareReferenceRelationship(SourceLocation Loc,
4220 QualType OrigT1, QualType OrigT2,
4221 bool &DerivedToBase,
4222 bool &ObjCConversion,
4223 bool &ObjCLifetimeConversion) {
4224 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4225, __extension__ __PRETTY_FUNCTION__))
4225 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4225, __extension__ __PRETTY_FUNCTION__))
;
4226 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4226, __extension__ __PRETTY_FUNCTION__))
;
4227
4228 QualType T1 = Context.getCanonicalType(OrigT1);
4229 QualType T2 = Context.getCanonicalType(OrigT2);
4230 Qualifiers T1Quals, T2Quals;
4231 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4232 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4233
4234 // C++ [dcl.init.ref]p4:
4235 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4236 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4237 // T1 is a base class of T2.
4238 DerivedToBase = false;
4239 ObjCConversion = false;
4240 ObjCLifetimeConversion = false;
4241 QualType ConvertedT2;
4242 if (UnqualT1 == UnqualT2) {
4243 // Nothing to do.
4244 } else if (isCompleteType(Loc, OrigT2) &&
4245 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4246 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4247 DerivedToBase = true;
4248 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4249 UnqualT2->isObjCObjectOrInterfaceType() &&
4250 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4251 ObjCConversion = true;
4252 else if (UnqualT2->isFunctionType() &&
4253 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4254 // C++1z [dcl.init.ref]p4:
4255 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4256 // function" and T1 is "function"
4257 //
4258 // We extend this to also apply to 'noreturn', so allow any function
4259 // conversion between function types.
4260 return Ref_Compatible;
4261 else
4262 return Ref_Incompatible;
4263
4264 // At this point, we know that T1 and T2 are reference-related (at
4265 // least).
4266
4267 // If the type is an array type, promote the element qualifiers to the type
4268 // for comparison.
4269 if (isa<ArrayType>(T1) && T1Quals)
4270 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4271 if (isa<ArrayType>(T2) && T2Quals)
4272 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4273
4274 // C++ [dcl.init.ref]p4:
4275 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4276 // reference-related to T2 and cv1 is the same cv-qualification
4277 // as, or greater cv-qualification than, cv2. For purposes of
4278 // overload resolution, cases for which cv1 is greater
4279 // cv-qualification than cv2 are identified as
4280 // reference-compatible with added qualification (see 13.3.3.2).
4281 //
4282 // Note that we also require equivalence of Objective-C GC and address-space
4283 // qualifiers when performing these computations, so that e.g., an int in
4284 // address space 1 is not reference-compatible with an int in address
4285 // space 2.
4286 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4287 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4288 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4289 ObjCLifetimeConversion = true;
4290
4291 T1Quals.removeObjCLifetime();
4292 T2Quals.removeObjCLifetime();
4293 }
4294
4295 // MS compiler ignores __unaligned qualifier for references; do the same.
4296 T1Quals.removeUnaligned();
4297 T2Quals.removeUnaligned();
4298
4299 if (T1Quals.compatiblyIncludes(T2Quals))
4300 return Ref_Compatible;
4301 else
4302 return Ref_Related;
4303}
4304
4305/// \brief Look for a user-defined conversion to a value reference-compatible
4306/// with DeclType. Return true if something definite is found.
4307static bool
4308FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4309 QualType DeclType, SourceLocation DeclLoc,
4310 Expr *Init, QualType T2, bool AllowRvalues,
4311 bool AllowExplicit) {
4312 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4312, __extension__ __PRETTY_FUNCTION__))
;
4313 CXXRecordDecl *T2RecordDecl
4314 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4315
4316 OverloadCandidateSet CandidateSet(
4317 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4318 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4319 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4320 NamedDecl *D = *I;
4321 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4322 if (isa<UsingShadowDecl>(D))
4323 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4324
4325 FunctionTemplateDecl *ConvTemplate
4326 = dyn_cast<FunctionTemplateDecl>(D);
4327 CXXConversionDecl *Conv;
4328 if (ConvTemplate)
4329 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4330 else
4331 Conv = cast<CXXConversionDecl>(D);
4332
4333 // If this is an explicit conversion, and we're not allowed to consider
4334 // explicit conversions, skip it.
4335 if (!AllowExplicit && Conv->isExplicit())
4336 continue;
4337
4338 if (AllowRvalues) {
4339 bool DerivedToBase = false;
4340 bool ObjCConversion = false;
4341 bool ObjCLifetimeConversion = false;
4342
4343 // If we are initializing an rvalue reference, don't permit conversion
4344 // functions that return lvalues.
4345 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4346 const ReferenceType *RefType
4347 = Conv->getConversionType()->getAs<LValueReferenceType>();
4348 if (RefType && !RefType->getPointeeType()->isFunctionType())
4349 continue;
4350 }
4351
4352 if (!ConvTemplate &&
4353 S.CompareReferenceRelationship(
4354 DeclLoc,
4355 Conv->getConversionType().getNonReferenceType()
4356 .getUnqualifiedType(),
4357 DeclType.getNonReferenceType().getUnqualifiedType(),
4358 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4359 Sema::Ref_Incompatible)
4360 continue;
4361 } else {
4362 // If the conversion function doesn't return a reference type,
4363 // it can't be considered for this conversion. An rvalue reference
4364 // is only acceptable if its referencee is a function type.
4365
4366 const ReferenceType *RefType =
4367 Conv->getConversionType()->getAs<ReferenceType>();
4368 if (!RefType ||
4369 (!RefType->isLValueReferenceType() &&
4370 !RefType->getPointeeType()->isFunctionType()))
4371 continue;
4372 }
4373
4374 if (ConvTemplate)
4375 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4376 Init, DeclType, CandidateSet,
4377 /*AllowObjCConversionOnExplicit=*/false);
4378 else
4379 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4380 DeclType, CandidateSet,
4381 /*AllowObjCConversionOnExplicit=*/false);
4382 }
4383
4384 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4385
4386 OverloadCandidateSet::iterator Best;
4387 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4388 case OR_Success:
4389 // C++ [over.ics.ref]p1:
4390 //
4391 // [...] If the parameter binds directly to the result of
4392 // applying a conversion function to the argument
4393 // expression, the implicit conversion sequence is a
4394 // user-defined conversion sequence (13.3.3.1.2), with the
4395 // second standard conversion sequence either an identity
4396 // conversion or, if the conversion function returns an
4397 // entity of a type that is a derived class of the parameter
4398 // type, a derived-to-base Conversion.
4399 if (!Best->FinalConversion.DirectBinding)
4400 return false;
4401
4402 ICS.setUserDefined();
4403 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4404 ICS.UserDefined.After = Best->FinalConversion;
4405 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4406 ICS.UserDefined.ConversionFunction = Best->Function;
4407 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4408 ICS.UserDefined.EllipsisConversion = false;
4409 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4411, __extension__ __PRETTY_FUNCTION__))
4410 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4411, __extension__ __PRETTY_FUNCTION__))
4411 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4411, __extension__ __PRETTY_FUNCTION__))
;
4412 return true;
4413
4414 case OR_Ambiguous:
4415 ICS.setAmbiguous();
4416 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4417 Cand != CandidateSet.end(); ++Cand)
4418 if (Cand->Viable)
4419 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4420 return true;
4421
4422 case OR_No_Viable_Function:
4423 case OR_Deleted:
4424 // There was no suitable conversion, or we found a deleted
4425 // conversion; continue with other checks.
4426 return false;
4427 }
4428
4429 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4429)
;
4430}
4431
4432/// \brief Compute an implicit conversion sequence for reference
4433/// initialization.
4434static ImplicitConversionSequence
4435TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4436 SourceLocation DeclLoc,
4437 bool SuppressUserConversions,
4438 bool AllowExplicit) {
4439 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
;
4440
4441 // Most paths end in a failed conversion.
4442 ImplicitConversionSequence ICS;
4443 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4444
4445 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4446 QualType T2 = Init->getType();
4447
4448 // If the initializer is the address of an overloaded function, try
4449 // to resolve the overloaded function. If all goes well, T2 is the
4450 // type of the resulting function.
4451 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4452 DeclAccessPair Found;
4453 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4454 false, Found))
4455 T2 = Fn->getType();
4456 }
4457
4458 // Compute some basic properties of the types and the initializer.
4459 bool isRValRef = DeclType->isRValueReferenceType();
4460 bool DerivedToBase = false;
4461 bool ObjCConversion = false;
4462 bool ObjCLifetimeConversion = false;
4463 Expr::Classification InitCategory = Init->Classify(S.Context);
4464 Sema::ReferenceCompareResult RefRelationship
4465 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4466 ObjCConversion, ObjCLifetimeConversion);
4467
4468
4469 // C++0x [dcl.init.ref]p5:
4470 // A reference to type "cv1 T1" is initialized by an expression
4471 // of type "cv2 T2" as follows:
4472
4473 // -- If reference is an lvalue reference and the initializer expression
4474 if (!isRValRef) {
4475 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4476 // reference-compatible with "cv2 T2," or
4477 //
4478 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4479 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4480 // C++ [over.ics.ref]p1:
4481 // When a parameter of reference type binds directly (8.5.3)
4482 // to an argument expression, the implicit conversion sequence
4483 // is the identity conversion, unless the argument expression
4484 // has a type that is a derived class of the parameter type,
4485 // in which case the implicit conversion sequence is a
4486 // derived-to-base Conversion (13.3.3.1).
4487 ICS.setStandard();
4488 ICS.Standard.First = ICK_Identity;
4489 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4490 : ObjCConversion? ICK_Compatible_Conversion
4491 : ICK_Identity;
4492 ICS.Standard.Third = ICK_Identity;
4493 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4494 ICS.Standard.setToType(0, T2);
4495 ICS.Standard.setToType(1, T1);
4496 ICS.Standard.setToType(2, T1);
4497 ICS.Standard.ReferenceBinding = true;
4498 ICS.Standard.DirectBinding = true;
4499 ICS.Standard.IsLvalueReference = !isRValRef;
4500 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4501 ICS.Standard.BindsToRvalue = false;
4502 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4503 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4504 ICS.Standard.CopyConstructor = nullptr;
4505 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4506
4507 // Nothing more to do: the inaccessibility/ambiguity check for
4508 // derived-to-base conversions is suppressed when we're
4509 // computing the implicit conversion sequence (C++
4510 // [over.best.ics]p2).
4511 return ICS;
4512 }
4513
4514 // -- has a class type (i.e., T2 is a class type), where T1 is
4515 // not reference-related to T2, and can be implicitly
4516 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4517 // is reference-compatible with "cv3 T3" 92) (this
4518 // conversion is selected by enumerating the applicable
4519 // conversion functions (13.3.1.6) and choosing the best
4520 // one through overload resolution (13.3)),
4521 if (!SuppressUserConversions && T2->isRecordType() &&
4522 S.isCompleteType(DeclLoc, T2) &&
4523 RefRelationship == Sema::Ref_Incompatible) {
4524 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4525 Init, T2, /*AllowRvalues=*/false,
4526 AllowExplicit))
4527 return ICS;
4528 }
4529 }
4530
4531 // -- Otherwise, the reference shall be an lvalue reference to a
4532 // non-volatile const type (i.e., cv1 shall be const), or the reference
4533 // shall be an rvalue reference.
4534 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4535 return ICS;
4536
4537 // -- If the initializer expression
4538 //
4539 // -- is an xvalue, class prvalue, array prvalue or function
4540 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4541 if (RefRelationship == Sema::Ref_Compatible &&
4542 (InitCategory.isXValue() ||
4543 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4544 (InitCategory.isLValue() && T2->isFunctionType()))) {
4545 ICS.setStandard();
4546 ICS.Standard.First = ICK_Identity;
4547 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4548 : ObjCConversion? ICK_Compatible_Conversion
4549 : ICK_Identity;
4550 ICS.Standard.Third = ICK_Identity;
4551 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4552 ICS.Standard.setToType(0, T2);
4553 ICS.Standard.setToType(1, T1);
4554 ICS.Standard.setToType(2, T1);
4555 ICS.Standard.ReferenceBinding = true;
4556 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4557 // binding unless we're binding to a class prvalue.
4558 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4559 // allow the use of rvalue references in C++98/03 for the benefit of
4560 // standard library implementors; therefore, we need the xvalue check here.
4561 ICS.Standard.DirectBinding =
4562 S.getLangOpts().CPlusPlus11 ||
4563 !(InitCategory.isPRValue() || T2->isRecordType());
4564 ICS.Standard.IsLvalueReference = !isRValRef;
4565 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4566 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4567 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4568 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4569 ICS.Standard.CopyConstructor = nullptr;
4570 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4571 return ICS;
4572 }
4573
4574 // -- has a class type (i.e., T2 is a class type), where T1 is not
4575 // reference-related to T2, and can be implicitly converted to
4576 // an xvalue, class prvalue, or function lvalue of type
4577 // "cv3 T3", where "cv1 T1" is reference-compatible with
4578 // "cv3 T3",
4579 //
4580 // then the reference is bound to the value of the initializer
4581 // expression in the first case and to the result of the conversion
4582 // in the second case (or, in either case, to an appropriate base
4583 // class subobject).
4584 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4585 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4586 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4587 Init, T2, /*AllowRvalues=*/true,
4588 AllowExplicit)) {
4589 // In the second case, if the reference is an rvalue reference
4590 // and the second standard conversion sequence of the
4591 // user-defined conversion sequence includes an lvalue-to-rvalue
4592 // conversion, the program is ill-formed.
4593 if (ICS.isUserDefined() && isRValRef &&
4594 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4595 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4596
4597 return ICS;
4598 }
4599
4600 // A temporary of function type cannot be created; don't even try.
4601 if (T1->isFunctionType())
4602 return ICS;
4603
4604 // -- Otherwise, a temporary of type "cv1 T1" is created and
4605 // initialized from the initializer expression using the
4606 // rules for a non-reference copy initialization (8.5). The
4607 // reference is then bound to the temporary. If T1 is
4608 // reference-related to T2, cv1 must be the same
4609 // cv-qualification as, or greater cv-qualification than,
4610 // cv2; otherwise, the program is ill-formed.
4611 if (RefRelationship == Sema::Ref_Related) {
4612 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4613 // we would be reference-compatible or reference-compatible with
4614 // added qualification. But that wasn't the case, so the reference
4615 // initialization fails.
4616 //
4617 // Note that we only want to check address spaces and cvr-qualifiers here.
4618 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4619 Qualifiers T1Quals = T1.getQualifiers();
4620 Qualifiers T2Quals = T2.getQualifiers();
4621 T1Quals.removeObjCGCAttr();
4622 T1Quals.removeObjCLifetime();
4623 T2Quals.removeObjCGCAttr();
4624 T2Quals.removeObjCLifetime();
4625 // MS compiler ignores __unaligned qualifier for references; do the same.
4626 T1Quals.removeUnaligned();
4627 T2Quals.removeUnaligned();
4628 if (!T1Quals.compatiblyIncludes(T2Quals))
4629 return ICS;
4630 }
4631
4632 // If at least one of the types is a class type, the types are not
4633 // related, and we aren't allowed any user conversions, the
4634 // reference binding fails. This case is important for breaking
4635 // recursion, since TryImplicitConversion below will attempt to
4636 // create a temporary through the use of a copy constructor.
4637 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4638 (T1->isRecordType() || T2->isRecordType()))
4639 return ICS;
4640
4641 // If T1 is reference-related to T2 and the reference is an rvalue
4642 // reference, the initializer expression shall not be an lvalue.
4643 if (RefRelationship >= Sema::Ref_Related &&
4644 isRValRef && Init->Classify(S.Context).isLValue())
4645 return ICS;
4646
4647 // C++ [over.ics.ref]p2:
4648 // When a parameter of reference type is not bound directly to
4649 // an argument expression, the conversion sequence is the one
4650 // required to convert the argument expression to the
4651 // underlying type of the reference according to
4652 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4653 // to copy-initializing a temporary of the underlying type with
4654 // the argument expression. Any difference in top-level
4655 // cv-qualification is subsumed by the initialization itself
4656 // and does not constitute a conversion.
4657 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4658 /*AllowExplicit=*/false,
4659 /*InOverloadResolution=*/false,
4660 /*CStyle=*/false,
4661 /*AllowObjCWritebackConversion=*/false,
4662 /*AllowObjCConversionOnExplicit=*/false);
4663
4664 // Of course, that's still a reference binding.
4665 if (ICS.isStandard()) {
4666 ICS.Standard.ReferenceBinding = true;
4667 ICS.Standard.IsLvalueReference = !isRValRef;
4668 ICS.Standard.BindsToFunctionLvalue = false;
4669 ICS.Standard.BindsToRvalue = true;
4670 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4671 ICS.Standard.ObjCLifetimeConversionBinding = false;
4672 } else if (ICS.isUserDefined()) {
4673 const ReferenceType *LValRefType =
4674 ICS.UserDefined.ConversionFunction->getReturnType()
4675 ->getAs<LValueReferenceType>();
4676
4677 // C++ [over.ics.ref]p3:
4678 // Except for an implicit object parameter, for which see 13.3.1, a
4679 // standard conversion sequence cannot be formed if it requires [...]
4680 // binding an rvalue reference to an lvalue other than a function
4681 // lvalue.
4682 // Note that the function case is not possible here.
4683 if (DeclType->isRValueReferenceType() && LValRefType) {
4684 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4685 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4686 // reference to an rvalue!
4687 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4688 return ICS;
4689 }
4690
4691 ICS.UserDefined.After.ReferenceBinding = true;
4692 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4693 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4694 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4695 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4696 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4697 }
4698
4699 return ICS;
4700}
4701
4702static ImplicitConversionSequence
4703TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4704 bool SuppressUserConversions,
4705 bool InOverloadResolution,
4706 bool AllowObjCWritebackConversion,
4707 bool AllowExplicit = false);
4708
4709/// TryListConversion - Try to copy-initialize a value of type ToType from the
4710/// initializer list From.
4711static ImplicitConversionSequence
4712TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4713 bool SuppressUserConversions,
4714 bool InOverloadResolution,
4715 bool AllowObjCWritebackConversion) {
4716 // C++11 [over.ics.list]p1:
4717 // When an argument is an initializer list, it is not an expression and
4718 // special rules apply for converting it to a parameter type.
4719
4720 ImplicitConversionSequence Result;
4721 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4722
4723 // We need a complete type for what follows. Incomplete types can never be
4724 // initialized from init lists.
4725 if (!S.isCompleteType(From->getLocStart(), ToType))
4726 return Result;
4727
4728 // Per DR1467:
4729 // If the parameter type is a class X and the initializer list has a single
4730 // element of type cv U, where U is X or a class derived from X, the
4731 // implicit conversion sequence is the one required to convert the element
4732 // to the parameter type.
4733 //
4734 // Otherwise, if the parameter type is a character array [... ]
4735 // and the initializer list has a single element that is an
4736 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4737 // implicit conversion sequence is the identity conversion.
4738 if (From->getNumInits() == 1) {
4739 if (ToType->isRecordType()) {
4740 QualType InitType = From->getInit(0)->getType();
4741 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4742 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4743 return TryCopyInitialization(S, From->getInit(0), ToType,
4744 SuppressUserConversions,
4745 InOverloadResolution,
4746 AllowObjCWritebackConversion);
4747 }
4748 // FIXME: Check the other conditions here: array of character type,
4749 // initializer is a string literal.
4750 if (ToType->isArrayType()) {
4751 InitializedEntity Entity =
4752 InitializedEntity::InitializeParameter(S.Context, ToType,
4753 /*Consumed=*/false);
4754 if (S.CanPerformCopyInitialization(Entity, From)) {
4755 Result.setStandard();
4756 Result.Standard.setAsIdentityConversion();
4757 Result.Standard.setFromType(ToType);
4758 Result.Standard.setAllToTypes(ToType);
4759 return Result;
4760 }
4761 }
4762 }
4763
4764 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4765 // C++11 [over.ics.list]p2:
4766 // If the parameter type is std::initializer_list<X> or "array of X" and
4767 // all the elements can be implicitly converted to X, the implicit
4768 // conversion sequence is the worst conversion necessary to convert an
4769 // element of the list to X.
4770 //
4771 // C++14 [over.ics.list]p3:
4772 // Otherwise, if the parameter type is "array of N X", if the initializer
4773 // list has exactly N elements or if it has fewer than N elements and X is
4774 // default-constructible, and if all the elements of the initializer list
4775 // can be implicitly converted to X, the implicit conversion sequence is
4776 // the worst conversion necessary to convert an element of the list to X.
4777 //
4778 // FIXME: We're missing a lot of these checks.
4779 bool toStdInitializerList = false;
4780 QualType X;
4781 if (ToType->isArrayType())
4782 X = S.Context.getAsArrayType(ToType)->getElementType();
4783 else
4784 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4785 if (!X.isNull()) {
4786 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4787 Expr *Init = From->getInit(i);
4788 ImplicitConversionSequence ICS =
4789 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4790 InOverloadResolution,
4791 AllowObjCWritebackConversion);
4792 // If a single element isn't convertible, fail.
4793 if (ICS.isBad()) {
4794 Result = ICS;
4795 break;
4796 }
4797 // Otherwise, look for the worst conversion.
4798 if (Result.isBad() ||
4799 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4800 Result) ==
4801 ImplicitConversionSequence::Worse)
4802 Result = ICS;
4803 }
4804
4805 // For an empty list, we won't have computed any conversion sequence.
4806 // Introduce the identity conversion sequence.
4807 if (From->getNumInits() == 0) {
4808 Result.setStandard();
4809 Result.Standard.setAsIdentityConversion();
4810 Result.Standard.setFromType(ToType);
4811 Result.Standard.setAllToTypes(ToType);
4812 }
4813
4814 Result.setStdInitializerListElement(toStdInitializerList);
4815 return Result;
4816 }
4817
4818 // C++14 [over.ics.list]p4:
4819 // C++11 [over.ics.list]p3:
4820 // Otherwise, if the parameter is a non-aggregate class X and overload
4821 // resolution chooses a single best constructor [...] the implicit
4822 // conversion sequence is a user-defined conversion sequence. If multiple
4823 // constructors are viable but none is better than the others, the
4824 // implicit conversion sequence is a user-defined conversion sequence.
4825 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4826 // This function can deal with initializer lists.
4827 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4828 /*AllowExplicit=*/false,
4829 InOverloadResolution, /*CStyle=*/false,
4830 AllowObjCWritebackConversion,
4831 /*AllowObjCConversionOnExplicit=*/false);
4832 }
4833
4834 // C++14 [over.ics.list]p5:
4835 // C++11 [over.ics.list]p4:
4836 // Otherwise, if the parameter has an aggregate type which can be
4837 // initialized from the initializer list [...] the implicit conversion
4838 // sequence is a user-defined conversion sequence.
4839 if (ToType->isAggregateType()) {
4840 // Type is an aggregate, argument is an init list. At this point it comes
4841 // down to checking whether the initialization works.
4842 // FIXME: Find out whether this parameter is consumed or not.
4843 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4844 // need to call into the initialization code here; overload resolution
4845 // should not be doing that.
4846 InitializedEntity Entity =
4847 InitializedEntity::InitializeParameter(S.Context, ToType,
4848 /*Consumed=*/false);
4849 if (S.CanPerformCopyInitialization(Entity, From)) {
4850 Result.setUserDefined();
4851 Result.UserDefined.Before.setAsIdentityConversion();
4852 // Initializer lists don't have a type.
4853 Result.UserDefined.Before.setFromType(QualType());
4854 Result.UserDefined.Before.setAllToTypes(QualType());
4855
4856 Result.UserDefined.After.setAsIdentityConversion();
4857 Result.UserDefined.After.setFromType(ToType);
4858 Result.UserDefined.After.setAllToTypes(ToType);
4859 Result.UserDefined.ConversionFunction = nullptr;
4860 }
4861 return Result;
4862 }
4863
4864 // C++14 [over.ics.list]p6:
4865 // C++11 [over.ics.list]p5:
4866 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4867 if (ToType->isReferenceType()) {
4868 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4869 // mention initializer lists in any way. So we go by what list-
4870 // initialization would do and try to extrapolate from that.
4871
4872 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4873
4874 // If the initializer list has a single element that is reference-related
4875 // to the parameter type, we initialize the reference from that.
4876 if (From->getNumInits() == 1) {
4877 Expr *Init = From->getInit(0);
4878
4879 QualType T2 = Init->getType();
4880
4881 // If the initializer is the address of an overloaded function, try
4882 // to resolve the overloaded function. If all goes well, T2 is the
4883 // type of the resulting function.
4884 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4885 DeclAccessPair Found;
4886 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4887 Init, ToType, false, Found))
4888 T2 = Fn->getType();
4889 }
4890
4891 // Compute some basic properties of the types and the initializer.
4892 bool dummy1 = false;
4893 bool dummy2 = false;
4894 bool dummy3 = false;
4895 Sema::ReferenceCompareResult RefRelationship
4896 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4897 dummy2, dummy3);
4898
4899 if (RefRelationship >= Sema::Ref_Related) {
4900 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4901 SuppressUserConversions,
4902 /*AllowExplicit=*/false);
4903 }
4904 }
4905
4906 // Otherwise, we bind the reference to a temporary created from the
4907 // initializer list.
4908 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4909 InOverloadResolution,
4910 AllowObjCWritebackConversion);
4911 if (Result.isFailure())
4912 return Result;
4913 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4914, __extension__ __PRETTY_FUNCTION__))
4914 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 4914, __extension__ __PRETTY_FUNCTION__))
;
4915
4916 // Can we even bind to a temporary?
4917 if (ToType->isRValueReferenceType() ||
4918 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4919 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4920 Result.UserDefined.After;
4921 SCS.ReferenceBinding = true;
4922 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4923 SCS.BindsToRvalue = true;
4924 SCS.BindsToFunctionLvalue = false;
4925 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4926 SCS.ObjCLifetimeConversionBinding = false;
4927 } else
4928 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4929 From, ToType);
4930 return Result;
4931 }
4932
4933 // C++14 [over.ics.list]p7:
4934 // C++11 [over.ics.list]p6:
4935 // Otherwise, if the parameter type is not a class:
4936 if (!ToType->isRecordType()) {
4937 // - if the initializer list has one element that is not itself an
4938 // initializer list, the implicit conversion sequence is the one
4939 // required to convert the element to the parameter type.
4940 unsigned NumInits = From->getNumInits();
4941 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4942 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4943 SuppressUserConversions,
4944 InOverloadResolution,
4945 AllowObjCWritebackConversion);
4946 // - if the initializer list has no elements, the implicit conversion
4947 // sequence is the identity conversion.
4948 else if (NumInits == 0) {
4949 Result.setStandard();
4950 Result.Standard.setAsIdentityConversion();
4951 Result.Standard.setFromType(ToType);
4952 Result.Standard.setAllToTypes(ToType);
4953 }
4954 return Result;
4955 }
4956
4957 // C++14 [over.ics.list]p8:
4958 // C++11 [over.ics.list]p7:
4959 // In all cases other than those enumerated above, no conversion is possible
4960 return Result;
4961}
4962
4963/// TryCopyInitialization - Try to copy-initialize a value of type
4964/// ToType from the expression From. Return the implicit conversion
4965/// sequence required to pass this argument, which may be a bad
4966/// conversion sequence (meaning that the argument cannot be passed to
4967/// a parameter of this type). If @p SuppressUserConversions, then we
4968/// do not permit any user-defined conversion sequences.
4969static ImplicitConversionSequence
4970TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4971 bool SuppressUserConversions,
4972 bool InOverloadResolution,
4973 bool AllowObjCWritebackConversion,
4974 bool AllowExplicit) {
4975 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4976 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4977 InOverloadResolution,AllowObjCWritebackConversion);
4978
4979 if (ToType->isReferenceType())
4980 return TryReferenceInit(S, From, ToType,
4981 /*FIXME:*/From->getLocStart(),
4982 SuppressUserConversions,
4983 AllowExplicit);
4984
4985 return TryImplicitConversion(S, From, ToType,
4986 SuppressUserConversions,
4987 /*AllowExplicit=*/false,
4988 InOverloadResolution,
4989 /*CStyle=*/false,
4990 AllowObjCWritebackConversion,
4991 /*AllowObjCConversionOnExplicit=*/false);
4992}
4993
4994static bool TryCopyInitialization(const CanQualType FromQTy,
4995 const CanQualType ToQTy,
4996 Sema &S,
4997 SourceLocation Loc,
4998 ExprValueKind FromVK) {
4999 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5000 ImplicitConversionSequence ICS =
5001 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5002
5003 return !ICS.isBad();
5004}
5005
5006/// TryObjectArgumentInitialization - Try to initialize the object
5007/// parameter of the given member function (@c Method) from the
5008/// expression @p From.
5009static ImplicitConversionSequence
5010TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5011 Expr::Classification FromClassification,
5012 CXXMethodDecl *Method,
5013 CXXRecordDecl *ActingContext) {
5014 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5015 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5016 // const volatile object.
5017 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5018 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5019 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
5020
5021 // Set up the conversion sequence as a "bad" conversion, to allow us
5022 // to exit early.
5023 ImplicitConversionSequence ICS;
5024
5025 // We need to have an object of class type.
5026 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5027 FromType = PT->getPointeeType();
5028
5029 // When we had a pointer, it's implicitly dereferenced, so we
5030 // better have an lvalue.
5031 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5031, __extension__ __PRETTY_FUNCTION__))
;
5032 }
5033
5034 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5034, __extension__ __PRETTY_FUNCTION__))
;
5035
5036 // C++0x [over.match.funcs]p4:
5037 // For non-static member functions, the type of the implicit object
5038 // parameter is
5039 //
5040 // - "lvalue reference to cv X" for functions declared without a
5041 // ref-qualifier or with the & ref-qualifier
5042 // - "rvalue reference to cv X" for functions declared with the &&
5043 // ref-qualifier
5044 //
5045 // where X is the class of which the function is a member and cv is the
5046 // cv-qualification on the member function declaration.
5047 //
5048 // However, when finding an implicit conversion sequence for the argument, we
5049 // are not allowed to perform user-defined conversions
5050 // (C++ [over.match.funcs]p5). We perform a simplified version of
5051 // reference binding here, that allows class rvalues to bind to
5052 // non-constant references.
5053
5054 // First check the qualifiers.
5055 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5056 if (ImplicitParamType.getCVRQualifiers()
5057 != FromTypeCanon.getLocalCVRQualifiers() &&
5058 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5059 ICS.setBad(BadConversionSequence::bad_qualifiers,
5060 FromType, ImplicitParamType);
5061 return ICS;
5062 }
5063
5064 // Check that we have either the same type or a derived type. It
5065 // affects the conversion rank.
5066 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5067 ImplicitConversionKind SecondKind;
5068 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5069 SecondKind = ICK_Identity;
5070 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5071 SecondKind = ICK_Derived_To_Base;
5072 else {
5073 ICS.setBad(BadConversionSequence::unrelated_class,
5074 FromType, ImplicitParamType);
5075 return ICS;
5076 }
5077
5078 // Check the ref-qualifier.
5079 switch (Method->getRefQualifier()) {
5080 case RQ_None:
5081 // Do nothing; we don't care about lvalueness or rvalueness.
5082 break;
5083
5084 case RQ_LValue:
5085 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5086 // non-const lvalue reference cannot bind to an rvalue
5087 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5088 ImplicitParamType);
5089 return ICS;
5090 }
5091 break;
5092
5093 case RQ_RValue:
5094 if (!FromClassification.isRValue()) {
5095 // rvalue reference cannot bind to an lvalue
5096 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5097 ImplicitParamType);
5098 return ICS;
5099 }
5100 break;
5101 }
5102
5103 // Success. Mark this as a reference binding.
5104 ICS.setStandard();
5105 ICS.Standard.setAsIdentityConversion();
5106 ICS.Standard.Second = SecondKind;
5107 ICS.Standard.setFromType(FromType);
5108 ICS.Standard.setAllToTypes(ImplicitParamType);
5109 ICS.Standard.ReferenceBinding = true;
5110 ICS.Standard.DirectBinding = true;
5111 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5112 ICS.Standard.BindsToFunctionLvalue = false;
5113 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5114 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5115 = (Method->getRefQualifier() == RQ_None);
5116 return ICS;
5117}
5118
5119/// PerformObjectArgumentInitialization - Perform initialization of
5120/// the implicit object parameter for the given Method with the given
5121/// expression.
5122ExprResult
5123Sema::PerformObjectArgumentInitialization(Expr *From,
5124 NestedNameSpecifier *Qualifier,
5125 NamedDecl *FoundDecl,
5126 CXXMethodDecl *Method) {
5127 QualType FromRecordType, DestType;
5128 QualType ImplicitParamRecordType =
5129 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5130
5131 Expr::Classification FromClassification;
5132 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5133 FromRecordType = PT->getPointeeType();
5134 DestType = Method->getThisType(Context);
5135 FromClassification = Expr::Classification::makeSimpleLValue();
5136 } else {
5137 FromRecordType = From->getType();
5138 DestType = ImplicitParamRecordType;
5139 FromClassification = From->Classify(Context);
5140 }
5141
5142 // Note that we always use the true parent context when performing
5143 // the actual argument initialization.
5144 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5145 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5146 Method->getParent());
5147 if (ICS.isBad()) {
5148 switch (ICS.Bad.Kind) {
5149 case BadConversionSequence::bad_qualifiers: {
5150 Qualifiers FromQs = FromRecordType.getQualifiers();
5151 Qualifiers ToQs = DestType.getQualifiers();
5152 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5153 if (CVR) {
5154 Diag(From->getLocStart(),
5155 diag::err_member_function_call_bad_cvr)
5156 << Method->getDeclName() << FromRecordType << (CVR - 1)
5157 << From->getSourceRange();
5158 Diag(Method->getLocation(), diag::note_previous_decl)
5159 << Method->getDeclName();
5160 return ExprError();
5161 }
5162 break;
5163 }
5164
5165 case BadConversionSequence::lvalue_ref_to_rvalue:
5166 case BadConversionSequence::rvalue_ref_to_lvalue: {
5167 bool IsRValueQualified =
5168 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5169 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5170 << Method->getDeclName() << FromClassification.isRValue()
5171 << IsRValueQualified;
5172 Diag(Method->getLocation(), diag::note_previous_decl)
5173 << Method->getDeclName();
5174 return ExprError();
5175 }
5176
5177 case BadConversionSequence::no_conversion:
5178 case BadConversionSequence::unrelated_class:
5179 break;
5180 }
5181
5182 return Diag(From->getLocStart(),
5183 diag::err_member_function_call_bad_type)
5184 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5185 }
5186
5187 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5188 ExprResult FromRes =
5189 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5190 if (FromRes.isInvalid())
5191 return ExprError();
5192 From = FromRes.get();
5193 }
5194
5195 if (!Context.hasSameType(From->getType(), DestType))
5196 From = ImpCastExprToType(From, DestType, CK_NoOp,
5197 From->getValueKind()).get();
5198 return From;
5199}
5200
5201/// TryContextuallyConvertToBool - Attempt to contextually convert the
5202/// expression From to bool (C++0x [conv]p3).
5203static ImplicitConversionSequence
5204TryContextuallyConvertToBool(Sema &S, Expr *From) {
5205 return TryImplicitConversion(S, From, S.Context.BoolTy,
5206 /*SuppressUserConversions=*/false,
5207 /*AllowExplicit=*/true,
5208 /*InOverloadResolution=*/false,
5209 /*CStyle=*/false,
5210 /*AllowObjCWritebackConversion=*/false,
5211 /*AllowObjCConversionOnExplicit=*/false);
5212}
5213
5214/// PerformContextuallyConvertToBool - Perform a contextual conversion
5215/// of the expression From to bool (C++0x [conv]p3).
5216ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5217 if (checkPlaceholderForOverload(*this, From))
5218 return ExprError();
5219
5220 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5221 if (!ICS.isBad())
5222 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5223
5224 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5225 return Diag(From->getLocStart(),
5226 diag::err_typecheck_bool_condition)
5227 << From->getType() << From->getSourceRange();
5228 return ExprError();
5229}
5230
5231/// Check that the specified conversion is permitted in a converted constant
5232/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5233/// is acceptable.
5234static bool CheckConvertedConstantConversions(Sema &S,
5235 StandardConversionSequence &SCS) {
5236 // Since we know that the target type is an integral or unscoped enumeration
5237 // type, most conversion kinds are impossible. All possible First and Third
5238 // conversions are fine.
5239 switch (SCS.Second) {
5240 case ICK_Identity:
5241 case ICK_Function_Conversion:
5242 case ICK_Integral_Promotion:
5243 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5244 case ICK_Zero_Queue_Conversion:
5245 return true;
5246
5247 case ICK_Boolean_Conversion:
5248 // Conversion from an integral or unscoped enumeration type to bool is
5249 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5250 // conversion, so we allow it in a converted constant expression.
5251 //
5252 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5253 // a lot of popular code. We should at least add a warning for this
5254 // (non-conforming) extension.
5255 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5256 SCS.getToType(2)->isBooleanType();
5257
5258 case ICK_Pointer_Conversion:
5259 case ICK_Pointer_Member:
5260 // C++1z: null pointer conversions and null member pointer conversions are
5261 // only permitted if the source type is std::nullptr_t.
5262 return SCS.getFromType()->isNullPtrType();
5263
5264 case ICK_Floating_Promotion:
5265 case ICK_Complex_Promotion:
5266 case ICK_Floating_Conversion:
5267 case ICK_Complex_Conversion:
5268 case ICK_Floating_Integral:
5269 case ICK_Compatible_Conversion:
5270 case ICK_Derived_To_Base:
5271 case ICK_Vector_Conversion:
5272 case ICK_Vector_Splat:
5273 case ICK_Complex_Real:
5274 case ICK_Block_Pointer_Conversion:
5275 case ICK_TransparentUnionConversion:
5276 case ICK_Writeback_Conversion:
5277 case ICK_Zero_Event_Conversion:
5278 case ICK_C_Only_Conversion:
5279 case ICK_Incompatible_Pointer_Conversion:
5280 return false;
5281
5282 case ICK_Lvalue_To_Rvalue:
5283 case ICK_Array_To_Pointer:
5284 case ICK_Function_To_Pointer:
5285 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5285)
;
5286
5287 case ICK_Qualification:
5288 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5288)
;
5289
5290 case ICK_Num_Conversion_Kinds:
5291 break;
5292 }
5293
5294 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5294)
;
5295}
5296
5297/// CheckConvertedConstantExpression - Check that the expression From is a
5298/// converted constant expression of type T, perform the conversion and produce
5299/// the converted expression, per C++11 [expr.const]p3.
5300static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5301 QualType T, APValue &Value,
5302 Sema::CCEKind CCE,
5303 bool RequireInt) {
5304 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5305, __extension__ __PRETTY_FUNCTION__))
5305 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5305, __extension__ __PRETTY_FUNCTION__))
;
5306
5307 if (checkPlaceholderForOverload(S, From))
5308 return ExprError();
5309
5310 // C++1z [expr.const]p3:
5311 // A converted constant expression of type T is an expression,
5312 // implicitly converted to type T, where the converted
5313 // expression is a constant expression and the implicit conversion
5314 // sequence contains only [... list of conversions ...].
5315 // C++1z [stmt.if]p2:
5316 // If the if statement is of the form if constexpr, the value of the
5317 // condition shall be a contextually converted constant expression of type
5318 // bool.
5319 ImplicitConversionSequence ICS =
5320 CCE == Sema::CCEK_ConstexprIf
5321 ? TryContextuallyConvertToBool(S, From)
5322 : TryCopyInitialization(S, From, T,
5323 /*SuppressUserConversions=*/false,
5324 /*InOverloadResolution=*/false,
5325 /*AllowObjcWritebackConversion=*/false,
5326 /*AllowExplicit=*/false);
5327 StandardConversionSequence *SCS = nullptr;
5328 switch (ICS.getKind()) {
5329 case ImplicitConversionSequence::StandardConversion:
5330 SCS = &ICS.Standard;
5331 break;
5332 case ImplicitConversionSequence::UserDefinedConversion:
5333 // We are converting to a non-class type, so the Before sequence
5334 // must be trivial.
5335 SCS = &ICS.UserDefined.After;
5336 break;
5337 case ImplicitConversionSequence::AmbiguousConversion:
5338 case ImplicitConversionSequence::BadConversion:
5339 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5340 return S.Diag(From->getLocStart(),
5341 diag::err_typecheck_converted_constant_expression)
5342 << From->getType() << From->getSourceRange() << T;
5343 return ExprError();
5344
5345 case ImplicitConversionSequence::EllipsisConversion:
5346 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5346)
;
5347 }
5348
5349 // Check that we would only use permitted conversions.
5350 if (!CheckConvertedConstantConversions(S, *SCS)) {
5351 return S.Diag(From->getLocStart(),
5352 diag::err_typecheck_converted_constant_expression_disallowed)
5353 << From->getType() << From->getSourceRange() << T;
5354 }
5355 // [...] and where the reference binding (if any) binds directly.
5356 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5357 return S.Diag(From->getLocStart(),
5358 diag::err_typecheck_converted_constant_expression_indirect)
5359 << From->getType() << From->getSourceRange() << T;
5360 }
5361
5362 ExprResult Result =
5363 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5364 if (Result.isInvalid())
5365 return Result;
5366
5367 // Check for a narrowing implicit conversion.
5368 APValue PreNarrowingValue;
5369 QualType PreNarrowingType;
5370 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5371 PreNarrowingType)) {
5372 case NK_Dependent_Narrowing:
5373 // Implicit conversion to a narrower type, but the expression is
5374 // value-dependent so we can't tell whether it's actually narrowing.
5375 case NK_Variable_Narrowing:
5376 // Implicit conversion to a narrower type, and the value is not a constant
5377 // expression. We'll diagnose this in a moment.
5378 case NK_Not_Narrowing:
5379 break;
5380
5381 case NK_Constant_Narrowing:
5382 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5383 << CCE << /*Constant*/1
5384 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5385 break;
5386
5387 case NK_Type_Narrowing:
5388 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5389 << CCE << /*Constant*/0 << From->getType() << T;
5390 break;
5391 }
5392
5393 if (Result.get()->isValueDependent()) {
5394 Value = APValue();
5395 return Result;
5396 }
5397
5398 // Check the expression is a constant expression.
5399 SmallVector<PartialDiagnosticAt, 8> Notes;
5400 Expr::EvalResult Eval;
5401 Eval.Diag = &Notes;
5402
5403 if ((T->isReferenceType()
5404 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5405 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5406 (RequireInt && !Eval.Val.isInt())) {
5407 // The expression can't be folded, so we can't keep it at this position in
5408 // the AST.
5409 Result = ExprError();
5410 } else {
5411 Value = Eval.Val;
5412
5413 if (Notes.empty()) {
5414 // It's a constant expression.
5415 return Result;
5416 }
5417 }
5418
5419 // It's not a constant expression. Produce an appropriate diagnostic.
5420 if (Notes.size() == 1 &&
5421 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5422 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5423 else {
5424 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5425 << CCE << From->getSourceRange();
5426 for (unsigned I = 0; I < Notes.size(); ++I)
5427 S.Diag(Notes[I].first, Notes[I].second);
5428 }
5429 return ExprError();
5430}
5431
5432ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5433 APValue &Value, CCEKind CCE) {
5434 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5435}
5436
5437ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5438 llvm::APSInt &Value,
5439 CCEKind CCE) {
5440 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5440, __extension__ __PRETTY_FUNCTION__))
;
5441
5442 APValue V;
5443 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5444 if (!R.isInvalid() && !R.get()->isValueDependent())
5445 Value = V.getInt();
5446 return R;
5447}
5448
5449
5450/// dropPointerConversions - If the given standard conversion sequence
5451/// involves any pointer conversions, remove them. This may change
5452/// the result type of the conversion sequence.
5453static void dropPointerConversion(StandardConversionSequence &SCS) {
5454 if (SCS.Second == ICK_Pointer_Conversion) {
5455 SCS.Second = ICK_Identity;
5456 SCS.Third = ICK_Identity;
5457 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5458 }
5459}
5460
5461/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5462/// convert the expression From to an Objective-C pointer type.
5463static ImplicitConversionSequence
5464TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5465 // Do an implicit conversion to 'id'.
5466 QualType Ty = S.Context.getObjCIdType();
5467 ImplicitConversionSequence ICS
5468 = TryImplicitConversion(S, From, Ty,
5469 // FIXME: Are these flags correct?
5470 /*SuppressUserConversions=*/false,
5471 /*AllowExplicit=*/true,
5472 /*InOverloadResolution=*/false,
5473 /*CStyle=*/false,
5474 /*AllowObjCWritebackConversion=*/false,
5475 /*AllowObjCConversionOnExplicit=*/true);
5476
5477 // Strip off any final conversions to 'id'.
5478 switch (ICS.getKind()) {
5479 case ImplicitConversionSequence::BadConversion:
5480 case ImplicitConversionSequence::AmbiguousConversion:
5481 case ImplicitConversionSequence::EllipsisConversion:
5482 break;
5483
5484 case ImplicitConversionSequence::UserDefinedConversion:
5485 dropPointerConversion(ICS.UserDefined.After);
5486 break;
5487
5488 case ImplicitConversionSequence::StandardConversion:
5489 dropPointerConversion(ICS.Standard);
5490 break;
5491 }
5492
5493 return ICS;
5494}
5495
5496/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5497/// conversion of the expression From to an Objective-C pointer type.
5498/// Returns a valid but null ExprResult if no conversion sequence exists.
5499ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5500 if (checkPlaceholderForOverload(*this, From))
5501 return ExprError();
5502
5503 QualType Ty = Context.getObjCIdType();
5504 ImplicitConversionSequence ICS =
5505 TryContextuallyConvertToObjCPointer(*this, From);
5506 if (!ICS.isBad())
5507 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5508 return ExprResult();
5509}
5510
5511/// Determine whether the provided type is an integral type, or an enumeration
5512/// type of a permitted flavor.
5513bool Sema::ICEConvertDiagnoser::match(QualType T) {
5514 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5515 : T->isIntegralOrUnscopedEnumerationType();
5516}
5517
5518static ExprResult
5519diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5520 Sema::ContextualImplicitConverter &Converter,
5521 QualType T, UnresolvedSetImpl &ViableConversions) {
5522
5523 if (Converter.Suppress)
5524 return ExprError();
5525
5526 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5527 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5528 CXXConversionDecl *Conv =
5529 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5530 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5531 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5532 }
5533 return From;
5534}
5535
5536static bool
5537diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5538 Sema::ContextualImplicitConverter &Converter,
5539 QualType T, bool HadMultipleCandidates,
5540 UnresolvedSetImpl &ExplicitConversions) {
5541 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5542 DeclAccessPair Found = ExplicitConversions[0];
5543 CXXConversionDecl *Conversion =
5544 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5545
5546 // The user probably meant to invoke the given explicit
5547 // conversion; use it.
5548 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5549 std::string TypeStr;
5550 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5551
5552 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5553 << FixItHint::CreateInsertion(From->getLocStart(),
5554 "static_cast<" + TypeStr + ">(")
5555 << FixItHint::CreateInsertion(
5556 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5557 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5558
5559 // If we aren't in a SFINAE context, build a call to the
5560 // explicit conversion function.
5561 if (SemaRef.isSFINAEContext())
5562 return true;
5563
5564 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5565 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5566 HadMultipleCandidates);
5567 if (Result.isInvalid())
5568 return true;
5569 // Record usage of conversion in an implicit cast.
5570 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5571 CK_UserDefinedConversion, Result.get(),
5572 nullptr, Result.get()->getValueKind());
5573 }
5574 return false;
5575}
5576
5577static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5578 Sema::ContextualImplicitConverter &Converter,
5579 QualType T, bool HadMultipleCandidates,
5580 DeclAccessPair &Found) {
5581 CXXConversionDecl *Conversion =
5582 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5583 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5584
5585 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5586 if (!Converter.SuppressConversion) {
5587 if (SemaRef.isSFINAEContext())
5588 return true;
5589
5590 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5591 << From->getSourceRange();
5592 }
5593
5594 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5595 HadMultipleCandidates);
5596 if (Result.isInvalid())
5597 return true;
5598 // Record usage of conversion in an implicit cast.
5599 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5600 CK_UserDefinedConversion, Result.get(),
5601 nullptr, Result.get()->getValueKind());
5602 return false;
5603}
5604
5605static ExprResult finishContextualImplicitConversion(
5606 Sema &SemaRef, SourceLocation Loc, Expr *From,
5607 Sema::ContextualImplicitConverter &Converter) {
5608 if (!Converter.match(From->getType()) && !Converter.Suppress)
5609 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5610 << From->getSourceRange();
5611
5612 return SemaRef.DefaultLvalueConversion(From);
5613}
5614
5615static void
5616collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5617 UnresolvedSetImpl &ViableConversions,
5618 OverloadCandidateSet &CandidateSet) {
5619 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5620 DeclAccessPair FoundDecl = ViableConversions[I];
5621 NamedDecl *D = FoundDecl.getDecl();
5622 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5623 if (isa<UsingShadowDecl>(D))
5624 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5625
5626 CXXConversionDecl *Conv;
5627 FunctionTemplateDecl *ConvTemplate;
5628 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5629 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5630 else
5631 Conv = cast<CXXConversionDecl>(D);
5632
5633 if (ConvTemplate)
5634 SemaRef.AddTemplateConversionCandidate(
5635 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5636 /*AllowObjCConversionOnExplicit=*/false);
5637 else
5638 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5639 ToType, CandidateSet,
5640 /*AllowObjCConversionOnExplicit=*/false);
5641 }
5642}
5643
5644/// \brief Attempt to convert the given expression to a type which is accepted
5645/// by the given converter.
5646///
5647/// This routine will attempt to convert an expression of class type to a
5648/// type accepted by the specified converter. In C++11 and before, the class
5649/// must have a single non-explicit conversion function converting to a matching
5650/// type. In C++1y, there can be multiple such conversion functions, but only
5651/// one target type.
5652///
5653/// \param Loc The source location of the construct that requires the
5654/// conversion.
5655///
5656/// \param From The expression we're converting from.
5657///
5658/// \param Converter Used to control and diagnose the conversion process.
5659///
5660/// \returns The expression, converted to an integral or enumeration type if
5661/// successful.
5662ExprResult Sema::PerformContextualImplicitConversion(
5663 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5664 // We can't perform any more checking for type-dependent expressions.
5665 if (From->isTypeDependent())
5666 return From;
5667
5668 // Process placeholders immediately.
5669 if (From->hasPlaceholderType()) {
5670 ExprResult result = CheckPlaceholderExpr(From);
5671 if (result.isInvalid())
5672 return result;
5673 From = result.get();
5674 }
5675
5676 // If the expression already has a matching type, we're golden.
5677 QualType T = From->getType();
5678 if (Converter.match(T))
5679 return DefaultLvalueConversion(From);
5680
5681 // FIXME: Check for missing '()' if T is a function type?
5682
5683 // We can only perform contextual implicit conversions on objects of class
5684 // type.
5685 const RecordType *RecordTy = T->getAs<RecordType>();
5686 if (!RecordTy || !getLangOpts().CPlusPlus) {
5687 if (!Converter.Suppress)
5688 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5689 return From;
5690 }
5691
5692 // We must have a complete class type.
5693 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5694 ContextualImplicitConverter &Converter;
5695 Expr *From;
5696
5697 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5698 : Converter(Converter), From(From) {}
5699
5700 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5701 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5702 }
5703 } IncompleteDiagnoser(Converter, From);
5704
5705 if (Converter.Suppress ? !isCompleteType(Loc, T)
5706 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5707 return From;
5708
5709 // Look for a conversion to an integral or enumeration type.
5710 UnresolvedSet<4>
5711 ViableConversions; // These are *potentially* viable in C++1y.
5712 UnresolvedSet<4> ExplicitConversions;
5713 const auto &Conversions =
5714 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5715
5716 bool HadMultipleCandidates =
5717 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5718
5719 // To check that there is only one target type, in C++1y:
5720 QualType ToType;
5721 bool HasUniqueTargetType = true;
5722
5723 // Collect explicit or viable (potentially in C++1y) conversions.
5724 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5725 NamedDecl *D = (*I)->getUnderlyingDecl();
5726 CXXConversionDecl *Conversion;
5727 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5728 if (ConvTemplate) {
5729 if (getLangOpts().CPlusPlus14)
5730 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5731 else
5732 continue; // C++11 does not consider conversion operator templates(?).
5733 } else
5734 Conversion = cast<CXXConversionDecl>(D);
5735
5736 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5738, __extension__ __PRETTY_FUNCTION__))
5737 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5738, __extension__ __PRETTY_FUNCTION__))
5738 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5738, __extension__ __PRETTY_FUNCTION__))
;
5739
5740 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5741 if (Converter.match(CurToType) || ConvTemplate) {
5742
5743 if (Conversion->isExplicit()) {
5744 // FIXME: For C++1y, do we need this restriction?
5745 // cf. diagnoseNoViableConversion()
5746 if (!ConvTemplate)
5747 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5748 } else {
5749 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5750 if (ToType.isNull())
5751 ToType = CurToType.getUnqualifiedType();
5752 else if (HasUniqueTargetType &&
5753 (CurToType.getUnqualifiedType() != ToType))
5754 HasUniqueTargetType = false;
5755 }
5756 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5757 }
5758 }
5759 }
5760
5761 if (getLangOpts().CPlusPlus14) {
5762 // C++1y [conv]p6:
5763 // ... An expression e of class type E appearing in such a context
5764 // is said to be contextually implicitly converted to a specified
5765 // type T and is well-formed if and only if e can be implicitly
5766 // converted to a type T that is determined as follows: E is searched
5767 // for conversion functions whose return type is cv T or reference to
5768 // cv T such that T is allowed by the context. There shall be
5769 // exactly one such T.
5770
5771 // If no unique T is found:
5772 if (ToType.isNull()) {
5773 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5774 HadMultipleCandidates,
5775 ExplicitConversions))
5776 return ExprError();
5777 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5778 }
5779
5780 // If more than one unique Ts are found:
5781 if (!HasUniqueTargetType)
5782 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5783 ViableConversions);
5784
5785 // If one unique T is found:
5786 // First, build a candidate set from the previously recorded
5787 // potentially viable conversions.
5788 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5789 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5790 CandidateSet);
5791
5792 // Then, perform overload resolution over the candidate set.
5793 OverloadCandidateSet::iterator Best;
5794 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5795 case OR_Success: {
5796 // Apply this conversion.
5797 DeclAccessPair Found =
5798 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5799 if (recordConversion(*this, Loc, From, Converter, T,
5800 HadMultipleCandidates, Found))
5801 return ExprError();
5802 break;
5803 }
5804 case OR_Ambiguous:
5805 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5806 ViableConversions);
5807 case OR_No_Viable_Function:
5808 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5809 HadMultipleCandidates,
5810 ExplicitConversions))
5811 return ExprError();
5812 LLVM_FALLTHROUGH[[clang::fallthrough]];
5813 case OR_Deleted:
5814 // We'll complain below about a non-integral condition type.
5815 break;
5816 }
5817 } else {
5818 switch (ViableConversions.size()) {
5819 case 0: {
5820 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5821 HadMultipleCandidates,
5822 ExplicitConversions))
5823 return ExprError();
5824
5825 // We'll complain below about a non-integral condition type.
5826 break;
5827 }
5828 case 1: {
5829 // Apply this conversion.
5830 DeclAccessPair Found = ViableConversions[0];
5831 if (recordConversion(*this, Loc, From, Converter, T,
5832 HadMultipleCandidates, Found))
5833 return ExprError();
5834 break;
5835 }
5836 default:
5837 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5838 ViableConversions);
5839 }
5840 }
5841
5842 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5843}
5844
5845/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5846/// an acceptable non-member overloaded operator for a call whose
5847/// arguments have types T1 (and, if non-empty, T2). This routine
5848/// implements the check in C++ [over.match.oper]p3b2 concerning
5849/// enumeration types.
5850static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5851 FunctionDecl *Fn,
5852 ArrayRef<Expr *> Args) {
5853 QualType T1 = Args[0]->getType();
5854 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5855
5856 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5857 return true;
5858
5859 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5860 return true;
5861
5862 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5863 if (Proto->getNumParams() < 1)
5864 return false;
5865
5866 if (T1->isEnumeralType()) {
5867 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5868 if (Context.hasSameUnqualifiedType(T1, ArgType))
5869 return true;
5870 }
5871
5872 if (Proto->getNumParams() < 2)
5873 return false;
5874
5875 if (!T2.isNull() && T2->isEnumeralType()) {
5876 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5877 if (Context.hasSameUnqualifiedType(T2, ArgType))
5878 return true;
5879 }
5880
5881 return false;
5882}
5883
5884/// AddOverloadCandidate - Adds the given function to the set of
5885/// candidate functions, using the given function call arguments. If
5886/// @p SuppressUserConversions, then don't allow user-defined
5887/// conversions via constructors or conversion operators.
5888///
5889/// \param PartialOverloading true if we are performing "partial" overloading
5890/// based on an incomplete set of function arguments. This feature is used by
5891/// code completion.
5892void
5893Sema::AddOverloadCandidate(FunctionDecl *Function,
5894 DeclAccessPair FoundDecl,
5895 ArrayRef<Expr *> Args,
5896 OverloadCandidateSet &CandidateSet,
5897 bool SuppressUserConversions,
5898 bool PartialOverloading,
5899 bool AllowExplicit,
5900 ConversionSequenceList EarlyConversions) {
5901 const FunctionProtoType *Proto
5902 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5903 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5903, __extension__ __PRETTY_FUNCTION__))
;
5904 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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5905, __extension__ __PRETTY_FUNCTION__))
5905 "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-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 5905, __extension__ __PRETTY_FUNCTION__))
;
5906
5907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5908 if (!isa<CXXConstructorDecl>(Method)) {
5909 // If we get here, it's because we're calling a member function
5910 // that is named without a member access expression (e.g.,
5911 // "this->f") that was either written explicitly or created
5912 // implicitly. This can happen with a qualified call to a member
5913 // function, e.g., X::f(). We use an empty type for the implied
5914 // object argument (C++ [over.call.func]p3), and the acting context
5915 // is irrelevant.
5916 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5917 Expr::Classification::makeSimpleLValue(), Args,
5918 CandidateSet, SuppressUserConversions,
5919 PartialOverloading, EarlyConversions);
5920 return;
5921 }
5922 // We treat a constructor like a non-member function, since its object
5923 // argument doesn't participate in overload resolution.
5924 }
5925
5926 if (!CandidateSet.isNewCandidate(Function))
5927 return;
5928
5929 // C++ [over.match.oper]p3:
5930 // if no operand has a class type, only those non-member functions in the
5931 // lookup set that have a first parameter of type T1 or "reference to
5932 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5933 // is a right operand) a second parameter of type T2 or "reference to
5934 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5935 // candidate functions.
5936 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5937 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5938 return;
5939
5940 // C++11 [class.copy]p11: [DR1402]
5941 // A defaulted move constructor that is defined as deleted is ignored by
5942 // overload resolution.
5943 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5944 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5945 Constructor->isMoveConstructor())
5946 return;
5947
5948 // Overload resolution is always an unevaluated context.
5949 EnterExpressionEvaluationContext Unevaluated(
5950 *this, Sema::ExpressionEvaluationContext::Unevaluated);
5951
5952 // Add this candidate
5953 OverloadCandidate &Candidate =
5954 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5955 Candidate.FoundDecl = FoundDecl;
5956 Candidate.Function = Function;
5957 Candidate.Viable = true;
5958 Candidate.IsSurrogate = false;
5959 Candidate.IgnoreObjectArgument = false;
5960 Candidate.ExplicitCallArguments = Args.size();
5961
5962 if (Constructor) {
5963 // C++ [class.copy]p3:
5964 // A member function template is never instantiated to perform the copy
5965 // of a class object to an object of its class type.
5966 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5967 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5968 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5969 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5970 ClassType))) {
5971 Candidate.Viable = false;
5972 Candidate.FailureKind = ovl_fail_illegal_constructor;
5973 return;
5974 }
5975
5976 // C++ [over.match.funcs]p8: (proposed DR resolution)
5977 // A constructor inherited from class type C that has a first parameter
5978 // of type "reference to P" (including such a constructor instantiated
5979 // from a template) is excluded from the set of candidate functions when
5980 // constructing an object of type cv D if the argument list has exactly
5981 // one argument and D is reference-related to P and P is reference-related
5982 // to C.
5983 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5984 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5985 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5986 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5987 QualType C = Context.getRecordType(Constructor->getParent());
5988 QualType D = Context.getRecordType(Shadow->getParent());
5989 SourceLocation Loc = Args.front()->getExprLoc();
5990 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5991 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5992 Candidate.Viable = false;
5993 Candidate.FailureKind = ovl_fail_inhctor_slice;
5994 return;
5995 }
5996 }
5997 }
5998
5999 unsigned NumParams = Proto->getNumParams();
6000
6001 // (C++ 13.3.2p2): A candidate function having fewer than m
6002 // parameters is viable only if it has an ellipsis in its parameter
6003 // list (8.3.5).
6004 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6005 !Proto->isVariadic()) {
6006 Candidate.Viable = false;
6007 Candidate.FailureKind = ovl_fail_too_many_arguments;
6008 return;
6009 }
6010
6011 // (C++ 13.3.2p2): A candidate function having more than m parameters
6012 // is viable only if the (m+1)st parameter has a default argument
6013 // (8.3.6). For the purposes of overload resolution, the
6014 // parameter list is truncated on the right, so that there are
6015 // exactly m parameters.
6016 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6017 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6018 // Not enough arguments.
6019 Candidate.Viable = false;
6020 Candidate.FailureKind = ovl_fail_too_few_arguments;
6021 return;
6022 }
6023
6024 // (CUDA B.1): Check for invalid calls between targets.
6025 if (getLangOpts().CUDA)
6026 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6027 // Skip the check for callers that are implicit members, because in this
6028 // case we may not yet know what the member's target is; the target is
6029 // inferred for the member automatically, based on the bases and fields of
6030 // the class.
6031 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6032 Candidate.Viable = false;
6033 Candidate.FailureKind = ovl_fail_bad_target;
6034 return;
6035 }
6036
6037 // Determine the implicit conversion sequences for each of the
6038 // arguments.
6039 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6040 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6041 // We already formed a conversion sequence for this parameter during
6042 // template argument deduction.
6043 } else if (ArgIdx < NumParams) {
6044 // (C++ 13.3.2p3): for F to be a viable function, there shall
6045 // exist for each argument an implicit conversion sequence
6046 // (13.3.3.1) that converts that argument to the corresponding
6047 // parameter of F.
6048 QualType ParamType = Proto->getParamType(ArgIdx);
6049 Candidate.Conversions[ArgIdx]
6050 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6051 SuppressUserConversions,
6052 /*InOverloadResolution=*/true,
6053 /*AllowObjCWritebackConversion=*/
6054 getLangOpts().ObjCAutoRefCount,
6055 AllowExplicit);
6056 if (Candidate.Conversions[ArgIdx].isBad()) {
6057 Candidate.Viable = false;
6058 Candidate.FailureKind = ovl_fail_bad_conversion;
6059 return;
6060 }
6061 } else {
6062 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6063 // argument for which there is no corresponding parameter is
6064 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6065 Candidate.Conversions[ArgIdx].setEllipsis();
6066 }
6067 }
6068
6069 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6070 Candidate.Viable = false;
6071 Candidate.FailureKind = ovl_fail_enable_if;
6072 Candidate.DeductionFailure.Data = FailedAttr;
6073 return;
6074 }
6075
6076 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6077 Candidate.Viable = false;
6078 Candidate.FailureKind = ovl_fail_ext_disabled;
6079 return;
6080 }
6081}
6082
6083ObjCMethodDecl *
6084Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6085 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6086 if (Methods.size() <= 1)
6087 return nullptr;
6088
6089 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6090 bool Match = true;
6091 ObjCMethodDecl *Method = Methods[b];
6092 unsigned NumNamedArgs = Sel.getNumArgs();
6093 // Method might have more arguments than selector indicates. This is due
6094 // to addition of c-style arguments in method.
6095 if (Method->param_size() > NumNamedArgs)
6096 NumNamedArgs = Method->param_size();
6097 if (Args.size() < NumNamedArgs)
6098 continue;
6099
6100 for (unsigned i = 0; i < NumNamedArgs; i++) {
6101 // We can't do any type-checking on a type-dependent argument.
6102 if (Args[i]->isTypeDependent()) {
6103 Match = false;
6104 break;
6105 }
6106
6107 ParmVarDecl *param = Method->parameters()[i];
6108 Expr *argExpr = Args[i];
6109 assert(argExpr && "SelectBestMethod(): missing expression")(static_cast <bool> (argExpr && "SelectBestMethod(): missing expression"
) ? void (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6109, __extension__ __PRETTY_FUNCTION__))
;
6110
6111 // Strip the unbridged-cast placeholder expression off unless it's
6112 // a consumed argument.
6113 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6114 !param->hasAttr<CFConsumedAttr>())
6115 argExpr = stripARCUnbridgedCast(argExpr);
6116
6117 // If the parameter is __unknown_anytype, move on to the next method.
6118 if (param->getType() == Context.UnknownAnyTy) {
6119 Match = false;
6120 break;
6121 }
6122
6123 ImplicitConversionSequence ConversionState
6124 = TryCopyInitialization(*this, argExpr, param->getType(),
6125 /*SuppressUserConversions*/false,
6126 /*InOverloadResolution=*/true,
6127 /*AllowObjCWritebackConversion=*/
6128 getLangOpts().ObjCAutoRefCount,
6129 /*AllowExplicit*/false);
6130 // This function looks for a reasonably-exact match, so we consider
6131 // incompatible pointer conversions to be a failure here.
6132 if (ConversionState.isBad() ||
6133 (ConversionState.isStandard() &&
6134 ConversionState.Standard.Second ==
6135 ICK_Incompatible_Pointer_Conversion)) {
6136 Match = false;
6137 break;
6138 }
6139 }
6140 // Promote additional arguments to variadic methods.
6141 if (Match && Method->isVariadic()) {
6142 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6143 if (Args[i]->isTypeDependent()) {
6144 Match = false;
6145 break;
6146 }
6147 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6148 nullptr);
6149 if (Arg.isInvalid()) {
6150 Match = false;
6151 break;
6152 }
6153 }
6154 } else {
6155 // Check for extra arguments to non-variadic methods.
6156 if (Args.size() != NumNamedArgs)
6157 Match = false;
6158 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6159 // Special case when selectors have no argument. In this case, select
6160 // one with the most general result type of 'id'.
6161 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6162 QualType ReturnT = Methods[b]->getReturnType();
6163 if (ReturnT->isObjCIdType())
6164 return Methods[b];
6165 }
6166 }
6167 }
6168
6169 if (Match)
6170 return Method;
6171 }
6172 return nullptr;
6173}
6174
6175// specific_attr_iterator iterates over enable_if attributes in reverse, and
6176// enable_if is order-sensitive. As a result, we need to reverse things
6177// sometimes. Size of 4 elements is arbitrary.
6178static SmallVector<EnableIfAttr *, 4>
6179getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6180 SmallVector<EnableIfAttr *, 4> Result;
6181 if (!Function->hasAttrs())
6182 return Result;
6183
6184 const auto &FuncAttrs = Function->getAttrs();
6185 for (Attr *Attr : FuncAttrs)
6186 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6187 Result.push_back(EnableIf);
6188
6189 std::reverse(Result.begin(), Result.end());
6190 return Result;
6191}
6192
6193static bool
6194convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6195 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6196 bool MissingImplicitThis, Expr *&ConvertedThis,
6197 SmallVectorImpl<Expr *> &ConvertedArgs) {
6198 if (ThisArg) {
6199 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6200 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6201, __extension__ __PRETTY_FUNCTION__))
6201 "Shouldn't have `this` for ctors!")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6201, __extension__ __PRETTY_FUNCTION__))
;
6202 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast <bool> (!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? void (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6202, __extension__ __PRETTY_FUNCTION__))
;
6203 ExprResult R = S.PerformObjectArgumentInitialization(
6204 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6205 if (R.isInvalid())
6206 return false;
6207 ConvertedThis = R.get();
6208 } else {
6209 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6210 (void)MD;
6211 assert((MissingImplicitThis || MD->isStatic() ||(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6213, __extension__ __PRETTY_FUNCTION__))
6212 isa<CXXConstructorDecl>(MD)) &&(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6213, __extension__ __PRETTY_FUNCTION__))
6213 "Expected `this` for non-ctor instance methods")(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6213, __extension__ __PRETTY_FUNCTION__))
;
6214 }
6215 ConvertedThis = nullptr;
6216 }
6217
6218 // Ignore any variadic arguments. Converting them is pointless, since the
6219 // user can't refer to them in the function condition.
6220 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6221
6222 // Convert the arguments.
6223 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6224 ExprResult R;
6225 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6226 S.Context, Function->getParamDecl(I)),
6227 SourceLocation(), Args[I]);
6228
6229 if (R.isInvalid())
6230 return false;
6231
6232 ConvertedArgs.push_back(R.get());
6233 }
6234
6235 if (Trap.hasErrorOccurred())
6236 return false;
6237
6238 // Push default arguments if needed.
6239 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6240 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6241 ParmVarDecl *P = Function->getParamDecl(i);
6242 ExprResult R = S.PerformCopyInitialization(
6243 InitializedEntity::InitializeParameter(S.Context,
6244 Function->getParamDecl(i)),
6245 SourceLocation(),
6246 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6247 : P->getDefaultArg());
6248 if (R.isInvalid())
6249 return false;
6250 ConvertedArgs.push_back(R.get());
6251 }
6252
6253 if (Trap.hasErrorOccurred())
6254 return false;
6255 }
6256 return true;
6257}
6258
6259EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6260 bool MissingImplicitThis) {
6261 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6262 getOrderedEnableIfAttrs(Function);
6263 if (EnableIfAttrs.empty())
6264 return nullptr;
6265
6266 SFINAETrap Trap(*this);
6267 SmallVector<Expr *, 16> ConvertedArgs;
6268 // FIXME: We should look into making enable_if late-parsed.
6269 Expr *DiscardedThis;
6270 if (!convertArgsForAvailabilityChecks(
6271 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6272 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6273 return EnableIfAttrs[0];
6274
6275 for (auto *EIA : EnableIfAttrs) {
6276 APValue Result;
6277 // FIXME: This doesn't consider value-dependent cases, because doing so is
6278 // very difficult. Ideally, we should handle them more gracefully.
6279 if (!EIA->getCond()->EvaluateWithSubstitution(
6280 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6281 return EIA;
6282
6283 if (!Result.isInt() || !Result.getInt().getBoolValue())
6284 return EIA;
6285 }
6286 return nullptr;
6287}
6288
6289template <typename CheckFn>
6290static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6291 bool ArgDependent, SourceLocation Loc,
6292 CheckFn &&IsSuccessful) {
6293 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6294 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6295 if (ArgDependent == DIA->getArgDependent())
6296 Attrs.push_back(DIA);
6297 }
6298
6299 // Common case: No diagnose_if attributes, so we can quit early.
6300 if (Attrs.empty())
6301 return false;
6302
6303 auto WarningBegin = std::stable_partition(
6304 Attrs.begin(), Attrs.end(),
6305 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6306
6307 // Note that diagnose_if attributes are late-parsed, so they appear in the
6308 // correct order (unlike enable_if attributes).
6309 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6310 IsSuccessful);
6311 if (ErrAttr != WarningBegin) {
6312 const DiagnoseIfAttr *DIA = *ErrAttr;
6313 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6314 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6315 << DIA->getParent() << DIA->getCond()->getSourceRange();
6316 return true;
6317 }
6318
6319 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6320 if (IsSuccessful(DIA)) {
6321 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6322 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6323 << DIA->getParent() << DIA->getCond()->getSourceRange();
6324 }
6325
6326 return false;
6327}
6328
6329bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6330 const Expr *ThisArg,
6331 ArrayRef<const Expr *> Args,
6332 SourceLocation Loc) {
6333 return diagnoseDiagnoseIfAttrsWith(
6334 *this, Function, /*ArgDependent=*/true, Loc,
6335 [&](const DiagnoseIfAttr *DIA) {
6336 APValue Result;
6337 // It's sane to use the same Args for any redecl of this function, since
6338 // EvaluateWithSubstitution only cares about the position of each
6339 // argument in the arg list, not the ParmVarDecl* it maps to.
6340 if (!DIA->getCond()->EvaluateWithSubstitution(
6341 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6342 return false;
6343 return Result.isInt() && Result.getInt().getBoolValue();
6344 });
6345}
6346
6347bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6348 SourceLocation Loc) {
6349 return diagnoseDiagnoseIfAttrsWith(
6350 *this, ND, /*ArgDependent=*/false, Loc,
6351 [&](const DiagnoseIfAttr *DIA) {
6352 bool Result;
6353 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6354 Result;
6355 });
6356}
6357
6358/// \brief Add all of the function declarations in the given function set to
6359/// the overload candidate set.
6360void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6361 ArrayRef<Expr *> Args,
6362 OverloadCandidateSet& CandidateSet,
6363 TemplateArgumentListInfo *ExplicitTemplateArgs,
6364 bool SuppressUserConversions,
6365 bool PartialOverloading,
6366 bool FirstArgumentIsBase) {
6367 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6368 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6369 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6370 ArrayRef<Expr *> FunctionArgs = Args;
6371 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6372 QualType ObjectType;
6373 Expr::Classification ObjectClassification;
6374 if (Args.size() > 0) {
6375 if (Expr *E = Args[0]) {
6376 // Use the explit base to restrict the lookup:
6377 ObjectType = E->getType();
6378 ObjectClassification = E->Classify(Context);
6379 } // .. else there is an implit base.
6380 FunctionArgs = Args.slice(1);
6381 }
6382 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6383 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6384 ObjectClassification, FunctionArgs, CandidateSet,
6385 SuppressUserConversions, PartialOverloading);
6386 } else {
6387 // Slice the first argument (which is the base) when we access
6388 // static method as non-static
6389 if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6390 !isa<CXXConstructorDecl>(FD)))) {
6391 assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast <bool> (cast<CXXMethodDecl>(FD)->
isStatic()) ? void (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6391, __extension__ __PRETTY_FUNCTION__))
;
6392 FunctionArgs = Args.slice(1);
6393 }
6394 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6395 SuppressUserConversions, PartialOverloading);
6396 }
6397 } else {
6398 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6399 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6400 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6401 QualType ObjectType;
6402 Expr::Classification ObjectClassification;
6403 if (Expr *E = Args[0]) {
6404 // Use the explit base to restrict the lookup:
6405 ObjectType = E->getType();
6406 ObjectClassification = E->Classify(Context);
6407 } // .. else there is an implit base.
6408 AddMethodTemplateCandidate(
6409 FunTmpl, F.getPair(),
6410 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6411 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6412 Args.slice(1), CandidateSet, SuppressUserConversions,
6413 PartialOverloading);
6414 } else {
6415 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6416 ExplicitTemplateArgs, Args,
6417 CandidateSet, SuppressUserConversions,
6418 PartialOverloading);
6419 }
6420 }
6421 }
6422}
6423
6424/// AddMethodCandidate - Adds a named decl (which is some kind of
6425/// method) as a method candidate to the given overload set.
6426void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6427 QualType ObjectType,
6428 Expr::Classification ObjectClassification,
6429 ArrayRef<Expr *> Args,
6430 OverloadCandidateSet& CandidateSet,
6431 bool SuppressUserConversions) {
6432 NamedDecl *Decl = FoundDecl.getDecl();
6433 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6434
6435 if (isa<UsingShadowDecl>(Decl))
6436 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6437
6438 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6439 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6440, __extension__ __PRETTY_FUNCTION__))
6440 "Expected a member function template")(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6440, __extension__ __PRETTY_FUNCTION__))
;
6441 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6442 /*ExplicitArgs*/ nullptr, ObjectType,
6443 ObjectClassification, Args, CandidateSet,
6444 SuppressUserConversions);
6445 } else {
6446 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6447 ObjectType, ObjectClassification, Args, CandidateSet,
6448 SuppressUserConversions);
6449 }
6450}
6451
6452/// AddMethodCandidate - Adds the given C++ member function to the set
6453/// of candidate functions, using the given function call arguments
6454/// and the object argument (@c Object). For example, in a call
6455/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6456/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6457/// allow user-defined conversions via constructors or conversion
6458/// operators.
6459void
6460Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6461 CXXRecordDecl *ActingContext, QualType ObjectType,
6462 Expr::Classification ObjectClassification,
6463 ArrayRef<Expr *> Args,
6464 OverloadCandidateSet &CandidateSet,
6465 bool SuppressUserConversions,
6466 bool PartialOverloading,
6467 ConversionSequenceList EarlyConversions) {
6468 const FunctionProtoType *Proto
6469 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6470 assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Methods without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6470, __extension__ __PRETTY_FUNCTION__))
;
6471 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6472, __extension__ __PRETTY_FUNCTION__))
6472 "Use AddOverloadCandidate for constructors")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6472, __extension__ __PRETTY_FUNCTION__))
;
6473
6474 if (!CandidateSet.isNewCandidate(Method))
6475 return;
6476
6477 // C++11 [class.copy]p23: [DR1402]
6478 // A defaulted move assignment operator that is defined as deleted is
6479 // ignored by overload resolution.
6480 if (Method->isDefaulted() && Method->isDeleted() &&
6481 Method->isMoveAssignmentOperator())
6482 return;
6483
6484 // Overload resolution is always an unevaluated context.
6485 EnterExpressionEvaluationContext Unevaluated(
6486 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6487
6488 // Add this candidate
6489 OverloadCandidate &Candidate =
6490 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6491 Candidate.FoundDecl = FoundDecl;
6492 Candidate.Function = Method;
6493 Candidate.IsSurrogate = false;
6494 Candidate.IgnoreObjectArgument = false;
6495 Candidate.ExplicitCallArguments = Args.size();
6496
6497 unsigned NumParams = Proto->getNumParams();
6498
6499 // (C++ 13.3.2p2): A candidate function having fewer than m
6500 // parameters is viable only if it has an ellipsis in its parameter
6501 // list (8.3.5).
6502 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6503 !Proto->isVariadic()) {
6504 Candidate.Viable = false;
6505 Candidate.FailureKind = ovl_fail_too_many_arguments;
6506 return;
6507 }
6508
6509 // (C++ 13.3.2p2): A candidate function having more than m parameters
6510 // is viable only if the (m+1)st parameter has a default argument
6511 // (8.3.6). For the purposes of overload resolution, the
6512 // parameter list is truncated on the right, so that there are
6513 // exactly m parameters.
6514 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6515 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6516 // Not enough arguments.
6517 Candidate.Viable = false;
6518 Candidate.FailureKind = ovl_fail_too_few_arguments;
6519 return;
6520 }
6521
6522 Candidate.Viable = true;
6523
6524 if (Method->isStatic() || ObjectType.isNull())
6525 // The implicit object argument is ignored.
6526 Candidate.IgnoreObjectArgument = true;
6527 else {
6528 // Determine the implicit conversion sequence for the object
6529 // parameter.
6530 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6531 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6532 Method, ActingContext);
6533 if (Candidate.Conversions[0].isBad()) {
6534 Candidate.Viable = false;
6535 Candidate.FailureKind = ovl_fail_bad_conversion;
6536 return;
6537 }
6538 }
6539
6540 // (CUDA B.1): Check for invalid calls between targets.
6541 if (getLangOpts().CUDA)
6542 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6543 if (!IsAllowedCUDACall(Caller, Method)) {
6544 Candidate.Viable = false;
6545 Candidate.FailureKind = ovl_fail_bad_target;
6546 return;
6547 }
6548
6549 // Determine the implicit conversion sequences for each of the
6550 // arguments.
6551 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6552 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6553 // We already formed a conversion sequence for this parameter during
6554 // template argument deduction.
6555 } else if (ArgIdx < NumParams) {
6556 // (C++ 13.3.2p3): for F to be a viable function, there shall
6557 // exist for each argument an implicit conversion sequence
6558 // (13.3.3.1) that converts that argument to the corresponding
6559 // parameter of F.
6560 QualType ParamType = Proto->getParamType(ArgIdx);
6561 Candidate.Conversions[ArgIdx + 1]
6562 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6563 SuppressUserConversions,
6564 /*InOverloadResolution=*/true,
6565 /*AllowObjCWritebackConversion=*/
6566 getLangOpts().ObjCAutoRefCount);
6567 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6568 Candidate.Viable = false;
6569 Candidate.FailureKind = ovl_fail_bad_conversion;
6570 return;
6571 }
6572 } else {
6573 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6574 // argument for which there is no corresponding parameter is
6575 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6576 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6577 }
6578 }
6579
6580 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6581 Candidate.Viable = false;
6582 Candidate.FailureKind = ovl_fail_enable_if;
6583 Candidate.DeductionFailure.Data = FailedAttr;
6584 return;
6585 }
6586}
6587
6588/// \brief Add a C++ member function template as a candidate to the candidate
6589/// set, using template argument deduction to produce an appropriate member
6590/// function template specialization.
6591void
6592Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6593 DeclAccessPair FoundDecl,
6594 CXXRecordDecl *ActingContext,
6595 TemplateArgumentListInfo *ExplicitTemplateArgs,
6596 QualType ObjectType,
6597 Expr::Classification ObjectClassification,
6598 ArrayRef<Expr *> Args,
6599 OverloadCandidateSet& CandidateSet,
6600 bool SuppressUserConversions,
6601 bool PartialOverloading) {
6602 if (!CandidateSet.isNewCandidate(MethodTmpl))
6603 return;
6604
6605 // C++ [over.match.funcs]p7:
6606 // In each case where a candidate is a function template, candidate
6607 // function template specializations are generated using template argument
6608 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6609 // candidate functions in the usual way.113) A given name can refer to one
6610 // or more function templates and also to a set of overloaded non-template
6611 // functions. In such a case, the candidate functions generated from each
6612 // function template are combined with the set of non-template candidate
6613 // functions.
6614 TemplateDeductionInfo Info(CandidateSet.getLocation());
6615 FunctionDecl *Specialization = nullptr;
6616 ConversionSequenceList Conversions;
6617 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6618 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6619 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6620 return CheckNonDependentConversions(
6621 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6622 SuppressUserConversions, ActingContext, ObjectType,
6623 ObjectClassification);
6624 })) {
6625 OverloadCandidate &Candidate =
6626 CandidateSet.addCandidate(Conversions.size(), Conversions);
6627 Candidate.FoundDecl = FoundDecl;
6628 Candidate.Function = MethodTmpl->getTemplatedDecl();
6629 Candidate.Viable = false;
6630 Candidate.IsSurrogate = false;
6631 Candidate.IgnoreObjectArgument =
6632 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6633 ObjectType.isNull();
6634 Candidate.ExplicitCallArguments = Args.size();
6635 if (Result == TDK_NonDependentConversionFailure)
6636 Candidate.FailureKind = ovl_fail_bad_conversion;
6637 else {
6638 Candidate.FailureKind = ovl_fail_bad_deduction;
6639 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6640 Info);
6641 }
6642 return;
6643 }
6644
6645 // Add the function template specialization produced by template argument
6646 // deduction as a candidate.
6647 assert(Specialization && "Missing member function template specialization?")(static_cast <bool> (Specialization && "Missing member function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6647, __extension__ __PRETTY_FUNCTION__))
;
6648 assert(isa<CXXMethodDecl>(Specialization) &&(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6649, __extension__ __PRETTY_FUNCTION__))
6649 "Specialization is not a member function?")(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6649, __extension__ __PRETTY_FUNCTION__))
;
6650 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6651 ActingContext, ObjectType, ObjectClassification, Args,
6652 CandidateSet, SuppressUserConversions, PartialOverloading,
6653 Conversions);
6654}
6655
6656/// \brief Add a C++ function template specialization as a candidate
6657/// in the candidate set, using template argument deduction to produce
6658/// an appropriate function template specialization.
6659void
6660Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6661 DeclAccessPair FoundDecl,
6662 TemplateArgumentListInfo *ExplicitTemplateArgs,
6663 ArrayRef<Expr *> Args,
6664 OverloadCandidateSet& CandidateSet,
6665 bool SuppressUserConversions,
6666 bool PartialOverloading) {
6667 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6668 return;
6669
6670 // C++ [over.match.funcs]p7:
6671 // In each case where a candidate is a function template, candidate
6672 // function template specializations are generated using template argument
6673 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6674 // candidate functions in the usual way.113) A given name can refer to one
6675 // or more function templates and also to a set of overloaded non-template
6676 // functions. In such a case, the candidate functions generated from each
6677 // function template are combined with the set of non-template candidate
6678 // functions.
6679 TemplateDeductionInfo Info(CandidateSet.getLocation());
6680 FunctionDecl *Specialization = nullptr;
6681 ConversionSequenceList Conversions;
6682 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6683 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6684 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6685 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6686 Args, CandidateSet, Conversions,
6687 SuppressUserConversions);
6688 })) {
6689 OverloadCandidate &Candidate =
6690 CandidateSet.addCandidate(Conversions.size(), Conversions);
6691 Candidate.FoundDecl = FoundDecl;
6692 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6693 Candidate.Viable = false;
6694 Candidate.IsSurrogate = false;
6695 // Ignore the object argument if there is one, since we don't have an object
6696 // type.
6697 Candidate.IgnoreObjectArgument =
6698 isa<CXXMethodDecl>(Candidate.Function) &&
6699 !isa<CXXConstructorDecl>(Candidate.Function);
6700 Candidate.ExplicitCallArguments = Args.size();
6701 if (Result == TDK_NonDependentConversionFailure)
6702 Candidate.FailureKind = ovl_fail_bad_conversion;
6703 else {
6704 Candidate.FailureKind = ovl_fail_bad_deduction;
6705 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6706 Info);
6707 }
6708 return;
6709 }
6710
6711 // Add the function template specialization produced by template argument
6712 // deduction as a candidate.
6713 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6713, __extension__ __PRETTY_FUNCTION__))
;
6714 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6715 SuppressUserConversions, PartialOverloading,
6716 /*AllowExplicit*/false, Conversions);
6717}
6718
6719/// Check that implicit conversion sequences can be formed for each argument
6720/// whose corresponding parameter has a non-dependent type, per DR1391's
6721/// [temp.deduct.call]p10.
6722bool Sema::CheckNonDependentConversions(
6723 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6724 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6725 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6726 CXXRecordDecl *ActingContext, QualType ObjectType,
6727 Expr::Classification ObjectClassification) {
6728 // FIXME: The cases in which we allow explicit conversions for constructor
6729 // arguments never consider calling a constructor template. It's not clear
6730 // that is correct.
6731 const bool AllowExplicit = false;
6732
6733 auto *FD = FunctionTemplate->getTemplatedDecl();
6734 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6735 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6736 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6737
6738 Conversions =
6739 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6740
6741 // Overload resolution is always an unevaluated context.
6742 EnterExpressionEvaluationContext Unevaluated(
6743 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6744
6745 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6746 // require that, but this check should never result in a hard error, and
6747 // overload resolution is permitted to sidestep instantiations.
6748 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6749 !ObjectType.isNull()) {
6750 Conversions[0] = TryObjectArgumentInitialization(
6751 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6752 Method, ActingContext);
6753 if (Conversions[0].isBad())
6754 return true;
6755 }
6756
6757 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6758 ++I) {
6759 QualType ParamType = ParamTypes[I];
6760 if (!ParamType->isDependentType()) {
6761 Conversions[ThisConversions + I]
6762 = TryCopyInitialization(*this, Args[I], ParamType,
6763 SuppressUserConversions,
6764 /*InOverloadResolution=*/true,
6765 /*AllowObjCWritebackConversion=*/
6766 getLangOpts().ObjCAutoRefCount,
6767 AllowExplicit);
6768 if (Conversions[ThisConversions + I].isBad())
6769 return true;
6770 }
6771 }
6772
6773 return false;
6774}
6775
6776/// Determine whether this is an allowable conversion from the result
6777/// of an explicit conversion operator to the expected type, per C++
6778/// [over.match.conv]p1 and [over.match.ref]p1.
6779///
6780/// \param ConvType The return type of the conversion function.
6781///
6782/// \param ToType The type we are converting to.
6783///
6784/// \param AllowObjCPointerConversion Allow a conversion from one
6785/// Objective-C pointer to another.
6786///
6787/// \returns true if the conversion is allowable, false otherwise.
6788static bool isAllowableExplicitConversion(Sema &S,
6789 QualType ConvType, QualType ToType,
6790 bool AllowObjCPointerConversion) {
6791 QualType ToNonRefType = ToType.getNonReferenceType();
6792
6793 // Easy case: the types are the same.
6794 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6795 return true;
6796
6797 // Allow qualification conversions.
6798 bool ObjCLifetimeConversion;
6799 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6800 ObjCLifetimeConversion))
6801 return true;
6802
6803 // If we're not allowed to consider Objective-C pointer conversions,
6804 // we're done.
6805 if (!AllowObjCPointerConversion)
6806 return false;
6807
6808 // Is this an Objective-C pointer conversion?
6809 bool IncompatibleObjC = false;
6810 QualType ConvertedType;
6811 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6812 IncompatibleObjC);
6813}
6814
6815/// AddConversionCandidate - Add a C++ conversion function as a
6816/// candidate in the candidate set (C++ [over.match.conv],
6817/// C++ [over.match.copy]). From is the expression we're converting from,
6818/// and ToType is the type that we're eventually trying to convert to
6819/// (which may or may not be the same type as the type that the
6820/// conversion function produces).
6821void
6822Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6823 DeclAccessPair FoundDecl,
6824 CXXRecordDecl *ActingContext,
6825 Expr *From, QualType ToType,
6826 OverloadCandidateSet& CandidateSet,
6827 bool AllowObjCConversionOnExplicit,
6828 bool AllowResultConversion) {
6829 assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6830, __extension__ __PRETTY_FUNCTION__))
6830 "Conversion function templates use AddTemplateConversionCandidate")(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6830, __extension__ __PRETTY_FUNCTION__))
;
6831 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6832 if (!CandidateSet.isNewCandidate(Conversion))
6833 return;
6834
6835 // If the conversion function has an undeduced return type, trigger its
6836 // deduction now.
6837 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6838 if (DeduceReturnType(Conversion, From->getExprLoc()))
6839 return;
6840 ConvType = Conversion->getConversionType().getNonReferenceType();
6841 }
6842
6843 // If we don't allow any conversion of the result type, ignore conversion
6844 // functions that don't convert to exactly (possibly cv-qualified) T.
6845 if (!AllowResultConversion &&
6846 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6847 return;
6848
6849 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6850 // operator is only a candidate if its return type is the target type or
6851 // can be converted to the target type with a qualification conversion.
6852 if (Conversion->isExplicit() &&
6853 !isAllowableExplicitConversion(*this, ConvType, ToType,
6854 AllowObjCConversionOnExplicit))
6855 return;
6856
6857 // Overload resolution is always an unevaluated context.
6858 EnterExpressionEvaluationContext Unevaluated(
6859 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6860
6861 // Add this candidate
6862 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6863 Candidate.FoundDecl = FoundDecl;
6864 Candidate.Function = Conversion;
6865 Candidate.IsSurrogate = false;
6866 Candidate.IgnoreObjectArgument = false;
6867 Candidate.FinalConversion.setAsIdentityConversion();
6868 Candidate.FinalConversion.setFromType(ConvType);
6869 Candidate.FinalConversion.setAllToTypes(ToType);
6870 Candidate.Viable = true;
6871 Candidate.ExplicitCallArguments = 1;
6872
6873 // C++ [over.match.funcs]p4:
6874 // For conversion functions, the function is considered to be a member of
6875 // the class of the implicit implied object argument for the purpose of
6876 // defining the type of the implicit object parameter.
6877 //
6878 // Determine the implicit conversion sequence for the implicit
6879 // object parameter.
6880 QualType ImplicitParamType = From->getType();
6881 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6882 ImplicitParamType = FromPtrType->getPointeeType();
6883 CXXRecordDecl *ConversionContext
6884 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6885
6886 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6887 *this, CandidateSet.getLocation(), From->getType(),
6888 From->Classify(Context), Conversion, ConversionContext);
6889
6890 if (Candidate.Conversions[0].isBad()) {
6891 Candidate.Viable = false;
6892 Candidate.FailureKind = ovl_fail_bad_conversion;
6893 return;
6894 }
6895
6896 // We won't go through a user-defined type conversion function to convert a
6897 // derived to base as such conversions are given Conversion Rank. They only
6898 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6899 QualType FromCanon
6900 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6901 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6902 if (FromCanon == ToCanon ||
6903 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6904 Candidate.Viable = false;
6905 Candidate.FailureKind = ovl_fail_trivial_conversion;
6906 return;
6907 }
6908
6909 // To determine what the conversion from the result of calling the
6910 // conversion function to the type we're eventually trying to
6911 // convert to (ToType), we need to synthesize a call to the
6912 // conversion function and attempt copy initialization from it. This
6913 // makes sure that we get the right semantics with respect to
6914 // lvalues/rvalues and the type. Fortunately, we can allocate this
6915 // call on the stack and we don't need its arguments to be
6916 // well-formed.
6917 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6918 VK_LValue, From->getLocStart());
6919 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6920 Context.getPointerType(Conversion->getType()),
6921 CK_FunctionToPointerDecay,
6922 &ConversionRef, VK_RValue);
6923
6924 QualType ConversionType = Conversion->getConversionType();
6925 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6926 Candidate.Viable = false;
6927 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6928 return;
6929 }
6930
6931 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6932
6933 // Note that it is safe to allocate CallExpr on the stack here because
6934 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6935 // allocator).
6936 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6937 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6938 From->getLocStart());
6939 ImplicitConversionSequence ICS =
6940 TryCopyInitialization(*this, &Call, ToType,
6941 /*SuppressUserConversions=*/true,
6942 /*InOverloadResolution=*/false,
6943 /*AllowObjCWritebackConversion=*/false);
6944
6945 switch (ICS.getKind()) {
6946 case ImplicitConversionSequence::StandardConversion:
6947 Candidate.FinalConversion = ICS.Standard;
6948
6949 // C++ [over.ics.user]p3:
6950 // If the user-defined conversion is specified by a specialization of a
6951 // conversion function template, the second standard conversion sequence
6952 // shall have exact match rank.
6953 if (Conversion->getPrimaryTemplate() &&
6954 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6955 Candidate.Viable = false;
6956 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6957 return;
6958 }
6959
6960 // C++0x [dcl.init.ref]p5:
6961 // In the second case, if the reference is an rvalue reference and
6962 // the second standard conversion sequence of the user-defined
6963 // conversion sequence includes an lvalue-to-rvalue conversion, the
6964 // program is ill-formed.
6965 if (ToType->isRValueReferenceType() &&
6966 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6967 Candidate.Viable = false;
6968 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6969 return;
6970 }
6971 break;
6972
6973 case ImplicitConversionSequence::BadConversion:
6974 Candidate.Viable = false;
6975 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6976 return;
6977
6978 default:
6979 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6980)
6980 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 6980)
;
6981 }
6982
6983 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6984 Candidate.Viable = false;
6985 Candidate.FailureKind = ovl_fail_enable_if;
6986 Candidate.DeductionFailure.Data = FailedAttr;
6987 return;
6988 }
6989}
6990
6991/// \brief Adds a conversion function template specialization
6992/// candidate to the overload set, using template argument deduction
6993/// to deduce the template arguments of the conversion function
6994/// template from the type that we are converting to (C++
6995/// [temp.deduct.conv]).
6996void
6997Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6998 DeclAccessPair FoundDecl,
6999 CXXRecordDecl *ActingDC,
7000 Expr *From, QualType ToType,
7001 OverloadCandidateSet &CandidateSet,
7002 bool AllowObjCConversionOnExplicit,
7003 bool AllowResultConversion) {
7004 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7005, __extension__ __PRETTY_FUNCTION__))
7005 "Only conversion function templates permitted here")(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7005, __extension__ __PRETTY_FUNCTION__))
;
7006
7007 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7008 return;
7009
7010 TemplateDeductionInfo Info(CandidateSet.getLocation());
7011 CXXConversionDecl *Specialization = nullptr;
7012 if (TemplateDeductionResult Result
7013 = DeduceTemplateArguments(FunctionTemplate, ToType,
7014 Specialization, Info)) {
7015 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7016 Candidate.FoundDecl = FoundDecl;
7017 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7018 Candidate.Viable = false;
7019 Candidate.FailureKind = ovl_fail_bad_deduction;
7020 Candidate.IsSurrogate = false;
7021 Candidate.IgnoreObjectArgument = false;
7022 Candidate.ExplicitCallArguments = 1;
7023 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7024 Info);
7025 return;
7026 }
7027
7028 // Add the conversion function template specialization produced by
7029 // template argument deduction as a candidate.
7030 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7030, __extension__ __PRETTY_FUNCTION__))
;
7031 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7032 CandidateSet, AllowObjCConversionOnExplicit,
7033 AllowResultConversion);
7034}
7035
7036/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7037/// converts the given @c Object to a function pointer via the
7038/// conversion function @c Conversion, and then attempts to call it
7039/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7040/// the type of function that we'll eventually be calling.
7041void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7042 DeclAccessPair FoundDecl,
7043 CXXRecordDecl *ActingContext,
7044 const FunctionProtoType *Proto,
7045 Expr *Object,
7046 ArrayRef<Expr *> Args,
7047 OverloadCandidateSet& CandidateSet) {
7048 if (!CandidateSet.isNewCandidate(Conversion))
7049 return;
7050
7051 // Overload resolution is always an unevaluated context.
7052 EnterExpressionEvaluationContext Unevaluated(
7053 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7054
7055 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7056 Candidate.FoundDecl = FoundDecl;
7057 Candidate.Function = nullptr;
7058 Candidate.Surrogate = Conversion;
7059 Candidate.Viable = true;
7060 Candidate.IsSurrogate = true;
7061 Candidate.IgnoreObjectArgument = false;
7062 Candidate.ExplicitCallArguments = Args.size();
7063
7064 // Determine the implicit conversion sequence for the implicit
7065 // object parameter.
7066 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7067 *this, CandidateSet.getLocation(), Object->getType(),
7068 Object->Classify(Context), Conversion, ActingContext);
7069 if (ObjectInit.isBad()) {
7070 Candidate.Viable = false;
7071 Candidate.FailureKind = ovl_fail_bad_conversion;
7072 Candidate.Conversions[0] = ObjectInit;
7073 return;
7074 }
7075
7076 // The first conversion is actually a user-defined conversion whose
7077 // first conversion is ObjectInit's standard conversion (which is
7078 // effectively a reference binding). Record it as such.
7079 Candidate.Conversions[0].setUserDefined();
7080 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7081 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7082 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7083 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7084 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7085 Candidate.Conversions[0].UserDefined.After
7086 = Candidate.Conversions[0].UserDefined.Before;
7087 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7088
7089 // Find the
7090 unsigned NumParams = Proto->getNumParams();
7091
7092 // (C++ 13.3.2p2): A candidate function having fewer than m
7093 // parameters is viable only if it has an ellipsis in its parameter
7094 // list (8.3.5).
7095 if (Args.size() > NumParams && !Proto->isVariadic()) {
7096 Candidate.Viable = false;
7097 Candidate.FailureKind = ovl_fail_too_many_arguments;
7098 return;
7099 }
7100
7101 // Function types don't have any default arguments, so just check if
7102 // we have enough arguments.
7103 if (Args.size() < NumParams) {
7104 // Not enough arguments.
7105 Candidate.Viable = false;
7106 Candidate.FailureKind = ovl_fail_too_few_arguments;
7107 return;
7108 }
7109
7110 // Determine the implicit conversion sequences for each of the
7111 // arguments.
7112 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7113 if (ArgIdx < NumParams) {
7114 // (C++ 13.3.2p3): for F to be a viable function, there shall
7115 // exist for each argument an implicit conversion sequence
7116 // (13.3.3.1) that converts that argument to the corresponding
7117 // parameter of F.
7118 QualType ParamType = Proto->getParamType(ArgIdx);
7119 Candidate.Conversions[ArgIdx + 1]
7120 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7121 /*SuppressUserConversions=*/false,
7122 /*InOverloadResolution=*/false,
7123 /*AllowObjCWritebackConversion=*/
7124 getLangOpts().ObjCAutoRefCount);
7125 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7126 Candidate.Viable = false;
7127 Candidate.FailureKind = ovl_fail_bad_conversion;
7128 return;
7129 }
7130 } else {
7131 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7132 // argument for which there is no corresponding parameter is
7133 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7134 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7135 }
7136 }
7137
7138 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7139 Candidate.Viable = false;
7140 Candidate.FailureKind = ovl_fail_enable_if;
7141 Candidate.DeductionFailure.Data = FailedAttr;
7142 return;
7143 }
7144}
7145
7146/// \brief Add overload candidates for overloaded operators that are
7147/// member functions.
7148///
7149/// Add the overloaded operator candidates that are member functions
7150/// for the operator Op that was used in an operator expression such
7151/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7152/// CandidateSet will store the added overload candidates. (C++
7153/// [over.match.oper]).
7154void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7155 SourceLocation OpLoc,
7156 ArrayRef<Expr *> Args,
7157 OverloadCandidateSet& CandidateSet,
7158 SourceRange OpRange) {
7159 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7160
7161 // C++ [over.match.oper]p3:
7162 // For a unary operator @ with an operand of a type whose
7163 // cv-unqualified version is T1, and for a binary operator @ with
7164 // a left operand of a type whose cv-unqualified version is T1 and
7165 // a right operand of a type whose cv-unqualified version is T2,
7166 // three sets of candidate functions, designated member
7167 // candidates, non-member candidates and built-in candidates, are
7168 // constructed as follows:
7169 QualType T1 = Args[0]->getType();
7170
7171 // -- If T1 is a complete class type or a class currently being
7172 // defined, the set of member candidates is the result of the
7173 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7174 // the set of member candidates is empty.
7175 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7176 // Complete the type if it can be completed.
7177 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7178 return;
7179 // If the type is neither complete nor being defined, bail out now.
7180 if (!T1Rec->getDecl()->getDefinition())
7181 return;
7182
7183 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7184 LookupQualifiedName(Operators, T1Rec->getDecl());
7185 Operators.suppressDiagnostics();
7186
7187 for (LookupResult::iterator Oper = Operators.begin(),
7188 OperEnd = Operators.end();
7189 Oper != OperEnd;
7190 ++Oper)
7191 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7192 Args[0]->Classify(Context), Args.slice(1),
7193 CandidateSet, /*SuppressUserConversions=*/false);
7194 }
7195}
7196
7197/// AddBuiltinCandidate - Add a candidate for a built-in
7198/// operator. ResultTy and ParamTys are the result and parameter types
7199/// of the built-in candidate, respectively. Args and NumArgs are the
7200/// arguments being passed to the candidate. IsAssignmentOperator
7201/// should be true when this built-in candidate is an assignment
7202/// operator. NumContextualBoolArguments is the number of arguments
7203/// (at the beginning of the argument list) that will be contextually
7204/// converted to bool.
7205void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7206 OverloadCandidateSet& CandidateSet,
7207 bool IsAssignmentOperator,
7208 unsigned NumContextualBoolArguments) {
7209 // Overload resolution is always an unevaluated context.
7210 EnterExpressionEvaluationContext Unevaluated(
7211 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7212
7213 // Add this candidate
7214 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7215 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7216 Candidate.Function = nullptr;
7217 Candidate.IsSurrogate = false;
7218 Candidate.IgnoreObjectArgument = false;
7219 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7220
7221 // Determine the implicit conversion sequences for each of the
7222 // arguments.
7223 Candidate.Viable = true;
7224 Candidate.ExplicitCallArguments = Args.size();
7225 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7226 // C++ [over.match.oper]p4:
7227 // For the built-in assignment operators, conversions of the
7228 // left operand are restricted as follows:
7229 // -- no temporaries are introduced to hold the left operand, and
7230 // -- no user-defined conversions are applied to the left
7231 // operand to achieve a type match with the left-most
7232 // parameter of a built-in candidate.
7233 //
7234 // We block these conversions by turning off user-defined
7235 // conversions, since that is the only way that initialization of
7236 // a reference to a non-class type can occur from something that
7237 // is not of the same type.
7238 if (ArgIdx < NumContextualBoolArguments) {
7239 assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7240, __extension__ __PRETTY_FUNCTION__))
7240 "Contextual conversion to bool requires bool type")(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7240, __extension__ __PRETTY_FUNCTION__))
;
7241 Candidate.Conversions[ArgIdx]
7242 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7243 } else {
7244 Candidate.Conversions[ArgIdx]
7245 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7246 ArgIdx == 0 && IsAssignmentOperator,
7247 /*InOverloadResolution=*/false,
7248 /*AllowObjCWritebackConversion=*/
7249 getLangOpts().ObjCAutoRefCount);
7250 }
7251 if (Candidate.Conversions[ArgIdx].isBad()) {
7252 Candidate.Viable = false;
7253 Candidate.FailureKind = ovl_fail_bad_conversion;
7254 break;
7255 }
7256 }
7257}
7258
7259namespace {
7260
7261/// BuiltinCandidateTypeSet - A set of types that will be used for the
7262/// candidate operator functions for built-in operators (C++
7263/// [over.built]). The types are separated into pointer types and
7264/// enumeration types.
7265class BuiltinCandidateTypeSet {
7266 /// TypeSet - A set of types.
7267 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7268 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7269
7270 /// PointerTypes - The set of pointer types that will be used in the
7271 /// built-in candidates.
7272 TypeSet PointerTypes;
7273
7274 /// MemberPointerTypes - The set of member pointer types that will be
7275 /// used in the built-in candidates.
7276 TypeSet MemberPointerTypes;
7277
7278 /// EnumerationTypes - The set of enumeration types that will be
7279 /// used in the built-in candidates.
7280 TypeSet EnumerationTypes;
7281
7282 /// \brief The set of vector types that will be used in the built-in
7283 /// candidates.
7284 TypeSet VectorTypes;
7285
7286 /// \brief A flag indicating non-record types are viable candidates
7287 bool HasNonRecordTypes;
7288
7289 /// \brief A flag indicating whether either arithmetic or enumeration types
7290 /// were present in the candidate set.
7291 bool HasArithmeticOrEnumeralTypes;
7292
7293 /// \brief A flag indicating whether the nullptr type was present in the
7294 /// candidate set.
7295 bool HasNullPtrType;
7296
7297 /// Sema - The semantic analysis instance where we are building the
7298 /// candidate type set.
7299 Sema &SemaRef;
7300
7301 /// Context - The AST context in which we will build the type sets.
7302 ASTContext &Context;
7303
7304 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7305 const Qualifiers &VisibleQuals);
7306 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7307
7308public:
7309 /// iterator - Iterates through the types that are part of the set.
7310 typedef TypeSet::iterator iterator;
7311
7312 BuiltinCandidateTypeSet(Sema &SemaRef)
7313 : HasNonRecordTypes(false),
7314 HasArithmeticOrEnumeralTypes(false),
7315 HasNullPtrType(false),
7316 SemaRef(SemaRef),
7317 Context(SemaRef.Context) { }
7318
7319 void AddTypesConvertedFrom(QualType Ty,
7320 SourceLocation Loc,
7321 bool AllowUserConversions,
7322 bool AllowExplicitConversions,
7323 const Qualifiers &VisibleTypeConversionsQuals);
7324
7325 /// pointer_begin - First pointer type found;
7326 iterator pointer_begin() { return PointerTypes.begin(); }
7327
7328 /// pointer_end - Past the last pointer type found;
7329 iterator pointer_end() { return PointerTypes.end(); }
7330
7331 /// member_pointer_begin - First member pointer type found;
7332 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7333
7334 /// member_pointer_end - Past the last member pointer type found;
7335 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7336
7337 /// enumeration_begin - First enumeration type found;
7338 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7339
7340 /// enumeration_end - Past the last enumeration type found;
7341 iterator enumeration_end() { return EnumerationTypes.end(); }
7342
7343 iterator vector_begin() { return VectorTypes.begin(); }
7344 iterator vector_end() { return VectorTypes.end(); }
7345
7346 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7347 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7348 bool hasNullPtrType() const { return HasNullPtrType; }
7349};
7350
7351} // end anonymous namespace
7352
7353/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7354/// the set of pointer types along with any more-qualified variants of
7355/// that type. For example, if @p Ty is "int const *", this routine
7356/// will add "int const *", "int const volatile *", "int const
7357/// restrict *", and "int const volatile restrict *" to the set of
7358/// pointer types. Returns true if the add of @p Ty itself succeeded,
7359/// false otherwise.
7360///
7361/// FIXME: what to do about extended qualifiers?
7362bool
7363BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7364 const Qualifiers &VisibleQuals) {
7365
7366 // Insert this type.
7367 if (!PointerTypes.insert(Ty))
7368 return false;
7369
7370 QualType PointeeTy;
7371 const PointerType *PointerTy = Ty->getAs<PointerType>();
7372 bool buildObjCPtr = false;
7373 if (!PointerTy) {
7374 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7375 PointeeTy = PTy->getPointeeType();
7376 buildObjCPtr = true;
7377 } else {
7378 PointeeTy = PointerTy->getPointeeType();
7379 }
7380
7381 // Don't add qualified variants of arrays. For one, they're not allowed
7382 // (the qualifier would sink to the element type), and for another, the
7383 // only overload situation where it matters is subscript or pointer +- int,
7384 // and those shouldn't have qualifier variants anyway.
7385 if (PointeeTy->isArrayType())
7386 return true;
7387
7388 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7389 bool hasVolatile = VisibleQuals.hasVolatile();
7390 bool hasRestrict = VisibleQuals.hasRestrict();
7391
7392 // Iterate through all strict supersets of BaseCVR.
7393 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7394 if ((CVR | BaseCVR) != CVR) continue;
7395 // Skip over volatile if no volatile found anywhere in the types.
7396 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7397
7398 // Skip over restrict if no restrict found anywhere in the types, or if
7399 // the type cannot be restrict-qualified.
7400 if ((CVR & Qualifiers::Restrict) &&
7401 (!hasRestrict ||
7402 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7403 continue;
7404
7405 // Build qualified pointee type.
7406 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7407
7408 // Build qualified pointer type.
7409 QualType QPointerTy;
7410 if (!buildObjCPtr)
7411 QPointerTy = Context.getPointerType(QPointeeTy);
7412 else
7413 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7414
7415 // Insert qualified pointer type.
7416 PointerTypes.insert(QPointerTy);
7417 }
7418
7419 return true;
7420}
7421
7422/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7423/// to the set of pointer types along with any more-qualified variants of
7424/// that type. For example, if @p Ty is "int const *", this routine
7425/// will add "int const *", "int const volatile *", "int const
7426/// restrict *", and "int const volatile restrict *" to the set of
7427/// pointer types. Returns true if the add of @p Ty itself succeeded,
7428/// false otherwise.
7429///
7430/// FIXME: what to do about extended qualifiers?
7431bool
7432BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7433 QualType Ty) {
7434 // Insert this type.
7435 if (!MemberPointerTypes.insert(Ty))
7436 return false;
7437
7438 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7439 assert(PointerTy && "type was not a member pointer type!")(static_cast <bool> (PointerTy && "type was not a member pointer type!"
) ? void (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7439, __extension__ __PRETTY_FUNCTION__))
;
7440
7441 QualType PointeeTy = PointerTy->getPointeeType();
7442 // Don't add qualified variants of arrays. For one, they're not allowed
7443 // (the qualifier would sink to the element type), and for another, the
7444 // only overload situation where it matters is subscript or pointer +- int,
7445 // and those shouldn't have qualifier variants anyway.
7446 if (PointeeTy->isArrayType())
7447 return true;
7448 const Type *ClassTy = PointerTy->getClass();
7449
7450 // Iterate through all strict supersets of the pointee type's CVR
7451 // qualifiers.
7452 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7453 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7454 if ((CVR | BaseCVR) != CVR) continue;
7455
7456 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7457 MemberPointerTypes.insert(
7458 Context.getMemberPointerType(QPointeeTy, ClassTy));
7459 }
7460
7461 return true;
7462}
7463
7464/// AddTypesConvertedFrom - Add each of the types to which the type @p
7465/// Ty can be implicit converted to the given set of @p Types. We're
7466/// primarily interested in pointer types and enumeration types. We also
7467/// take member pointer types, for the conditional operator.
7468/// AllowUserConversions is true if we should look at the conversion
7469/// functions of a class type, and AllowExplicitConversions if we
7470/// should also include the explicit conversion functions of a class
7471/// type.
7472void
7473BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7474 SourceLocation Loc,
7475 bool AllowUserConversions,
7476 bool AllowExplicitConversions,
7477 const Qualifiers &VisibleQuals) {
7478 // Only deal with canonical types.
7479 Ty = Context.getCanonicalType(Ty);
7480
7481 // Look through reference types; they aren't part of the type of an
7482 // expression for the purposes of conversions.
7483 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7484 Ty = RefTy->getPointeeType();
7485
7486 // If we're dealing with an array type, decay to the pointer.
7487 if (Ty->isArrayType())
7488 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7489
7490 // Otherwise, we don't care about qualifiers on the type.
7491 Ty = Ty.getLocalUnqualifiedType();
7492
7493 // Flag if we ever add a non-record type.
7494 const RecordType *TyRec = Ty->getAs<RecordType>();
7495 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7496
7497 // Flag if we encounter an arithmetic type.
7498 HasArithmeticOrEnumeralTypes =
7499 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7500
7501 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7502 PointerTypes.insert(Ty);
7503 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7504 // Insert our type, and its more-qualified variants, into the set
7505 // of types.
7506 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7507 return;
7508 } else if (Ty->isMemberPointerType()) {
7509 // Member pointers are far easier, since the pointee can't be converted.
7510 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7511 return;
7512 } else if (Ty->isEnumeralType()) {
7513 HasArithmeticOrEnumeralTypes = true;
7514 EnumerationTypes.insert(Ty);
7515 } else if (Ty->isVectorType()) {
7516 // We treat vector types as arithmetic types in many contexts as an
7517 // extension.
7518 HasArithmeticOrEnumeralTypes = true;
7519 VectorTypes.insert(Ty);
7520 } else if (Ty->isNullPtrType()) {
7521 HasNullPtrType = true;
7522 } else if (AllowUserConversions && TyRec) {
7523 // No conversion functions in incomplete types.
7524 if (!SemaRef.isCompleteType(Loc, Ty))
7525 return;
7526
7527 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7528 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7529 if (isa<UsingShadowDecl>(D))
7530 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7531
7532 // Skip conversion function templates; they don't tell us anything
7533 // about which builtin types we can convert to.
7534 if (isa<FunctionTemplateDecl>(D))
7535 continue;
7536
7537 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7538 if (AllowExplicitConversions || !Conv->isExplicit()) {
7539 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7540 VisibleQuals);
7541 }
7542 }
7543 }
7544}
7545
7546/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7547/// the volatile- and non-volatile-qualified assignment operators for the
7548/// given type to the candidate set.
7549static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7550 QualType T,
7551 ArrayRef<Expr *> Args,
7552 OverloadCandidateSet &CandidateSet) {
7553 QualType ParamTypes[2];
7554
7555 // T& operator=(T&, T)
7556 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7557 ParamTypes[1] = T;
7558 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7559 /*IsAssignmentOperator=*/true);
7560
7561 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7562 // volatile T& operator=(volatile T&, T)
7563 ParamTypes[0]
7564 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7565 ParamTypes[1] = T;
7566 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7567 /*IsAssignmentOperator=*/true);
7568 }
7569}
7570
7571/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7572/// if any, found in visible type conversion functions found in ArgExpr's type.
7573static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7574 Qualifiers VRQuals;
7575 const RecordType *TyRec;
7576 if (const MemberPointerType *RHSMPType =
7577 ArgExpr->getType()->getAs<MemberPointerType>())
7578 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7579 else
7580 TyRec = ArgExpr->getType()->getAs<RecordType>();
7581 if (!TyRec) {
7582 // Just to be safe, assume the worst case.
7583 VRQuals.addVolatile();
7584 VRQuals.addRestrict();
7585 return VRQuals;
7586 }
7587
7588 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7589 if (!ClassDecl->hasDefinition())
7590 return VRQuals;
7591
7592 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7593 if (isa<UsingShadowDecl>(D))
7594 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7595 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7596 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7597 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7598 CanTy = ResTypeRef->getPointeeType();
7599 // Need to go down the pointer/mempointer chain and add qualifiers
7600 // as see them.
7601 bool done = false;
7602 while (!done) {
7603 if (CanTy.isRestrictQualified())
7604 VRQuals.addRestrict();
7605 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7606 CanTy = ResTypePtr->getPointeeType();
7607 else if (const MemberPointerType *ResTypeMPtr =
7608 CanTy->getAs<MemberPointerType>())
7609 CanTy = ResTypeMPtr->getPointeeType();
7610 else
7611 done = true;
7612 if (CanTy.isVolatileQualified())
7613 VRQuals.addVolatile();
7614 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7615 return VRQuals;
7616 }
7617 }
7618 }
7619 return VRQuals;
7620}
7621
7622namespace {
7623
7624/// \brief Helper class to manage the addition of builtin operator overload
7625/// candidates. It provides shared state and utility methods used throughout
7626/// the process, as well as a helper method to add each group of builtin
7627/// operator overloads from the standard to a candidate set.
7628class BuiltinOperatorOverloadBuilder {
7629 // Common instance state available to all overload candidate addition methods.
7630 Sema &S;
7631 ArrayRef<Expr *> Args;
7632 Qualifiers VisibleTypeConversionsQuals;
7633 bool HasArithmeticOrEnumeralCandidateType;
7634 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7635 OverloadCandidateSet &CandidateSet;
7636
7637 static constexpr int ArithmeticTypesCap = 24;
7638 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7639
7640 // Define some indices used to iterate over the arithemetic types in
7641 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
7642 // types are that preserved by promotion (C++ [over.built]p2).
7643 unsigned FirstIntegralType,
7644 LastIntegralType;
7645 unsigned FirstPromotedIntegralType,
7646 LastPromotedIntegralType;
7647 unsigned FirstPromotedArithmeticType,
7648 LastPromotedArithmeticType;
7649 unsigned NumArithmeticTypes;
7650
7651 void InitArithmeticTypes() {
7652 // Start of promoted types.
7653 FirstPromotedArithmeticType = 0;
7654 ArithmeticTypes.push_back(S.Context.FloatTy);
7655 ArithmeticTypes.push_back(S.Context.DoubleTy);
7656 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7657 if (S.Context.getTargetInfo().hasFloat128Type())
7658 ArithmeticTypes.push_back(S.Context.Float128Ty);
7659
7660 // Start of integral types.
7661 FirstIntegralType = ArithmeticTypes.size();
7662 FirstPromotedIntegralType = ArithmeticTypes.size();
7663 ArithmeticTypes.push_back(S.Context.IntTy);
7664 ArithmeticTypes.push_back(S.Context.LongTy);
7665 ArithmeticTypes.push_back(S.Context.LongLongTy);
7666 if (S.Context.getTargetInfo().hasInt128Type())
7667 ArithmeticTypes.push_back(S.Context.Int128Ty);
7668 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7669 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7670 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7671 if (S.Context.getTargetInfo().hasInt128Type())
7672 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7673 LastPromotedIntegralType = ArithmeticTypes.size();
7674 LastPromotedArithmeticType = ArithmeticTypes.size();
7675 // End of promoted types.
7676
7677 ArithmeticTypes.push_back(S.Context.BoolTy);
7678 ArithmeticTypes.push_back(S.Context.CharTy);
7679 ArithmeticTypes.push_back(S.Context.WCharTy);
7680 ArithmeticTypes.push_back(S.Context.Char16Ty);
7681 ArithmeticTypes.push_back(S.Context.Char32Ty);
7682 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7683 ArithmeticTypes.push_back(S.Context.ShortTy);
7684 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7685 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7686 LastIntegralType = ArithmeticTypes.size();
7687 NumArithmeticTypes = ArithmeticTypes.size();
7688 // End of integral types.
7689 // FIXME: What about complex? What about half?
7690
7691 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7692, __extension__ __PRETTY_FUNCTION__))
7692 "Enough inline storage for all arithmetic types.")(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/Sema/SemaOverload.cpp"
, 7692, __extension__ __PRETTY_FUNCTION__))
;
7693 }
7694
7695 /// \brief Helper method to factor out the common pattern of adding overloads
7696 /// for '++' and '--' builtin operators.
7697 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7698 bool HasVolatile,
7699 bool HasRestrict) {
7700 QualType ParamTypes[2] = {
7701 S.Context.getLValueReferenceType(CandidateTy),
7702 S.Context.IntTy
7703 };
7704
7705 // Non-volatile version.
7706 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7707
7708 // Use a heuristic to reduce number of builtin candidates in the set:
7709 // add volatile version only if there are conversions to a volatile type.
7710 if (HasVolatile) {
7711 ParamTypes[0] =
7712 S.Context.getLValueReferenceType(
7713 S.Context.getVolatileType(CandidateTy));
7714 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7715 }
7716
7717 // Add restrict version only if there are conversions to a restrict type
7718 // and our candidate type is a non-restrict-qualified pointer.
7719 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7720 !CandidateTy.isRestrictQualified()) {
7721 ParamTypes[0]
7722 = S.Context.getLValueReferenceType(
7723 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7724 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7725
7726 if (HasVolatile) {
7727 ParamTypes[0]
7728 = S.Context.getLValueReferenceType(
7729 S.Context.getCVRQualifiedType(CandidateTy,
7730