clang  16.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
30 #include "clang/Sema/Template.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
44 
46  return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47  return P->hasAttr<PassObjectSizeAttr>();
48  });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
53  Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
54  bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
55  const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
56  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
57  return ExprError();
58  // If FoundDecl is different from Fn (such as if one is a template
59  // and the other a specialization), make sure DiagnoseUseOfDecl is
60  // called on both.
61  // FIXME: This would be more comprehensively addressed by modifying
62  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
63  // being used.
64  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
65  return ExprError();
66  DeclRefExpr *DRE = new (S.Context)
67  DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68  if (HadMultipleCandidates)
69  DRE->setHadMultipleCandidates(true);
70 
72  if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
73  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
74  S.ResolveExceptionSpec(Loc, FPT);
75  DRE->setType(Fn->getType());
76  }
77  }
78  return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
79  CK_FunctionToPointerDecay);
80 }
81 
82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
83  bool InOverloadResolution,
85  bool CStyle,
86  bool AllowObjCWritebackConversion);
87 
88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
89  QualType &ToType,
90  bool InOverloadResolution,
92  bool CStyle);
93 static OverloadingResult
94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96  OverloadCandidateSet& Conversions,
97  AllowedExplicit AllowExplicit,
98  bool AllowObjCConversionOnExplicit);
99 
102  const StandardConversionSequence& SCS1,
103  const StandardConversionSequence& SCS2);
104 
107  const StandardConversionSequence& SCS1,
108  const StandardConversionSequence& SCS2);
109 
112  const StandardConversionSequence& SCS1,
113  const StandardConversionSequence& SCS2);
114 
115 /// GetConversionRank - Retrieve the implicit conversion rank
116 /// corresponding to the given implicit conversion kind.
118  static const ImplicitConversionRank
119  Rank[(int)ICK_Num_Conversion_Kinds] = {
145  ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146  // it was omitted by the patch that added
147  // ICK_Zero_Event_Conversion
150  };
151  return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
157  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158  "No conversion",
159  "Lvalue-to-rvalue",
160  "Array-to-pointer",
161  "Function-to-pointer",
162  "Function pointer conversion",
163  "Qualification",
164  "Integral promotion",
165  "Floating point promotion",
166  "Complex promotion",
167  "Integral conversion",
168  "Floating conversion",
169  "Complex conversion",
170  "Floating-integral conversion",
171  "Pointer conversion",
172  "Pointer-to-member conversion",
173  "Boolean conversion",
174  "Compatible-types conversion",
175  "Derived-to-base conversion",
176  "Vector conversion",
177  "SVE Vector conversion",
178  "Vector splat",
179  "Complex-real conversion",
180  "Block Pointer conversion",
181  "Transparent Union Conversion",
182  "Writeback conversion",
183  "OpenCL Zero Event Conversion",
184  "C specific type conversion",
185  "Incompatible pointer conversion"
186  };
187  return Name[Kind];
188 }
189 
190 /// StandardConversionSequence - Set the standard conversion
191 /// sequence to the identity conversion.
194  Second = ICK_Identity;
195  Third = ICK_Identity;
196  DeprecatedStringLiteralToCharPtr = false;
197  QualificationIncludesObjCLifetime = false;
198  ReferenceBinding = false;
199  DirectBinding = false;
200  IsLvalueReference = true;
201  BindsToFunctionLvalue = false;
202  BindsToRvalue = false;
203  BindsImplicitObjectArgumentWithoutRefQualifier = false;
204  ObjCLifetimeConversionBinding = false;
205  CopyConstructor = nullptr;
206 }
207 
208 /// getRank - Retrieve the rank of this standard conversion sequence
209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
210 /// implicit conversions.
213  if (GetConversionRank(First) > Rank)
214  Rank = GetConversionRank(First);
215  if (GetConversionRank(Second) > Rank)
216  Rank = GetConversionRank(Second);
217  if (GetConversionRank(Third) > Rank)
218  Rank = GetConversionRank(Third);
219  return Rank;
220 }
221 
222 /// isPointerConversionToBool - Determines whether this conversion is
223 /// a conversion of a pointer or pointer-to-member to bool. This is
224 /// used as part of the ranking of standard conversion sequences
225 /// (C++ 13.3.3.2p4).
227  // Note that FromType has not necessarily been transformed by the
228  // array-to-pointer or function-to-pointer implicit conversions, so
229  // check for their presence as well as checking whether FromType is
230  // a pointer.
231  if (getToType(1)->isBooleanType() &&
232  (getFromType()->isPointerType() ||
233  getFromType()->isMemberPointerType() ||
234  getFromType()->isObjCObjectPointerType() ||
235  getFromType()->isBlockPointerType() ||
237  return true;
238 
239  return false;
240 }
241 
242 /// isPointerConversionToVoidPointer - Determines whether this
243 /// conversion is a conversion of a pointer to a void pointer. This is
244 /// used as part of the ranking of standard conversion sequences (C++
245 /// 13.3.3.2p4).
246 bool
249  QualType FromType = getFromType();
250  QualType ToType = getToType(1);
251 
252  // Note that FromType has not necessarily been transformed by the
253  // array-to-pointer implicit conversion, so check for its presence
254  // and redo the conversion to get a pointer.
256  FromType = Context.getArrayDecayedType(FromType);
257 
258  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
259  if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
260  return ToPtrType->getPointeeType()->isVoidType();
261 
262  return false;
263 }
264 
265 /// Skip any implicit casts which could be either part of a narrowing conversion
266 /// or after one in an implicit conversion.
268  const Expr *Converted) {
269  // We can have cleanups wrapping the converted expression; these need to be
270  // preserved so that destructors run if necessary.
271  if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
272  Expr *Inner =
273  const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
274  return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275  EWC->getObjects());
276  }
277 
278  while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
279  switch (ICE->getCastKind()) {
280  case CK_NoOp:
281  case CK_IntegralCast:
282  case CK_IntegralToBoolean:
283  case CK_IntegralToFloating:
284  case CK_BooleanToSignedIntegral:
285  case CK_FloatingToIntegral:
286  case CK_FloatingToBoolean:
287  case CK_FloatingCast:
288  Converted = ICE->getSubExpr();
289  continue;
290 
291  default:
292  return Converted;
293  }
294  }
295 
296  return Converted;
297 }
298 
299 /// Check if this standard conversion sequence represents a narrowing
300 /// conversion, according to C++11 [dcl.init.list]p7.
301 ///
302 /// \param Ctx The AST context.
303 /// \param Converted The result of applying this standard conversion sequence.
304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305 /// value of the expression prior to the narrowing conversion.
306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307 /// type of the expression prior to the narrowing conversion.
308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
309 /// from floating point types to integral types should be ignored.
311  ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
312  QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
313  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
314 
315  // C++11 [dcl.init.list]p7:
316  // A narrowing conversion is an implicit conversion ...
317  QualType FromType = getToType(0);
318  QualType ToType = getToType(1);
319 
320  // A conversion to an enumeration type is narrowing if the conversion to
321  // the underlying type is narrowing. This only arises for expressions of
322  // the form 'Enum{init}'.
323  if (auto *ET = ToType->getAs<EnumType>())
324  ToType = ET->getDecl()->getIntegerType();
325 
326  switch (Second) {
327  // 'bool' is an integral type; dispatch to the right place to handle it.
329  if (FromType->isRealFloatingType())
330  goto FloatingIntegralConversion;
331  if (FromType->isIntegralOrUnscopedEnumerationType())
332  goto IntegralConversion;
333  // -- from a pointer type or pointer-to-member type to bool, or
334  return NK_Type_Narrowing;
335 
336  // -- from a floating-point type to an integer type, or
337  //
338  // -- from an integer type or unscoped enumeration type to a floating-point
339  // type, except where the source is a constant expression and the actual
340  // value after conversion will fit into the target type and will produce
341  // the original value when converted back to the original type, or
343  FloatingIntegralConversion:
344  if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
345  return NK_Type_Narrowing;
346  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
347  ToType->isRealFloatingType()) {
348  if (IgnoreFloatToIntegralConversion)
349  return NK_Not_Narrowing;
350  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351  assert(Initializer && "Unknown conversion expression");
352 
353  // If it's value-dependent, we can't tell whether it's narrowing.
354  if (Initializer->isValueDependent())
355  return NK_Dependent_Narrowing;
356 
357  if (Optional<llvm::APSInt> IntConstantValue =
358  Initializer->getIntegerConstantExpr(Ctx)) {
359  // Convert the integer to the floating type.
360  llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
361  Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
362  llvm::APFloat::rmNearestTiesToEven);
363  // And back.
364  llvm::APSInt ConvertedValue = *IntConstantValue;
365  bool ignored;
366  Result.convertToInteger(ConvertedValue,
367  llvm::APFloat::rmTowardZero, &ignored);
368  // If the resulting value is different, this was a narrowing conversion.
369  if (*IntConstantValue != ConvertedValue) {
370  ConstantValue = APValue(*IntConstantValue);
371  ConstantType = Initializer->getType();
372  return NK_Constant_Narrowing;
373  }
374  } else {
375  // Variables are always narrowings.
376  return NK_Variable_Narrowing;
377  }
378  }
379  return NK_Not_Narrowing;
380 
381  // -- from long double to double or float, or from double to float, except
382  // where the source is a constant expression and the actual value after
383  // conversion is within the range of values that can be represented (even
384  // if it cannot be represented exactly), or
386  if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
387  Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
388  // FromType is larger than ToType.
389  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
390 
391  // If it's value-dependent, we can't tell whether it's narrowing.
392  if (Initializer->isValueDependent())
393  return NK_Dependent_Narrowing;
394 
395  if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
396  // Constant!
397  assert(ConstantValue.isFloat());
398  llvm::APFloat FloatVal = ConstantValue.getFloat();
399  // Convert the source value into the target type.
400  bool ignored;
401  llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
402  Ctx.getFloatTypeSemantics(ToType),
403  llvm::APFloat::rmNearestTiesToEven, &ignored);
404  // If there was no overflow, the source value is within the range of
405  // values that can be represented.
406  if (ConvertStatus & llvm::APFloat::opOverflow) {
407  ConstantType = Initializer->getType();
408  return NK_Constant_Narrowing;
409  }
410  } else {
411  return NK_Variable_Narrowing;
412  }
413  }
414  return NK_Not_Narrowing;
415 
416  // -- from an integer type or unscoped enumeration type to an integer type
417  // that cannot represent all the values of the original type, except where
418  // the source is a constant expression and the actual value after
419  // conversion will fit into the target type and will produce the original
420  // value when converted back to the original type.
422  IntegralConversion: {
423  assert(FromType->isIntegralOrUnscopedEnumerationType());
424  assert(ToType->isIntegralOrUnscopedEnumerationType());
425  const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
426  const unsigned FromWidth = Ctx.getIntWidth(FromType);
427  const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
428  const unsigned ToWidth = Ctx.getIntWidth(ToType);
429 
430  if (FromWidth > ToWidth ||
431  (FromWidth == ToWidth && FromSigned != ToSigned) ||
432  (FromSigned && !ToSigned)) {
433  // Not all values of FromType can be represented in ToType.
434  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436  // If it's value-dependent, we can't tell whether it's narrowing.
437  if (Initializer->isValueDependent())
438  return NK_Dependent_Narrowing;
439 
440  Optional<llvm::APSInt> OptInitializerValue;
441  if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
442  // Such conversions on variables are always narrowing.
443  return NK_Variable_Narrowing;
444  }
445  llvm::APSInt &InitializerValue = *OptInitializerValue;
446  bool Narrowing = false;
447  if (FromWidth < ToWidth) {
448  // Negative -> unsigned is narrowing. Otherwise, more bits is never
449  // narrowing.
450  if (InitializerValue.isSigned() && InitializerValue.isNegative())
451  Narrowing = true;
452  } else {
453  // Add a bit to the InitializerValue so we don't have to worry about
454  // signed vs. unsigned comparisons.
455  InitializerValue = InitializerValue.extend(
456  InitializerValue.getBitWidth() + 1);
457  // Convert the initializer to and from the target width and signed-ness.
458  llvm::APSInt ConvertedValue = InitializerValue;
459  ConvertedValue = ConvertedValue.trunc(ToWidth);
460  ConvertedValue.setIsSigned(ToSigned);
461  ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
462  ConvertedValue.setIsSigned(InitializerValue.isSigned());
463  // If the result is different, this was a narrowing conversion.
464  if (ConvertedValue != InitializerValue)
465  Narrowing = true;
466  }
467  if (Narrowing) {
468  ConstantType = Initializer->getType();
469  ConstantValue = APValue(InitializerValue);
470  return NK_Constant_Narrowing;
471  }
472  }
473  return NK_Not_Narrowing;
474  }
475 
476  default:
477  // Other kinds of conversions are not narrowings.
478  return NK_Not_Narrowing;
479  }
480 }
481 
482 /// dump - Print this standard conversion sequence to standard
483 /// error. Useful for debugging overloading issues.
484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
485  raw_ostream &OS = llvm::errs();
486  bool PrintedSomething = false;
487  if (First != ICK_Identity) {
489  PrintedSomething = true;
490  }
491 
492  if (Second != ICK_Identity) {
493  if (PrintedSomething) {
494  OS << " -> ";
495  }
496  OS << GetImplicitConversionName(Second);
497 
498  if (CopyConstructor) {
499  OS << " (by copy constructor)";
500  } else if (DirectBinding) {
501  OS << " (direct reference binding)";
502  } else if (ReferenceBinding) {
503  OS << " (reference binding)";
504  }
505  PrintedSomething = true;
506  }
507 
508  if (Third != ICK_Identity) {
509  if (PrintedSomething) {
510  OS << " -> ";
511  }
512  OS << GetImplicitConversionName(Third);
513  PrintedSomething = true;
514  }
515 
516  if (!PrintedSomething) {
517  OS << "No conversions required";
518  }
519 }
520 
521 /// dump - Print this user-defined conversion sequence to standard
522 /// error. Useful for debugging overloading issues.
524  raw_ostream &OS = llvm::errs();
525  if (Before.First || Before.Second || Before.Third) {
526  Before.dump();
527  OS << " -> ";
528  }
529  if (ConversionFunction)
530  OS << '\'' << *ConversionFunction << '\'';
531  else
532  OS << "aggregate initialization";
533  if (After.First || After.Second || After.Third) {
534  OS << " -> ";
535  After.dump();
536  }
537 }
538 
539 /// dump - Print this implicit conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
542  raw_ostream &OS = llvm::errs();
543  if (hasInitializerListContainerType())
544  OS << "Worst list element conversion: ";
545  switch (ConversionKind) {
546  case StandardConversion:
547  OS << "Standard conversion: ";
548  Standard.dump();
549  break;
550  case UserDefinedConversion:
551  OS << "User-defined conversion: ";
552  UserDefined.dump();
553  break;
554  case EllipsisConversion:
555  OS << "Ellipsis conversion";
556  break;
557  case AmbiguousConversion:
558  OS << "Ambiguous conversion";
559  break;
560  case BadConversion:
561  OS << "Bad conversion";
562  break;
563  }
564 
565  OS << "\n";
566 }
567 
569  new (&conversions()) ConversionSet();
570 }
571 
573  conversions().~ConversionSet();
574 }
575 
576 void
578  FromTypePtr = O.FromTypePtr;
579  ToTypePtr = O.ToTypePtr;
580  new (&conversions()) ConversionSet(O.conversions());
581 }
582 
583 namespace {
584  // Structure used by DeductionFailureInfo to store
585  // template argument information.
586  struct DFIArguments {
587  TemplateArgument FirstArg;
588  TemplateArgument SecondArg;
589  };
590  // Structure used by DeductionFailureInfo to store
591  // template parameter and template argument information.
592  struct DFIParamWithArguments : DFIArguments {
593  TemplateParameter Param;
594  };
595  // Structure used by DeductionFailureInfo to store template argument
596  // information and the index of the problematic call argument.
597  struct DFIDeducedMismatchArgs : DFIArguments {
598  TemplateArgumentList *TemplateArgs;
599  unsigned CallArgIndex;
600  };
601  // Structure used by DeductionFailureInfo to store information about
602  // unsatisfied constraints.
603  struct CNSInfo {
604  TemplateArgumentList *TemplateArgs;
605  ConstraintSatisfaction Satisfaction;
606  };
607 }
608 
609 /// Convert from Sema's representation of template deduction information
610 /// to the form used in overload-candidate information.
614  TemplateDeductionInfo &Info) {
615  DeductionFailureInfo Result;
616  Result.Result = static_cast<unsigned>(TDK);
617  Result.HasDiagnostic = false;
618  switch (TDK) {
619  case Sema::TDK_Invalid:
625  Result.Data = nullptr;
626  break;
627 
630  Result.Data = Info.Param.getOpaqueValue();
631  break;
632 
635  // FIXME: Should allocate from normal heap so that we can free this later.
636  auto *Saved = new (Context) DFIDeducedMismatchArgs;
637  Saved->FirstArg = Info.FirstArg;
638  Saved->SecondArg = Info.SecondArg;
639  Saved->TemplateArgs = Info.take();
640  Saved->CallArgIndex = Info.CallArgIndex;
641  Result.Data = Saved;
642  break;
643  }
644 
646  // FIXME: Should allocate from normal heap so that we can free this later.
647  DFIArguments *Saved = new (Context) DFIArguments;
648  Saved->FirstArg = Info.FirstArg;
649  Saved->SecondArg = Info.SecondArg;
650  Result.Data = Saved;
651  break;
652  }
653 
655  // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
658  // FIXME: Should allocate from normal heap so that we can free this later.
659  DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
660  Saved->Param = Info.Param;
661  Saved->FirstArg = Info.FirstArg;
662  Saved->SecondArg = Info.SecondArg;
663  Result.Data = Saved;
664  break;
665  }
666 
668  Result.Data = Info.take();
669  if (Info.hasSFINAEDiagnostic()) {
670  PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672  Info.takeSFINAEDiagnostic(*Diag);
673  Result.HasDiagnostic = true;
674  }
675  break;
676 
678  CNSInfo *Saved = new (Context) CNSInfo;
679  Saved->TemplateArgs = Info.take();
680  Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
681  Result.Data = Saved;
682  break;
683  }
684 
685  case Sema::TDK_Success:
688  llvm_unreachable("not a deduction failure");
689  }
690 
691  return Result;
692 }
693 
695  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696  case Sema::TDK_Success:
697  case Sema::TDK_Invalid:
705  break;
706 
713  // FIXME: Destroy the data?
714  Data = nullptr;
715  break;
716 
718  // FIXME: Destroy the template argument list?
719  Data = nullptr;
720  if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721  Diag->~PartialDiagnosticAt();
722  HasDiagnostic = false;
723  }
724  break;
725 
727  // FIXME: Destroy the template argument list?
728  Data = nullptr;
729  if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730  Diag->~PartialDiagnosticAt();
731  HasDiagnostic = false;
732  }
733  break;
734 
735  // Unhandled
738  break;
739  }
740 }
741 
743  if (HasDiagnostic)
744  return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
745  return nullptr;
746 }
747 
749  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
750  case Sema::TDK_Success:
751  case Sema::TDK_Invalid:
762  return TemplateParameter();
763 
766  return TemplateParameter::getFromOpaqueValue(Data);
767 
771  return static_cast<DFIParamWithArguments*>(Data)->Param;
772 
773  // Unhandled
776  break;
777  }
778 
779  return TemplateParameter();
780 }
781 
783  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
784  case Sema::TDK_Success:
785  case Sema::TDK_Invalid:
797  return nullptr;
798 
801  return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
802 
804  return static_cast<TemplateArgumentList*>(Data);
805 
807  return static_cast<CNSInfo*>(Data)->TemplateArgs;
808 
809  // Unhandled
812  break;
813  }
814 
815  return nullptr;
816 }
817 
819  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
820  case Sema::TDK_Success:
821  case Sema::TDK_Invalid:
831  return nullptr;
832 
839  return &static_cast<DFIArguments*>(Data)->FirstArg;
840 
841  // Unhandled
844  break;
845  }
846 
847  return nullptr;
848 }
849 
851  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
852  case Sema::TDK_Success:
853  case Sema::TDK_Invalid:
864  return nullptr;
865 
871  return &static_cast<DFIArguments*>(Data)->SecondArg;
872 
873  // Unhandled
876  break;
877  }
878 
879  return nullptr;
880 }
881 
883  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
886  return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
887 
888  default:
889  return llvm::None;
890  }
891 }
892 
895  if (!AllowRewrittenCandidates)
896  return false;
897  return Op == OO_EqualEqual || Op == OO_Spaceship;
898 }
899 
901  ASTContext &Ctx, const FunctionDecl *FD) {
902  if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
903  return false;
904  // Don't bother adding a reversed candidate that can never be a better
905  // match than the non-reversed version.
906  return FD->getNumParams() != 2 ||
908  FD->getParamDecl(1)->getType()) ||
909  FD->hasAttr<EnableIfAttr>();
910 }
911 
912 void OverloadCandidateSet::destroyCandidates() {
913  for (iterator i = begin(), e = end(); i != e; ++i) {
914  for (auto &C : i->Conversions)
915  C.~ImplicitConversionSequence();
916  if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
917  i->DeductionFailure.Destroy();
918  }
919 }
920 
922  destroyCandidates();
923  SlabAllocator.Reset();
924  NumInlineBytesUsed = 0;
925  Candidates.clear();
926  Functions.clear();
927  Kind = CSK;
928 }
929 
930 namespace {
931  class UnbridgedCastsSet {
932  struct Entry {
933  Expr **Addr;
934  Expr *Saved;
935  };
936  SmallVector<Entry, 2> Entries;
937 
938  public:
939  void save(Sema &S, Expr *&E) {
940  assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
941  Entry entry = { &E, E };
942  Entries.push_back(entry);
943  E = S.stripARCUnbridgedCast(E);
944  }
945 
946  void restore() {
948  i = Entries.begin(), e = Entries.end(); i != e; ++i)
949  *i->Addr = i->Saved;
950  }
951  };
952 }
953 
954 /// checkPlaceholderForOverload - Do any interesting placeholder-like
955 /// preprocessing on the given expression.
956 ///
957 /// \param unbridgedCasts a collection to which to add unbridged casts;
958 /// without this, they will be immediately diagnosed as errors
959 ///
960 /// Return true on unrecoverable error.
961 static bool
963  UnbridgedCastsSet *unbridgedCasts = nullptr) {
964  if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
965  // We can't handle overloaded expressions here because overload
966  // resolution might reasonably tweak them.
967  if (placeholder->getKind() == BuiltinType::Overload) return false;
968 
969  // If the context potentially accepts unbridged ARC casts, strip
970  // the unbridged cast and add it to the collection for later restoration.
971  if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
972  unbridgedCasts) {
973  unbridgedCasts->save(S, E);
974  return false;
975  }
976 
977  // Go ahead and check everything else.
978  ExprResult result = S.CheckPlaceholderExpr(E);
979  if (result.isInvalid())
980  return true;
981 
982  E = result.get();
983  return false;
984  }
985 
986  // Nothing to do.
987  return false;
988 }
989 
990 /// checkArgPlaceholdersForOverload - Check a set of call operands for
991 /// placeholders.
993  UnbridgedCastsSet &unbridged) {
994  for (unsigned i = 0, e = Args.size(); i != e; ++i)
995  if (checkPlaceholderForOverload(S, Args[i], &unbridged))
996  return true;
997 
998  return false;
999 }
1000 
1001 /// Determine whether the given New declaration is an overload of the
1002 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1003 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1004 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1005 /// functions (or function templates) at all. When it does return Ovl_Match or
1006 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1007 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1008 /// declaration.
1009 ///
1010 /// Example: Given the following input:
1011 ///
1012 /// void f(int, float); // #1
1013 /// void f(int, int); // #2
1014 /// int f(int, int); // #3
1015 ///
1016 /// When we process #1, there is no previous declaration of "f", so IsOverload
1017 /// will not be used.
1018 ///
1019 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1020 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1021 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1022 /// unchanged.
1023 ///
1024 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1025 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1026 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1027 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1028 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1029 ///
1030 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1031 /// by a using declaration. The rules for whether to hide shadow declarations
1032 /// ignore some properties which otherwise figure into a function template's
1033 /// signature.
1036  NamedDecl *&Match, bool NewIsUsingDecl) {
1037  for (LookupResult::iterator I = Old.begin(), E = Old.end();
1038  I != E; ++I) {
1039  NamedDecl *OldD = *I;
1040 
1041  bool OldIsUsingDecl = false;
1042  if (isa<UsingShadowDecl>(OldD)) {
1043  OldIsUsingDecl = true;
1044 
1045  // We can always introduce two using declarations into the same
1046  // context, even if they have identical signatures.
1047  if (NewIsUsingDecl) continue;
1048 
1049  OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1050  }
1051 
1052  // A using-declaration does not conflict with another declaration
1053  // if one of them is hidden.
1054  if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1055  continue;
1056 
1057  // If either declaration was introduced by a using declaration,
1058  // we'll need to use slightly different rules for matching.
1059  // Essentially, these rules are the normal rules, except that
1060  // function templates hide function templates with different
1061  // return types or template parameter lists.
1062  bool UseMemberUsingDeclRules =
1063  (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1064  !New->getFriendObjectKind();
1065 
1066  if (FunctionDecl *OldF = OldD->getAsFunction()) {
1067  if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1068  if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1069  HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1070  continue;
1071  }
1072 
1073  if (!isa<FunctionTemplateDecl>(OldD) &&
1074  !shouldLinkPossiblyHiddenDecl(*I, New))
1075  continue;
1076 
1077  Match = *I;
1078  return Ovl_Match;
1079  }
1080 
1081  // Builtins that have custom typechecking or have a reference should
1082  // not be overloadable or redeclarable.
1083  if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1084  Match = *I;
1085  return Ovl_NonFunction;
1086  }
1087  } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1088  // We can overload with these, which can show up when doing
1089  // redeclaration checks for UsingDecls.
1090  assert(Old.getLookupKind() == LookupUsingDeclName);
1091  } else if (isa<TagDecl>(OldD)) {
1092  // We can always overload with tags by hiding them.
1093  } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1094  // Optimistically assume that an unresolved using decl will
1095  // overload; if it doesn't, we'll have to diagnose during
1096  // template instantiation.
1097  //
1098  // Exception: if the scope is dependent and this is not a class
1099  // member, the using declaration can only introduce an enumerator.
1100  if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1101  Match = *I;
1102  return Ovl_NonFunction;
1103  }
1104  } else {
1105  // (C++ 13p1):
1106  // Only function declarations can be overloaded; object and type
1107  // declarations cannot be overloaded.
1108  Match = *I;
1109  return Ovl_NonFunction;
1110  }
1111  }
1112 
1113  // C++ [temp.friend]p1:
1114  // For a friend function declaration that is not a template declaration:
1115  // -- if the name of the friend is a qualified or unqualified template-id,
1116  // [...], otherwise
1117  // -- if the name of the friend is a qualified-id and a matching
1118  // non-template function is found in the specified class or namespace,
1119  // the friend declaration refers to that function, otherwise,
1120  // -- if the name of the friend is a qualified-id and a matching function
1121  // template is found in the specified class or namespace, the friend
1122  // declaration refers to the deduced specialization of that function
1123  // template, otherwise
1124  // -- the name shall be an unqualified-id [...]
1125  // If we get here for a qualified friend declaration, we've just reached the
1126  // third bullet. If the type of the friend is dependent, skip this lookup
1127  // until instantiation.
1128  if (New->getFriendObjectKind() && New->getQualifier() &&
1129  !New->getDescribedFunctionTemplate() &&
1131  !New->getType()->isDependentType()) {
1132  LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1133  TemplateSpecResult.addAllDecls(Old);
1134  if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1135  /*QualifiedFriend*/true)) {
1136  New->setInvalidDecl();
1137  return Ovl_Overload;
1138  }
1139 
1140  Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1141  return Ovl_Match;
1142  }
1143 
1144  return Ovl_Overload;
1145 }
1146 
1148  bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1149  bool ConsiderRequiresClauses) {
1150  // C++ [basic.start.main]p2: This function shall not be overloaded.
1151  if (New->isMain())
1152  return false;
1153 
1154  // MSVCRT user defined entry points cannot be overloaded.
1155  if (New->isMSVCRTEntryPoint())
1156  return false;
1157 
1158  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1159  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1160 
1161  // C++ [temp.fct]p2:
1162  // A function template can be overloaded with other function templates
1163  // and with normal (non-template) functions.
1164  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1165  return true;
1166 
1167  // Is the function New an overload of the function Old?
1168  QualType OldQType = Context.getCanonicalType(Old->getType());
1169  QualType NewQType = Context.getCanonicalType(New->getType());
1170 
1171  // Compare the signatures (C++ 1.3.10) of the two functions to
1172  // determine whether they are overloads. If we find any mismatch
1173  // in the signature, they are overloads.
1174 
1175  // If either of these functions is a K&R-style function (no
1176  // prototype), then we consider them to have matching signatures.
1177  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1178  isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1179  return false;
1180 
1181  const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1182  const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1183 
1184  // The signature of a function includes the types of its
1185  // parameters (C++ 1.3.10), which includes the presence or absence
1186  // of the ellipsis; see C++ DR 357).
1187  if (OldQType != NewQType &&
1188  (OldType->getNumParams() != NewType->getNumParams() ||
1189  OldType->isVariadic() != NewType->isVariadic() ||
1190  !FunctionParamTypesAreEqual(OldType, NewType)))
1191  return true;
1192 
1193  // C++ [temp.over.link]p4:
1194  // The signature of a function template consists of its function
1195  // signature, its return type and its template parameter list. The names
1196  // of the template parameters are significant only for establishing the
1197  // relationship between the template parameters and the rest of the
1198  // signature.
1199  //
1200  // We check the return type and template parameter lists for function
1201  // templates first; the remaining checks follow.
1202  //
1203  // However, we don't consider either of these when deciding whether
1204  // a member introduced by a shadow declaration is hidden.
1205  if (!UseMemberUsingDeclRules && NewTemplate &&
1206  (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1207  OldTemplate->getTemplateParameters(),
1208  false, TPL_TemplateMatch) ||
1209  !Context.hasSameType(Old->getDeclaredReturnType(),
1210  New->getDeclaredReturnType())))
1211  return true;
1212 
1213  // If the function is a class member, its signature includes the
1214  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1215  //
1216  // As part of this, also check whether one of the member functions
1217  // is static, in which case they are not overloads (C++
1218  // 13.1p2). While not part of the definition of the signature,
1219  // this check is important to determine whether these functions
1220  // can be overloaded.
1221  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1222  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1223  if (OldMethod && NewMethod &&
1224  !OldMethod->isStatic() && !NewMethod->isStatic()) {
1225  if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1226  if (!UseMemberUsingDeclRules &&
1227  (OldMethod->getRefQualifier() == RQ_None ||
1228  NewMethod->getRefQualifier() == RQ_None)) {
1229  // C++0x [over.load]p2:
1230  // - Member function declarations with the same name and the same
1231  // parameter-type-list as well as member function template
1232  // declarations with the same name, the same parameter-type-list, and
1233  // the same template parameter lists cannot be overloaded if any of
1234  // them, but not all, have a ref-qualifier (8.3.5).
1235  Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1236  << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1237  Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1238  }
1239  return true;
1240  }
1241 
1242  // We may not have applied the implicit const for a constexpr member
1243  // function yet (because we haven't yet resolved whether this is a static
1244  // or non-static member function). Add it now, on the assumption that this
1245  // is a redeclaration of OldMethod.
1246  auto OldQuals = OldMethod->getMethodQualifiers();
1247  auto NewQuals = NewMethod->getMethodQualifiers();
1248  if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1249  !isa<CXXConstructorDecl>(NewMethod))
1250  NewQuals.addConst();
1251  // We do not allow overloading based off of '__restrict'.
1252  OldQuals.removeRestrict();
1253  NewQuals.removeRestrict();
1254  if (OldQuals != NewQuals)
1255  return true;
1256  }
1257 
1258  // Though pass_object_size is placed on parameters and takes an argument, we
1259  // consider it to be a function-level modifier for the sake of function
1260  // identity. Either the function has one or more parameters with
1261  // pass_object_size or it doesn't.
1264  return true;
1265 
1266  // enable_if attributes are an order-sensitive part of the signature.
1268  NewI = New->specific_attr_begin<EnableIfAttr>(),
1269  NewE = New->specific_attr_end<EnableIfAttr>(),
1270  OldI = Old->specific_attr_begin<EnableIfAttr>(),
1271  OldE = Old->specific_attr_end<EnableIfAttr>();
1272  NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1273  if (NewI == NewE || OldI == OldE)
1274  return true;
1275  llvm::FoldingSetNodeID NewID, OldID;
1276  NewI->getCond()->Profile(NewID, Context, true);
1277  OldI->getCond()->Profile(OldID, Context, true);
1278  if (NewID != OldID)
1279  return true;
1280  }
1281 
1282  if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1283  // Don't allow overloading of destructors. (In theory we could, but it
1284  // would be a giant change to clang.)
1285  if (!isa<CXXDestructorDecl>(New)) {
1286  CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1287  OldTarget = IdentifyCUDATarget(Old);
1288  if (NewTarget != CFT_InvalidTarget) {
1289  assert((OldTarget != CFT_InvalidTarget) &&
1290  "Unexpected invalid target.");
1291 
1292  // Allow overloading of functions with same signature and different CUDA
1293  // target attributes.
1294  if (NewTarget != OldTarget)
1295  return true;
1296  }
1297  }
1298  }
1299 
1300  if (ConsiderRequiresClauses) {
1301  Expr *NewRC = New->getTrailingRequiresClause(),
1302  *OldRC = Old->getTrailingRequiresClause();
1303  if ((NewRC != nullptr) != (OldRC != nullptr))
1304  // RC are most certainly different - these are overloads.
1305  return true;
1306 
1307  if (NewRC) {
1308  llvm::FoldingSetNodeID NewID, OldID;
1309  NewRC->Profile(NewID, Context, /*Canonical=*/true);
1310  OldRC->Profile(OldID, Context, /*Canonical=*/true);
1311  if (NewID != OldID)
1312  // RCs are not equivalent - these are overloads.
1313  return true;
1314  }
1315  }
1316 
1317  // The signatures match; this is not an overload.
1318  return false;
1319 }
1320 
1321 /// Tries a user-defined conversion from From to ToType.
1322 ///
1323 /// Produces an implicit conversion sequence for when a standard conversion
1324 /// is not an option. See TryImplicitConversion for more information.
1327  bool SuppressUserConversions,
1328  AllowedExplicit AllowExplicit,
1329  bool InOverloadResolution,
1330  bool CStyle,
1331  bool AllowObjCWritebackConversion,
1332  bool AllowObjCConversionOnExplicit) {
1334 
1335  if (SuppressUserConversions) {
1336  // We're not in the case above, so there is no conversion that
1337  // we can perform.
1338  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1339  return ICS;
1340  }
1341 
1342  // Attempt user-defined conversion.
1343  OverloadCandidateSet Conversions(From->getExprLoc(),
1345  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1346  Conversions, AllowExplicit,
1347  AllowObjCConversionOnExplicit)) {
1348  case OR_Success:
1349  case OR_Deleted:
1350  ICS.setUserDefined();
1351  // C++ [over.ics.user]p4:
1352  // A conversion of an expression of class type to the same class
1353  // type is given Exact Match rank, and a conversion of an
1354  // expression of class type to a base class of that type is
1355  // given Conversion rank, in spite of the fact that a copy
1356  // constructor (i.e., a user-defined conversion function) is
1357  // called for those cases.
1358  if (CXXConstructorDecl *Constructor
1359  = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1360  QualType FromCanon
1362  QualType ToCanon
1364  if (Constructor->isCopyConstructor() &&
1365  (FromCanon == ToCanon ||
1366  S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1367  // Turn this into a "standard" conversion sequence, so that it
1368  // gets ranked with standard conversion sequences.
1370  ICS.setStandard();
1372  ICS.Standard.setFromType(From->getType());
1373  ICS.Standard.setAllToTypes(ToType);
1374  ICS.Standard.CopyConstructor = Constructor;
1375  ICS.Standard.FoundCopyConstructor = Found;
1376  if (ToCanon != FromCanon)
1378  }
1379  }
1380  break;
1381 
1382  case OR_Ambiguous:
1383  ICS.setAmbiguous();
1384  ICS.Ambiguous.setFromType(From->getType());
1385  ICS.Ambiguous.setToType(ToType);
1386  for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1387  Cand != Conversions.end(); ++Cand)
1388  if (Cand->Best)
1389  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1390  break;
1391 
1392  // Fall through.
1393  case OR_No_Viable_Function:
1394  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1395  break;
1396  }
1397 
1398  return ICS;
1399 }
1400 
1401 /// TryImplicitConversion - Attempt to perform an implicit conversion
1402 /// from the given expression (Expr) to the given type (ToType). This
1403 /// function returns an implicit conversion sequence that can be used
1404 /// to perform the initialization. Given
1405 ///
1406 /// void f(float f);
1407 /// void g(int i) { f(i); }
1408 ///
1409 /// this routine would produce an implicit conversion sequence to
1410 /// describe the initialization of f from i, which will be a standard
1411 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1412 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1413 //
1414 /// Note that this routine only determines how the conversion can be
1415 /// performed; it does not actually perform the conversion. As such,
1416 /// it will not produce any diagnostics if no conversion is available,
1417 /// but will instead return an implicit conversion sequence of kind
1418 /// "BadConversion".
1419 ///
1420 /// If @p SuppressUserConversions, then user-defined conversions are
1421 /// not permitted.
1422 /// If @p AllowExplicit, then explicit user-defined conversions are
1423 /// permitted.
1424 ///
1425 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1426 /// writeback conversion, which allows __autoreleasing id* parameters to
1427 /// be initialized with __strong id* or __weak id* arguments.
1430  bool SuppressUserConversions,
1431  AllowedExplicit AllowExplicit,
1432  bool InOverloadResolution,
1433  bool CStyle,
1434  bool AllowObjCWritebackConversion,
1435  bool AllowObjCConversionOnExplicit) {
1437  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1438  ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1439  ICS.setStandard();
1440  return ICS;
1441  }
1442 
1443  if (!S.getLangOpts().CPlusPlus) {
1444  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1445  return ICS;
1446  }
1447 
1448  // C++ [over.ics.user]p4:
1449  // A conversion of an expression of class type to the same class
1450  // type is given Exact Match rank, and a conversion of an
1451  // expression of class type to a base class of that type is
1452  // given Conversion rank, in spite of the fact that a copy/move
1453  // constructor (i.e., a user-defined conversion function) is
1454  // called for those cases.
1455  QualType FromType = From->getType();
1456  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1457  (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1458  S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1459  ICS.setStandard();
1461  ICS.Standard.setFromType(FromType);
1462  ICS.Standard.setAllToTypes(ToType);
1463 
1464  // We don't actually check at this point whether there is a valid
1465  // copy/move constructor, since overloading just assumes that it
1466  // exists. When we actually perform initialization, we'll find the
1467  // appropriate constructor to copy the returned object, if needed.
1468  ICS.Standard.CopyConstructor = nullptr;
1469 
1470  // Determine whether this is considered a derived-to-base conversion.
1471  if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1473 
1474  return ICS;
1475  }
1476 
1477  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1478  AllowExplicit, InOverloadResolution, CStyle,
1479  AllowObjCWritebackConversion,
1480  AllowObjCConversionOnExplicit);
1481 }
1482 
1485  bool SuppressUserConversions,
1486  AllowedExplicit AllowExplicit,
1487  bool InOverloadResolution,
1488  bool CStyle,
1489  bool AllowObjCWritebackConversion) {
1490  return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1491  AllowExplicit, InOverloadResolution, CStyle,
1492  AllowObjCWritebackConversion,
1493  /*AllowObjCConversionOnExplicit=*/false);
1494 }
1495 
1496 /// PerformImplicitConversion - Perform an implicit conversion of the
1497 /// expression From to the type ToType. Returns the
1498 /// converted expression. Flavor is the kind of conversion we're
1499 /// performing, used in the error message. If @p AllowExplicit,
1500 /// explicit user-defined conversions are permitted.
1502  AssignmentAction Action,
1503  bool AllowExplicit) {
1504  if (checkPlaceholderForOverload(*this, From))
1505  return ExprError();
1506 
1507  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1508  bool AllowObjCWritebackConversion
1509  = getLangOpts().ObjCAutoRefCount &&
1510  (Action == AA_Passing || Action == AA_Sending);
1511  if (getLangOpts().ObjC)
1512  CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1513  From->getType(), From);
1515  *this, From, ToType,
1516  /*SuppressUserConversions=*/false,
1517  AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1518  /*InOverloadResolution=*/false,
1519  /*CStyle=*/false, AllowObjCWritebackConversion,
1520  /*AllowObjCConversionOnExplicit=*/false);
1521  return PerformImplicitConversion(From, ToType, ICS, Action);
1522 }
1523 
1524 /// Determine whether the conversion from FromType to ToType is a valid
1525 /// conversion that strips "noexcept" or "noreturn" off the nested function
1526 /// type.
1528  QualType &ResultTy) {
1529  if (Context.hasSameUnqualifiedType(FromType, ToType))
1530  return false;
1531 
1532  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1533  // or F(t noexcept) -> F(t)
1534  // where F adds one of the following at most once:
1535  // - a pointer
1536  // - a member pointer
1537  // - a block pointer
1538  // Changes here need matching changes in FindCompositePointerType.
1539  CanQualType CanTo = Context.getCanonicalType(ToType);
1540  CanQualType CanFrom = Context.getCanonicalType(FromType);
1541  Type::TypeClass TyClass = CanTo->getTypeClass();
1542  if (TyClass != CanFrom->getTypeClass()) return false;
1543  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1544  if (TyClass == Type::Pointer) {
1545  CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1546  CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1547  } else if (TyClass == Type::BlockPointer) {
1548  CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1549  CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1550  } else if (TyClass == Type::MemberPointer) {
1551  auto ToMPT = CanTo.castAs<MemberPointerType>();
1552  auto FromMPT = CanFrom.castAs<MemberPointerType>();
1553  // A function pointer conversion cannot change the class of the function.
1554  if (ToMPT->getClass() != FromMPT->getClass())
1555  return false;
1556  CanTo = ToMPT->getPointeeType();
1557  CanFrom = FromMPT->getPointeeType();
1558  } else {
1559  return false;
1560  }
1561 
1562  TyClass = CanTo->getTypeClass();
1563  if (TyClass != CanFrom->getTypeClass()) return false;
1564  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1565  return false;
1566  }
1567 
1568  const auto *FromFn = cast<FunctionType>(CanFrom);
1569  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1570 
1571  const auto *ToFn = cast<FunctionType>(CanTo);
1572  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1573 
1574  bool Changed = false;
1575 
1576  // Drop 'noreturn' if not present in target type.
1577  if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1578  FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1579  Changed = true;
1580  }
1581 
1582  // Drop 'noexcept' if not present in target type.
1583  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1584  const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1585  if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1586  FromFn = cast<FunctionType>(
1587  Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1588  EST_None)
1589  .getTypePtr());
1590  Changed = true;
1591  }
1592 
1593  // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1594  // only if the ExtParameterInfo lists of the two function prototypes can be
1595  // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597  bool CanUseToFPT, CanUseFromFPT;
1598  if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1599  CanUseFromFPT, NewParamInfos) &&
1600  CanUseToFPT && !CanUseFromFPT) {
1601  FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1602  ExtInfo.ExtParameterInfos =
1603  NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1604  QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1605  FromFPT->getParamTypes(), ExtInfo);
1606  FromFn = QT->getAs<FunctionType>();
1607  Changed = true;
1608  }
1609  }
1610 
1611  if (!Changed)
1612  return false;
1613 
1614  assert(QualType(FromFn, 0).isCanonical());
1615  if (QualType(FromFn, 0) != CanTo) return false;
1616 
1617  ResultTy = ToType;
1618  return true;
1619 }
1620 
1621 /// Determine whether the conversion from FromType to ToType is a valid
1622 /// vector conversion.
1623 ///
1624 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1625 /// conversion.
1626 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1627  ImplicitConversionKind &ICK, Expr *From,
1628  bool InOverloadResolution) {
1629  // We need at least one of these types to be a vector type to have a vector
1630  // conversion.
1631  if (!ToType->isVectorType() && !FromType->isVectorType())
1632  return false;
1633 
1634  // Identical types require no conversions.
1635  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636  return false;
1637 
1638  // There are no conversions between extended vector types, only identity.
1639  if (ToType->isExtVectorType()) {
1640  // There are no conversions between extended vector types other than the
1641  // identity conversion.
1642  if (FromType->isExtVectorType())
1643  return false;
1644 
1645  // Vector splat from any arithmetic type to a vector.
1646  if (FromType->isArithmeticType()) {
1647  ICK = ICK_Vector_Splat;
1648  return true;
1649  }
1650  }
1651 
1652  if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1653  if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1654  S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1656  return true;
1657  }
1658 
1659  // We can perform the conversion between vector types in the following cases:
1660  // 1)vector types are equivalent AltiVec and GCC vector types
1661  // 2)lax vector conversions are permitted and the vector types are of the
1662  // same size
1663  // 3)the destination type does not have the ARM MVE strict-polymorphism
1664  // attribute, which inhibits lax vector conversion for overload resolution
1665  // only
1666  if (ToType->isVectorType() && FromType->isVectorType()) {
1667  if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1668  (S.isLaxVectorConversion(FromType, ToType) &&
1669  !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1670  if (S.isLaxVectorConversion(FromType, ToType) &&
1671  S.anyAltivecTypes(FromType, ToType) &&
1672  !S.areSameVectorElemTypes(FromType, ToType) &&
1673  !InOverloadResolution) {
1674  S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1675  << FromType << ToType;
1676  }
1677  ICK = ICK_Vector_Conversion;
1678  return true;
1679  }
1680  }
1681 
1682  return false;
1683 }
1684 
1685 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1686  bool InOverloadResolution,
1688  bool CStyle);
1689 
1690 /// IsStandardConversion - Determines whether there is a standard
1691 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1692 /// expression From to the type ToType. Standard conversion sequences
1693 /// only consider non-class types; for conversions that involve class
1694 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1695 /// contain the standard conversion sequence required to perform this
1696 /// conversion and this routine will return true. Otherwise, this
1697 /// routine will return false and the value of SCS is unspecified.
1698 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1699  bool InOverloadResolution,
1701  bool CStyle,
1702  bool AllowObjCWritebackConversion) {
1703  QualType FromType = From->getType();
1704 
1705  // Standard conversions (C++ [conv])
1707  SCS.IncompatibleObjC = false;
1708  SCS.setFromType(FromType);
1709  SCS.CopyConstructor = nullptr;
1710 
1711  // There are no standard conversions for class types in C++, so
1712  // abort early. When overloading in C, however, we do permit them.
1713  if (S.getLangOpts().CPlusPlus &&
1714  (FromType->isRecordType() || ToType->isRecordType()))
1715  return false;
1716 
1717  // The first conversion can be an lvalue-to-rvalue conversion,
1718  // array-to-pointer conversion, or function-to-pointer conversion
1719  // (C++ 4p1).
1720 
1721  if (FromType == S.Context.OverloadTy) {
1722  DeclAccessPair AccessPair;
1723  if (FunctionDecl *Fn
1724  = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1725  AccessPair)) {
1726  // We were able to resolve the address of the overloaded function,
1727  // so we can convert to the type of that function.
1728  FromType = Fn->getType();
1729  SCS.setFromType(FromType);
1730 
1731  // we can sometimes resolve &foo<int> regardless of ToType, so check
1732  // if the type matches (identity) or we are converting to bool
1734  S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1735  QualType resultTy;
1736  // if the function type matches except for [[noreturn]], it's ok
1737  if (!S.IsFunctionConversion(FromType,
1738  S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1739  // otherwise, only a boolean conversion is standard
1740  if (!ToType->isBooleanType())
1741  return false;
1742  }
1743 
1744  // Check if the "from" expression is taking the address of an overloaded
1745  // function and recompute the FromType accordingly. Take advantage of the
1746  // fact that non-static member functions *must* have such an address-of
1747  // expression.
1748  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1749  if (Method && !Method->isStatic()) {
1750  assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1751  "Non-unary operator on non-static member address");
1752  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1753  == UO_AddrOf &&
1754  "Non-address-of operator on non-static member address");
1755  const Type *ClassType
1756  = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1757  FromType = S.Context.getMemberPointerType(FromType, ClassType);
1758  } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1759  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1760  UO_AddrOf &&
1761  "Non-address-of operator for overloaded function expression");
1762  FromType = S.Context.getPointerType(FromType);
1763  }
1764  } else {
1765  return false;
1766  }
1767  }
1768  // Lvalue-to-rvalue conversion (C++11 4.1):
1769  // A glvalue (3.10) of a non-function, non-array type T can
1770  // be converted to a prvalue.
1771  bool argIsLValue = From->isGLValue();
1772  if (argIsLValue &&
1773  !FromType->isFunctionType() && !FromType->isArrayType() &&
1774  S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1776 
1777  // C11 6.3.2.1p2:
1778  // ... if the lvalue has atomic type, the value has the non-atomic version
1779  // of the type of the lvalue ...
1780  if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1781  FromType = Atomic->getValueType();
1782 
1783  // If T is a non-class type, the type of the rvalue is the
1784  // cv-unqualified version of T. Otherwise, the type of the rvalue
1785  // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1786  // just strip the qualifiers because they don't matter.
1787  FromType = FromType.getUnqualifiedType();
1788  } else if (FromType->isArrayType()) {
1789  // Array-to-pointer conversion (C++ 4.2)
1791 
1792  // An lvalue or rvalue of type "array of N T" or "array of unknown
1793  // bound of T" can be converted to an rvalue of type "pointer to
1794  // T" (C++ 4.2p1).
1795  FromType = S.Context.getArrayDecayedType(FromType);
1796 
1797  if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1798  // This conversion is deprecated in C++03 (D.4)
1800 
1801  // For the purpose of ranking in overload resolution
1802  // (13.3.3.1.1), this conversion is considered an
1803  // array-to-pointer conversion followed by a qualification
1804  // conversion (4.4). (C++ 4.2p2)
1805  SCS.Second = ICK_Identity;
1806  SCS.Third = ICK_Qualification;
1808  SCS.setAllToTypes(FromType);
1809  return true;
1810  }
1811  } else if (FromType->isFunctionType() && argIsLValue) {
1812  // Function-to-pointer conversion (C++ 4.3).
1814 
1815  if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1816  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1818  return false;
1819 
1820  // An lvalue of function type T can be converted to an rvalue of
1821  // type "pointer to T." The result is a pointer to the
1822  // function. (C++ 4.3p1).
1823  FromType = S.Context.getPointerType(FromType);
1824  } else {
1825  // We don't require any conversions for the first step.
1826  SCS.First = ICK_Identity;
1827  }
1828  SCS.setToType(0, FromType);
1829 
1830  // The second conversion can be an integral promotion, floating
1831  // point promotion, integral conversion, floating point conversion,
1832  // floating-integral conversion, pointer conversion,
1833  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1834  // For overloading in C, this can also be a "compatible-type"
1835  // conversion.
1836  bool IncompatibleObjC = false;
1838  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1839  // The unqualified versions of the types are the same: there's no
1840  // conversion to do.
1841  SCS.Second = ICK_Identity;
1842  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1843  // Integral promotion (C++ 4.5).
1845  FromType = ToType.getUnqualifiedType();
1846  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1847  // Floating point promotion (C++ 4.6).
1849  FromType = ToType.getUnqualifiedType();
1850  } else if (S.IsComplexPromotion(FromType, ToType)) {
1851  // Complex promotion (Clang extension)
1853  FromType = ToType.getUnqualifiedType();
1854  } else if (ToType->isBooleanType() &&
1855  (FromType->isArithmeticType() ||
1856  FromType->isAnyPointerType() ||
1857  FromType->isBlockPointerType() ||
1858  FromType->isMemberPointerType())) {
1859  // Boolean conversions (C++ 4.12).
1861  FromType = S.Context.BoolTy;
1862  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1863  ToType->isIntegralType(S.Context)) {
1864  // Integral conversions (C++ 4.7).
1866  FromType = ToType.getUnqualifiedType();
1867  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1868  // Complex conversions (C99 6.3.1.6)
1870  FromType = ToType.getUnqualifiedType();
1871  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1872  (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1873  // Complex-real conversions (C99 6.3.1.7)
1874  SCS.Second = ICK_Complex_Real;
1875  FromType = ToType.getUnqualifiedType();
1876  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1877  // FIXME: disable conversions between long double, __ibm128 and __float128
1878  // if their representation is different until there is back end support
1879  // We of course allow this conversion if long double is really double.
1880 
1881  // Conversions between bfloat and other floats are not permitted.
1882  if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1883  return false;
1884 
1885  // Conversions between IEEE-quad and IBM-extended semantics are not
1886  // permitted.
1887  const llvm::fltSemantics &FromSem =
1888  S.Context.getFloatTypeSemantics(FromType);
1889  const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1890  if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1891  &ToSem == &llvm::APFloat::IEEEquad()) ||
1892  (&FromSem == &llvm::APFloat::IEEEquad() &&
1893  &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1894  return false;
1895 
1896  // Floating point conversions (C++ 4.8).
1898  FromType = ToType.getUnqualifiedType();
1899  } else if ((FromType->isRealFloatingType() &&
1900  ToType->isIntegralType(S.Context)) ||
1901  (FromType->isIntegralOrUnscopedEnumerationType() &&
1902  ToType->isRealFloatingType())) {
1903  // Conversions between bfloat and int are not permitted.
1904  if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1905  return false;
1906 
1907  // Floating-integral conversions (C++ 4.9).
1909  FromType = ToType.getUnqualifiedType();
1910  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1912  } else if (AllowObjCWritebackConversion &&
1913  S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1915  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1916  FromType, IncompatibleObjC)) {
1917  // Pointer conversions (C++ 4.10).
1919  SCS.IncompatibleObjC = IncompatibleObjC;
1920  FromType = FromType.getUnqualifiedType();
1921  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1922  InOverloadResolution, FromType)) {
1923  // Pointer to member conversions (4.11).
1924  SCS.Second = ICK_Pointer_Member;
1925  } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
1926  InOverloadResolution)) {
1927  SCS.Second = SecondICK;
1928  FromType = ToType.getUnqualifiedType();
1929  } else if (!S.getLangOpts().CPlusPlus &&
1930  S.Context.typesAreCompatible(ToType, FromType)) {
1931  // Compatible conversions (Clang extension for C function overloading)
1933  FromType = ToType.getUnqualifiedType();
1934  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1935  InOverloadResolution,
1936  SCS, CStyle)) {
1938  FromType = ToType;
1939  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1940  CStyle)) {
1941  // tryAtomicConversion has updated the standard conversion sequence
1942  // appropriately.
1943  return true;
1944  } else if (ToType->isEventT() &&
1945  From->isIntegerConstantExpr(S.getASTContext()) &&
1946  From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1948  FromType = ToType;
1949  } else if (ToType->isQueueT() &&
1950  From->isIntegerConstantExpr(S.getASTContext()) &&
1951  (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1953  FromType = ToType;
1954  } else if (ToType->isSamplerT() &&
1955  From->isIntegerConstantExpr(S.getASTContext())) {
1957  FromType = ToType;
1958  } else {
1959  // No second conversion required.
1960  SCS.Second = ICK_Identity;
1961  }
1962  SCS.setToType(1, FromType);
1963 
1964  // The third conversion can be a function pointer conversion or a
1965  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1966  bool ObjCLifetimeConversion;
1967  if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1968  // Function pointer conversions (removing 'noexcept') including removal of
1969  // 'noreturn' (Clang extension).
1971  } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1972  ObjCLifetimeConversion)) {
1973  SCS.Third = ICK_Qualification;
1974  SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1975  FromType = ToType;
1976  } else {
1977  // No conversion required
1978  SCS.Third = ICK_Identity;
1979  }
1980 
1981  // C++ [over.best.ics]p6:
1982  // [...] Any difference in top-level cv-qualification is
1983  // subsumed by the initialization itself and does not constitute
1984  // a conversion. [...]
1985  QualType CanonFrom = S.Context.getCanonicalType(FromType);
1986  QualType CanonTo = S.Context.getCanonicalType(ToType);
1987  if (CanonFrom.getLocalUnqualifiedType()
1988  == CanonTo.getLocalUnqualifiedType() &&
1989  CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1990  FromType = ToType;
1991  CanonFrom = CanonTo;
1992  }
1993 
1994  SCS.setToType(2, FromType);
1995 
1996  if (CanonFrom == CanonTo)
1997  return true;
1998 
1999  // If we have not converted the argument type to the parameter type,
2000  // this is a bad conversion sequence, unless we're resolving an overload in C.
2001  if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2002  return false;
2003 
2004  ExprResult ER = ExprResult{From};
2006  S.CheckSingleAssignmentConstraints(ToType, ER,
2007  /*Diagnose=*/false,
2008  /*DiagnoseCFAudited=*/false,
2009  /*ConvertRHS=*/false);
2010  ImplicitConversionKind SecondConv;
2011  switch (Conv) {
2012  case Sema::Compatible:
2013  SecondConv = ICK_C_Only_Conversion;
2014  break;
2015  // For our purposes, discarding qualifiers is just as bad as using an
2016  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2017  // qualifiers, as well.
2022  break;
2023  default:
2024  return false;
2025  }
2026 
2027  // First can only be an lvalue conversion, so we pretend that this was the
2028  // second conversion. First should already be valid from earlier in the
2029  // function.
2030  SCS.Second = SecondConv;
2031  SCS.setToType(1, ToType);
2032 
2033  // Third is Identity, because Second should rank us worse than any other
2034  // conversion. This could also be ICK_Qualification, but it's simpler to just
2035  // lump everything in with the second conversion, and we don't gain anything
2036  // from making this ICK_Qualification.
2037  SCS.Third = ICK_Identity;
2038  SCS.setToType(2, ToType);
2039  return true;
2040 }
2041 
2042 static bool
2044  QualType &ToType,
2045  bool InOverloadResolution,
2047  bool CStyle) {
2048 
2049  const RecordType *UT = ToType->getAsUnionType();
2050  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2051  return false;
2052  // The field to initialize within the transparent union.
2053  RecordDecl *UD = UT->getDecl();
2054  // It's compatible if the expression matches any of the fields.
2055  for (const auto *it : UD->fields()) {
2056  if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2057  CStyle, /*AllowObjCWritebackConversion=*/false)) {
2058  ToType = it->getType();
2059  return true;
2060  }
2061  }
2062  return false;
2063 }
2064 
2065 /// IsIntegralPromotion - Determines whether the conversion from the
2066 /// expression From (whose potentially-adjusted type is FromType) to
2067 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2068 /// sets PromotedType to the promoted type.
2069 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2070  const BuiltinType *To = ToType->getAs<BuiltinType>();
2071  // All integers are built-in.
2072  if (!To) {
2073  return false;
2074  }
2075 
2076  // An rvalue of type char, signed char, unsigned char, short int, or
2077  // unsigned short int can be converted to an rvalue of type int if
2078  // int can represent all the values of the source type; otherwise,
2079  // the source rvalue can be converted to an rvalue of type unsigned
2080  // int (C++ 4.5p1).
2081  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2082  !FromType->isEnumeralType()) {
2083  if (// We can promote any signed, promotable integer type to an int
2084  (FromType->isSignedIntegerType() ||
2085  // We can promote any unsigned integer type whose size is
2086  // less than int to an int.
2087  Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2088  return To->getKind() == BuiltinType::Int;
2089  }
2090 
2091  return To->getKind() == BuiltinType::UInt;
2092  }
2093 
2094  // C++11 [conv.prom]p3:
2095  // A prvalue of an unscoped enumeration type whose underlying type is not
2096  // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2097  // following types that can represent all the values of the enumeration
2098  // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2099  // unsigned int, long int, unsigned long int, long long int, or unsigned
2100  // long long int. If none of the types in that list can represent all the
2101  // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2102  // type can be converted to an rvalue a prvalue of the extended integer type
2103  // with lowest integer conversion rank (4.13) greater than the rank of long
2104  // long in which all the values of the enumeration can be represented. If
2105  // there are two such extended types, the signed one is chosen.
2106  // C++11 [conv.prom]p4:
2107  // A prvalue of an unscoped enumeration type whose underlying type is fixed
2108  // can be converted to a prvalue of its underlying type. Moreover, if
2109  // integral promotion can be applied to its underlying type, a prvalue of an
2110  // unscoped enumeration type whose underlying type is fixed can also be
2111  // converted to a prvalue of the promoted underlying type.
2112  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2113  // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2114  // provided for a scoped enumeration.
2115  if (FromEnumType->getDecl()->isScoped())
2116  return false;
2117 
2118  // We can perform an integral promotion to the underlying type of the enum,
2119  // even if that's not the promoted type. Note that the check for promoting
2120  // the underlying type is based on the type alone, and does not consider
2121  // the bitfield-ness of the actual source expression.
2122  if (FromEnumType->getDecl()->isFixed()) {
2123  QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2124  return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2125  IsIntegralPromotion(nullptr, Underlying, ToType);
2126  }
2127 
2128  // We have already pre-calculated the promotion type, so this is trivial.
2129  if (ToType->isIntegerType() &&
2130  isCompleteType(From->getBeginLoc(), FromType))
2131  return Context.hasSameUnqualifiedType(
2132  ToType, FromEnumType->getDecl()->getPromotionType());
2133 
2134  // C++ [conv.prom]p5:
2135  // If the bit-field has an enumerated type, it is treated as any other
2136  // value of that type for promotion purposes.
2137  //
2138  // ... so do not fall through into the bit-field checks below in C++.
2139  if (getLangOpts().CPlusPlus)
2140  return false;
2141  }
2142 
2143  // C++0x [conv.prom]p2:
2144  // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2145  // to an rvalue a prvalue of the first of the following types that can
2146  // represent all the values of its underlying type: int, unsigned int,
2147  // long int, unsigned long int, long long int, or unsigned long long int.
2148  // If none of the types in that list can represent all the values of its
2149  // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2150  // or wchar_t can be converted to an rvalue a prvalue of its underlying
2151  // type.
2152  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2153  ToType->isIntegerType()) {
2154  // Determine whether the type we're converting from is signed or
2155  // unsigned.
2156  bool FromIsSigned = FromType->isSignedIntegerType();
2157  uint64_t FromSize = Context.getTypeSize(FromType);
2158 
2159  // The types we'll try to promote to, in the appropriate
2160  // order. Try each of these types.
2161  QualType PromoteTypes[6] = {
2162  Context.IntTy, Context.UnsignedIntTy,
2163  Context.LongTy, Context.UnsignedLongTy ,
2164  Context.LongLongTy, Context.UnsignedLongLongTy
2165  };
2166  for (int Idx = 0; Idx < 6; ++Idx) {
2167  uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2168  if (FromSize < ToSize ||
2169  (FromSize == ToSize &&
2170  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2171  // We found the type that we can promote to. If this is the
2172  // type we wanted, we have a promotion. Otherwise, no
2173  // promotion.
2174  return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2175  }
2176  }
2177  }
2178 
2179  // An rvalue for an integral bit-field (9.6) can be converted to an
2180  // rvalue of type int if int can represent all the values of the
2181  // bit-field; otherwise, it can be converted to unsigned int if
2182  // unsigned int can represent all the values of the bit-field. If
2183  // the bit-field is larger yet, no integral promotion applies to
2184  // it. If the bit-field has an enumerated type, it is treated as any
2185  // other value of that type for promotion purposes (C++ 4.5p3).
2186  // FIXME: We should delay checking of bit-fields until we actually perform the
2187  // conversion.
2188  //
2189  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2190  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2191  // bit-fields and those whose underlying type is larger than int) for GCC
2192  // compatibility.
2193  if (From) {
2194  if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2195  Optional<llvm::APSInt> BitWidth;
2196  if (FromType->isIntegralType(Context) &&
2197  (BitWidth =
2198  MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2199  llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2200  ToSize = Context.getTypeSize(ToType);
2201 
2202  // Are we promoting to an int from a bitfield that fits in an int?
2203  if (*BitWidth < ToSize ||
2204  (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2205  return To->getKind() == BuiltinType::Int;
2206  }
2207 
2208  // Are we promoting to an unsigned int from an unsigned bitfield
2209  // that fits into an unsigned int?
2210  if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2211  return To->getKind() == BuiltinType::UInt;
2212  }
2213 
2214  return false;
2215  }
2216  }
2217  }
2218 
2219  // An rvalue of type bool can be converted to an rvalue of type int,
2220  // with false becoming zero and true becoming one (C++ 4.5p4).
2221  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2222  return true;
2223  }
2224 
2225  return false;
2226 }
2227 
2228 /// IsFloatingPointPromotion - Determines whether the conversion from
2229 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2230 /// returns true and sets PromotedType to the promoted type.
2232  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2233  if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2234  /// An rvalue of type float can be converted to an rvalue of type
2235  /// double. (C++ 4.6p1).
2236  if (FromBuiltin->getKind() == BuiltinType::Float &&
2237  ToBuiltin->getKind() == BuiltinType::Double)
2238  return true;
2239 
2240  // C99 6.3.1.5p1:
2241  // When a float is promoted to double or long double, or a
2242  // double is promoted to long double [...].
2243  if (!getLangOpts().CPlusPlus &&
2244  (FromBuiltin->getKind() == BuiltinType::Float ||
2245  FromBuiltin->getKind() == BuiltinType::Double) &&
2246  (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2247  ToBuiltin->getKind() == BuiltinType::Float128 ||
2248  ToBuiltin->getKind() == BuiltinType::Ibm128))
2249  return true;
2250 
2251  // Half can be promoted to float.
2252  if (!getLangOpts().NativeHalfType &&
2253  FromBuiltin->getKind() == BuiltinType::Half &&
2254  ToBuiltin->getKind() == BuiltinType::Float)
2255  return true;
2256  }
2257 
2258  return false;
2259 }
2260 
2261 /// Determine if a conversion is a complex promotion.
2262 ///
2263 /// A complex promotion is defined as a complex -> complex conversion
2264 /// where the conversion between the underlying real types is a
2265 /// floating-point or integral promotion.
2267  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2268  if (!FromComplex)
2269  return false;
2270 
2271  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2272  if (!ToComplex)
2273  return false;
2274 
2275  return IsFloatingPointPromotion(FromComplex->getElementType(),
2276  ToComplex->getElementType()) ||
2277  IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2278  ToComplex->getElementType());
2279 }
2280 
2281 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2282 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2283 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2284 /// if non-empty, will be a pointer to ToType that may or may not have
2285 /// the right set of qualifiers on its pointee.
2286 ///
2287 static QualType
2289  QualType ToPointee, QualType ToType,
2290  ASTContext &Context,
2291  bool StripObjCLifetime = false) {
2292  assert((FromPtr->getTypeClass() == Type::Pointer ||
2293  FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2294  "Invalid similarly-qualified pointer type");
2295 
2296  /// Conversions to 'id' subsume cv-qualifier conversions.
2297  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2298  return ToType.getUnqualifiedType();
2299 
2300  QualType CanonFromPointee
2301  = Context.getCanonicalType(FromPtr->getPointeeType());
2302  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2303  Qualifiers Quals = CanonFromPointee.getQualifiers();
2304 
2305  if (StripObjCLifetime)
2306  Quals.removeObjCLifetime();
2307 
2308  // Exact qualifier match -> return the pointer type we're converting to.
2309  if (CanonToPointee.getLocalQualifiers() == Quals) {
2310  // ToType is exactly what we need. Return it.
2311  if (!ToType.isNull())
2312  return ToType.getUnqualifiedType();
2313 
2314  // Build a pointer to ToPointee. It has the right qualifiers
2315  // already.
2316  if (isa<ObjCObjectPointerType>(ToType))
2317  return Context.getObjCObjectPointerType(ToPointee);
2318  return Context.getPointerType(ToPointee);
2319  }
2320 
2321  // Just build a canonical type that has the right qualifiers.
2322  QualType QualifiedCanonToPointee
2323  = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2324 
2325  if (isa<ObjCObjectPointerType>(ToType))
2326  return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2327  return Context.getPointerType(QualifiedCanonToPointee);
2328 }
2329 
2331  bool InOverloadResolution,
2332  ASTContext &Context) {
2333  // Handle value-dependent integral null pointer constants correctly.
2334  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2335  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2337  return !InOverloadResolution;
2338 
2339  return Expr->isNullPointerConstant(Context,
2340  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2342 }
2343 
2344 /// IsPointerConversion - Determines whether the conversion of the
2345 /// expression From, which has the (possibly adjusted) type FromType,
2346 /// can be converted to the type ToType via a pointer conversion (C++
2347 /// 4.10). If so, returns true and places the converted type (that
2348 /// might differ from ToType in its cv-qualifiers at some level) into
2349 /// ConvertedType.
2350 ///
2351 /// This routine also supports conversions to and from block pointers
2352 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2353 /// pointers to interfaces. FIXME: Once we've determined the
2354 /// appropriate overloading rules for Objective-C, we may want to
2355 /// split the Objective-C checks into a different routine; however,
2356 /// GCC seems to consider all of these conversions to be pointer
2357 /// conversions, so for now they live here. IncompatibleObjC will be
2358 /// set if the conversion is an allowed Objective-C conversion that
2359 /// should result in a warning.
2360 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2361  bool InOverloadResolution,
2362  QualType& ConvertedType,
2363  bool &IncompatibleObjC) {
2364  IncompatibleObjC = false;
2365  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2366  IncompatibleObjC))
2367  return true;
2368 
2369  // Conversion from a null pointer constant to any Objective-C pointer type.
2370  if (ToType->isObjCObjectPointerType() &&
2371  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372  ConvertedType = ToType;
2373  return true;
2374  }
2375 
2376  // Blocks: Block pointers can be converted to void*.
2377  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2378  ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2379  ConvertedType = ToType;
2380  return true;
2381  }
2382  // Blocks: A null pointer constant can be converted to a block
2383  // pointer type.
2384  if (ToType->isBlockPointerType() &&
2385  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386  ConvertedType = ToType;
2387  return true;
2388  }
2389 
2390  // If the left-hand-side is nullptr_t, the right side can be a null
2391  // pointer constant.
2392  if (ToType->isNullPtrType() &&
2393  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2394  ConvertedType = ToType;
2395  return true;
2396  }
2397 
2398  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2399  if (!ToTypePtr)
2400  return false;
2401 
2402  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2403  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2404  ConvertedType = ToType;
2405  return true;
2406  }
2407 
2408  // Beyond this point, both types need to be pointers
2409  // , including objective-c pointers.
2410  QualType ToPointeeType = ToTypePtr->getPointeeType();
2411  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2412  !getLangOpts().ObjCAutoRefCount) {
2413  ConvertedType = BuildSimilarlyQualifiedPointerType(
2414  FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2415  Context);
2416  return true;
2417  }
2418  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2419  if (!FromTypePtr)
2420  return false;
2421 
2422  QualType FromPointeeType = FromTypePtr->getPointeeType();
2423 
2424  // If the unqualified pointee types are the same, this can't be a
2425  // pointer conversion, so don't do all of the work below.
2426  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2427  return false;
2428 
2429  // An rvalue of type "pointer to cv T," where T is an object type,
2430  // can be converted to an rvalue of type "pointer to cv void" (C++
2431  // 4.10p2).
2432  if (FromPointeeType->isIncompleteOrObjectType() &&
2433  ToPointeeType->isVoidType()) {
2434  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2435  ToPointeeType,
2436  ToType, Context,
2437  /*StripObjCLifetime=*/true);
2438  return true;
2439  }
2440 
2441  // MSVC allows implicit function to void* type conversion.
2442  if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2443  ToPointeeType->isVoidType()) {
2444  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2445  ToPointeeType,
2446  ToType, Context);
2447  return true;
2448  }
2449 
2450  // When we're overloading in C, we allow a special kind of pointer
2451  // conversion for compatible-but-not-identical pointee types.
2452  if (!getLangOpts().CPlusPlus &&
2453  Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2454  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2455  ToPointeeType,
2456  ToType, Context);
2457  return true;
2458  }
2459 
2460  // C++ [conv.ptr]p3:
2461  //
2462  // An rvalue of type "pointer to cv D," where D is a class type,
2463  // can be converted to an rvalue of type "pointer to cv B," where
2464  // B is a base class (clause 10) of D. If B is an inaccessible
2465  // (clause 11) or ambiguous (10.2) base class of D, a program that
2466  // necessitates this conversion is ill-formed. The result of the
2467  // conversion is a pointer to the base class sub-object of the
2468  // derived class object. The null pointer value is converted to
2469  // the null pointer value of the destination type.
2470  //
2471  // Note that we do not check for ambiguity or inaccessibility
2472  // here. That is handled by CheckPointerConversion.
2473  if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2474  ToPointeeType->isRecordType() &&
2475  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2476  IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2477  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478  ToPointeeType,
2479  ToType, Context);
2480  return true;
2481  }
2482 
2483  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2484  Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2485  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2486  ToPointeeType,
2487  ToType, Context);
2488  return true;
2489  }
2490 
2491  return false;
2492 }
2493 
2494 /// Adopt the given qualifiers for the given type.
2496  Qualifiers TQs = T.getQualifiers();
2497 
2498  // Check whether qualifiers already match.
2499  if (TQs == Qs)
2500  return T;
2501 
2502  if (Qs.compatiblyIncludes(TQs))
2503  return Context.getQualifiedType(T, Qs);
2504 
2505  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2506 }
2507 
2508 /// isObjCPointerConversion - Determines whether this is an
2509 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2510 /// with the same arguments and return values.
2512  QualType& ConvertedType,
2513  bool &IncompatibleObjC) {
2514  if (!getLangOpts().ObjC)
2515  return false;
2516 
2517  // The set of qualifiers on the type we're converting from.
2518  Qualifiers FromQualifiers = FromType.getQualifiers();
2519 
2520  // First, we handle all conversions on ObjC object pointer types.
2521  const ObjCObjectPointerType* ToObjCPtr =
2522  ToType->getAs<ObjCObjectPointerType>();
2523  const ObjCObjectPointerType *FromObjCPtr =
2524  FromType->getAs<ObjCObjectPointerType>();
2525 
2526  if (ToObjCPtr && FromObjCPtr) {
2527  // If the pointee types are the same (ignoring qualifications),
2528  // then this is not a pointer conversion.
2529  if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2530  FromObjCPtr->getPointeeType()))
2531  return false;
2532 
2533  // Conversion between Objective-C pointers.
2534  if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2535  const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2536  const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2537  if (getLangOpts().CPlusPlus && LHS && RHS &&
2538  !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2539  FromObjCPtr->getPointeeType()))
2540  return false;
2541  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2542  ToObjCPtr->getPointeeType(),
2543  ToType, Context);
2544  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2545  return true;
2546  }
2547 
2548  if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2549  // Okay: this is some kind of implicit downcast of Objective-C
2550  // interfaces, which is permitted. However, we're going to
2551  // complain about it.
2552  IncompatibleObjC = true;
2553  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2554  ToObjCPtr->getPointeeType(),
2555  ToType, Context);
2556  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2557  return true;
2558  }
2559  }
2560  // Beyond this point, both types need to be C pointers or block pointers.
2561  QualType ToPointeeType;
2562  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2563  ToPointeeType = ToCPtr->getPointeeType();
2564  else if (const BlockPointerType *ToBlockPtr =
2565  ToType->getAs<BlockPointerType>()) {
2566  // Objective C++: We're able to convert from a pointer to any object
2567  // to a block pointer type.
2568  if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2569  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2570  return true;
2571  }
2572  ToPointeeType = ToBlockPtr->getPointeeType();
2573  }
2574  else if (FromType->getAs<BlockPointerType>() &&
2575  ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2576  // Objective C++: We're able to convert from a block pointer type to a
2577  // pointer to any object.
2578  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2579  return true;
2580  }
2581  else
2582  return false;
2583 
2584  QualType FromPointeeType;
2585  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2586  FromPointeeType = FromCPtr->getPointeeType();
2587  else if (const BlockPointerType *FromBlockPtr =
2588  FromType->getAs<BlockPointerType>())
2589  FromPointeeType = FromBlockPtr->getPointeeType();
2590  else
2591  return false;
2592 
2593  // If we have pointers to pointers, recursively check whether this
2594  // is an Objective-C conversion.
2595  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2596  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2597  IncompatibleObjC)) {
2598  // We always complain about this conversion.
2599  IncompatibleObjC = true;
2600  ConvertedType = Context.getPointerType(ConvertedType);
2601  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2602  return true;
2603  }
2604  // Allow conversion of pointee being objective-c pointer to another one;
2605  // as in I* to id.
2606  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2607  ToPointeeType->getAs<ObjCObjectPointerType>() &&
2608  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2609  IncompatibleObjC)) {
2610 
2611  ConvertedType = Context.getPointerType(ConvertedType);
2612  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2613  return true;
2614  }
2615 
2616  // If we have pointers to functions or blocks, check whether the only
2617  // differences in the argument and result types are in Objective-C
2618  // pointer conversions. If so, we permit the conversion (but
2619  // complain about it).
2620  const FunctionProtoType *FromFunctionType
2621  = FromPointeeType->getAs<FunctionProtoType>();
2622  const FunctionProtoType *ToFunctionType
2623  = ToPointeeType->getAs<FunctionProtoType>();
2624  if (FromFunctionType && ToFunctionType) {
2625  // If the function types are exactly the same, this isn't an
2626  // Objective-C pointer conversion.
2627  if (Context.getCanonicalType(FromPointeeType)
2628  == Context.getCanonicalType(ToPointeeType))
2629  return false;
2630 
2631  // Perform the quick checks that will tell us whether these
2632  // function types are obviously different.
2633  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2634  FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2635  FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2636  return false;
2637 
2638  bool HasObjCConversion = false;
2639  if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2640  Context.getCanonicalType(ToFunctionType->getReturnType())) {
2641  // Okay, the types match exactly. Nothing to do.
2642  } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2643  ToFunctionType->getReturnType(),
2644  ConvertedType, IncompatibleObjC)) {
2645  // Okay, we have an Objective-C pointer conversion.
2646  HasObjCConversion = true;
2647  } else {
2648  // Function types are too different. Abort.
2649  return false;
2650  }
2651 
2652  // Check argument types.
2653  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2654  ArgIdx != NumArgs; ++ArgIdx) {
2655  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2656  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2657  if (Context.getCanonicalType(FromArgType)
2658  == Context.getCanonicalType(ToArgType)) {
2659  // Okay, the types match exactly. Nothing to do.
2660  } else if (isObjCPointerConversion(FromArgType, ToArgType,
2661  ConvertedType, IncompatibleObjC)) {
2662  // Okay, we have an Objective-C pointer conversion.
2663  HasObjCConversion = true;
2664  } else {
2665  // Argument types are too different. Abort.
2666  return false;
2667  }
2668  }
2669 
2670  if (HasObjCConversion) {
2671  // We had an Objective-C conversion. Allow this pointer
2672  // conversion, but complain about it.
2673  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2674  IncompatibleObjC = true;
2675  return true;
2676  }
2677  }
2678 
2679  return false;
2680 }
2681 
2682 /// Determine whether this is an Objective-C writeback conversion,
2683 /// used for parameter passing when performing automatic reference counting.
2684 ///
2685 /// \param FromType The type we're converting form.
2686 ///
2687 /// \param ToType The type we're converting to.
2688 ///
2689 /// \param ConvertedType The type that will be produced after applying
2690 /// this conversion.
2692  QualType &ConvertedType) {
2693  if (!getLangOpts().ObjCAutoRefCount ||
2694  Context.hasSameUnqualifiedType(FromType, ToType))
2695  return false;
2696 
2697  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2698  QualType ToPointee;
2699  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2700  ToPointee = ToPointer->getPointeeType();
2701  else
2702  return false;
2703 
2704  Qualifiers ToQuals = ToPointee.getQualifiers();
2705  if (!ToPointee->isObjCLifetimeType() ||
2707  !ToQuals.withoutObjCLifetime().empty())
2708  return false;
2709 
2710  // Argument must be a pointer to __strong to __weak.
2711  QualType FromPointee;
2712  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2713  FromPointee = FromPointer->getPointeeType();
2714  else
2715  return false;
2716 
2717  Qualifiers FromQuals = FromPointee.getQualifiers();
2718  if (!FromPointee->isObjCLifetimeType() ||
2719  (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2720  FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2721  return false;
2722 
2723  // Make sure that we have compatible qualifiers.
2725  if (!ToQuals.compatiblyIncludes(FromQuals))
2726  return false;
2727 
2728  // Remove qualifiers from the pointee type we're converting from; they
2729  // aren't used in the compatibility check belong, and we'll be adding back
2730  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2731  FromPointee = FromPointee.getUnqualifiedType();
2732 
2733  // The unqualified form of the pointee types must be compatible.
2734  ToPointee = ToPointee.getUnqualifiedType();
2735  bool IncompatibleObjC;
2736  if (Context.typesAreCompatible(FromPointee, ToPointee))
2737  FromPointee = ToPointee;
2738  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2739  IncompatibleObjC))
2740  return false;
2741 
2742  /// Construct the type we're converting to, which is a pointer to
2743  /// __autoreleasing pointee.
2744  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2745  ConvertedType = Context.getPointerType(FromPointee);
2746  return true;
2747 }
2748 
2750  QualType& ConvertedType) {
2751  QualType ToPointeeType;
2752  if (const BlockPointerType *ToBlockPtr =
2753  ToType->getAs<BlockPointerType>())
2754  ToPointeeType = ToBlockPtr->getPointeeType();
2755  else
2756  return false;
2757 
2758  QualType FromPointeeType;
2759  if (const BlockPointerType *FromBlockPtr =
2760  FromType->getAs<BlockPointerType>())
2761  FromPointeeType = FromBlockPtr->getPointeeType();
2762  else
2763  return false;
2764  // We have pointer to blocks, check whether the only
2765  // differences in the argument and result types are in Objective-C
2766  // pointer conversions. If so, we permit the conversion.
2767 
2768  const FunctionProtoType *FromFunctionType
2769  = FromPointeeType->getAs<FunctionProtoType>();
2770  const FunctionProtoType *ToFunctionType
2771  = ToPointeeType->getAs<FunctionProtoType>();
2772 
2773  if (!FromFunctionType || !ToFunctionType)
2774  return false;
2775 
2776  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2777  return true;
2778 
2779  // Perform the quick checks that will tell us whether these
2780  // function types are obviously different.
2781  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2782  FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2783  return false;
2784 
2785  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2786  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2787  if (FromEInfo != ToEInfo)
2788  return false;
2789 
2790  bool IncompatibleObjC = false;
2791  if (Context.hasSameType(FromFunctionType->getReturnType(),
2792  ToFunctionType->getReturnType())) {
2793  // Okay, the types match exactly. Nothing to do.
2794  } else {
2795  QualType RHS = FromFunctionType->getReturnType();
2796  QualType LHS = ToFunctionType->getReturnType();
2797  if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2798  !RHS.hasQualifiers() && LHS.hasQualifiers())
2799  LHS = LHS.getUnqualifiedType();
2800 
2801  if (Context.hasSameType(RHS,LHS)) {
2802  // OK exact match.
2803  } else if (isObjCPointerConversion(RHS, LHS,
2804  ConvertedType, IncompatibleObjC)) {
2805  if (IncompatibleObjC)
2806  return false;
2807  // Okay, we have an Objective-C pointer conversion.
2808  }
2809  else
2810  return false;
2811  }
2812 
2813  // Check argument types.
2814  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2815  ArgIdx != NumArgs; ++ArgIdx) {
2816  IncompatibleObjC = false;
2817  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2818  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2819  if (Context.hasSameType(FromArgType, ToArgType)) {
2820  // Okay, the types match exactly. Nothing to do.
2821  } else if (isObjCPointerConversion(ToArgType, FromArgType,
2822  ConvertedType, IncompatibleObjC)) {
2823  if (IncompatibleObjC)
2824  return false;
2825  // Okay, we have an Objective-C pointer conversion.
2826  } else
2827  // Argument types are too different. Abort.
2828  return false;
2829  }
2830 
2832  bool CanUseToFPT, CanUseFromFPT;
2833  if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2834  CanUseToFPT, CanUseFromFPT,
2835  NewParamInfos))
2836  return false;
2837 
2838  ConvertedType = ToType;
2839  return true;
2840 }
2841 
2842 enum {
2850 };
2851 
2852 /// Attempts to get the FunctionProtoType from a Type. Handles
2853 /// MemberFunctionPointers properly.
2855  if (auto *FPT = FromType->getAs<FunctionProtoType>())
2856  return FPT;
2857 
2858  if (auto *MPT = FromType->getAs<MemberPointerType>())
2859  return MPT->getPointeeType()->getAs<FunctionProtoType>();
2860 
2861  return nullptr;
2862 }
2863 
2864 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2865 /// function types. Catches different number of parameter, mismatch in
2866 /// parameter types, and different return types.
2868  QualType FromType, QualType ToType) {
2869  // If either type is not valid, include no extra info.
2870  if (FromType.isNull() || ToType.isNull()) {
2871  PDiag << ft_default;
2872  return;
2873  }
2874 
2875  // Get the function type from the pointers.
2876  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2877  const auto *FromMember = FromType->castAs<MemberPointerType>(),
2878  *ToMember = ToType->castAs<MemberPointerType>();
2879  if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2880  PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2881  << QualType(FromMember->getClass(), 0);
2882  return;
2883  }
2884  FromType = FromMember->getPointeeType();
2885  ToType = ToMember->getPointeeType();
2886  }
2887 
2888  if (FromType->isPointerType())
2889  FromType = FromType->getPointeeType();
2890  if (ToType->isPointerType())
2891  ToType = ToType->getPointeeType();
2892 
2893  // Remove references.
2894  FromType = FromType.getNonReferenceType();
2895  ToType = ToType.getNonReferenceType();
2896 
2897  // Don't print extra info for non-specialized template functions.
2898  if (FromType->isInstantiationDependentType() &&
2899  !FromType->getAs<TemplateSpecializationType>()) {
2900  PDiag << ft_default;
2901  return;
2902  }
2903 
2904  // No extra info for same types.
2905  if (Context.hasSameType(FromType, ToType)) {
2906  PDiag << ft_default;
2907  return;
2908  }
2909 
2910  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2911  *ToFunction = tryGetFunctionProtoType(ToType);
2912 
2913  // Both types need to be function types.
2914  if (!FromFunction || !ToFunction) {
2915  PDiag << ft_default;
2916  return;
2917  }
2918 
2919  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2920  PDiag << ft_parameter_arity << ToFunction->getNumParams()
2921  << FromFunction->getNumParams();
2922  return;
2923  }
2924 
2925  // Handle different parameter types.
2926  unsigned ArgPos;
2927  if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2928  PDiag << ft_parameter_mismatch << ArgPos + 1
2929  << ToFunction->getParamType(ArgPos)
2930  << FromFunction->getParamType(ArgPos);
2931  return;
2932  }
2933 
2934  // Handle different return type.
2935  if (!Context.hasSameType(FromFunction->getReturnType(),
2936  ToFunction->getReturnType())) {
2937  PDiag << ft_return_type << ToFunction->getReturnType()
2938  << FromFunction->getReturnType();
2939  return;
2940  }
2941 
2942  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2943  PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2944  << FromFunction->getMethodQuals();
2945  return;
2946  }
2947 
2948  // Handle exception specification differences on canonical type (in C++17
2949  // onwards).
2950  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2951  ->isNothrow() !=
2952  cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2953  ->isNothrow()) {
2954  PDiag << ft_noexcept;
2955  return;
2956  }
2957 
2958  // Unable to find a difference, so add no extra info.
2959  PDiag << ft_default;
2960 }
2961 
2962 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2963 /// for equality of their parameter types. Caller has already checked that
2964 /// they have same number of parameters. If the parameters are different,
2965 /// ArgPos will have the parameter index of the first different parameter.
2966 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2967 /// reverse order. That's useful if one of the functions is being used as a C++20
2968 /// synthesized operator overload with a reversed parameter order.
2970  const FunctionProtoType *NewType,
2971  unsigned *ArgPos, bool Reversed) {
2972  assert(OldType->getNumParams() == NewType->getNumParams() &&
2973  "Can't compare parameters of functions with different number of "
2974  "parameters!");
2975  for (size_t I = 0; I < OldType->getNumParams(); I++) {
2976  // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2977  size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2978 
2979  // Ignore address spaces in pointee type. This is to disallow overloading
2980  // on __ptr32/__ptr64 address spaces.
2981  QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2982  QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2983 
2984  if (!Context.hasSameType(Old, New)) {
2985  if (ArgPos)
2986  *ArgPos = I;
2987  return false;
2988  }
2989  }
2990  return true;
2991 }
2992 
2993 /// CheckPointerConversion - Check the pointer conversion from the
2994 /// expression From to the type ToType. This routine checks for
2995 /// ambiguous or inaccessible derived-to-base pointer
2996 /// conversions for which IsPointerConversion has already returned
2997 /// true. It returns true and produces a diagnostic if there was an
2998 /// error, or returns false otherwise.
3000  CastKind &Kind,
3001  CXXCastPath& BasePath,
3002  bool IgnoreBaseAccess,
3003  bool Diagnose) {
3004  QualType FromType = From->getType();
3005  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3006 
3007  Kind = CK_BitCast;
3008 
3009  if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3012  if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3013  DiagRuntimeBehavior(From->getExprLoc(), From,
3014  PDiag(diag::warn_impcast_bool_to_null_pointer)
3015  << ToType << From->getSourceRange());
3016  else if (!isUnevaluatedContext())
3017  Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3018  << ToType << From->getSourceRange();
3019  }
3020  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3021  if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3022  QualType FromPointeeType = FromPtrType->getPointeeType(),
3023  ToPointeeType = ToPtrType->getPointeeType();
3024 
3025  if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3026  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3027  // We must have a derived-to-base conversion. Check an
3028  // ambiguous or inaccessible conversion.
3029  unsigned InaccessibleID = 0;
3030  unsigned AmbiguousID = 0;
3031  if (Diagnose) {
3032  InaccessibleID = diag::err_upcast_to_inaccessible_base;
3033  AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3034  }
3035  if (CheckDerivedToBaseConversion(
3036  FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3037  From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3038  &BasePath, IgnoreBaseAccess))
3039  return true;
3040 
3041  // The conversion was successful.
3042  Kind = CK_DerivedToBase;
3043  }
3044 
3045  if (Diagnose && !IsCStyleOrFunctionalCast &&
3046  FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3047  assert(getLangOpts().MSVCCompat &&
3048  "this should only be possible with MSVCCompat!");
3049  Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3050  << From->getSourceRange();
3051  }
3052  }
3053  } else if (const ObjCObjectPointerType *ToPtrType =
3054  ToType->getAs<ObjCObjectPointerType>()) {
3055  if (const ObjCObjectPointerType *FromPtrType =
3056  FromType->getAs<ObjCObjectPointerType>()) {
3057  // Objective-C++ conversions are always okay.
3058  // FIXME: We should have a different class of conversions for the
3059  // Objective-C++ implicit conversions.
3060  if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3061  return false;
3062  } else if (FromType->isBlockPointerType()) {
3063  Kind = CK_BlockPointerToObjCPointerCast;
3064  } else {
3065  Kind = CK_CPointerToObjCPointerCast;
3066  }
3067  } else if (ToType->isBlockPointerType()) {
3068  if (!FromType->isBlockPointerType())
3069  Kind = CK_AnyPointerToBlockPointerCast;
3070  }
3071 
3072  // We shouldn't fall into this case unless it's valid for other
3073  // reasons.
3075  Kind = CK_NullToPointer;
3076 
3077  return false;
3078 }
3079 
3080 /// IsMemberPointerConversion - Determines whether the conversion of the
3081 /// expression From, which has the (possibly adjusted) type FromType, can be
3082 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3083 /// If so, returns true and places the converted type (that might differ from
3084 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3086  QualType ToType,
3087  bool InOverloadResolution,
3088  QualType &ConvertedType) {
3089  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3090  if (!ToTypePtr)
3091  return false;
3092 
3093  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3094  if (From->isNullPointerConstant(Context,
3095  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3097  ConvertedType = ToType;
3098  return true;
3099  }
3100 
3101  // Otherwise, both types have to be member pointers.
3102  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3103  if (!FromTypePtr)
3104  return false;
3105 
3106  // A pointer to member of B can be converted to a pointer to member of D,
3107  // where D is derived from B (C++ 4.11p2).
3108  QualType FromClass(FromTypePtr->getClass(), 0);
3109  QualType ToClass(ToTypePtr->getClass(), 0);
3110 
3111  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3112  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3113  ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3114  ToClass.getTypePtr());
3115  return true;
3116  }
3117 
3118  return false;
3119 }
3120 
3121 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3122 /// expression From to the type ToType. This routine checks for ambiguous or
3123 /// virtual or inaccessible base-to-derived member pointer conversions
3124 /// for which IsMemberPointerConversion has already returned true. It returns
3125 /// true and produces a diagnostic if there was an error, or returns false
3126 /// otherwise.
3128  CastKind &Kind,
3129  CXXCastPath &BasePath,
3130  bool IgnoreBaseAccess) {
3131  QualType FromType = From->getType();
3132  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3133  if (!FromPtrType) {
3134  // This must be a null pointer to member pointer conversion
3135  assert(From->isNullPointerConstant(Context,
3137  "Expr must be null pointer constant!");
3138  Kind = CK_NullToMemberPointer;
3139  return false;
3140  }
3141 
3142  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3143  assert(ToPtrType && "No member pointer cast has a target type "
3144  "that is not a member pointer.");
3145 
3146  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3147  QualType ToClass = QualType(ToPtrType->getClass(), 0);
3148 
3149  // FIXME: What about dependent types?
3150  assert(FromClass->isRecordType() && "Pointer into non-class.");
3151  assert(ToClass->isRecordType() && "Pointer into non-class.");
3152 
3153  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3154  /*DetectVirtual=*/true);
3155  bool DerivationOkay =
3156  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3157  assert(DerivationOkay &&
3158  "Should not have been called if derivation isn't OK.");
3159  (void)DerivationOkay;
3160 
3161  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3162  getUnqualifiedType())) {
3163  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3164  Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3165  << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3166  return true;
3167  }
3168 
3169  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3170  Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3171  << FromClass << ToClass << QualType(VBase, 0)
3172  << From->getSourceRange();
3173  return true;
3174  }
3175 
3176  if (!IgnoreBaseAccess)
3177  CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3178  Paths.front(),
3179  diag::err_downcast_from_inaccessible_base);
3180 
3181  // Must be a base to derived member conversion.
3182  BuildBasePathArray(Paths, BasePath);
3183  Kind = CK_BaseToDerivedMemberPointer;
3184  return false;
3185 }
3186 
3187 /// Determine whether the lifetime conversion between the two given
3188 /// qualifiers sets is nontrivial.
3190  Qualifiers ToQuals) {
3191  // Converting anything to const __unsafe_unretained is trivial.
3192  if (ToQuals.hasConst() &&
3194  return false;
3195 
3196  return true;
3197 }
3198 
3199 /// Perform a single iteration of the loop for checking if a qualification
3200 /// conversion is valid.
3201 ///
3202 /// Specifically, check whether any change between the qualifiers of \p
3203 /// FromType and \p ToType is permissible, given knowledge about whether every
3204 /// outer layer is const-qualified.
3205 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3206  bool CStyle, bool IsTopLevel,
3207  bool &PreviousToQualsIncludeConst,
3208  bool &ObjCLifetimeConversion) {
3209  Qualifiers FromQuals = FromType.getQualifiers();
3210  Qualifiers ToQuals = ToType.getQualifiers();
3211 
3212  // Ignore __unaligned qualifier.
3213  FromQuals.removeUnaligned();
3214 
3215  // Objective-C ARC:
3216  // Check Objective-C lifetime conversions.
3217  if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3218  if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3219  if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3220  ObjCLifetimeConversion = true;
3221  FromQuals.removeObjCLifetime();
3222  ToQuals.removeObjCLifetime();
3223  } else {
3224  // Qualification conversions cannot cast between different
3225  // Objective-C lifetime qualifiers.
3226  return false;
3227  }
3228  }
3229 
3230  // Allow addition/removal of GC attributes but not changing GC attributes.
3231  if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3232  (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3233  FromQuals.removeObjCGCAttr();
3234  ToQuals.removeObjCGCAttr();
3235  }
3236 
3237  // -- for every j > 0, if const is in cv 1,j then const is in cv
3238  // 2,j, and similarly for volatile.
3239  if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3240  return false;
3241 
3242  // If address spaces mismatch:
3243  // - in top level it is only valid to convert to addr space that is a
3244  // superset in all cases apart from C-style casts where we allow
3245  // conversions between overlapping address spaces.
3246  // - in non-top levels it is not a valid conversion.
3247  if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3248  (!IsTopLevel ||
3249  !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3250  (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3251  return false;
3252 
3253  // -- if the cv 1,j and cv 2,j are different, then const is in
3254  // every cv for 0 < k < j.
3255  if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3256  !PreviousToQualsIncludeConst)
3257  return false;
3258 
3259  // The following wording is from C++20, where the result of the conversion
3260  // is T3, not T2.
3261  // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3262  // "array of unknown bound of"
3263  if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3264  return false;
3265 
3266  // -- if the resulting P3,i is different from P1,i [...], then const is
3267  // added to every cv 3_k for 0 < k < i.
3268  if (!CStyle && FromType->isConstantArrayType() &&
3269  ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3270  return false;
3271 
3272  // Keep track of whether all prior cv-qualifiers in the "to" type
3273  // include const.
3274  PreviousToQualsIncludeConst =
3275  PreviousToQualsIncludeConst && ToQuals.hasConst();
3276  return true;
3277 }
3278 
3279 /// IsQualificationConversion - Determines whether the conversion from
3280 /// an rvalue of type FromType to ToType is a qualification conversion
3281 /// (C++ 4.4).
3282 ///
3283 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3284 /// when the qualification conversion involves a change in the Objective-C
3285 /// object lifetime.
3286 bool
3288  bool CStyle, bool &ObjCLifetimeConversion) {
3289  FromType = Context.getCanonicalType(FromType);
3290  ToType = Context.getCanonicalType(ToType);
3291  ObjCLifetimeConversion = false;
3292 
3293  // If FromType and ToType are the same type, this is not a
3294  // qualification conversion.
3295  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3296  return false;
3297 
3298  // (C++ 4.4p4):
3299  // A conversion can add cv-qualifiers at levels other than the first
3300  // in multi-level pointers, subject to the following rules: [...]
3301  bool PreviousToQualsIncludeConst = true;
3302  bool UnwrappedAnyPointer = false;
3303  while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3305  FromType, ToType, CStyle, !UnwrappedAnyPointer,
3306  PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3307  return false;
3308  UnwrappedAnyPointer = true;
3309  }
3310 
3311  // We are left with FromType and ToType being the pointee types
3312  // after unwrapping the original FromType and ToType the same number
3313  // of times. If we unwrapped any pointers, and if FromType and
3314  // ToType have the same unqualified type (since we checked
3315  // qualifiers above), then this is a qualification conversion.
3316  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3317 }
3318 
3319 /// - Determine whether this is a conversion from a scalar type to an
3320 /// atomic type.
3321 ///
3322 /// If successful, updates \c SCS's second and third steps in the conversion
3323 /// sequence to finish the conversion.
3324 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3325  bool InOverloadResolution,
3327  bool CStyle) {
3328  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3329  if (!ToAtomic)
3330  return false;
3331 
3332  StandardConversionSequence InnerSCS;
3333  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3334  InOverloadResolution, InnerSCS,
3335  CStyle, /*AllowObjCWritebackConversion=*/false))
3336  return false;
3337 
3338  SCS.Second = InnerSCS.Second;
3339  SCS.setToType(1, InnerSCS.getToType(1));
3340  SCS.Third = InnerSCS.Third;
3343  SCS.setToType(2, InnerSCS.getToType(2));
3344  return true;
3345 }
3346 
3348  CXXConstructorDecl *Constructor,
3349  QualType Type) {
3350  const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3351  if (CtorType->getNumParams() > 0) {
3352  QualType FirstArg = CtorType->getParamType(0);
3353  if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3354  return true;
3355  }
3356  return false;
3357 }
3358 
3359 static OverloadingResult
3361  CXXRecordDecl *To,
3363  OverloadCandidateSet &CandidateSet,
3364  bool AllowExplicit) {
3366  for (auto *D : S.LookupConstructors(To)) {
3367  auto Info = getConstructorInfo(D);
3368  if (!Info)
3369  continue;
3370 
3371  bool Usable = !Info.Constructor->isInvalidDecl() &&
3372  S.isInitListConstructor(Info.Constructor);
3373  if (Usable) {
3374  bool SuppressUserConversions = false;
3375  if (Info.ConstructorTmpl)
3376  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3377  /*ExplicitArgs*/ nullptr, From,
3378  CandidateSet, SuppressUserConversions,
3379  /*PartialOverloading*/ false,
3380  AllowExplicit);
3381  else
3382  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3383  CandidateSet, SuppressUserConversions,
3384  /*PartialOverloading*/ false, AllowExplicit);
3385  }
3386  }
3387 
3388  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3389 
3391  switch (auto Result =
3392  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3393  case OR_Deleted:
3394  case OR_Success: {
3395  // Record the standard conversion we used and the conversion function.
3396  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3397  QualType ThisType = Constructor->getThisType();
3398  // Initializer lists don't have conversions as such.
3400  User.HadMultipleCandidates = HadMultipleCandidates;
3401  User.ConversionFunction = Constructor;
3402  User.FoundConversionFunction = Best->FoundDecl;
3404  User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3405  User.After.setAllToTypes(ToType);
3406  return Result;
3407  }
3408 
3409  case OR_No_Viable_Function:
3410  return OR_No_Viable_Function;
3411  case OR_Ambiguous:
3412  return OR_Ambiguous;
3413  }
3414 
3415  llvm_unreachable("Invalid OverloadResult!");
3416 }
3417 
3418 /// Determines whether there is a user-defined conversion sequence
3419 /// (C++ [over.ics.user]) that converts expression From to the type
3420 /// ToType. If such a conversion exists, User will contain the
3421 /// user-defined conversion sequence that performs such a conversion
3422 /// and this routine will return true. Otherwise, this routine returns
3423 /// false and User is unspecified.
3424 ///
3425 /// \param AllowExplicit true if the conversion should consider C++0x
3426 /// "explicit" conversion functions as well as non-explicit conversion
3427 /// functions (C++0x [class.conv.fct]p2).
3428 ///
3429 /// \param AllowObjCConversionOnExplicit true if the conversion should
3430 /// allow an extra Objective-C pointer conversion on uses of explicit
3431 /// constructors. Requires \c AllowExplicit to also be set.
3432 static OverloadingResult
3435  OverloadCandidateSet &CandidateSet,
3436  AllowedExplicit AllowExplicit,
3437  bool AllowObjCConversionOnExplicit) {
3438  assert(AllowExplicit != AllowedExplicit::None ||
3439  !AllowObjCConversionOnExplicit);
3441 
3442  // Whether we will only visit constructors.
3443  bool ConstructorsOnly = false;
3444 
3445  // If the type we are conversion to is a class type, enumerate its
3446  // constructors.
3447  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3448  // C++ [over.match.ctor]p1:
3449  // When objects of class type are direct-initialized (8.5), or
3450  // copy-initialized from an expression of the same or a
3451  // derived class type (8.5), overload resolution selects the
3452  // constructor. [...] For copy-initialization, the candidate
3453  // functions are all the converting constructors (12.3.1) of
3454  // that class. The argument list is the expression-list within
3455  // the parentheses of the initializer.
3456  if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3457  (From->getType()->getAs<RecordType>() &&
3458  S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3459  ConstructorsOnly = true;
3460 
3461  if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3462  // We're not going to find any constructors.
3463  } else if (CXXRecordDecl *ToRecordDecl
3464  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3465 
3466  Expr **Args = &From;
3467  unsigned NumArgs = 1;
3468  bool ListInitializing = false;
3469  if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3470  // But first, see if there is an init-list-constructor that will work.
3472  S, From, ToType, ToRecordDecl, User, CandidateSet,
3473  AllowExplicit == AllowedExplicit::All);
3474  if (Result != OR_No_Viable_Function)
3475  return Result;
3476  // Never mind.
3477  CandidateSet.clear(
3479 
3480  // If we're list-initializing, we pass the individual elements as
3481  // arguments, not the entire list.
3482  Args = InitList->getInits();
3483  NumArgs = InitList->getNumInits();
3484  ListInitializing = true;
3485  }
3486 
3487  for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3488  auto Info = getConstructorInfo(D);
3489  if (!Info)
3490  continue;
3491 
3492  bool Usable = !Info.Constructor->isInvalidDecl();
3493  if (!ListInitializing)
3494  Usable = Usable && Info.Constructor->isConvertingConstructor(
3495  /*AllowExplicit*/ true);
3496  if (Usable) {
3497  bool SuppressUserConversions = !ConstructorsOnly;
3498  // C++20 [over.best.ics.general]/4.5:
3499  // if the target is the first parameter of a constructor [of class
3500  // X] and the constructor [...] is a candidate by [...] the second
3501  // phase of [over.match.list] when the initializer list has exactly
3502  // one element that is itself an initializer list, [...] and the
3503  // conversion is to X or reference to cv X, user-defined conversion
3504  // sequences are not cnosidered.
3505  if (SuppressUserConversions && ListInitializing) {
3506  SuppressUserConversions =
3507  NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3508  isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3509  ToType);
3510  }
3511  if (Info.ConstructorTmpl)
3513  Info.ConstructorTmpl, Info.FoundDecl,
3514  /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3515  CandidateSet, SuppressUserConversions,
3516  /*PartialOverloading*/ false,
3517  AllowExplicit == AllowedExplicit::All);
3518  else
3519  // Allow one user-defined conversion when user specifies a
3520  // From->ToType conversion via an static cast (c-style, etc).
3521  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3522  llvm::makeArrayRef(Args, NumArgs),
3523  CandidateSet, SuppressUserConversions,
3524  /*PartialOverloading*/ false,
3525  AllowExplicit == AllowedExplicit::All);
3526  }
3527  }
3528  }
3529  }
3530 
3531  // Enumerate conversion functions, if we're allowed to.
3532  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3533  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3534  // No conversion functions from incomplete types.
3535  } else if (const RecordType *FromRecordType =
3536  From->getType()->getAs<RecordType>()) {
3537  if (CXXRecordDecl *FromRecordDecl
3538  = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3539  // Add all of the conversion functions as candidates.
3540  const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3541  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3542  DeclAccessPair FoundDecl = I.getPair();
3543  NamedDecl *D = FoundDecl.getDecl();
3544  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3545  if (isa<UsingShadowDecl>(D))
3546  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3547 
3548  CXXConversionDecl *Conv;
3549  FunctionTemplateDecl *ConvTemplate;
3550  if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3551  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3552  else
3553  Conv = cast<CXXConversionDecl>(D);
3554 
3555  if (ConvTemplate)
3557  ConvTemplate, FoundDecl, ActingContext, From, ToType,
3558  CandidateSet, AllowObjCConversionOnExplicit,
3559  AllowExplicit != AllowedExplicit::None);
3560  else
3561  S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3562  CandidateSet, AllowObjCConversionOnExplicit,
3563  AllowExplicit != AllowedExplicit::None);
3564  }
3565  }
3566  }
3567 
3568  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3569 
3571  switch (auto Result =
3572  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3573  case OR_Success:
3574  case OR_Deleted:
3575  // Record the standard conversion we used and the conversion function.
3576  if (CXXConstructorDecl *Constructor
3577  = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3578  // C++ [over.ics.user]p1:
3579  // If the user-defined conversion is specified by a
3580  // constructor (12.3.1), the initial standard conversion
3581  // sequence converts the source type to the type required by
3582  // the argument of the constructor.
3583  //
3584  QualType ThisType = Constructor->getThisType();
3585  if (isa<InitListExpr>(From)) {
3586  // Initializer lists don't have conversions as such.
3588  } else {
3589  if (Best->Conversions[0].isEllipsis())
3590  User.EllipsisConversion = true;
3591  else {
3592  User.Before = Best->Conversions[0].Standard;
3593  User.EllipsisConversion = false;
3594  }
3595  }
3596  User.HadMultipleCandidates = HadMultipleCandidates;
3597  User.ConversionFunction = Constructor;
3598  User.FoundConversionFunction = Best->FoundDecl;
3600  User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3601  User.After.setAllToTypes(ToType);
3602  return Result;
3603  }
3604  if (CXXConversionDecl *Conversion
3605  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3606  // C++ [over.ics.user]p1:
3607  //
3608  // [...] If the user-defined conversion is specified by a
3609  // conversion function (12.3.2), the initial standard
3610  // conversion sequence converts the source type to the
3611  // implicit object parameter of the conversion function.
3612  User.Before = Best->Conversions[0].Standard;
3613  User.HadMultipleCandidates = HadMultipleCandidates;
3614  User.ConversionFunction = Conversion;
3615  User.FoundConversionFunction = Best->FoundDecl;
3616  User.EllipsisConversion = false;
3617 
3618  // C++ [over.ics.user]p2:
3619  // The second standard conversion sequence converts the
3620  // result of the user-defined conversion to the target type
3621  // for the sequence. Since an implicit conversion sequence
3622  // is an initialization, the special rules for
3623  // initialization by user-defined conversion apply when
3624  // selecting the best user-defined conversion for a
3625  // user-defined conversion sequence (see 13.3.3 and
3626  // 13.3.3.1).
3627  User.After = Best->FinalConversion;
3628  return Result;
3629  }
3630  llvm_unreachable("Not a constructor or conversion function?");
3631 
3632  case OR_No_Viable_Function:
3633  return OR_No_Viable_Function;
3634 
3635  case OR_Ambiguous:
3636  return OR_Ambiguous;
3637  }
3638 
3639  llvm_unreachable("Invalid OverloadResult!");
3640 }
3641 
3642 bool
3645  OverloadCandidateSet CandidateSet(From->getExprLoc(),
3647  OverloadingResult OvResult =
3648  IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3649  CandidateSet, AllowedExplicit::None, false);
3650 
3651  if (!(OvResult == OR_Ambiguous ||
3652  (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3653  return false;
3654 
3655  auto Cands = CandidateSet.CompleteCandidates(
3656  *this,
3658  From);
3659  if (OvResult == OR_Ambiguous)
3660  Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3661  << From->getType() << ToType << From->getSourceRange();
3662  else { // OR_No_Viable_Function && !CandidateSet.empty()
3663  if (!RequireCompleteType(From->getBeginLoc(), ToType,
3664  diag::err_typecheck_nonviable_condition_incomplete,
3665  From->getType(), From->getSourceRange()))
3666  Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3667  << false << From->getType() << From->getSourceRange() << ToType;
3668  }
3669 
3670  CandidateSet.NoteCandidates(
3671  *this, From, Cands);
3672  return true;
3673 }
3674 
3675 // Helper for compareConversionFunctions that gets the FunctionType that the
3676 // conversion-operator return value 'points' to, or nullptr.
3677 static const FunctionType *
3679  const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3680  const PointerType *RetPtrTy =
3681  ConvFuncTy->getReturnType()->getAs<PointerType>();
3682 
3683  if (!RetPtrTy)
3684  return nullptr;
3685 
3686  return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3687 }
3688 
3689 /// Compare the user-defined conversion functions or constructors
3690 /// of two user-defined conversion sequences to determine whether any ordering
3691 /// is possible.
3694  FunctionDecl *Function2) {
3695  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3696  CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3697  if (!Conv1 || !Conv2)
3699 
3700  if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3702 
3703  // Objective-C++:
3704  // If both conversion functions are implicitly-declared conversions from
3705  // a lambda closure type to a function pointer and a block pointer,
3706  // respectively, always prefer the conversion to a function pointer,
3707  // because the function pointer is more lightweight and is more likely
3708  // to keep code working.
3709  if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3710  bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3711  bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3712  if (Block1 != Block2)
3713  return Block1 ? ImplicitConversionSequence::Worse
3715  }
3716 
3717  // In order to support multiple calling conventions for the lambda conversion
3718  // operator (such as when the free and member function calling convention is
3719  // different), prefer the 'free' mechanism, followed by the calling-convention
3720  // of operator(). The latter is in place to support the MSVC-like solution of
3721  // defining ALL of the possible conversions in regards to calling-convention.
3722  const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3723  const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3724 
3725  if (Conv1FuncRet && Conv2FuncRet &&
3726  Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3727  CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3728  CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3729 
3730  CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3731  const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3732 
3733  CallingConv CallOpCC =
3734  CallOp->getType()->castAs<FunctionType>()->getCallConv();
3736  CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3738  CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3739 
3740  CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3741  for (CallingConv CC : PrefOrder) {
3742  if (Conv1CC == CC)
3744  if (Conv2CC == CC)
3746  }
3747  }
3748 
3750 }
3751 
3753  const ImplicitConversionSequence &ICS) {
3754  return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3755  (ICS.isUserDefined() &&
3757 }
3758 
3759 /// CompareImplicitConversionSequences - Compare two implicit
3760 /// conversion sequences to determine whether one is better than the
3761 /// other or if they are indistinguishable (C++ 13.3.3.2).
3764  const ImplicitConversionSequence& ICS1,
3765  const ImplicitConversionSequence& ICS2)
3766 {
3767  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3768  // conversion sequences (as defined in 13.3.3.1)
3769  // -- a standard conversion sequence (13.3.3.1.1) is a better
3770  // conversion sequence than a user-defined conversion sequence or
3771  // an ellipsis conversion sequence, and
3772  // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3773  // conversion sequence than an ellipsis conversion sequence
3774  // (13.3.3.1.3).
3775  //
3776  // C++0x [over.best.ics]p10:
3777  // For the purpose of ranking implicit conversion sequences as
3778  // described in 13.3.3.2, the ambiguous conversion sequence is
3779  // treated as a user-defined sequence that is indistinguishable
3780  // from any other user-defined conversion sequence.
3781 
3782  // String literal to 'char *' conversion has been deprecated in C++03. It has
3783  // been removed from C++11. We still accept this conversion, if it happens at
3784  // the best viable function. Otherwise, this conversion is considered worse
3785  // than ellipsis conversion. Consider this as an extension; this is not in the
3786  // standard. For example:
3787  //
3788  // int &f(...); // #1
3789  // void f(char*); // #2
3790  // void g() { int &r = f("foo"); }
3791  //
3792  // In C++03, we pick #2 as the best viable function.
3793  // In C++11, we pick #1 as the best viable function, because ellipsis
3794  // conversion is better than string-literal to char* conversion (since there
3795  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3796  // convert arguments, #2 would be the best viable function in C++11.
3797  // If the best viable function has this conversion, a warning will be issued
3798  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3799 
3800  if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3803  // Ill-formedness must not differ
3804  ICS1.isBad() == ICS2.isBad())
3808 
3809  if (ICS1.getKindRank() < ICS2.getKindRank())
3811  if (ICS2.getKindRank() < ICS1.getKindRank())
3813 
3814  // The following checks require both conversion sequences to be of
3815  // the same kind.
3816  if (ICS1.getKind() != ICS2.getKind())
3818 
3821 
3822  // Two implicit conversion sequences of the same form are
3823  // indistinguishable conversion sequences unless one of the
3824  // following rules apply: (C++ 13.3.3.2p3):
3825 
3826  // List-initialization sequence L1 is a better conversion sequence than
3827  // list-initialization sequence L2 if:
3828  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3829  // if not that,
3830  // — L1 and L2 convert to arrays of the same element type, and either the
3831  // number of elements n_1 initialized by L1 is less than the number of
3832  // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3833  // an array of unknown bound and L1 does not,
3834  // even if one of the other rules in this paragraph would otherwise apply.
3835  if (!ICS1.isBad()) {
3836  bool StdInit1 = false, StdInit2 = false;
3839  nullptr);
3842  nullptr);
3843  if (StdInit1 != StdInit2)
3844  return StdInit1 ? ImplicitConversionSequence::Better
3846 
3847  if (ICS1.hasInitializerListContainerType() &&
3849  if (auto *CAT1 = S.Context.getAsConstantArrayType(
3851  if (auto *CAT2 = S.Context.getAsConstantArrayType(
3853  if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3854  CAT2->getElementType())) {
3855  // Both to arrays of the same element type
3856  if (CAT1->getSize() != CAT2->getSize())
3857  // Different sized, the smaller wins
3858  return CAT1->getSize().ult(CAT2->getSize())
3863  // One is incomplete, it loses
3867  }
3868  }
3869  }
3870 
3871  if (ICS1.isStandard())
3872  // Standard conversion sequence S1 is a better conversion sequence than
3873  // standard conversion sequence S2 if [...]
3874  Result = CompareStandardConversionSequences(S, Loc,
3875  ICS1.Standard, ICS2.Standard);
3876  else if (ICS1.isUserDefined()) {
3877  // User-defined conversion sequence U1 is a better conversion
3878  // sequence than another user-defined conversion sequence U2 if
3879  // they contain the same user-defined conversion function or
3880  // constructor and if the second standard conversion sequence of
3881  // U1 is better than the second standard conversion sequence of
3882  // U2 (C++ 13.3.3.2p3).
3883  if (ICS1.UserDefined.ConversionFunction ==
3885  Result = CompareStandardConversionSequences(S, Loc,
3886  ICS1.UserDefined.After,
3887  ICS2.UserDefined.After);
3888  else
3889  Result = compareConversionFunctions(S,
3892  }
3893 
3894  return Result;
3895 }
3896 
3897 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3898 // determine if one is a proper subset of the other.
3901  const StandardConversionSequence& SCS1,
3902  const StandardConversionSequence& SCS2) {
3905 
3906  // the identity conversion sequence is considered to be a subsequence of
3907  // any non-identity conversion sequence
3908  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3910  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3912 
3913  if (SCS1.Second != SCS2.Second) {
3914  if (SCS1.Second == ICK_Identity)
3916  else if (SCS2.Second == ICK_Identity)
3918  else
3920  } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3922 
3923  if (SCS1.Third == SCS2.Third) {
3924  return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3926  }
3927 
3928  if (SCS1.Third == ICK_Identity)
3929  return Result == ImplicitConversionSequence::Worse
3932 
3933  if (SCS2.Third == ICK_Identity)
3934  return Result == ImplicitConversionSequence::Better
3937 
3939 }
3940 
3941 /// Determine whether one of the given reference bindings is better
3942 /// than the other based on what kind of bindings they are.
3943 static bool
3945  const StandardConversionSequence &SCS2) {
3946  // C++0x [over.ics.rank]p3b4:
3947  // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3948  // implicit object parameter of a non-static member function declared
3949  // without a ref-qualifier, and *either* S1 binds an rvalue reference
3950  // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3951  // lvalue reference to a function lvalue and S2 binds an rvalue
3952  // reference*.
3953  //
3954  // FIXME: Rvalue references. We're going rogue with the above edits,
3955  // because the semantics in the current C++0x working paper (N3225 at the
3956  // time of this writing) break the standard definition of std::forward
3957  // and std::reference_wrapper when dealing with references to functions.
3958  // Proposed wording changes submitted to CWG for consideration.
3961  return false;
3962 
3963  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3964  SCS2.IsLvalueReference) ||
3965  (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3967 }
3968 
3970  None,
3973 };
3974 
3975 /// Returns kind of fixed enum promotion the \a SCS uses.
3976 static FixedEnumPromotion
3978 
3979  if (SCS.Second != ICK_Integral_Promotion)
3980  return FixedEnumPromotion::None;
3981 
3982  QualType FromType = SCS.getFromType();
3983  if (!FromType->isEnumeralType())
3984  return FixedEnumPromotion::None;
3985 
3986  EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3987  if (!Enum->isFixed())
3988  return FixedEnumPromotion::None;
3989 
3990  QualType UnderlyingType = Enum->getIntegerType();
3991  if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3993 
3995 }
3996 
3997 /// CompareStandardConversionSequences - Compare two standard
3998 /// conversion sequences to determine whether one is better than the
3999 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4002  const StandardConversionSequence& SCS1,
4003  const StandardConversionSequence& SCS2)
4004 {
4005  // Standard conversion sequence S1 is a better conversion sequence
4006  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4007 
4008  // -- S1 is a proper subsequence of S2 (comparing the conversion
4009  // sequences in the canonical form defined by 13.3.3.1.1,
4010  // excluding any Lvalue Transformation; the identity conversion
4011  // sequence is considered to be a subsequence of any
4012  // non-identity conversion sequence) or, if not that,
4014  = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4015  return CK;
4016 
4017  // -- the rank of S1 is better than the rank of S2 (by the rules
4018  // defined below), or, if not that,
4019  ImplicitConversionRank Rank1 = SCS1.getRank();
4020  ImplicitConversionRank Rank2 = SCS2.getRank();
4021  if (Rank1 < Rank2)
4023  else if (Rank2 < Rank1)
4025 
4026  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4027  // are indistinguishable unless one of the following rules
4028  // applies:
4029 
4030  // A conversion that is not a conversion of a pointer, or
4031  // pointer to member, to bool is better than another conversion
4032  // that is such a conversion.
4034  return SCS2.isPointerConversionToBool()
4037 
4038  // C++14 [over.ics.rank]p4b2:
4039  // This is retroactively applied to C++11 by CWG 1601.
4040  //
4041  // A conversion that promotes an enumeration whose underlying type is fixed
4042  // to its underlying type is better than one that promotes to the promoted
4043  // underlying type, if the two are different.
4044  FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4045  FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4046  if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4047  FEP1 != FEP2)
4051 
4052  // C++ [over.ics.rank]p4b2:
4053  //
4054  // If class B is derived directly or indirectly from class A,
4055  // conversion of B* to A* is better than conversion of B* to
4056  // void*, and conversion of A* to void* is better than conversion
4057  // of B* to void*.
4058  bool SCS1ConvertsToVoid
4060  bool SCS2ConvertsToVoid
4062  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4063  // Exactly one of the conversion sequences is a conversion to
4064  // a void pointer; it's the worse conversion.
4065  return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4067  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4068  // Neither conversion sequence converts to a void pointer; compare
4069  // their derived-to-base conversions.
4071  = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4072  return DerivedCK;
4073  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4074  !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4075  // Both conversion sequences are conversions to void
4076  // pointers. Compare the source types to determine if there's an
4077  // inheritance relationship in their sources.
4078  QualType FromType1 = SCS1.getFromType();
4079  QualType FromType2 = SCS2.getFromType();
4080 
4081  // Adjust the types we're converting from via the array-to-pointer
4082  // conversion, if we need to.
4083  if (SCS1.First == ICK_Array_To_Pointer)
4084  FromType1 = S.Context.getArrayDecayedType(FromType1);
4085  if (SCS2.First == ICK_Array_To_Pointer)
4086  FromType2 = S.Context.getArrayDecayedType(FromType2);
4087 
4088  QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4089  QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4090 
4091  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4093  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4095 
4096  // Objective-C++: If one interface is more specific than the
4097  // other, it is the better one.
4098  const ObjCObjectPointerType* FromObjCPtr1
4099  = FromType1->getAs<ObjCObjectPointerType>();
4100  const ObjCObjectPointerType* FromObjCPtr2
4101  = FromType2->getAs<ObjCObjectPointerType>();
4102  if (FromObjCPtr1 && FromObjCPtr2) {
4103  bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4104  FromObjCPtr2);
4105  bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4106  FromObjCPtr1);
4107  if (AssignLeft != AssignRight) {
4108  return AssignLeft? ImplicitConversionSequence::Better
4110  }
4111  }
4112  }
4113 
4114  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4115  // Check for a better reference binding based on the kind of bindings.
4116  if (isBetterReferenceBindingKind(SCS1, SCS2))
4118  else if (isBetterReferenceBindingKind(SCS2, SCS1))
4120  }
4121 
4122  // Compare based on qualification conversions (C++ 13.3.3.2p3,
4123  // bullet 3).
4125  = CompareQualificationConversions(S, SCS1, SCS2))
4126  return QualCK;
4127 
4128  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4129  // C++ [over.ics.rank]p3b4:
4130  // -- S1 and S2 are reference bindings (8.5.3), and the types to
4131  // which the references refer are the same type except for
4132  // top-level cv-qualifiers, and the type to which the reference
4133  // initialized by S2 refers is more cv-qualified than the type
4134  // to which the reference initialized by S1 refers.
4135  QualType T1 = SCS1.getToType(2);
4136  QualType T2 = SCS2.getToType(2);
4137  T1 = S.Context.getCanonicalType(T1);
4138  T2 = S.Context.getCanonicalType(T2);
4139  Qualifiers T1Quals, T2Quals;
4140  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4141  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4142  if (UnqualT1 == UnqualT2) {
4143  // Objective-C++ ARC: If the references refer to objects with different
4144  // lifetimes, prefer bindings that don't change lifetime.
4145  if (SCS1.ObjCLifetimeConversionBinding !=
4147  return SCS1.ObjCLifetimeConversionBinding
4150  }
4151 
4152  // If the type is an array type, promote the element qualifiers to the
4153  // type for comparison.
4154  if (isa<ArrayType>(T1) && T1Quals)
4155  T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4156  if (isa<ArrayType>(T2) && T2Quals)
4157  T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4158  if (T2.isMoreQualifiedThan(T1))
4160  if (T1.isMoreQualifiedThan(T2))
4162  }
4163  }
4164 
4165  // In Microsoft mode (below 19.28), prefer an integral conversion to a
4166  // floating-to-integral conversion if the integral conversion
4167  // is between types of the same size.
4168  // For example:
4169  // void f(float);
4170  // void f(int);
4171  // int main {
4172  // long a;
4173  // f(a);
4174  // }
4175  // Here, MSVC will call f(int) instead of generating a compile error
4176  // as clang will do in standard mode.
4177  if (S.getLangOpts().MSVCCompat &&
4179  SCS1.Second == ICK_Integral_Conversion &&
4180  SCS2.Second == ICK_Floating_Integral &&
4181  S.Context.getTypeSize(SCS1.getFromType()) ==
4182  S.Context.getTypeSize(SCS1.getToType(2)))
4184 
4185  // Prefer a compatible vector conversion over a lax vector conversion
4186  // For example:
4187  //
4188  // typedef float __v4sf __attribute__((__vector_size__(16)));
4189  // void f(vector float);
4190  // void f(vector signed int);
4191  // int main() {
4192  // __v4sf a;
4193  // f(a);
4194  // }
4195  // Here, we'd like to choose f(vector float) and not
4196  // report an ambiguous call error
4197  if (SCS1.Second == ICK_Vector_Conversion &&
4198  SCS2.Second == ICK_Vector_Conversion) {
4199  bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4200  SCS1.getFromType(), SCS1.getToType(2));
4201  bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4202  SCS2.getFromType(), SCS2.getToType(2));
4203 
4204  if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4205  return SCS1IsCompatibleVectorConversion
4208  }
4209 
4210  if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4212  bool SCS1IsCompatibleSVEVectorConversion =
4214  bool SCS2IsCompatibleSVEVectorConversion =
4216 
4217  if (SCS1IsCompatibleSVEVectorConversion !=
4218  SCS2IsCompatibleSVEVectorConversion)
4219  return SCS1IsCompatibleSVEVectorConversion
4222  }
4223 
4225 }
4226 
4227 /// CompareQualificationConversions - Compares two standard conversion
4228 /// sequences to determine whether they can be ranked based on their
4229 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4232  const StandardConversionSequence& SCS1,
4233  const StandardConversionSequence& SCS2) {
4234  // C++ [over.ics.rank]p3:
4235  // -- S1 and S2 differ only in their qualification conversion and
4236  // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4237  // [C++98]
4238  // [...] and the cv-qualification signature of type T1 is a proper subset
4239  // of the cv-qualification signature of type T2, and S1 is not the
4240  // deprecated string literal array-to-pointer conversion (4.2).
4241  // [C++2a]
4242  // [...] where T1 can be converted to T2 by a qualification conversion.
4243  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4244  SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4246 
4247  // FIXME: the example in the standard doesn't use a qualification
4248  // conversion (!)
4249  QualType T1 = SCS1.getToType(2);
4250  QualType T2 = SCS2.getToType(2);
4251  T1 = S.Context.getCanonicalType(T1);
4252  T2 = S.Context.getCanonicalType(T2);
4253  assert(!T1->isReferenceType() && !T2->isReferenceType());
4254  Qualifiers T1Quals, T2Quals;
4255  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4256  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4257 
4258  // If the types are the same, we won't learn anything by unwrapping
4259  // them.
4260  if (UnqualT1 == UnqualT2)
4262 
4263  // Don't ever prefer a standard conversion sequence that uses the deprecated
4264  // string literal array to pointer conversion.
4265  bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4266  bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4267 
4268  // Objective-C++ ARC:
4269  // Prefer qualification conversions not involving a change in lifetime
4270  // to qualification conversions that do change lifetime.
4273  CanPick1 = false;
4276  CanPick2 = false;
4277 
4278  bool ObjCLifetimeConversion;
4279  if (CanPick1 &&
4280  !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4281  CanPick1 = false;
4282  // FIXME: In Objective-C ARC, we can have qualification conversions in both
4283  // directions, so we can't short-cut this second check in general.
4284  if (CanPick2 &&
4285  !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4286  CanPick2 = false;
4287 
4288  if (CanPick1 != CanPick2)
4289  return CanPick1 ? ImplicitConversionSequence::Better
4292 }
4293 
4294 /// CompareDerivedToBaseConversions - Compares two standard conversion
4295 /// sequences to determine whether they can be ranked based on their
4296 /// various kinds of derived-to-base conversions (C++
4297 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4298 /// conversions between Objective-C interface types.
4301  const StandardConversionSequence& SCS1,
4302  const StandardConversionSequence& SCS2) {
4303  QualType FromType1 = SCS1.getFromType();
4304  QualType ToType1 = SCS1.getToType(1);
4305  QualType FromType2 = SCS2.getFromType();
4306  QualType ToType2 = SCS2.getToType(1);
4307 
4308  // Adjust the types we're converting from via the array-to-pointer
4309  // conversion, if we need to.
4310  if (SCS1.First == ICK_Array_To_Pointer)
4311  FromType1 = S.Context.getArrayDecayedType(FromType1);
4312  if (SCS2.First == ICK_Array_To_Pointer)
4313  FromType2 = S.Context.getArrayDecayedType(FromType2);
4314 
4315  // Canonicalize all of the types.
4316  FromType1 = S.Context.getCanonicalType(FromType1);
4317  ToType1 = S.Context.getCanonicalType(ToType1);
4318  FromType2 = S.Context.getCanonicalType(FromType2);
4319  ToType2 = S.Context.getCanonicalType(ToType2);
4320 
4321  // C++ [over.ics.rank]p4b3:
4322  //
4323  // If class B is derived directly or indirectly from class A and
4324  // class C is derived directly or indirectly from B,
4325  //
4326  // Compare based on pointer conversions.
4327  if (SCS1.Second == ICK_Pointer_Conversion &&
4328  SCS2.Second == ICK_Pointer_Conversion &&
4329  /*FIXME: Remove if Objective-C id conversions get their own rank*/
4330  FromType1->isPointerType() && FromType2->isPointerType() &&
4331  ToType1->isPointerType() && ToType2->isPointerType()) {
4332  QualType FromPointee1 =
4333  FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4334  QualType ToPointee1 =
4335  ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4336  QualType FromPointee2 =
4337  FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4338  QualType ToPointee2 =
4339  ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4340 
4341  // -- conversion of C* to B* is better than conversion of C* to A*,
4342  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4343  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4345  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4347  }
4348 
4349  // -- conversion of B* to A* is better than conversion of C* to A*,
4350  if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4351  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4353  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4355  }
4356  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4357  SCS2.Second == ICK_Pointer_Conversion) {
4358  const ObjCObjectPointerType *FromPtr1
4359  = FromType1->getAs<ObjCObjectPointerType>();
4360  const ObjCObjectPointerType *FromPtr2
4361  = FromType2->getAs<ObjCObjectPointerType>();
4362  const ObjCObjectPointerType *ToPtr1
4363  = ToType1->getAs<ObjCObjectPointerType>();
4364  const ObjCObjectPointerType *ToPtr2
4365  = ToType2->getAs<ObjCObjectPointerType>();
4366 
4367  if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4368  // Apply the same conversion ranking rules for Objective-C pointer types
4369  // that we do for C++ pointers to class types. However, we employ the
4370  // Objective-C pseudo-subtyping relationship used for assignment of
4371  // Objective-C pointer types.
4372  bool FromAssignLeft
4373  = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4374  bool FromAssignRight
4375  = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4376  bool ToAssignLeft
4377  = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4378  bool ToAssignRight
4379  = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4380 
4381  // A conversion to an a non-id object pointer type or qualified 'id'
4382  // type is better than a conversion to 'id'.
4383  if (ToPtr1->isObjCIdType() &&
4384  (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4386  if (ToPtr2->isObjCIdType() &&
4387  (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4389 
4390  // A conversion to a non-id object pointer type is better than a
4391  // conversion to a qualified 'id' type
4392  if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4394  if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4396 
4397  // A conversion to an a non-Class object pointer type or qualified 'Class'
4398  // type is better than a conversion to 'Class'.
4399  if (ToPtr1->isObjCClassType() &&
4400  (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4402  if (ToPtr2->isObjCClassType() &&
4403  (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4405 
4406  // A conversion to a non-Class object pointer type is better than a
4407  // conversion to a qualified 'Class' type.
4408  if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4410  if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4412 
4413  // -- "conversion of C* to B* is better than conversion of C* to A*,"
4414  if (S.Context.hasSameType(FromType1, FromType2) &&
4415  !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4416  (ToAssignLeft != ToAssignRight)) {
4417  if (FromPtr1->isSpecialized()) {
4418  // "conversion of B<A> * to B * is better than conversion of B * to
4419  // C *.
4420  bool IsFirstSame =
4421  FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4422  bool IsSecondSame =
4423  FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4424  if (IsFirstSame) {
4425  if (!IsSecondSame)
4427  } else if (IsSecondSame)
4429  }
4430  return ToAssignLeft? ImplicitConversionSequence::Worse
4432  }
4433 
4434  // -- "conversion of B* to A* is better than conversion of C* to A*,"
4435  if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4436  (FromAssignLeft != FromAssignRight))
4437  return FromAssignLeft? ImplicitConversionSequence::Better
4439  }
4440  }
4441 
4442  // Ranking of member-pointer types.
4443  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4444  FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4445  ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4446  const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4447  const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4448  const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4449  const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4450  const Type *FromPointeeType1 = FromMemPointer1->getClass();
4451  const Type *ToPointeeType1 = ToMemPointer1->getClass();
4452  const Type *FromPointeeType2 = FromMemPointer2->getClass();
4453  const Type *ToPointeeType2 = ToMemPointer2->getClass();
4454  QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4455  QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4456  QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4457  QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4458  // conversion of A::* to B::* is better than conversion of A::* to C::*,
4459  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4460  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4462  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4464  }
4465  // conversion of B::* to C::* is better than conversion of A::* to C::*
4466  if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4467  if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4469  else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4471  }
4472  }
4473 
4474  if (SCS1.Second == ICK_Derived_To_Base) {
4475  // -- conversion of C to B is better than conversion of C to A,
4476  // -- binding of an expression of type C to a reference of type
4477  // B& is better than binding an expression of type C to a
4478  // reference of type A&,
4479  if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4480  !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4481  if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4483  else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4485  }
4486 
4487  // -- conversion of B to A is better than conversion of C to A.
4488  // -- binding of an expression of type B to a reference of type
4489  // A& is better than binding an expression of type C to a
4490  // reference of type A&,
4491  if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4492  S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4493  if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4495  else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4497  }
4498  }
4499 
4501 }
4502 
4503 /// Determine whether the given type is valid, e.g., it is not an invalid
4504 /// C++ class.
4505 static bool isTypeValid(QualType T) {
4506  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4507  return !Record->isInvalidDecl();
4508 
4509  return true;
4510 }
4511 
4513  if (!T.getQualifiers().hasUnaligned())
4514  return T;
4515 
4516  Qualifiers Q;
4517  T = Ctx.getUnqualifiedArrayType(T, Q);
4518  Q.removeUnaligned();
4519  return Ctx.getQualifiedType(T, Q);
4520 }
4521 
4522 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4523 /// determine whether they are reference-compatible,
4524 /// reference-related, or incompatible, for use in C++ initialization by
4525 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4526 /// type, and the first type (T1) is the pointee type of the reference
4527 /// type being initialized.
4530  QualType OrigT1, QualType OrigT2,
4531  ReferenceConversions *ConvOut) {
4532  assert(!OrigT1->isReferenceType() &&
4533  "T1 must be the pointee type of the reference type");
4534  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4535 
4536  QualType T1 = Context.getCanonicalType(OrigT1);
4537  QualType T2 = Context.getCanonicalType(OrigT2);
4538  Qualifiers T1Quals, T2Quals;
4539  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4540  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4541 
4542  ReferenceConversions ConvTmp;
4543  ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4544  Conv = ReferenceConversions();
4545 
4546  // C++2a [dcl.init.ref]p4:
4547  // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4548  // reference-related to "cv2 T2" if T1 is similar to T2, or
4549  // T1 is a base class of T2.
4550  // "cv1 T1" is reference-compatible with "cv2 T2" if
4551  // a prvalue of type "pointer to cv2 T2" can be converted to the type
4552  // "pointer to cv1 T1" via a standard conversion sequence.
4553 
4554  // Check for standard conversions we can apply to pointers: derived-to-base
4555  // conversions, ObjC pointer conversions, and function pointer conversions.
4556  // (Qualification conversions are checked last.)
4557  QualType ConvertedT2;
4558  if (UnqualT1 == UnqualT2) {
4559  // Nothing to do.
4560  } else if (isCompleteType(Loc, OrigT2) &&
4561  isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4562  IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4563  Conv |= ReferenceConversions::DerivedToBase;
4564  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4565  UnqualT2->isObjCObjectOrInterfaceType() &&
4566  Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4568  else if (UnqualT2->isFunctionType() &&
4569  IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4570  Conv |= ReferenceConversions::Function;
4571  // No need to check qualifiers; function types don't have them.
4572  return Ref_Compatible;
4573  }
4574  bool ConvertedReferent = Conv != 0;
4575 
4576  // We can have a qualification conversion. Compute whether the types are
4577  // similar at the same time.
4578  bool PreviousToQualsIncludeConst = true;
4579  bool TopLevel = true;
4580  do {
4581  if (T1 == T2)
4582  break;
4583 
4584  // We will need a qualification conversion.
4585  Conv |= ReferenceConversions::Qualification;
4586 
4587  // Track whether we performed a qualification conversion anywhere other
4588  // than the top level. This matters for ranking reference bindings in
4589  // overload resolution.
4590  if (!TopLevel)
4591  Conv |= ReferenceConversions::NestedQualification;
4592 
4593  // MS compiler ignores __unaligned qualifier for references; do the same.
4594  T1 = withoutUnaligned(Context, T1);
4595  T2 = withoutUnaligned(Context, T2);
4596 
4597  // If we find a qualifier mismatch, the types are not reference-compatible,
4598  // but are still be reference-related if they're similar.
4599  bool ObjCLifetimeConversion = false;
4600  if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4601  PreviousToQualsIncludeConst,
4602  ObjCLifetimeConversion))
4603  return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4604  ? Ref_Related
4605  : Ref_Incompatible;
4606 
4607  // FIXME: Should we track this for any level other than the first?
4608  if (ObjCLifetimeConversion)
4609  Conv |= ReferenceConversions::ObjCLifetime;
4610 
4611  TopLevel = false;
4612  } while (Context.UnwrapSimilarTypes(T1, T2));
4613 
4614  // At this point, if the types are reference-related, we must either have the
4615  // same inner type (ignoring qualifiers), or must have already worked out how
4616  // to convert the referent.
4617  return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4618  ? Ref_Compatible
4619  : Ref_Incompatible;
4620 }
4621 
4622 /// Look for a user-defined conversion to a value reference-compatible
4623 /// with DeclType. Return true if something definite is found.
4624 static bool
4626  QualType DeclType, SourceLocation DeclLoc,
4627  Expr *Init, QualType T2, bool AllowRvalues,
4628  bool AllowExplicit) {
4629  assert(T2->isRecordType() && "Can only find conversions of record types.");
4630  auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4631 
4632  OverloadCandidateSet CandidateSet(
4634  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4635  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4636  NamedDecl *D = *I;
4637  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4638  if (isa<UsingShadowDecl>(D))
4639  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4640 
4641  FunctionTemplateDecl *ConvTemplate
4642  = dyn_cast<FunctionTemplateDecl>(D);
4643  CXXConversionDecl *Conv;
4644  if (ConvTemplate)
4645  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4646  else
4647  Conv = cast<CXXConversionDecl>(D);
4648 
4649  if (AllowRvalues) {
4650  // If we are initializing an rvalue reference, don't permit conversion
4651  // functions that return lvalues.
4652  if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4653  const ReferenceType *RefType
4655  if (RefType && !RefType->getPointeeType()->isFunctionType())
4656  continue;
4657  }
4658 
4659  if (!ConvTemplate &&
4661  DeclLoc,
4662  Conv->getConversionType()
4664  .getUnqualifiedType(),
4665  DeclType.getNonReferenceType().getUnqualifiedType()) ==
4667  continue;
4668  } else {
4669  // If the conversion function doesn't return a reference type,
4670  // it can't be considered for this conversion. An rvalue reference
4671  // is only acceptable if its referencee is a function type.
4672 
4673  const ReferenceType *RefType =
4675  if (!RefType ||
4676  (!RefType->isLValueReferenceType() &&
4677  !RefType->getPointeeType()->isFunctionType()))
4678  continue;
4679  }
4680 
4681  if (ConvTemplate)
4683  ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4684  /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4685  else
4687  Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4688  /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4689  }
4690 
4691  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4692 
4694  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4695  case OR_Success:
4696  // C++ [over.ics.ref]p1:
4697  //
4698  // [...] If the parameter binds directly to the result of
4699  // applying a conversion function to the argument
4700  // expression, the implicit conversion sequence is a
4701  // user-defined conversion sequence (13.3.3.1.2), with the
4702  // second standard conversion sequence either an identity
4703  // conversion or, if the conversion function returns an
4704  // entity of a type that is a derived class of the parameter
4705  // type, a derived-to-base Conversion.
4706  if (!Best->FinalConversion.DirectBinding)
4707  return false;
4708 
4709  ICS.setUserDefined();
4710  ICS.UserDefined.Before = Best->Conversions[0].Standard;
4711  ICS.UserDefined.After = Best->FinalConversion;
4712  ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4713  ICS.UserDefined.ConversionFunction = Best->Function;
4714  ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4715  ICS.UserDefined.EllipsisConversion = false;
4716  assert(ICS.UserDefined.After.ReferenceBinding &&
4718  "Expected a direct reference binding!");
4719  return true;
4720 
4721  case OR_Ambiguous:
4722  ICS.setAmbiguous();
4723  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4724  Cand != CandidateSet.end(); ++Cand)
4725  if (Cand->Best)
4726  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4727  return true;
4728 
4729  case OR_No_Viable_Function:
4730  case OR_Deleted:
4731  // There was no suitable conversion, or we found a deleted
4732  // conversion; continue with other checks.
4733  return false;
4734  }
4735 
4736  llvm_unreachable("Invalid OverloadResult!");
4737 }
4738 
4739 /// Compute an implicit conversion sequence for reference
4740 /// initialization.
4742 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4743  SourceLocation DeclLoc,
4744  bool SuppressUserConversions,
4745  bool AllowExplicit) {
4746  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4747 
4748  // Most paths end in a failed conversion.
4750  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4751 
4752  QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4753  QualType T2 = Init->getType();
4754 
4755  // If the initializer is the address of an overloaded function, try
4756  // to resolve the overloaded function. If all goes well, T2 is the
4757  // type of the resulting function.
4758  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4759  DeclAccessPair Found;
4760  if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4761  false, Found))
4762  T2 = Fn->getType();
4763  }
4764 
4765  // Compute some basic properties of the types and the initializer.
4766  bool isRValRef = DeclType->isRValueReferenceType();
4767  Expr::Classification InitCategory = Init->Classify(S.Context);
4768 
4770  Sema::ReferenceCompareResult RefRelationship =
4771  S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4772 
4773  auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4774  ICS.setStandard();
4775  ICS.Standard.First = ICK_Identity;
4776  // FIXME: A reference binding can be a function conversion too. We should
4777  // consider that when ordering reference-to-function bindings.
4778  ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4780  : (RefConv & Sema::ReferenceConversions::ObjC)
4782  : ICK_Identity;
4783  // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4784  // a reference binding that performs a non-top-level qualification
4785  // conversion as a qualification conversion, not as an identity conversion.
4786  ICS.Standard.Third = (RefConv &
4787  Sema::ReferenceConversions::NestedQualification)
4789  : ICK_Identity;
4790  ICS.Standard.setFromType(T2);
4791  ICS.Standard.setToType(0, T2);
4792  ICS.Standard.setToType(1, T1);
4793  ICS.Standard.setToType(2, T1);
4794  ICS.Standard.ReferenceBinding = true;
4795  ICS.Standard.DirectBinding = BindsDirectly;
4796  ICS.Standard.IsLvalueReference = !isRValRef;
4798  ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4801  (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4802  ICS.Standard.CopyConstructor = nullptr;
4804  };
4805 
4806  // C++0x [dcl.init.ref]p5:
4807  // A reference to type "cv1 T1" is initialized by an expression
4808  // of type "cv2 T2" as follows:
4809 
4810  // -- If reference is an lvalue reference and the initializer expression
4811  if (!isRValRef) {
4812  // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4813  // reference-compatible with "cv2 T2," or
4814  //
4815  // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4816  if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4817  // C++ [over.ics.ref]p1:
4818  // When a parameter of reference type binds directly (8.5.3)
4819  // to an argument expression, the implicit conversion sequence
4820  // is the identity conversion, unless the argument expression
4821  // has a type that is a derived class of the parameter type,
4822  // in which case the implicit conversion sequence is a
4823  // derived-to-base Conversion (13.3.3.1).
4824  SetAsReferenceBinding(/*BindsDirectly=*/true);
4825 
4826  // Nothing more to do: the inaccessibility/ambiguity check for
4827  // derived-to-base conversions is suppressed when we're
4828  // computing the implicit conversion sequence (C++
4829  // [over.best.ics]p2).
4830  return ICS;
4831  }
4832 
4833  // -- has a class type (i.e., T2 is a class type), where T1 is
4834  // not reference-related to T2, and can be implicitly
4835  // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4836  // is reference-compatible with "cv3 T3" 92) (this
4837  // conversion is selected by enumerating the applicable
4838  // conversion functions (13.3.1.6) and choosing the best
4839  // one through overload resolution (13.3)),
4840  if (!SuppressUserConversions && T2->isRecordType() &&
4841  S.isCompleteType(DeclLoc, T2) &&
4842  RefRelationship == Sema::Ref_Incompatible) {
4843  if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4844  Init, T2, /*AllowRvalues=*/false,
4845  AllowExplicit))
4846  return ICS;
4847  }
4848  }
4849 
4850  // -- Otherwise, the reference shall be an lvalue reference to a
4851  // non-volatile const type (i.e., cv1 shall be const), or the reference
4852  // shall be an rvalue reference.
4853  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4854  if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4856  return ICS;
4857  }
4858 
4859  // -- If the initializer expression
4860  //
4861  // -- is an xvalue, class prvalue, array prvalue or function
4862  // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4863  if (RefRelationship == Sema::Ref_Compatible &&
4864  (InitCategory.isXValue() ||
4865  (InitCategory.isPRValue() &&
4866  (T2->isRecordType() || T2->isArrayType())) ||
4867  (InitCategory.isLValue() && T2->isFunctionType()))) {
4868  // In C++11, this is always a direct binding. In C++98/03, it's a direct
4869  // binding unless we're binding to a class prvalue.
4870  // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4871  // allow the use of rvalue references in C++98/03 for the benefit of
4872  // standard library implementors; therefore, we need the xvalue check here.
4873  SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4874  !(InitCategory.isPRValue() || T2->isRecordType()));
4875  return ICS;
4876  }
4877 
4878  // -- has a class type (i.e., T2 is a class type), where T1 is not
4879  // reference-related to T2, and can be implicitly converted to
4880  // an xvalue, class prvalue, or function lvalue of type
4881  // "cv3 T3", where "cv1 T1" is reference-compatible with
4882  // "cv3 T3",
4883  //
4884  // then the reference is bound to the value of the initializer
4885  // expression in the first case and to the result of the conversion
4886  // in the second case (or, in either case, to an appropriate base
4887  // class subobject).
4888  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4889  T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4890  FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4891  Init, T2, /*AllowRvalues=*/true,
4892  AllowExplicit)) {
4893  // In the second case, if the reference is an rvalue reference
4894  // and the second standard conversion sequence of the
4895  // user-defined conversion sequence includes an lvalue-to-rvalue
4896  // conversion, the program is ill-formed.
4897  if (ICS.isUserDefined() && isRValRef &&
4899  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4900 
4901  return ICS;
4902  }
4903 
4904  // A temporary of function type cannot be created; don't even try.
4905  if (T1->isFunctionType())
4906  return ICS;
4907 
4908  // -- Otherwise, a temporary of type "cv1 T1" is created and
4909  // initialized from the initializer expression using the
4910  // rules for a non-reference copy initialization (8.5). The
4911  // reference is then bound to the temporary. If T1 is
4912  // reference-related to T2, cv1 must be the same
4913  // cv-qualification as, or greater cv-qualification than,
4914  // cv2; otherwise, the program is ill-formed.
4915  if (RefRelationship == Sema::Ref_Related) {
4916  // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4917  // we would be reference-compatible or reference-compatible with
4918  // added qualification. But that wasn't the case, so the reference
4919  // initialization fails.
4920  //
4921  // Note that we only want to check address spaces and cvr-qualifiers here.
4922  // ObjC GC, lifetime and unaligned qualifiers aren't important.
4923  Qualifiers T1Quals = T1.getQualifiers();
4924  Qualifiers T2Quals = T2.getQualifiers();
4925  T1Quals.removeObjCGCAttr();
4926  T1Quals.removeObjCLifetime();
4927  T2Quals.removeObjCGCAttr();
4928  T2Quals.removeObjCLifetime();
4929  // MS compiler ignores __unaligned qualifier for references; do the same.
4930  T1Quals.removeUnaligned();
4931  T2Quals.removeUnaligned();
4932  if (!T1Quals.compatiblyIncludes(T2Quals))
4933  return ICS;
4934  }
4935 
4936  // If at least one of the types is a class type, the types are not
4937  // related, and we aren't allowed any user conversions, the
4938  // reference binding fails. This case is important for breaking
4939  // recursion, since TryImplicitConversion below will attempt to
4940  // create a temporary through the use of a copy constructor.
4941  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4942  (T1->isRecordType() || T2->isRecordType()))
4943  return ICS;
4944 
4945  // If T1 is reference-related to T2 and the reference is an rvalue
4946  // reference, the initializer expression shall not be an lvalue.
4947  if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4948  Init->Classify(S.Context).isLValue()) {
4950  return ICS;
4951  }
4952 
4953  // C++ [over.ics.ref]p2:
4954  // When a parameter of reference type is not bound directly to
4955  // an argument expression, the conversion sequence is the one
4956  // required to convert the argument expression to the
4957  // underlying type of the reference according to
4958  // 13.3.3.1. Conceptually, this conversion sequence corresponds
4959  // to copy-initializing a temporary of the underlying type with
4960  // the argument expression. Any difference in top-level
4961  // cv-qualification is subsumed by the initialization itself
4962  // and does not constitute a conversion.
4963  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4964  AllowedExplicit::None,
4965  /*InOverloadResolution=*/false,
4966  /*CStyle=*/false,
4967  /*AllowObjCWritebackConversion=*/false,
4968  /*AllowObjCConversionOnExplicit=*/false);
4969 
4970  // Of course, that's still a reference binding.
4971  if (ICS.isStandard()) {
4972  ICS.Standard.ReferenceBinding = true;
4973  ICS.Standard.IsLvalueReference = !isRValRef;
4974  ICS.Standard.BindsToFunctionLvalue = false;
4975  ICS.Standard.BindsToRvalue = true;
4978  } else if (ICS.isUserDefined()) {
4979  const ReferenceType *LValRefType =
4982 
4983  // C++ [over.ics.ref]p3:
4984  // Except for an implicit object parameter, for which see 13.3.1, a
4985  // standard conversion sequence cannot be formed if it requires [...]
4986  // binding an rvalue reference to an lvalue other than a function
4987  // lvalue.
4988  // Note that the function case is not possible here.
4989  if (isRValRef && LValRefType) {
4990  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4991  return ICS;
4992  }
4993 
4994  ICS.UserDefined.After.ReferenceBinding = true;
4995  ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4997  ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5000  }
5001 
5002  return ICS;
5003 }
5004 
5006 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5007  bool SuppressUserConversions,
5008  bool InOverloadResolution,
5009  bool AllowObjCWritebackConversion,
5010  bool AllowExplicit = false);
5011 
5012 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5013 /// initializer list From.
5016  bool SuppressUserConversions,
5017  bool InOverloadResolution,
5018  bool AllowObjCWritebackConversion) {
5019  // C++11 [over.ics.list]p1:
5020  // When an argument is an initializer list, it is not an expression and
5021  // special rules apply for converting it to a parameter type.
5022 
5024  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5025 
5026  // We need a complete type for what follows. With one C++20 exception,
5027  // incomplete types can never be initialized from init lists.
5028  QualType InitTy = ToType;
5029  const ArrayType *AT = S.Context.getAsArrayType(ToType);
5030  if (AT && S.getLangOpts().CPlusPlus20)
5031  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5032  // C++20 allows list initialization of an incomplete array type.
5033  InitTy = IAT->getElementType();
5034  if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5035  return Result;
5036 
5037  // Per DR1467:
5038  // If the parameter type is a class X and the initializer list has a single
5039  // element of type cv U, where U is X or a class derived from X, the
5040  // implicit conversion sequence is the one required to convert the element
5041  // to the parameter type.
5042  //
5043  // Otherwise, if the parameter type is a character array [... ]
5044  // and the initializer list has a single element that is an
5045  // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5046  // implicit conversion sequence is the identity conversion.
5047  if (From->getNumInits() == 1) {
5048  if (ToType->isRecordType()) {
5049  QualType InitType = From->getInit(0)->getType();
5050  if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5051  S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5052  return TryCopyInitialization(S, From->getInit(0), ToType,
5053  SuppressUserConversions,
5054  InOverloadResolution,
5055  AllowObjCWritebackConversion);
5056  }
5057 
5058  if (AT && S.IsStringInit(From->getInit(0), AT)) {
5059  InitializedEntity Entity =
5061  /*Consumed=*/false);
5062  if (S.CanPerformCopyInitialization(Entity, From)) {
5063  Result.setStandard();
5064  Result.Standard.setAsIdentityConversion();
5065  Result.Standard.setFromType(ToType);
5066  Result.Standard.setAllToTypes(ToType);
5067  return Result;
5068  }
5069  }
5070  }
5071 
5072  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5073  // C++11 [over.ics.list]p2:
5074  // If the parameter type is std::initializer_list<X> or "array of X" and
5075  // all the elements can be implicitly converted to X, the implicit
5076  // conversion sequence is the worst conversion necessary to convert an
5077  // element of the list to X.
5078  //
5079  // C++14 [over.ics.list]p3:
5080  // Otherwise, if the parameter type is "array of N X", if the initializer
5081  // list has exactly N elements or if it has fewer than N elements and X is
5082  // default-constructible, and if all the elements of the initializer list
5083  // can be implicitly converted to X, the implicit conversion sequence is
5084  // the worst conversion necessary to convert an element of the list to X.
5085  if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5086  unsigned e = From->getNumInits();
5089  QualType());
5090  QualType ContTy = ToType;
5091  bool IsUnbounded = false;
5092  if (AT) {
5093  InitTy = AT->getElementType();
5094  if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5095  if (CT->getSize().ult(e)) {
5096  // Too many inits, fatally bad
5098  ToType);
5099  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5100  return Result;
5101  }
5102  if (CT->getSize().ugt(e)) {
5103  // Need an init from empty {}, is there one?
5104  InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5105  From->getEndLoc());
5106  EmptyList.setType(S.Context.VoidTy);
5107  DfltElt = TryListConversion(
5108  S, &EmptyList, InitTy, SuppressUserConversions,
5109  InOverloadResolution, AllowObjCWritebackConversion);
5110  if (DfltElt.isBad()) {
5111  // No {} init, fatally bad
5112  Result.setBad(BadConversionSequence::too_few_initializers, From,
5113  ToType);
5114  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5115  return Result;
5116  }
5117  }
5118  } else {
5119  assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5120  IsUnbounded = true;
5121  if (!e) {
5122  // Cannot convert to zero-sized.
5123  Result.setBad(BadConversionSequence::too_few_initializers, From,
5124  ToType);
5125  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5126  return Result;
5127  }
5129  ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5130  ArrayType::Normal, 0);
5131  }
5132  }
5133 
5134  Result.setStandard();
5135  Result.Standard.setAsIdentityConversion();
5136  Result.Standard.setFromType(InitTy);
5137  Result.Standard.setAllToTypes(InitTy);
5138  for (unsigned i = 0; i < e; ++i) {
5139  Expr *Init = From->getInit(i);
5141  S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5142  AllowObjCWritebackConversion);
5143 
5144  // Keep the worse conversion seen so far.
5145  // FIXME: Sequences are not totally ordered, so 'worse' can be
5146  // ambiguous. CWG has been informed.
5147  if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5148  Result) ==
5150  Result = ICS;
5151  // Bail as soon as we find something unconvertible.
5152  if (Result.isBad()) {
5153  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5154  return Result;
5155  }
5156  }
5157  }
5158 
5159  // If we needed any implicit {} initialization, compare that now.
5160  // over.ics.list/6 indicates we should compare that conversion. Again CWG
5161  // has been informed that this might not be the best thing.
5162  if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5163  S, From->getEndLoc(), DfltElt, Result) ==
5165  Result = DfltElt;
5166  // Record the type being initialized so that we may compare sequences
5167  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5168  return Result;
5169  }
5170 
5171  // C++14 [over.ics.list]p4:
5172  // C++11 [over.ics.list]p3:
5173  // Otherwise, if the parameter is a non-aggregate class X and overload
5174  // resolution chooses a single best constructor [...] the implicit
5175  // conversion sequence is a user-defined conversion sequence. If multiple
5176  // constructors are viable but none is better than the others, the
5177  // implicit conversion sequence is a user-defined conversion sequence.
5178  if (ToType->isRecordType() && !ToType->isAggregateType()) {
5179  // This function can deal with initializer lists.
5180  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5181  AllowedExplicit::None,
5182  InOverloadResolution, /*CStyle=*/false,
5183  AllowObjCWritebackConversion,
5184  /*AllowObjCConversionOnExplicit=*/false);
5185  }
5186 
5187  // C++14 [over.ics.list]p5:
5188  // C++11 [over.ics.list]p4:
5189  // Otherwise, if the parameter has an aggregate type which can be
5190  // initialized from the initializer list [...] the implicit conversion
5191  // sequence is a user-defined conversion sequence.
5192  if (ToType->isAggregateType()) {
5193  // Type is an aggregate, argument is an init list. At this point it comes
5194  // down to checking whether the initialization works.
5195  // FIXME: Find out whether this parameter is consumed or not.
5196  InitializedEntity Entity =
5198  /*Consumed=*/false);
5200  From)) {
5201  Result.setUserDefined();
5202  Result.UserDefined.Before.setAsIdentityConversion();
5203  // Initializer lists don't have a type.
5204  Result.UserDefined.Before.setFromType(QualType());
5205  Result.UserDefined.Before.setAllToTypes(QualType());
5206 
5207  Result.UserDefined.After.setAsIdentityConversion();
5208  Result.UserDefined.After.setFromType(ToType);
5209  Result.UserDefined.After.setAllToTypes(ToType);
5210  Result.UserDefined.ConversionFunction = nullptr;
5211  }
5212  return Result;
5213  }
5214 
5215  // C++14 [over.ics.list]p6:
5216  // C++11 [over.ics.list]p5:
5217  // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5218  if (ToType->isReferenceType()) {
5219  // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5220  // mention initializer lists in any way. So we go by what list-
5221  // initialization would do and try to extrapolate from that.
5222 
5223  QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5224 
5225  // If the initializer list has a single element that is reference-related
5226  // to the parameter type, we initialize the reference from that.
5227  if (From->getNumInits() == 1) {
5228  Expr *Init = From->getInit(0);
5229 
5230  QualType T2 = Init->getType();
5231 
5232  // If the initializer is the address of an overloaded function, try
5233  // to resolve the overloaded function. If all goes well, T2 is the
5234  // type of the resulting function.
5235  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5236  DeclAccessPair Found;
5238  Init, ToType, false, Found))
5239  T2 = Fn->getType();
5240  }
5241 
5242  // Compute some basic properties of the types and the initializer.
5243  Sema::ReferenceCompareResult RefRelationship =
5244  S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5245 
5246  if (RefRelationship >= Sema::Ref_Related) {
5247  return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->