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